报错信息

expected scalar type Long but found Int
或者
expected scalar type Long but found Float

报错场景

pytorch的分类,本例具体为torch.nn.CrossEntropyLoss

原因

pytorch的分类的loss函数的label的类型只能是torch.LongTensor类型(也是torch.int64类型),其他类型比如torch.int32,torch.float32等等会报错。
我自己的是从np.long转成tensor时,由于np.long也是np.int32,转成tensor是转成了torch.int32,所以会报错。
np和torch的long类型不能直接转换,它们之间不等价,因为前者是int32,后者是int64。

解决办法

把label类型改成torch.LongTensor类型即可:
label = label.type(torch.LongTensor) # 原来的label是torch.int32类型,转换后是torch.int64

代码示例


import numpy as np
import torch

a = [1,2,3]
a = np.array(a, dtype=np.long)
print(a.dtype)
new_a = torch.from_numpy(a.copy())
print(new_a.dtype)

another_a = new_a.type(torch.LongTensor)
print(another_a.dtype)

输出:

int32
torch.int32
torch.int64
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐