PyTorch F.cross_entropy报错: RuntimeError: 1D target tensor expected, multi-target not supported

原因

cross_entropy target参数只需要标签即可, 不需要传one-hot向量

代码试验

传入one-hot向量报错

import torch
import torch.nn.functional as F
a = torch.Tensor([[0, 0, 1], [1, 0, 0]]).long()
b = torch.Tensor([[0.8, 0.1, 0.1], [0.9, 0.05, 0.05]])
print(F.cross_entropy(input = b, target = a))

结果:

Traceback (most recent call last):
  File "D:/PycharmProjects/AAE_pytorch-master/半监督AAE/1.py", line 11, in <module>
    print(F.cross_entropy(input = b, target = a))
  File "D:\Program Files\Python38\lib\site-packages\torch\nn\functional.py", line 2422, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
  File "D:\Program Files\Python38\lib\site-packages\torch\nn\functional.py", line 2218, in nll_loss
    ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported

传入label值计算正确

import torch
import torch.nn.functional as F
a = torch.Tensor([1, 1]).long()
b = torch.Tensor([[0.8, 0.1, 0.1], [0.9, 0.05, 0.05]])
print(F.cross_entropy(input = b, target = a))

结果:

tensor(1.4288)

你可能感兴趣的:(Pytorch,Pytorch,CrossEntropy,multi-target)