Scikit-learn의 sklearn.preprocessing
모듈은 데이터 전처리를 위한 다양한 도구들을 제공합니다.
여러 Encoder들 중 몇 가지를 살펴보겠습니다.
LabelEncoder
는 주로 목표 변수(라벨, 클래스 등)를 숫자로 변환하는 데 사용됩니다.
예를 들어, 'cat', 'dog', 'bird'와 같은 문자열 라벨을 0, 1, 2와 같은 숫자로 매핑합니다.
pythonCopy code
from sklearn.preprocessing import LabelEncoder
# 예제 데이터
labels = ['cat', 'dog', 'bird', 'cat']
# LabelEncoder 객체 생성 및 학습
label_encoder = LabelEncoder()
encoded_labels = label_encoder.fit_transform(labels)
# 변환된 결과 출력
print(encoded_labels)
# 출력: array([0, 1, 2, 0])
OneHotEncoder
는 범주형 변수를 이진(0 또는 1) 형태로 인코딩합니다.
주로 범주형 변수의 각 카테고리를 새로운 이진 열로 만들어줍니다.
유의할 점
판다스의 시리즈가 아닌 numpy 행렬을 입력해야함 → values 이용
벡터 입력을 허용하지 않음 → reshape을 이용해 Matrix로 변환 필요
sparse=True가 디폴트이며 이는 Matrix를 반환한다.
원핫인코딩에서 필요한 것은 array이므로 sparse 옵션에 False를 넣어준다.
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
# 예제 데이터
data = [['cat'], ['dog'], ['bird'], ['cat']]
# OneHotEncoder 객체 생성 및 학습
onehot_encoder = OneHotEncoder()
onehot_encoded = onehot_encoder.fit_transform(data).toarray()
# 결과를 DataFrame으로 변환
df_onehot = pd.DataFrame(onehot_encoded, columns=onehot_encoder.get_feature_names_out(['animal']))
# 변환된 결과 출력
print(df_onehot)
# 출력:
# animal_cat animal_dog animal_bird
# 0 1.0 0.0 0.0
# 1 0.0 1.0 0.0
# 2 0.0 0.0 1.0
# 3 1.0 0.0 0.0
get_feature_names_out
메서드는 열 이름을 얻기 위해 사용됩니다.
ColumnTransformer
는 여러 열 변환기를 동시에 사용하여 데이터 프레임의 여러 열에 대한 전처리를 할 수 있습니다.
예를 들어, LabelEncoder
와 OneHotEncoder
를 함께 사용할 수 있습니다.
pythonCopy code
from sklearn.compose import ColumnTransformer
# 예제 데이터
data = pd.DataFrame({'animal': ['cat', 'dog', 'bird', 'cat'], 'color': ['red', 'blue', 'green', 'red']})
# ColumnTransformer 정의
preprocessor = ColumnTransformer(
transformers=[
('animal', LabelEncoder(), ['animal']),
('color', OneHotEncoder(), ['color'])
])
# 변환된 결과 출력
transformed_data = preprocessor.fit_transform(data)
print(transformed_data)
이런 방식으로, ColumnTransformer
를 사용하여 각 열에 대해 다른 전처리 단계를 적용할 수 있습니다.