因为模型在GPU上,但是数据在cpu上,所以会出现此错误。因此,您需要将输入张量发送到GPU。
inputs, labels = data # this is what you had
inputs, labels = inputs.cuda(), labels.cuda() # add this line
或者像这样,与其他代码保持一致:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
inputs, labels = inputs.to(device), labels.to(device)
在 ,如果你输入张量在GPU上,但你的模型权重不是会得到提升。在这种情况下,您需要将模型权重发送到GPU。
model = MyModel()
if torch.cuda.is_available():
model.cuda()