我有一个类名数组:
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
: