运行 conv2d错误:RuntimeError: _thnn_conv2d_forward not supported on CPUType for Long


先看一下源代码:(怎么可能会有错,毕竟我是复制的土堆的代码)

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 <module>

    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)

第一次写博客,如有错误之处还请大家批评指正~ 

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值