问题:
anchor_label = np.array(self.id_dict[int(anchor_id)])
identity_loss = criterion_identity(predicted_id_rgb, anchor_label) + criterion_identity(predicted_id_ir, anchor_label)
RuntimeError: Expected object of type torch.cuda.LongTensor but found type torch.cuda.IntTensor for argument #2 'target'
释义:
第二个参数 anchor_label 类型为 IntTensor,不符合要求的 LongTensor
原因:
python2 中取消了long 型,python3 统一用 int 型代替
python3中int 支持位数等于 python2 中long型位数
测试:
import numpy as np
x = np.float32(1.0)
>>> x
1.0
y = np.int_([1,2,4])
>>> y
array([1, 2, 4])
# dtype 属性确定数组元素的类型,dtype参数说明,详见下面链接
# https://www.jianshu.com/p/6ca8729dd102
z1 =np.array(12752649778202, dtype=np.int_)
>>> z1
OverflowError: Python int too large to convert to C long
z2 =np.array(12752649778202, dtype=np.int32)
>>> z2
OverflowError: Python int too large to convert to C long
z3 =np.array(12752649778202, dtype=np.int64)
>>> z3
OverflowError: Python int too large to convert to C long
z4 =np.array(12752649778202, dtype=np.int)
>>> z4
OverflowError: Python int too large to convert to C long
# 成功找到解决办法
z =np.array(12752649778202, dtype=np.intp)
>>> z
12752649778202
解决办法:
- dtype 设为 np.intp,可使 python2中 long 类型 等价到 python3 中使用
- 采用C/C++语言的强制转化,int(long型数值), 可能将超过int位数的字符截断,故建议使用dtype 方式
anchor_label = np.array(self.id_dict[int(anchor_id)],dtype=np.intp) # python3
或者
anchor_label = np.array(int(self.id_dict[int(anchor_id)])) # C/C++ 强制转化