Convert array of indices to 1-hot encoded numpy array

1.6K    Asked by ClareMatthews in Devops , Asked on Jul 1, 2021

I want to encode a 1-D numpy array:

x = array([1,0,3]) 

As a 2-D 1-hot array

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

Suggest me some faster technique other than looping. 

Answered by Amit jaisawal

Numpy one hot encoding can be done by following steps as mentioned below:


rows = np. arange(data. size)
print(rows)
one_hot[rows, data] = 1.
print(one_hot)

OR

You can also refer to the following code it may help.

>>> x = [1, 0, 3]
>>> z = np.max(x) + 1
>>> np.eye(z)[x]
array([[ 0., 1., 0., 0.],
      [ 1., 0., 0., 0.],
      [ 0., 0., 0., 1.]])

Alernatively, you can use:

>>> x = np.array([1, 0, 3])
>>> z= np.zeros((3, 4))
>>> z[np.arange(3), x] = 1
>>> y
array([[ 0., 1., 0., 0.],
      [ 1., 0., 0., 0.],
      [ 0., 0., 0., 1.]])

Your Answer

Interviews

Parent Categories