【问题标题】:Expect FloatTensors but got LongTensors in MNIST-like task期待 FloatTensors 但在类似 MNIST 的任务中得到 LongTensors
【发布时间】:2019-06-02 18:22:09
【问题描述】:

我正在执行类似 MNIST 的任务,输入是 10 类图像,预期输出是图像的预测类别。

但现在output 类似于 [-2.3274, -2.2723, ...],其长度为 batch_size。而target 是 [4., 2., 2., 8., ...]

Error message: RuntimeError: 标量类型 Long 的预期对象,但参数 #2 'target' 的标量类型浮点数

class Net(nn.Module):
    ...
    ...
    def forward(self, x):
        ...
        ...
        return F.log_softmax(x, dim = 1)


criterion = torch.nn.NLLLoss()

谁能给我一些建议?谢谢。

【问题讨论】:

    标签: python machine-learning deep-learning computer-vision pytorch


    【解决方案1】:

    您得到的错误指的是损失的 second (#2) 参数:target.
    NLLLoss 期望(对于每个元素)有一个 float 概率向量,每个元素有一个 long(即整数)目标。
    在您的情况下,您的“目标”值是[4., 2., 2., 8., ...],其类型为 float。您需要将目标转换为长:

    target = target.to(dtype=torch.long)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2021-08-15
      • 2022-12-22
      • 1970-01-01
      • 2022-08-22
      • 2020-11-09
      相关资源
      最近更新 更多