Usually, when you want to get a hot encoding for classification in machine learning, you have an array of indices.
import numpy as np nb_classes = 6 targets = np.array([[2, 3, 4, 0]]).reshape(-1) one_hot_targets = np.eye(nb_classes)[targets]
Now one_hot_targets
array([[[ 0., 0., 1., 0., 0., 0.], [ 0., 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 1., 0.], [ 1., 0., 0., 0., 0., 0.]]])
.reshape(-1) must be sure that you have the correct label format (you can also have [[2], [3], [4], [0]] ). -1 is a special meaning that means "put everything else in this dimension." Since there is only one, it aligns the array.
Copy-Paste Solution
def get_one_hot(targets, nb_classes): return np.eye(nb_classes)[np.array(targets).reshape(-1)]
Martin Thoma Mar 18 '17 at 13:01 2017-03-18 13:01
source share