I have a sequence s = [4,3,1,0,5]
and num_classes = 6
and I want to generate a Numpy matrix m
of shape (len(s), num_classes)
Since you want a single 1
per row, you can fancy-index using arange(len(s))
along the first axis, and using s
along the second:
s = [4,3,1,0,5]
n = len(s)
k = 6
m = np.zeros((n, k))
m[np.arange(n), s] = 1
m
=>
array([[ 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 1., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1.]])
m.nonzero()
=> (array([0, 1, 2, 3, 4]), array([4, 3, 1, 0, 5]))
This can be thought of as using index (0,4), then (1,3), then (2,1), (3,0), (4,5).