상세 컨텐츠

본문 제목

[머신러닝중급]Categorical Variables

로봇-AI

by happynaraepapa 2025. 1. 22. 09:39

본문

sources :
https://www.kaggle.com/code/alexisbcook/categorical-variables

Categorical Variables

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com

In this tutorial, you will learn what a categorical variable is, along with three approaches for handling this type of data.
여기서는 명목변수에  대해서 다루고 3가지 접근 방식을 알아 보겠다.
#통계부문에서 categorical  variable을 명목변수라고 어려운 말로 부르고 있다 나중에 통계 공부를 염두해서 우리도 그렇게 부를까 한다.
#명목 변수 nominal variable; categorial variable
#통계분석에서 측정수준에 따른 변수를 구분할때 명목, 서열, 등간, 비율로 나누는데, 다른것은 대충 알겠고 명목이란 말그대로 임의의 숫자로 구분하거나 단순히 이름이라서 변수의 크기나 순서에 의미가 없는 경우이다 (예를 들어, 성별 (남=0, 여=1), 자동차브랜드(현대=1. 기아=2, ...))


Introduction
A categorical variable takes only a limited number of values.
명목변수는 제한적인 값을 고려하는 경우가 일반적이다. (그렇지 않으면 구분 categorized 하는 의미가 없지 않은가?))

Consider a survey that asks how often you eat breakfast and provides four options: "Never", "Rarely", "Most days", or "Every day".
예를 들어 아침을 얼마나 자주 먹냐는 설문에는 '전혀', '가끔', '대부분', '매일' 과 같이 4가지 답변을 고려해 볼 수 있다.
In this case, the data is categorical, because responses fall into a fixed set of categories.
이 경우 수집된 답변 데이터는 4가지 카테고리 집합에 정리될수 있고 따라서, 명목데이터라고 볼 수 있다.

If people responded to a survey about which what brand of car they owned, the responses would fall into categories like "Honda", "Toyota", and "Ford". In this case, the data is also categorical.
만약 사람들에게 소유하고 있는 차의 브랜드를 묻는다면 일부는 Honda, Toyota Ford 등 답변을 할 수 있고,, 이 경우 역시 높은 확률로 일부 업체에 편중되기도 하고 업체도 한정적이므로 caegorical로 볼 수 있다.

You will get an error if you try to plug these variables into most machine learning models in Python without preprocessing them first. In this tutorial, we'll compare three approaches that you can use to prepare your categorical data.
만약 이런 명목변수를 파이썬에 있는 머신러닝 라이브러리에 이대로 넣는다면 대부분의 경우 에러가 난다. 이번 튜토리얼에서는 이 자료를 어떻게 "전처리"하는지에 대해서 배우게 될 것이다.
#전처리 - 에러가 나지 않도록 사전에 처리하는 것. 앞서 배운 결측치 처리도 전처리 중 하나.

Three Approaches
3가지 접근방식이 있다.
1) Drop Categorical Variables
The easiest approach to dealing with categorical variables is to simply remove them from the dataset. This approach will only work well if the columns did not contain useful information.
1) 드랍

2) Ordinal Encoding
Ordinal encoding assigns each unique value to a different integer.
2) 순차적엔코딩(순차부여)
각 유니크 값에 각 정수interger 부여

This approach assumes an ordering of the categories: "Never" (0) < "Rarely" (1) < "Most days" (2) < "Every day" (3).
예를 들면, 앞서 아침 식사 빈도에 대한 질문에서
"Never" (0) < "Rarely" (1) < "Most days" (2) < "Every day" (3).

This assumption makes sense in this example, because there is an indisputable ranking to the categories. Not all categorical variables have a clear ordering in the values, but we refer to those that do as ordinal variables. For tree-based models (like decision trees and random forests), you can expect ordinal encoding to work well with ordinal variables
이러한 방법은 이 아침 식사 빈도 예제에 대해서는 말이되는 것 같다. 왜냐하면 각 정수를 랭킹으로 보더라도 순서가 뒤섞여 있다는 느낌은 아니다. 즉 숫자가 클수록 자주 먹는다고 봐도 상충되지 않는다는 것이다. 하지만 모든 명목변수가 이렇게 순차적인 변수부여가 가능한 것은 아니지만 이걸 지향하는게 좋다. 특히 트리 기반의 모델(DT나 RF)은 이런 순차적 변수부여가 잘 통한다.

3) One-Hot Encoding (원 핫 엔코딩)
One-hot encoding creates new columns indicating the presence (or absence) of each possible value in the original data. To understand this, we'll work through an example.
원 핫 엔코딩이란건 새로운 컬럼을 만든 다음 해당 컬럼의 특성값이 존재여부를 코딩하는 것으로 다음 예시를 참고.

In the original dataset, "Color" is a categorical variable with three categories: "Red", "Yellow", and "Green". The corresponding one-hot encoding contains one column for each possible value, and one row for each row in the original dataset. Wherever the original value was "Red", we put a 1 in the "Red" column; if the original value was "Yellow", we put a 1 in the "Yellow" column, and so on.

원 데이터셋에서 'color'는 명목변수로 다음과 같은 분류가 있다. 'Red', 'Yellow', 'Green'.
이걸 만약 원핫 엔코딩을 한다면 각 값에 대해 컬럼을 만든 뒤, Red 가 있으면 Red column에다가 1을 Yellow가 있으면 Yellow에다 1 ..이런방식으로 표현.



In contrast to ordinal encoding, one-hot encoding does not assume an ordering of the categories. Thus, you can expect this approach to work particularly well if there is no clear ordering in the categorical data (e.g., "Red" is neither more nor less than "Yellow"). We refer to categorical variables without an intrinsic ranking as nominal variables.
이것은 순차적 엔코딩과 달리 카테고리간에 어떤 순차적인 관계가 없다고 보는것.
따라서 실제 다루고 있는 명목데이터의 카테고리가 뚜렷한 순차성이 보이지 않는다면 (예를 들어 'Yellow', 'Green', 'Red' 사이에는 어떠한 순차성이 없다.)


One-hot encoding generally does not perform well if the categorical variable takes on a large number of values (i.e., you generally won't use it for variables taking more than 15 different values).
원 핫 엔코딩은 일반적으로 명목변수의 종류가 너무 많으면 퍼포먼스가 떨어진다. (일반적으로 명목변수의  카테고리 숫자가 15 미만일 때 사용.)


예시
(이하생략)

관련글 더보기