先看一下源代码:(怎么可能会有错,毕竟我是复制的土堆的代码)
import torch import torch.nn.functional as F input = torch.tensor([[1, 2, 0, 3, 1], [0, 1, 3, 3, 1], [1, 2, 1, 0, 0], [5, 2, 3, 1, 1], [2, 1, 0, 1, 1]]) kernel = torch.tensor([[1, 2, 1], [0, 1, 0], [2, 1, 0]]) print(input.shape) print(kernel.shape) input = torch.reshape(input, (1, 1, 5, 5)) kernel = torch.reshape(kernel, (1, 1, 3, 3)) output = F.conv2d(input, kernel, stride=1) print(output)
然鹅竟然出错了
Traceback (most recent call last):
File "F:/learn_pytorch/test_conv.py", line 47, in
output = F.conv2d(input, kernel, stride=1)
RuntimeError: _thnn_conv2d_forward not supported on CPUType for Long
在网上找了一些资料,还是大佬的话给了启发,程序报错的原因是CPUType不支持Long类型,需要更改数据类型
再来看一眼代码,是否真的是Long类型,
print(input.dtype) #torch.int64 print(kernel.dtype) #torch.int64
所以就更改类型吧,
1、 input = torch.tensor(input, dtype=torch.float)
kernel = torch.tensor(kernel, dtype=torch.float)
2、input = input.float()
kernel = kernel.float()
3、可以把input、kernel中矩阵的数字换成浮点型
input = torch.tensor([[1., 2., 0., 3., 1.], [0., 1., 2., 3., 1.], [1., 2., 1., 0., 0.], [5., 2., 3., 1., 1.], [2., 1., 0., 1., 1.]]) kernel = torch.tensor([[1., 2., 1.], [0., 1., 0.], [2., 1., 0.]])或者还可以直接在原来矩阵后面加上(注意要导入相关库)
from torch import float32 dtype=float32
问题就成功解决了!!!
可以成功看到下面的卷积输出了~
torch.Size([5, 5])
torch.Size([3, 3])
tensor([[[[10., 13., 12.],
[19., 18., 17.],
[13., 9., 3.]]]])
但是有Warnings:小白并不知道如何消除这些Warnings
F:/learn_pytorch/test_conv.py:17: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
input = torch.tensor(input, dtype=torch.float)
F:/learn_pytorch/test_conv.py:18: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
kernel = torch.tensor(kernel, dtype=torch.float)
第一次写博客,如有错误之处还请大家批评指正~