범주형 열 인코딩 I: LabelEncoder
이제 XGBoost에 사용할 주택 데이터를 어떻게 준비해야 하는지 살펴보셨으니, 단계별로 진행해 보겠습니다.
먼저 결측값을 채워야 합니다. 앞에서 보셨듯 LotFrontage 열에는 결측값이 많이 있습니다. 다음으로, 데이터셋의 모든 범주형 열을 원-핫 인코딩 같은 방법으로 숫자형으로 변환해야 합니다. 아이디어가 필요하시면 Supervised Learning with scikit-learn의 이 영상을 참고하세요.
이 데이터에는 MSZoning, PavedDrive, Neighborhood, BldgType, HouseStyle 다섯 개의 범주형 열이 있습니다. Scikit-learn에는 각 범주형 열의 값을 정수로 변환하는 LabelEncoder 함수가 있습니다. 여기서는 이를 연습해 보겠습니다.
이 연습은 강의의 일부입니다
XGBoost로 익히는 Extreme Gradient Boosting
연습 안내
sklearn.preprocessing에서LabelEncoder를 임포트하세요..fillna()를 사용해LotFrontage열의 결측값을0으로 채우세요.- 범주형 열에 대한 불리언 마스크를 만드세요.
df.dtypes가object인지 확인하면 됩니다. LabelEncoder객체를 생성하세요. 다른 scikit-learn 추정기와 동일한 방식으로 인스턴스화하면 됩니다.- 제공된 람다 함수에서
le의.fit_transform()메서드를 사용해 모든 범주형 열을 정수로 인코딩하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import LabelEncoder
____
# Fill missing values with 0
df.LotFrontage = ____
# Create a boolean mask for categorical columns
categorical_mask = (____ == ____)
# Get list of categorical column names
categorical_columns = df.columns[categorical_mask].tolist()
# Print the head of the categorical columns
print(df[categorical_columns].head())
# Create LabelEncoder object: le
le = ____
# Apply LabelEncoder to categorical columns
df[categorical_columns] = df[categorical_columns].apply(lambda x: ____(x))
# Print the head of the LabelEncoded categorical columns
print(df[categorical_columns].head())