開始使用免費開始

類別欄位編碼 I:LabelEncoder

既然你已經了解要如何準備房價資料以供 XGBoost 使用,現在就一步一步完成整個流程。

首先要補齊遺漏值——如同先前所見,LotFrontage 欄位有許多遺漏值。接著,你需要對資料集中的任何類別欄位做 one-hot 編碼,讓它們以數值方式表示。你可以觀看 這支影片(課程:Supervised Learning with scikit-learn)來複習這個概念。

這份資料有 5 個類別欄位:MSZoningPavedDriveNeighborhoodBldgTypeHouseStyle。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())
編輯並執行程式碼