類別欄位編碼 I:LabelEncoder
既然你已經了解要如何準備房價資料以供 XGBoost 使用,現在就一步一步完成整個流程。
首先要補齊遺漏值——如同先前所見,LotFrontage 欄位有許多遺漏值。接著,你需要對資料集中的任何類別欄位做 one-hot 編碼,讓它們以數值方式表示。你可以觀看 這支影片(課程:Supervised Learning with scikit-learn)來複習這個概念。
這份資料有 5 個類別欄位:MSZoning、PavedDrive、Neighborhood、BldgType 與 HouseStyle。Scikit-learn 提供了 LabelEncoder 函式,可以把每個類別欄位中的值轉成整數。你將在這裡練習使用它。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 從
sklearn.preprocessing匯入LabelEncoder。 - 使用
.fillna()將LotFrontage欄位中的遺漏值填成0。 - 建立類別欄位的布林遮罩。你可以檢查
df.dtypes是否等於object來達成。 - 建立一個
LabelEncoder物件。作法就和你實例化任何 scikit-learn 估計器一樣。 - 使用
LabelEncoder()將所有類別欄位編碼成整數。為此,請在提供的 lambda 函式中使用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())