【问题标题】:PyTorch: Comparing predicted label and target label to compute accuracyPyTorch:比较预测标签和目标标签以计算准确性
【发布时间】:2018-08-24 13:56:15
【问题描述】:

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

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:\anaconda\envs\pytorch_cuda\lib\site-packages\torch\tensor.py",
> line 360, in __eq__
>     return self.eq(other) RuntimeError: invalid argument 3: sizes do not match at
> c:\anaconda2\conda-bld\pytorch_1519501749874\work\torch\lib\thc\generated\../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] 正在返回一行而不是列。

如何让它工作?

【问题讨论】:

  • 你能详细说明test_labelspredicted 代表什么(它们的意思)吗?错误似乎很明显,因为:(predicted == test_labels2[0]) - test_labels2[0] 的大小为 2,predicted 的大小为 3。
  • predicted 是通过神经网络传播的预测图像类别。 test_labels 是训练数据中的真实标签。两者都有三行,因为在这种情况下,数据加载器的 batch_size 设置为 3。事实上,我想我只需要知道如何索引 TorchLongTensor 中的某些列,这样我就可以比较预测和 test_labels。我该怎么做?
  • 您可以像在 numpy 中一样简单地使用索引:test_labels2[:, 0] 例如会给您第一列。这解决了您的问题吗?
  • 好的,谢谢。我想我需要学习一些 numpy 课程:|

标签: python python-3.x torch pytorch tensor


【解决方案1】:

pytorch 中的索引与numpy 中的索引很相似。要索引某一列j 的所有行,请使用:

tensor[:, j]

或者,也可以使用 pytorch 中的 select 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2018-10-18
    • 2020-12-14
    • 2020-08-14
    相关资源
    最近更新 更多