pytorch测试集看每类准确率遇到了一点bug

报错如下:
class_correct[label] +=( c[i].item())
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

代码原本就用的.item(),不知道为何依然报这个错。。试着改了几次都不行

源代码就是网上常用的

    N_CLASSES=6;
    BATCH_SIZE=16

    classes = ('Sun', 'Rain', 'SmallFog', 'MidFog','BigFog','Snow')
    class_correct = list(0. for i in range(N_CLASSES))  
    class_total = list(0. for i in range(N_CLASSES))        
    with torch.no_grad():
        for data in val_loader:
            images, labels = data
            images, labels = images.to(device1), labels.to(device1)
            outputs = Incep(images)
            _, predicted = torch.max(outputs, 1)
            c = (predicted == labels).squeeze()
            print(c.size())
            for i in range(BATCH_SIZE):
                label = labels[i]
                class_correct[label] += c[i].item()
                class_total[label] += 1
        for i in range(N_CLASSES):
            print('Accuracy of %5s : %2d %%' % (
            classes[i], 100 * class_correct[i] / class_total[i]))

2个回答

class_correct[label] +=( c.item())

weixin_43572396
Codewyf-top 回复yunfanxiang: 楼主请问你下你这个问题解决了嘛?我也遇到了同样的问题
3 个月之前 回复
yunfanxiang
yunfanxiang 这样感觉就更不太对了,应该是加上c[i]那个,但不知道为啥用了.item()不行
12 个月之前 回复
yunfanxiang
yunfanxiang File "load data2.py", line 87, in <module> class_correct[label] += c.item() ValueError: only one element tensors can be converted to Python scalars
12 个月之前 回复

这一块代码改成这样试试看

images = images.to(device)
        labels = labels.to(device)
        output = net(images)
        _, predicted = torch.max(output, 1)
        c = (predicted == labels).squeeze()
        label = labels.item()
        if c.item():
            class_correct[label] +=1
        class_total[label] += 1

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐