我正在尝试实现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]
正在返回一行而不是列。
如何让它发挥作用?
答案 0 :(得分:0)