gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:29:57 25 4
gpt4 key购买 nike

我有一个类名数组:

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

最佳答案

你可以用 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.]])

关于python - 来自 sklearn 的 OneHotEncoder 在传递类别时给出 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com