考虑以下数据:
from sklearn.preprocessing import OneHotEncoder
import numpy as np
dt = 'object, i4, i4'
d = np.array([('aaa', 1, 1), ('bbb', 2, 2)], dtype=dt)
我想使用OHE功能排除文本列。
为什么下面的不起作用?
ohe = OneHotEncoder(categorical_features=np.array([False,True,True], dtype=bool))
ohe.fit(d)
ValueError: could not convert string to float: 'bbb'
上面写着:
categorical_features: “all” or array of indices or mask :
Specify what features are treated as categorical.
‘all’ (default): All features are treated as categorical.
array of indices: Array of categorical feature indices.
mask: Array of length n_features and with dtype=bool.
我正在使用一个掩码,但它仍然试图转换为float。
甚至使用
ohe = OneHotEncoder(categorical_features=np.array([False,True,True], dtype=bool),
dtype=dt)
ohe.fit(d)
同样的错误。
在“索引数组”的情况下:
ohe = OneHotEncoder(categorical_features=np.array([1, 2]), dtype=dt)
ohe.fit(d)
我想这里有些混乱。您仍然需要输入数值,但是在encoder中,您可以指定哪些值是分类的,哪些不是。
所以在下面的例子中,我将
aaa
更改为5
,将bbb
更改为6
。这样它将区别于1
和2
数值:现在您可以检查功能类别:
您应该知道,Scikit Learn中的所有估计器都是为数值输入而设计的。因此,从这个角度来看,在这个表单中保留文本列是没有意义的。您必须将该文本列转换为数字形式,或者将其删除。
如果您从Pandas DataFrame获得了数据集,那么可以看看这个小包装:https://github.com/paulgb/sklearn-pandas。它将帮助您同时转换所有需要的列(或以数字形式保留一些行)
我也遇到过同样的行为,觉得很沮丧。正如其他人指出的,Scikit Learn在考虑选择
categorical_features
参数中提供的列之前,要求所有数据都是数值型的。具体来说,列选择由^{} 中的
_transform_selected()
方法处理,该方法的第一行是X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
。如果所提供数据帧
X
中的任何数据都无法成功转换为浮点,则此检查将失败。我同意^{} 的文件在这方面具有误导性。
相关问题 更多 >
编程相关推荐