類別欄位編碼 II:OneHotEncoder
好了——你已經把類別欄位轉成數值了。現在可以直接用 pipeline 搭配 XGBoost 了嗎?還不行!在這個資料集的類別欄位中,各個值之間沒有自然的順序。例如:用 LabelEncoder 後,Neighborhood 的 CollgCr 被編成 5,Veenker 被編成 24,Crawfor 則是 6。難道 Veenker 就「大於」Crawfor 和 CollgCr 嗎?當然不是——讓模型誤以為存在這種自然順序,可能會導致效能變差。
因此還需要另一個步驟:你必須套用 one-hot 編碼,產生二元(或稱「虛擬」)變數。你可以使用 scikit-learn 的 OneHotEncoder 來完成。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 從
sklearn.preprocessing匯入OneHotEncoder。 - 建立名為
ohe的OneHotEncoder物件,並指定參數sparse=False。 - 使用其
.fit_transform()方法,將OneHotEncoder套用到df,並將結果儲存為df_encoded。輸出會是 NumPy 陣列。 - 印出
df_encoded的前 5 列,接著分別印出df與df_encoded的形狀以比較差異。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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)