RuntimeError:对于torch.cuda.LongTensor类型

时间:2019-02-26 04:22:32

标签: python image-processing machine-learning computer-vision pytorch

我正在使用PyTorch,但出现错误! 我的错误代码如下:


for train_data in trainloader:
    example_count += 1
    if example_count == 100:
        break
    optimer.zero_grad()
    image, label = train_data
    image = image.cuda()
    label = label.cuda()
    out = model(image)
    _, out = torch.max(out, 1)
    # print(out.cpu().data.numpy())
    # print(label.cpu().data.numpy())
    # out = torch.zeros(4, 10).scatter_(1, out.cpu(), 1).cuda()
    # label= torch.zeros(4, 10).scatter_(1, label.cpu(), 1).cuda()
    l = loss(out, label)
    l.bakeward()
    optimer.setp()
    j += 1
    count += label.size(0)
    acc += (out == label).sum().item()
    if j % 1000 == 0:
        print(j + ' step:curent accurity is %f' % (acc / count))

回溯:

    Traceback (most recent call last):
  File "VGG实现.py", line 178, in <module>
    utils.train(testloader,model)
  File "VGG实现.py", line 153, in train
    l=loss(out,label)
  File "/home/tang/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 489, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/tang/anaconda3/lib/python3.7/site-packages/torch/nn/modules/loss.py", line 435, in forward
    return F.mse_loss(input, target, reduction=self.reduction)
  File "/home/tang/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 2156, in mse_loss
    ret = torch._C._nn.mse_loss(expanded_input, expanded_target, _Reduction.get_enum(reduction))
RuntimeError: _thnn_mse_loss_forward is not implemented for type torch.cuda.LongTensor

我得到一个答案,答案在这里 Pytorch RuntimeError: "host_softmax" not implemented for 'torch.cuda.LongTensor'

但是我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

查看torch.max()的文档:

torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)
     

返回给定输入张量的每一行的最大值   尺寸暗淡。第二个返回值是每个索引的索引位置   找到最大值(argmax)。

您的代码行

_, out = torch.max(out, 1)

对模型{em> float 进行预测out,并使用torch.max()返回 argmax =类型 long 最大预测的整数索引。
您收到的错误消息是您的loss函数(我想将交叉熵与softmax一起使用)不支持 long 类型的第一个参数。
此外,您不能通过argmax求导数-因此我认为使用.to(torch.float)out转换为float不会对您有任何好处。
您正在使用的损失函数中的softmax函数会为您照顾argmax。