開始使用免費開始

類別欄位編碼 II:OneHotEncoder

好了——你已經把類別欄位轉成數值了。現在可以直接用 pipeline 搭配 XGBoost 了嗎?還不行!在這個資料集的類別欄位中,各個值之間沒有自然的順序。例如:用 LabelEncoder 後,NeighborhoodCollgCr 被編成 5Veenker 被編成 24Crawfor 則是 6。難道 Veenker 就「大於」CrawforCollgCr 嗎?當然不是——讓模型誤以為存在這種自然順序,可能會導致效能變差。

因此還需要另一個步驟:你必須套用 one-hot 編碼,產生二元(或稱「虛擬」)變數。你可以使用 scikit-learn 的 OneHotEncoder 來完成。

本練習屬於課程

使用 XGBoost 的極端梯度提升

檢視課程

練習說明

  • sklearn.preprocessing 匯入 OneHotEncoder
  • 建立名為 oheOneHotEncoder 物件,並指定參數 sparse=False
  • 使用其 .fit_transform() 方法,將 OneHotEncoder 套用到 df,並將結果儲存為 df_encoded。輸出會是 NumPy 陣列。
  • 印出 df_encoded 的前 5 列,接著分別印出 dfdf_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)
編輯並執行程式碼