开始使用免费开始使用

分类列编码 II:OneHotEncoder

好的——现在您的分类列已经被数值化编码。可以直接进入使用管道和 XGBoost 了吗?还不行!在本数据集的分类列中,各个取值之间没有自然的大小顺序。举个例子:使用 LabelEncoder 时,Neighborhood 中的 CollgCr 被编码为 5Veenker 被编码为 24,而 Crawfor6。那么,Veenker 是否"比" CrawforCollgCr 更大?并不是——如果让模型误以为存在这种自然顺序,可能会导致性能不佳。

因此,还需要再做一步:需要进行独热编码(one-hot encoding),把分类取值转换为二元的"哑变量"。您可以使用 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)
编辑并运行代码