在跑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)
这下问题解决了。