Pytorch 需要 Long 类型但得到的是 int 类型

Pytorch expected type Long but got type int

我恢复了一个错误

 Expected object of scalar type Long but got scalar type Int for argument #3 'index'

这是来自这一行。

targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)

我不确定该怎么做,因为我尝试使用多个地方将其转换为 long。我试着放一个

.long

最后以及将 dtype 设置为 torch.long 仍然无效。

与此非常相似,但他没有做任何事情来得到答案 "Expected Long but got Int" while running PyTorch script

我更改了很多代码,这是我的最后一次演绎,但现在给我同样的问题。

    def forward(self, inputs, targets):
            """
            Args:
                inputs: prediction matrix (before softmax) with shape (batch_size, num_classes)
                targets: ground truth labels with shape (num_classes)
            """
            log_probs = self.logsoftmax(inputs)
            targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)
            if self.use_gpu: targets = targets.to(torch.device('cuda'))
            targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
            loss = (- targets * log_probs).mean(0).sum()
            return loss

您的索引参数(即 targets.unsqueeze(1).data.cpu())的 dtype 需要是 torch.int64

(错误消息有点混乱:torch.long 不存在。但是 PyTorch 内部的 "Long" 表示 int64)。

targets = torch.zeros(log_probs.size()).scatter_(1, (targets.unsqueeze(1).data.cpu()).long(), 1)