我是机器学习新手。我有一个疑问:为什么使用 toarray()
进行一种热编码,而不使用标签编码。我不明白。请有人帮忙。
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
label_encoder_x = LabelEncoder()
x[:, 0] = label_encoder_x.fit_transform(x[:, 0])
onehotencoder = OneHotEncoder(categorical_features= [0])
x = onehotencoder.fit_transform(x).toarray()
label_encoder_y = LabelEncoder()
y = label_encoder_y.fit_transform(y)
最佳答案
如 docs 中所述,OneHotEncoder
默认情况下会返回一个稀疏矩阵,这使用起来不太直观。作为一个最小的例子:
>>> df
0
0 2
1 2
2 2
3 1
4 1
5 2
6 2
7 1
8 1
9 1
onehotencoder = OneHotEncoder(categorical_features= [0])
>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1))
<1x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in COOrdinate format>
但是,如果您调用 toarray
,您会得到更容易使用的东西,或者至少更容易理解:
>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1)).toarray()
array([[1., 2., 2., 1., 1., 2., 2., 1., 1., 1.]])
另一种方法是在创建 OneHotEncoder 时使用 sparse = False
,然后它默认创建一个密集数组:
onehotencoder = OneHotEncoder(categorical_features= [0], sparse=False)
>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1))
array([[1., 2., 2., 1., 1., 2., 2., 1., 1., 1.]])
关于python - 在数据预处理期间使用 toarray() 和 onehotencoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52846604/