Scikit-learn LabelEncoder: IndexError: arrays used as indices must be of integer (or boolean) type

安稳与你 提交于 2020-02-03 01:53:06

问题


I am trying to preprocess adult data in order to make a classification. I deal with categorical attributes with scikit-learn.

from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
X[:,0] = labelencoder.fit_transform(X[:,0])
labelencoder.classes_

output:

array(['Federal-gov', 'Local-gov', 'Private', 'Self-emp-inc',
       'Self-emp-not-inc', 'State-gov', 'Without-pay'], dtype=object)

new content:

X[:3]
array([[5, 'Bachelors', 'Under-Graduate', 'Never-married',
        'Adm-clerical', 'Not-in-family', 'White', 'Male',
        'United-States', 39.0, 77516.0, 13.0, 2174.0, 0.0, 40.0],
       [4, 'Bachelors', 'Under-Graduate', 'Married-civ-spouse',
        'Exec-managerial', 'Husband', 'White', 'Male', 'United-States',
        50.0, 83311.0, 13.0, 0.0, 0.0, 13.0],
       [2, 'HS-grad', 'HS-grad', 'Divorced', 'Handlers-cleaners',
        'Not-in-family', 'White', 'Male', 'United-States', 38.0,
        215646.0, 9.0, 0.0, 0.0, 40.0]], dtype=object)

Everything is fine till here. But I needed to see original attributes and try to get back with the following:

original = labelencoder.inverse_transform(X[:,0])

I got this error:

IndexError                                Traceback (most recent call last)
<ipython-input-78-f8cf404b255a> in <module>
----> 1 original = labelencoder.inverse_transform(X[:,0])

D:\Anaconda\lib\site-packages\sklearn\preprocessing\label.py in inverse_transform(self, y)
    281                     "y contains previously unseen labels: %s" % str(diff))
    282         y = np.asarray(y)
--> 283         return self.classes_[y]
    284 
    285 

IndexError: arrays used as indices must be of integer (or boolean) type

回答1:


The error comes from the fact that your array has an "object" type. And even if you extract the first column, the type remains "object" (check X[:,0].dtype). Furthermore inverse_transform requires int type. So in order to use inverse_transform you need to cast your vector to int like that:

original = labelencoder.inverse_transform(X[:,0].astype(int))

Output:

array(['a', 'b', 'c'], dtype=object)


来源:https://stackoverflow.com/questions/55501848/scikit-learn-labelencoder-indexerror-arrays-used-as-indices-must-be-of-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!