开始使用免费开始使用

对分类列进行编码 I:LabelEncoder

既然您已经了解了为 XGBoost 准备住房数据需要做什么,接下来我们一步一步完成整个流程。

首先,需要填补缺失值——正如之前看到的,LotFrontage 列存在大量缺失。然后,您需要对数据集中的所有分类列进行独热编码,使其转为数值形式。若需回顾这一概念,您可以观看 这段视频,来自课程 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())
编辑并运行代码