Convert array of indices to 1-hot encoded numpy array Convert array of indices to 1-hot encoded numpy array numpy numpy

Convert array of indices to 1-hot encoded numpy array


Your array a defines the columns of the nonzero elements in the output array. You need to also define the rows and then use fancy indexing:

>>> a = np.array([1, 0, 3])>>> b = np.zeros((a.size, a.max()+1))>>> b[np.arange(a.size),a] = 1>>> barray([[ 0.,  1.,  0.,  0.],       [ 1.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  1.]])


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


In case you are using keras, there is a built in utility for that:

from keras.utils.np_utils import to_categorical   categorical_labels = to_categorical(int_labels, num_classes=3)

And it does pretty much the same as @YXD's answer (see source-code).