label to one-hot

pytorch tensor——

label_one_hot = torch.nn.functional.one_hot(labels, self.num_classes).float().to(self.device)

or

target_batch = Variable(torch.LongTensor(target_batch))

torch.eye(n_class)[target_batch]

numpy——

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

 or

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325730288&siteId=291194637