반응형
📌 Label Encoding
: 범주형 변수를 0부터 N-1까지의 숫자로 변환합니다.
문제점 : 예를 들어, 변수 간의 관계가 없는 경우, 인코딩 된 숫자가 변수 간의 관계를 표현하며, 모델이 이러한 쓸모없는 관계를 이해하려고 시도할 수 있습니다. 그리고 변수의 값이 크거나 작은 경우, 변수의 중요도가 부작용을 일으킬 수 있습니다.
예제 코드:
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
encoded_labels = le.fit_transform(['good', 'good', 'bad', 'average'])
📌 One-hot Encoding
범주형 변수를 이진 벡터로 변환합니다. 이진 벡터는 한 가지 확실한 답을 가지며, 모델이 이러한 벡터의 의미를 이해하기 쉬우므로 일반적으로 Label Encoding보다 더 좋은 선택입니다.
예제코드:
import pandas as pd
df = pd.DataFrame({'label': ['good', 'good', 'bad', 'average']})
one_hot_df = pd.get_dummies(df)
"df" dataframe의 지정 컬럼 'a', 'b', 'c'을 원핫인코딩 :
pd.get_dummies(data=df, columns=['a', 'b', 'c'], drop_first=True)
data : 배열 유사, Series 또는 DataFrame
더미 지표를 얻을 데이터
drop_first 부울, 기본값 False
첫 번째 수준을 제거하여 k 범주 수준에서 k-1 더미를 가져올지 여부
모델링할 때 Numpy 배열에는 to_categorical을 사용할 수 있습니다.
from tensorflow.keras.utils import to_categorical
class_n = len(np.unique(y_train))
y_train = to_categorical(y_train, class_n)
y_test = to_categorical(y_test, class_n)
반응형
'AI > Preprocessing' 카테고리의 다른 글
데이터 정규분포화, 표준화 (0) | 2023.04.11 |
---|---|
text preprecessing_numpy.argmax() (0) | 2023.04.03 |
이미지들을 배열 데이터셋으로 만들기 (0) | 2023.03.22 |
python_폴더(파일) 복사하기 (copytree, copy_tree) (0) | 2023.03.20 |
python_폴더(파일)명 변경하기 (os.rename) (0) | 2023.03.20 |