PyTorch:比较预测标签和目标标签以计算准确性



我正在尝试实现这个循环以获得我的 PyTorch CNN 的准确性(它的完整代码在这里(到目前为止,我的循环版本是:

correct = 0
    test_total = 0
    for itera, testdata2 in enumerate(test_loader, 0):
        test_images2, test_labels2 = testdata2
        if use_gpu:
            test_images2 = Variable(test_images2.cuda())
        else:
            test_images2 = Variable(test_images2)
        outputs = model(test_images2)
        _, predicted = torch.max(outputs.data, 1)       
        test_total += test_labels2.size(0)      
        test_labels2 = test_labels2.type_as(predicted)
        correct += (predicted == test_labels2[0]).sum()    
    print('Accuracy of the network on all the test images: %d %%' % (
        100 * correct / test_total))

如果我像这样运行它,我会得到:

> Traceback (most recent call last):   File
> "c:/python_code/Customized-DataLoader-master_two/multi_label_classifier_for2classes.py",
> line 186, in <module>
>     main()   File "c:/python_code/Customized-DataLoader-master_two/multi_label_classifier_for2classes.py",
> line 177, in main
>     correct += (predicted == test_labels2[0]).sum()   File "C:anacondaenvspytorch_cudalibsite-packagestorchtensor.py",
> line 360, in __eq__
>     return self.eq(other) RuntimeError: invalid argument 3: sizes do not match at
> c:anaconda2conda-bldpytorch_1519501749874worktorchlibthcgenerated../THCTensorMathCompareT.cuh:65

我曾经test_labels2 = test_labels2.type_as(predicted)将两个张量都作为 LongTensors,这似乎可以很好地避免"预期这个......但是得到了..."错误。它们现在看起来像这样:

test_labels2 after conversion:
 0  1
 1  0
 1  0
[torch.cuda.LongTensor of size 3x2 (GPU 0)]
predicted:
 1
 1
 1
[torch.cuda.LongTensor of size 3 (GPU 0)]

我认为现在的问题是,test_labels2[0]返回的是一行而不是列。

我如何让它工作?

pytorch中的索引主要类似于numpy中的索引。要索引特定列的所有行j请使用:

tensor[:, j]

或者,可以使用来自pytorch的选择功能。

最新更新