PyTorch——Tensor_把索引标签转换成one-hot标签表示

对于分类问题,标签可以是类别索引值也可以是one-hot表示。以10类别分类为例,lable=[3] 和label=[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]是一致的.

现在给定索引标签,怎么将其转换为one-hot标签表示?

>>>class_num = 10
>>>batch_size = 4
>>>label = torch.LongTensor(batch_size, 1).random_() % class_num
 3
 0
 0
 8

>>>one_hot = torch.zeros(batch_size, class_num).scatter_(1, label, 1)
    0     0     0     1     0     0     0     0     0     0
    1     0     0     0     0     0     0     0     0     0
    1     0     0     0     0     0     0     0     0     0
    0     0     0     0     0     0     0     0     1     0

版权声明:本文为VictoriaW原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。