타겟 인코딩
타겟 인코딩(Target Encoding)은 범주형 데이터의 인코딩 방법 중(One-Hot Encoding, Ordinal Encoding, ..) 하나로 범주형 자료의 값들을 트레이닝 데이터에서 "타겟"에 해당하는 변수로 바꿔주는 방식이다.
1. Target Encoding
가장 간단한 타겟 인코딩을 적용하는 방식은 평균을 이용한 방식이다.
autos['make_encoded'] = autos.groupby('make')['price'].transform('mean')
위와 같은 타겟 인코딩은 평균 인코딩이라고 불린다.
2. Smoothing
평균 인코딩과 같은 방식은 첫번째로 새로운 범주와 드문 범주에 대해 문제가 발생하게 된다.
위의 문제에 대해서 평활화를 이용하면 문제를 해결할 수 있다. 평활화란 전체 평균과 범주에 대한 평균을 섞는 개념이다. 드문 범주의 경우 범주 평균에 대해서 적은 가중치를 갖게 되고, 새로운 범주는 전체 평균을 적용하게 된다.
$$ Encoding = weight \times in_category + (1- weight) \times overall $$
가중치는 0과 1의 값을 갖게 되는데 m-estimate를 계산하여 가중치를 계산해준다.
$$ weight = \frac{n}{n+m} $$
n은 범주가 데이터셋에서 얼마나 발생했는지를 나타내고 m은 평활와 인수로 m이 크면 클수록 전체 평균에 대한 가중치를 증가 시킨다.
- 타겟 인코딩을 사용하는 법
- 범주의 수가 매우 많은 범주형 변수
- feature metric에서 약한 상관관계를 갖는 범주형 변수
# Split datasets
X = df.copy()
y = X.pop('Rating')
X_encode = X.sample(frac=0.25)
y_encode = y[X_encode.index]
X_pretrain = X.drop(X_encode.index)
y_train = y[X_pretrain.index]
from category_encoders import MEstimateEncoder
# Create the encoder instance. Choose m to control noise.
encoder = MEstimateEncoder(cols=["Zipcode"], m=5.0)
# Fit the encoder on the encoding split.
encoder.fit(X_encode, y_encode)
# Encode the Zipcode column to create the final training data
X_train = encoder.transform(X_pretrain)
Sourec of the course : Kaggle Course _ Target Encoding
Target Encoding
Explore and run machine learning code with Kaggle Notebooks | Using data from FE Course Data
www.kaggle.com
'Course > [Kaggle] Data Science' 카테고리의 다른 글
[SQL] Select, From & Where (0) | 2022.02.23 |
---|---|
[SQL] Getting Started with SQL and BigQuery (0) | 2022.02.23 |
[FE] Principal Component Analysis (0) | 2022.02.21 |
[FE] Clustering with K-means (0) | 2022.02.21 |
[FE] Creating Features (0) | 2022.02.21 |