我正在使用共享的here代码来测试CNN图像分类器。调用测试函数时,我在line 155上收到了此错误:
test_acc += torch.sum(prediction == labels.data)
TypeError: eq() received an invalid combination of arguments - got (numpy.ndarray), but expected one of:
* (Tensor other)
didn't match because some of the arguments have invalid types: ([31;1mnumpy.ndarray[0m)
* (Number other)
didn't match because some of the arguments have invalid types: ([31;1mnumpy.ndarray[0m)
test
函数的片段:
def test():
model.eval()
test_acc = 0.0
for i, (images, labels) in enumerate(test_loader):
if cuda_avail:
images = Variable(images.cuda())
labels = Variable(labels.cuda())
#Predict classes using images from the test set
outputs = model(images)
_,prediction = torch.max(outputs.data, 1)
prediction = prediction.cpu().numpy()
test_acc += torch.sum(prediction == labels.data) #line 155
#Compute the average acc and loss over all 10000 test images
test_acc = test_acc / 10000
return test_acc
快速搜索后,我发现该错误可能与SO question中的prediction
和labels
之间的比较有关。
如何解决此问题,而不对其余代码进行打扰?
答案 0 :(得分:1)
您为什么在<input type='file' webkitdirectory='' directory='' multiple='true' />
有.numpy()
?
这样,您可以将PyTorch张量转换为NumPy数组,从而使其类型与prediction = prediction.cpu().numpy()
不兼容。
删除labels.data
部分应该可以解决此问题。