generate sequence by indices / one-hot encoding

后端 未结 4 729
时光说笑
时光说笑 2020-12-21 13:36

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)

4条回答
  •  礼貌的吻别
    2020-12-21 14:06

    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).

提交回复
热议问题