记录问题并解决Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

在跑resenet的时候出现下面的问题,记录下,并写出解决方法,以供后续参考。

RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

报错的代码

Traceback (most recent call last):
  File "E:/workspace/MachineLearning-master/main.py", line 159, in <module>
    trained_model, record = train_and_valid(resnet50, loss_func, optimizer, num_epochs)
  File "E:/workspace/MachineLearning-master/main.py", line 97, in train_and_valid
    outputs = model(inputs)
  File "C:\Anaconda3\envs\torch1.6\lib\site-packages\torch\nn\modules\module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "E:\workspace\MachineLearning-master\models\resnet.py", line 197, in forward
    x = self.conv1(x)
  File "C:\Anaconda3\envs\torch1.6\lib\site-packages\torch\nn\modules\module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "C:\Anaconda3\envs\torch1.6\lib\site-packages\torch\nn\modules\conv.py", line 423, in forward
    return self._conv_forward(input, self.weight)
  File "C:\Anaconda3\envs\torch1.6\lib\site-packages\torch\nn\modules\conv.py", line 419, in _conv_forward
    return F.conv2d(input, weight, self.bias, self.stride,
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

翻译过来是输入的数据类型与网络参数的类型不符,查阅了很多资料说是

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input = input.to(device)

看下我的代码

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
inputs = inputs.to(device)
labels = labels.to(device)

没有问题啊,是这么写的

接下来看到有在基础网络那边写的,将网络都写在初始化中,通过self去构建网络,看看我的代码,没问题

回到错误代码,显示outputs = model(inputs)这里报错

那我大胆猜测可能是mode没有调用cuda,而input却调用了,造成了不统一。于是添加model.to('cuda')代码:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to('cuda')
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)

这下问题解决了。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值