使用pytorch将标签转为one-hot向量

使用nn.functional.one_hot

print(torch.nn.functional.one_hot(labels, num_classes=5))

使用scatter_

https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html?highlight=scatter_#torch.Tensor.scatter_

小样本

n_way = 5
n_shot = 1
print(labels.shape) # torch.Size([5])
one_hot_labels  = torch.zeros(n_way * n_shot, n_way).scatter_(1, labels.view(-1, 1), 1)
print(one_hot_labels)
"""
tensor([[1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 0., 1., 0.],
        [0., 0., 0., 0., 1.]])
"""

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37252519/article/details/120234389
今日推荐