0维张量的索引无效。使用tensor.item()将0暗张量转换为Python数

时间:2019-06-25 19:38:38

标签: pytorch

我正在使用PyTorch教程来计算每个班级的准确性,并且使用tensor.item()中已经存在的class_correct[target] += c[i].item()抛出了错误

class_correct = list(0. for i in range(15))
class_total = list(0. for i in range(15))

with torch.no_grad():

    for ii, data in enumerate(test_loader): 

        t_image, target, classess, image_path  = data

        t_image = t_image.to(device)
        target = target.to(device)

        outputs = model(t_image)

        _, predicted = torch.max(outputs, 1)
        c = (predicted == target).squeeze()

        for i in range(4):
            target = target[i]
            class_correct[target] += c[i].item()
            class_total[target] += 1

for i in range(14):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))  

任何评论将不胜感激。

1 个答案:

答案 0 :(得分:0)

由于c.shape,未列出torch.Size([])。所以有错误。 您可以使用use c.item()