分类列编码 II:OneHotEncoder
好的——现在您的分类列已经被数值化编码。可以直接进入使用管道和 XGBoost 了吗?还不行!在本数据集的分类列中,各个取值之间没有自然的大小顺序。举个例子:使用 LabelEncoder 时,Neighborhood 中的 CollgCr 被编码为 5,Veenker 被编码为 24,而 Crawfor 为 6。那么,Veenker 是否"比" Crawfor 和 CollgCr 更大?并不是——如果让模型误以为存在这种自然顺序,可能会导致性能不佳。
因此,还需要再做一步:需要进行独热编码(one-hot encoding),把分类取值转换为二元的"哑变量"。您可以使用 scikit-learn 的 OneHotEncoder 来完成这一点。
本练习是课程的一部分
使用 XGBoost 的极端梯度提升
练习说明
- 从
sklearn.preprocessing导入OneHotEncoder。 - 实例化一个名为
ohe的OneHotEncoder对象,并将关键字参数sparse=False。 - 使用其
.fit_transform()方法,将OneHotEncoder应用于df,并将结果保存为df_encoded。输出将是一个 NumPy 数组。 - 打印
df_encoded的前 5 行,然后分别打印df和df_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)