在Pytorch中使用GPU(CUDA)需要给定训练有素的NN评分一组图像。 以下代码旨在对一组转换后的图像进行一次评分。
model.to('cuda')
model.eval()
for ii, (inputs, classes) in enumerate(dataloaders['test']):
inputs, classes = inputs, classes
results = model.forward(inputs)
ps = torch.exp(results)
错误堆栈:
RuntimeError Traceback (most recent call last)
<ipython-input-24-948390e2b25a> in <module>()
5 for ii, (inputs, classes) in enumerate(dataloaders['test']):
6 inputs, classes = inputs, classes
----> 7 results = model(inputs)
8 ps = torch.exp(results)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
489 result = self._slow_forward(*input, **kwargs)
490 else:
--> 491 result = self.forward(*input, **kwargs)
492 for hook in self._forward_hooks.values():
493 hook_result = hook(self, input, result)
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/vgg.py in forward(self, x)
40
41 def forward(self, x):
---> 42 x = self.features(x)
43 x = x.view(x.size(0), -1)
44 x = self.classifier(x)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
489 result = self._slow_forward(*input, **kwargs)
490 else:
--> 491 result = self.forward(*input, **kwargs)
492 for hook in self._forward_hooks.values():
493 hook_result = hook(self, input, result)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/container.py in forward(self, input)
89 def forward(self, input):
90 for module in self._modules.values():
---> 91 input = module(input)
92 return input
93
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
489 result = self._slow_forward(*input, **kwargs)
490 else:
--> 491 result = self.forward(*input, **kwargs)
492 for hook in self._forward_hooks.values():
493 hook_result = hook(self, input, result)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input)
299 def forward(self, input):
300 return F.conv2d(input, self.weight, self.bias, self.stride,
--> 301 self.padding, self.dilation, self.groups)
302
303
RuntimeError:类型为torch.FloatTensor的预期对象,但为参数#2'weight'发现类型为torch.cuda.FloatTensor
在GPU(CUDA)上制作的模型。
答案 0 :(得分:3)
这可以解决问题并提供准确率。
model.to('cuda')
model.eval()
accuracy = 0
for ii, (inputs, classes) in enumerate(dataloaders['test']):
inputs, classes = inputs.to('cuda'), classes.to('cuda')
# Forward and backward passes
with torch.no_grad():
output = model.forward(inputs)
ps = torch.exp(output)
equality = (classes.data == ps.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
accuracy = accuracy/len(dataloaders['test'])
print(accuracy)