가. One Hot Encoding은 머신러닝 알고리즘에서 더 나은 예측을 위해 제공되는 하나의 과정입니다. 나. One-Hot Encoding은 범주형 변수를 바이너리벡터(0,1)로 표현한 것. 다. Label Encoding이 범주형 구분을 숫자로 변경하는 것이라면, OneHotEncoding은 KR => ( 1 , 0, 0, 0 ) US => ( 0, 1, 0, 0 ) UK => ( 0, 0, 1, 0 ) CN => ( 0 , 0, 0, 1 ) 로 벡터의 요소로 변경하는 것이다.
from IPython.display import display, Image
display(Image(filename='img/onehotencoding.png'))
(가) 범주형 값에 의해 가장 가치 있는 모델은 값이 높은 값이 가치있다고 생각합니다. VW > Acura > Honda이다. - 이 내용은 오류가 발생합니다. 이 값을 가지고 모델을 예측한다는 것은 많은 오류가 있다. (나) 하지만 순서가 없을 경우, 문제가 될 수 있습니다. - (dog, cat, bird..) (다) 이 경우, 표현력이 있는 one-hot encoding를 이용하면 더 정밀한 예측이 가능해 질 수 있다.
### 01. 데이터 준비
import pandas as pd
data = { "eng": ["b", "c", "a", "d"] }
df = pd.DataFrame(data)
print(type(df))
df
<class 'pandas.core.frame.DataFrame'>
eng | |
---|---|
0 | b |
1 | c |
2 | a |
3 | d |
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
en_x = LabelEncoder()
df['라벨인코딩'] = en_x.fit_transform(df['eng'])
df
eng | 라벨인코딩 | |
---|---|---|
0 | b | 1 |
1 | c | 2 |
2 | a | 0 |
3 | d | 3 |
df['라벨인코딩'].values
array([1, 2, 0, 3])
onehot = OneHotEncoder()
val = df['라벨인코딩'].values.reshape(-1,1) # OneHotEncoder()를 사용을 위한 적합한 값으로 변경.
y = onehot.fit_transform( val ).toarray() # 값을 변경후, 배열로 만들어준다.
y
array([[0., 1., 0., 0.], [0., 0., 1., 0.], [1., 0., 0., 0.], [0., 0., 0., 1.]])
onehot_val = pd.DataFrame(y, dtype=int)
onehot_val
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0 | 1 | 0 | 0 |
1 | 0 | 0 | 1 | 0 |
2 | 1 | 0 | 0 | 0 |
3 | 0 | 0 | 0 | 1 |
df_new = pd.concat([df, onehot_val], axis=1)
df_new
eng | 라벨인코딩 | 0 | 1 | 2 | 3 | |
---|---|---|---|---|---|---|
0 | b | 1 | 0 | 1 | 0 | 0 |
1 | c | 2 | 0 | 0 | 1 | 0 |
2 | a | 0 | 1 | 0 | 0 | 0 |
3 | d | 3 | 0 | 0 | 0 | 1 |
data = { "회사명": ["MS","Apple", "Google", "Google"]}
df1 = pd.DataFrame(data)
df2 = df1.copy()
df2
회사명 | |
---|---|
0 | MS |
1 | Apple |
2 | |
3 |
### OneHotEncoding
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
df1['회사명']
0 MS 1 Apple 2 Google 3 Google Name: 회사명, dtype: object
### LabelEncoder
encoder_x = LabelEncoder()
df1['lbl_en'] = encoder_x.fit_transform(df1['회사명']) #
df1
회사명 | lbl_en | |
---|---|---|
0 | MS | 2 |
1 | Apple | 0 |
2 | 1 | |
3 | 1 |
df1['lbl_en'].values
array([2, 0, 1, 1])
onehot = OneHotEncoder()
y = onehot.fit_transform(df1['lbl_en'].values.reshape(-1,1) ).toarray()
print(y)
[[0. 0. 1.] [1. 0. 0.] [0. 1. 0.] [0. 1. 0.]]
# 변경된 값을 DataFrame형태로 변경
dx = pd.DataFrame(y, dtype=int)
dx
0 | 1 | 2 | |
---|---|---|---|
0 | 0 | 0 | 1 |
1 | 1 | 0 | 0 |
2 | 0 | 1 | 0 |
3 | 0 | 1 | 0 |
df1_new = pd.concat([df1, dx], axis=1)
df1_new
회사명 | lbl_en | 0 | 1 | 2 | |
---|---|---|---|---|---|
0 | MS | 2 | 0 | 0 | 1 |
1 | Apple | 0 | 1 | 0 | 0 |
2 | 1 | 0 | 1 | 0 | |
3 | 1 | 0 | 1 | 0 |
from tensorflow.keras.utils import to_categorical
import numpy as np
# define example
data = [15,17,5,10,0]
dat = np.array(data)
print(dat)
# one hot encode
encoded = to_categorical(dat)
print(encoded)
[15 17 5 10 0] [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
# invert encoding
inverted = np.argmax(encoded[1])
print(inverted)
17
집을 선택할 때, 다음과 같은 유형의 조건이 있다. Inside, Corner, FR2, CulDSac 이에 대한 정보를 레이블 인코딩, OneHotEncoding를 해보자.
import pandas as pd
import os
demo_df = pd.DataFrame({"범주형_feature":['양말', '여우', '양말', '상자']})
display(demo_df)
범주형_feature | |
---|---|
0 | 양말 |
1 | 여우 |
2 | 양말 |
3 | 상자 |
onehot = pd.get_dummies(demo_df)
onehot
범주형_feature_상자 | 범주형_feature_양말 | 범주형_feature_여우 | |
---|---|---|---|
0 | 0 | 1 | 0 |
1 | 0 | 0 | 1 |
2 | 0 | 1 | 0 |
3 | 1 | 0 | 0 |
df = pd.concat([demo_df, onehot], axis=1)
df
범주형_feature | 범주형_feature_상자 | 범주형_feature_양말 | 범주형_feature_여우 | |
---|---|---|---|---|
0 | 양말 | 0 | 1 | 0 |
1 | 여우 | 0 | 0 | 1 |
2 | 양말 | 0 | 1 | 0 |
3 | 상자 | 1 | 0 | 0 |