one hot encode a binary value in numpy

2019-07-17 21:55发布

问题:

I have a numpy array that looks like the following:

array([[0],[1],[1]])

And I want it to be represented as the one hot encoded equivalent:

array([[1,0],[0,1],[0,1]])

Any body have any ideas? I tried using sklearn.preprocessing.LabelBinarizer but this just re-produces the input.

Thanks.

EDIT

As requested, here is the code using LabelBinarizer

from sklearn.preprocessing import LabelBinarizer

train_y = np.array([[0],[1],[1]])
lb = LabelBinarizer()
lb.fit(train_y)
label_vecs = lb.transform(train_y)

Output:

array([[0],[1],[1]])

Note that it does state in the documentation 'Binary targets transform to a column vector'

回答1:

To use sklearn, it seems we could use OneHotEncoder, like so -

from sklearn.preprocessing import OneHotEncoder

train_y = np.array([[0],[1],[1]]) # Input

enc = OneHotEncoder()
enc.fit(train_y)
out = enc.transform(train_y).toarray()

Sample inputs, outputs -

In [314]: train_y
Out[314]: 
array([[0],
       [1],
       [1]])

In [315]: out
Out[315]: 
array([[ 1.,  0.],
       [ 0.,  1.],
       [ 0.,  1.]])

In [320]: train_y
Out[320]: 
array([[9],
       [4],
       [1],
       [6],
       [2]])

In [321]: out
Out[321]: 
array([[ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.]])

Another approach with initialization -

def initialization_based(A): # A is Input array
    a = np.unique(A, return_inverse=1)[1]
    out = np.zeros((a.shape[0],a.max()+1),dtype=int)
    out[np.arange(out.shape[0]), a.ravel()] = 1
    return out

Another with broadcasting -

def broadcasting_based(A):  # A is Input array
    a = np.unique(A, return_inverse=1)[1]
    return (a.ravel()[:,None] == np.arange(a.max()+1)).astype(int)