Reputation: 438
I have an array of class names:
classes = np.array(['A', 'B'])
And I have an array of data (but this data only contains instances of one class):
vals = np.array(['A', 'A', 'A'])
vals = vals.reshape(len(vals), 1)
I want to end up with one-hot encoding for the vals
array, such that it accounts for the fact that there might be some other classes. I am trying to use sklearn.preprocessing.OneHotEncoder
:
ohe = OneHotEncoder(sparse=False, categories=classes)
ohe.fit_transform(vals)
But when I run this, I get the following error:
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()
Upvotes: 3
Views: 274
Reputation: 6475
You can fit the encoder with classes
and then trasform 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.]])
Upvotes: 4