【问题标题】:how to fix class-accuracy of my classifier如何修复我的分类器的类精度
【发布时间】:2020-02-20 08:00:05
【问题描述】:

我正在尝试查看我的图像分类器对每类数据的准确性。但是,我是一个初学者,我正在尝试使用 Pytorch 教程提供的代码来训练分类器。 当我运行代码时:

class_correct = list(0. for i in range(7))
class_total = list(0. for i in range(7))
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = network(images)
        print(outputs.shape)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels.argmax(dim=1)).squeeze()
        print(c.shape)
        for i in range(5):
            label = labels[i]
            class_correct[label] += c[i].item()
            class_total[label] += 1
for i in range(7):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))

" 出现以下错误:

torch.Size([100, 7])
torch.Size([100])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-b4cabf540645> in <module>
     11         for i in range(5):
     12             label = labels[i]
---> 13             class_correct[label] += c[i].item()
     14             class_total[label] += 1
     15 for i in range(7):

TypeError: only integer tensors of a single element can be converted to an index

我知道问题出在标签张量上,但我不知道如何解决。 非常感谢任何帮助! 先谢谢大家了

在上一个单元格中,我运行了下面提供的代码以获得有效的整体准确性,但我在获取每个类的准确性时遇到了问题。

correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = network(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels.float().argmax(dim=1)).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))

【问题讨论】:

    标签: python classification conv-neural-network


    【解决方案1】:

    我无法在手上运行您的代码,所以我只是在猜测.. 但是

    我认为变量label不是int类型。

    #label = labels[i]
    label = int(labels[i])
    

    希望对你有帮助


    对不起,其实我没有对你的问题给予足够的重视。我又读了一遍你的代码。

    希望对你有帮助。

    label_index = labels.argmax(dim=1)
    for i in range(labels.size(0)):
        #label = labels[i]
        label = label_index[i]
        class_correct[label] += c[i].item()
        class_total[label] += 1
    

    关键点:变量标签是概率函数或one-hot编码。您需要获取最大值的索引。

    我真的希望它有效...!!

    【讨论】:

    • 当我实施您建议的更改时,出现以下错误:ValueError:只有一个元素张量可以转换为 Python 标量。我想问题出在我的标签张量的维度上,因为当我运行 print(labels.shape) 它说 (100,7) 我想它应该是一维张量之类的!再次感谢
    • 我添加了另一个解决方案,请检查一下^^
    猜你喜欢
    • 2015-06-15
    • 2020-09-08
    • 2019-09-29
    • 2017-05-17
    • 1970-01-01
    • 2015-02-21
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多