PyTorch手动初始化卷积层并进行卷积运算报数据类型错误Expected object of scalar type Double but got scalar type Float for arg

Expected object of scalar type Double but got scalar type Float for argument #4 ‘bias’

尝试脱离nn.Module模块手动定义conv2d层,并对权重init和卷积运算

X = torch.arange(1,17,dtype=float).reshape((1,1,4,4))
K = torch.arange(1,10,dtype=float).reshape((1,1,3,3))
conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, padding=0)
print(conv.weight)

conv.weight = torch.nn.Parameter(K)
print(conv.weight)
print(conv.forward(X))

然而运行之后会报错
Expected object of scalar type Double but got scalar type Float for argument #4 'bias'
大概看了下,报的是数据类型的错误
解决方法也很简单,在初始化参数X和K的时候,把数据类型都换成单精度torch.float32

X = torch.arange(1,17,dtype=torch.float32).reshape((1,1,4,4))
K = torch.arange(1,10,dtype=torch.float32).reshape((1,1,3,3))

PyTorch手动初始化卷积层并进行卷积运算报数据类型错误Expected object of scalar type Double but got scalar type Float for arg_第1张图片
参考链接:
https://cloud.tencent.com/developer/article/1754995

你可能感兴趣的:(从掉坑到爬坑,python,pytorch,机器学习)