시작하기무료로 시작하기

범주형 열 인코딩 II: OneHotEncoder

좋아요. 이제 범주형 열을 숫자로 인코딩했네요. 바로 파이프라인과 XGBoost로 넘어가면 될까요? 아직은요! 이 데이터셋의 범주형 열에는 항목 간에 자연스러운 순서가 없습니다. 예를 들어, LabelEncoder를 사용하면 NeighborhoodCollgCr5, Veenker24, Crawfor6으로 인코딩됩니다. 그렇다면 VeenkerCrawforCollgCr보다 "더 크다"고 볼 수 있을까요? 그렇지 않습니다. 모델이 이런 자연스러운 순서를 가정하도록 두면 성능이 저하될 수 있어요.

따라서 한 단계가 더 필요합니다. 이진(또는 "더미") 변수를 만들기 위해 원-핫 인코딩을 적용해야 합니다. 이는 scikit-learn의 OneHotEncoder로 수행할 수 있습니다.

이 연습은 강의의 일부입니다

XGBoost로 익히는 Extreme Gradient Boosting

강의 보기

연습 안내

  • sklearn.preprocessing에서 OneHotEncoder를 임포트하세요.
  • ohe라는 이름의 OneHotEncoder 객체를 인스턴스화하세요. 키워드 인수로 sparse=False를 지정하세요.
  • .fit_transform() 메서드를 사용해 OneHotEncoderdf에 적용하고 결과를 df_encoded로 저장하세요. 출력은 NumPy 배열입니다.
  • df_encoded의 처음 5개 행을 출력하고, 이어서 dfdf_encoded의 shape을 출력해 차이를 비교하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Import OneHotEncoder
____

# Create OneHotEncoder: ohe
ohe = ____

# Apply OneHotEncoder to categorical columns - output is no longer a dataframe: df_encoded
df_encoded = ____

# Print first 5 rows of the resulting dataset - again, this will no longer be a pandas dataframe
print(df_encoded[:5, :])

# Print the shape of the original DataFrame
print(df.shape)

# Print the shape of the transformed array
print(df_encoded.shape)
코드 편집 및 실행