類別欄位編碼 III:DictVectorizer
在進入 pipelines 之前,先來看最後一招。你剛剛用的兩步驟流程——先用 LabelEncoder,再用 OneHotEncoder——其實可以用 DictVectorizer 來簡化。
把 DataFrame 轉成字典之後,對它使用 DictVectorizer,就能一次完成標籤編碼與獨熱編碼。
這個練習就要帶你實作這個方法!
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 從
sklearn.feature_extraction匯入DictVectorizer。 - 使用
.to_dict()方法搭配引數"records",把df轉成名為df_dict的字典。 - 建立一個
DictVectorizer物件,命名為dv,並設定關鍵字引數sparse=False。 - 對
df_dict使用DictVectorizer的.fit_transform()方法。 - 按下「送出答案」來列印結果的前 5 列與字彙表(vocabulary)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import DictVectorizer
____
# Convert df into a dictionary: df_dict
df_dict = ____
# Create the DictVectorizer object: dv
dv = ____
# Apply dv on df: df_encoded
df_encoded = ____
# Print the resulting first five rows
print(df_encoded[:5,:])
# Print the vocabulary
print(dv.vocabulary_)