onehotencoder 的 sklearn 掩码不起作用

sklearn mask for onehotencoder does not work

考虑如下数据:

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'

它在 documentation 中说:

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)

同样的错误。

还有 "array of indices" 的情况:

ohe = OneHotEncoder(categorical_features=np.array([1, 2]), dtype=dt)        
ohe.fit(d)

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

The input to this transformer should be a matrix of integers, denoting the values taken on by categorical (discrete) features.

因此在下面的示例中,我将 aaa 更改为 5,将 bbb 更改为 6。这样它将与 12 数值区分开来:

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)

您应该明白,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)

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

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

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

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

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