来自 sklearn 的 OneHotEncoder 在传递类别时会给出 ValueError

Posted

技术标签:

【中文标题】来自 sklearn 的 OneHotEncoder 在传递类别时会给出 ValueError【英文标题】:OneHotEncoder from sklearn gives a ValueError when passing categories 【发布时间】:2020-07-28 16:53:01 【问题描述】:

我有一个类名数组:

classes = np.array(['A', 'B'])

我有一个数据数组(但这个数据只包含一个类的实例):

vals = np.array(['A', 'A', 'A'])
vals = vals.reshape(len(vals), 1)

我想对vals 数组进行一次热编码,这样它就可以解释可能存在其他一些类的事实。我正在尝试使用sklearn.preprocessing.OneHotEncoder:

ohe = OneHotEncoder(sparse=False, categories=classes)
ohe.fit_transform(vals)

但是当我运行它时,我得到以下错误:

Traceback (most recent call last):
  File "/usr/local/anaconda3/envs/my_project/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-10-08d325b5e8a7>", line 1, in <module>
    ohe.fit_transform(vals)
  File "/usr/local/anaconda3/envs/my_project/lib/python3.6/site-packages/sklearn/preprocessing/_encoders.py", line 372, in fit_transform
    return super().fit_transform(X, y)
  File "/usr/local/anaconda3/envs/my_project/lib/python3.6/site-packages/sklearn/base.py", line 571, in fit_transform
    return self.fit(X, **fit_params).transform(X)
  File "/usr/local/anaconda3/envs/my_project/lib/python3.6/site-packages/sklearn/preprocessing/_encoders.py", line 347, in fit
    self._fit(X, handle_unknown=self.handle_unknown)
  File "/usr/local/anaconda3/envs/my_project/lib/python3.6/site-packages/sklearn/preprocessing/_encoders.py", line 76, in _fit
    if self.categories != 'auto':
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

【参考方案1】:

你可以用classes适配编码器,然后转换vals

import numpy as np
from sklearn.preprocessing import OneHotEncoder

classes = np.array(['A', 'B'])
vals = np.array(['A', 'A', 'A'])
vals = vals.reshape(-1, 1)

ohe = OneHotEncoder(sparse=False)
ohe.fit(classes.reshape(-1, 1))

ohe.transform(vals)
array([[1., 0.],
       [1., 0.],
       [1., 0.]])

【讨论】:

以上是关于来自 sklearn 的 OneHotEncoder 在传递类别时会给出 ValueError的主要内容,如果未能解决你的问题,请参考以下文章

来自 .csv 的 Sklearn 朴素贝叶斯 GaussianNB

来自 sklearn.metrics.silhouette_samples 的 MemoryError

sklearn 中的 RFECV,来自 grid_scores_ 的分数

F_Regression 来自 sklearn.feature_selection

sklearn 绘制来自 SVM 分类器的结果

来自 sklearn 的 OneHotEncoder 在传递类别时会给出 ValueError