使用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.]])
"""