PyTorch报”RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 ‘mat2’ “的原因以及解决办法

  • Post category:Python

问题描述:

在使用PyTorch时,出现了以下报错:

Traceback (most recent call last):
File "main.py", line 37, in <module>
outputs = model(inputs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 550, in __call__
result = self.forward(*input, **kwargs)
File "model.py", line 43, in forward
x = self.dense(x)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 550, in __call__
result = self.forward(*input, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/linear.py", line 87, in forward
return F.linear(input, self.weight, self.bias)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py", line 1350, in linear
output = input.matmul(weight.t())
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'mat2' in call to _th_mm

问题分析:

这个错误通常出现在使用torch.nn中的Linear或者CrossEntropyLoss等函数时发生,默认情况下,这些函数期望的输入tensor数据类型为LongTensor,但是我们输入了FloatTensor,因此就会出现这个错误。

解决办法:

  1. 检查代码中的输入数据类型,确保输入的tensor类型为LongTensor,比如对于模型的输入数据,需要对输入数据调用long()方法,将其转换为LongTensor类型。
inputs = inputs.long()
  1. 对于模型的输出数据,需要对输出结果进行softmax操作,并将输出结果tensor类型转换为LongTensor。
softmax = nn.Softmax(dim=1)
outputs = softmax(outputs)
outputs = torch.argmax(outputs, dim=1).long()
  1. 对于CrossEntropyLoss损失函数,在计算loss之前,需要对标签输出数据(y_true)调用long()方法,将其转换为LongTensor类型。
y_true = y_true.long()
criterion = nn.CrossEntropyLoss()
loss = criterion(outputs, y_true)

如果以上方法依然无法解决问题,则可以检查模型中是否存在类型错误或者其他数据处理错误,并逐一排查解决。

总结:

以上就是解决PyTorch报错”Expected object of scalar type Long but got scalar type Float for argument #2 ‘mat2’ “的问题的完整攻略,总结来说,这个错误通常出现在深度学习模型的训练过程中,在CodeReview过程中需要注意tensor数据的类型,并逐一检查处理过程中是否存在类型错误或者其他数据处理错误。