首页 > 解决方案 > 无效的参数组合 - eq()

问题描述

我正在使用此处共享的代码来测试 CNN 图像分类器。当我调用测试函数时,我在第 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

快速搜索后,我发现该错误可能与predictionand之间的比较有关labels,就像在这个SO question中所显示的那样。

关于如何解决这个问题的任何想法?

标签: pythonnumpyimage-processingmachine-learningpytorch

解决方案


你为什么在.numpy()这里prediction = prediction.cpu().numpy()?这样你就可以将 PyTorch 张量转换为 NumPy 数组,使其与labels.data.

删除.numpy()部分应该可以解决问题。


推荐阅读