5

考虑以下数据:

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.

我正在使用面具,但它仍然试图转换为浮动。

即使使用

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)
4

3 回答 3

2

你应该明白,Scikit-Learn 中的所有估计器都是为数字输入而设计的。因此,从这个角度来看,以这种形式留下文本列是没有意义的。您必须将该文本列转换为数字形式,或者摆脱它。

如果您从 Pandas DataFrame 获得数据集 - 您可以查看这个小包装器:https ://github.com/paulgb/sklearn-pandas 。它将帮助您同时转换所有需要的列(或以数字形式保留一些行)

import pandas as pd
import numpy as np
from sklearn_pandas import DataFrameMapper
from sklearn.preprocessing import OneHotEncoder

data = pd.DataFrame({'text':['aaa', 'bbb'], 'number_1':[1, 1], 'number_2':[2, 2]})

#    number_1  number_2 text
# 0         1         2  aaa
# 1         1         2  bbb

# SomeEncoder here must be any encoder which will help you to get
# numerical representation from text column
mapper = DataFrameMapper([
    ('text', SomeEncoder),
    (['number_1', 'number_2'], OneHotEncoder())
])
mapper.fit_transform(data)
于 2015-12-10T13:09:22.090 回答
2

我认为这里有些混乱。您仍然需要输入数值,但在编码器中您可以指定哪些值是分类值,哪些不是。

这个转换器的输入应该是一个整数矩阵,表示分类(离散)特征所采用的值。

因此,在下面的示例中,我更改aaa5和。这样,它将与数值和数值区分开来:bbb612

d = np.array([[5, 1, 1], [6, 2, 2]])
ohe = OneHotEncoder(categorical_features=np.array([True,False,False], dtype=bool))
ohe.fit(d)

现在您可以检查您的功能类别:

ohe.active_features_
Out[22]: array([5, 6], dtype=int64)
于 2015-12-04T14:58:21.067 回答
1

我遇到了同样的行为,发现它令人沮丧。正如其他人指出的那样,Scikit-Learn甚至在考虑选择参数中提供的列之前都要求所有categorical_features数据都是数字的。

具体来说,列选择由 in 方法处理,该_transform_selected()方法/sklearn/preprocessing/data.py的第一行是

X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES).

如果提供的数据框中的任何数据X无法成功转换为浮点数,则此检查失败。

我同意 的文档sklearn.preprocessing.OneHotEncoder在这方面具有误导性。

于 2018-02-14T23:54:53.557 回答