如何在Sklearn中执行OneHotEncoding,获取值错误

时间:2017-12-13 10:33:33

标签: python scikit-learn preprocessor sklearn-pandas one-hot-encoding

我刚开始学习机器学习,在练习其中一项任务时,我收到了价值错误,但我按照与教练相同的步骤进行了。

我收到了价值错误,请帮忙。

DFF

     Country    Name
 0     AUS      Sri
 1     USA      Vignesh
 2     IND      Pechi
 3     USA      Raj

首先我执行了labelencoding,

X=dff.values
label_encoder=LabelEncoder()
X[:,0]=label_encoder.fit_transform(X[:,0])

out:
X
array([[0, 'Sri'],
       [2, 'Vignesh'],
       [1, 'Pechi'],
       [2, 'Raj']], dtype=object)

然后对同一个X

执行一次热编码
onehotencoder=OneHotEncoder( categorical_features=[0])
X=onehotencoder.fit_transform(X).toarray()

我收到以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-472-be8c3472db63> in <module>()
----> 1 X=onehotencoder.fit_transform(X).toarray()

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in fit_transform(self, X, y)
   1900         """
   1901         return _transform_selected(X, self._fit_transform,
-> 1902                                    self.categorical_features, copy=True)
   1903 
   1904     def _transform(self, X):

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in _transform_selected(X, transform, selected, copy)
   1695     X : array or sparse matrix, shape=(n_samples, n_features_new)
   1696     """
-> 1697     X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
   1698 
   1699     if isinstance(selected, six.string_types) and selected == "all":

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    380                                       force_all_finite)
    381     else:
--> 382         array = np.array(array, dtype=dtype, order=order, copy=copy)
    383 
    384         if ensure_2d:

ValueError: could not convert string to float: 'Raj'

请编辑我的问题有什么不对,提前谢谢!

4 个答案:

答案 0 :(得分:3)

如果您想对多个分类功能进行编码,另一种方法是使用带有FeatureUnion的管道和一些自定义变换器。

首先需要两个变换器 - 一个用于选择单个列,另一个用于使LabelEncoder在管道中可用(fit_transform方法只需要X,它需要在管道中使用可选的y)。

from sklearn.base import BaseEstimator, TransformerMixin

class SingleColumnSelector(TransformerMixin, BaseEstimator):
    def __init__(self, column):
        self.column = column

    def transform(self, X, y=None):
        return X[:, self.column].reshape(-1, 1)

    def fit(self, X, y=None):
        return self

class PipelineAwareLabelEncoder(TransformerMixin, BaseEstimator):
    def fit(self, X, y=None):
        return self

    def transform(self, X, y=None):
        return LabelEncoder().fit_transform(X).reshape(-1, 1)

接下来创建一个具有2个分支的管道(或者只是一个FeatureUnion) - 每个分支对应一个分支。在每个选择1列中,对标签进行编码,然后对一个热编码进行编码。

import pandas as pd
import numpy as np

from sklearn.preprocessing import LabelEncoder, OneHotEncoder, FunctionTransformer
from sklearn.pipeline import Pipeline, make_pipeline, FeatureUnion

pipeline = Pipeline([(
    'encoded_features',
    FeatureUnion([('countries',
        make_pipeline(
            SingleColumnSelector(0),
            PipelineAwareLabelEncoder(),
            OneHotEncoder()
        )), 
        ('names', make_pipeline(
            SingleColumnSelector(1),
            PipelineAwareLabelEncoder(),
            OneHotEncoder()
        ))
    ]))
])

最后通过管道运行完整的数据帧 - 它将分别对每个列进行热编码并在最后连接。

df = pd.DataFrame([["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]], columns=['Country', 'Name'])
X = df.values
transformed_X = pipeline.fit_transform(X)
print(transformed_X.toarray())

返回(前三列是国家,第二列是名称)

[[ 1.  0.  0.  0.  0.  1.  0.]
 [ 0.  0.  1.  0.  0.  0.  1.]
 [ 0.  1.  0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  1.  0.  0.]]

答案 1 :(得分:2)

以下实施应该运作良好。注意onehotencoder的输入 fit_transform不能是1-rank数组,输出也是稀疏的,我们使用to_array()来扩展它。

import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

data= [["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]]


df = pd.DataFrame(data, columns=['Country', 'Name'])
X = df.values

le = LabelEncoder()
X_num = le.fit_transform(X[:,0]).reshape(-1,1)

ohe = OneHotEncoder()
X_num = ohe.fit_transform(X_num)

print (X_num.toarray())

X[:,0] = X_num

print (X)

答案 2 :(得分:2)

您现在可以使用直接 转到 OneHotEncoding > LabelEncoder ,并且当我们朝0.22版迈进时,许多人可能希望通过这种方式来避免警告和潜在的错误(请参见DOCSEXAMPLES )。


示例代码1,其中对所有列进行了编码,并且明确指定了类别:

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

data= [["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]]

df = pd.DataFrame(data, columns=['Country', 'Name'])
X = df.values

countries = np.unique(X[:,0])
names = np.unique(X[:,1])

ohe = OneHotEncoder(categories=[countries, names])
X = ohe.fit_transform(X).toarray()

print (X)

代码示例1的输出:

[[1. 0. 0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0. 0. 1.]
 [0. 1. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 1. 0. 0.]]

示例代码2显示了用于指定类别的“自动”选项:

前3列对国家/地区名称进行编码,后四列对个人名称进行编码。

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

data= [["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]]

df = pd.DataFrame(data, columns=['Country', 'Name'])
X = df.values

ohe = OneHotEncoder(categories='auto')
X = ohe.fit_transform(X).toarray()

print (X)

代码示例2的输出(与1相同):

[[1. 0. 0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0. 0. 1.]
 [0. 1. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 1. 0. 0.]]

示例代码3,其中只有第一列是经过热编码的:

现在,这是独特的部分。如果您只需要对数据的特定列进行“热编码”怎么办?

注意:,为了便于说明,我将最后一列留为字符串。实际上,当最后一列已经是数字时,这样做更有意义)。

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

data= [["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]]

df = pd.DataFrame(data, columns=['Country', 'Name'])
X = df.values

countries = np.unique(X[:,0])
names = np.unique(X[:,1])

ohe = OneHotEncoder(categories=[countries]) # specify ONLY unique country names
tmp = ohe.fit_transform(X[:,0].reshape(-1, 1)).toarray()

X = np.append(tmp, names.reshape(-1,1), axis=1)

print (X)

代码示例3的输出:

[[1.0 0.0 0.0 'Pechi']
 [0.0 0.0 1.0 'Raj']
 [0.0 1.0 0.0 'Sri']
 [0.0 0.0 1.0 'Vignesh']]

答案 3 :(得分:0)

简而言之,如果您想使df实体化,请使用dummy=pd.get_dummies

dummy=pd.get_dummies(df['str'])
df=pd.concat([df,dummy], axis=1)
print(Data)