【问题标题】:how to identify wrong classification with batches in pytorch如何在pytorch中使用批次识别错误分类
【发布时间】:2019-09-19 22:05:31
【问题描述】:

我有一个这样的脚本,其中使用了批量图像

correct = 0
total = 0
incorrect_classification=[]
for (i, [images, labels]) in enumerate(test_loader):
  images = Variable(images.view(-1, n_pixel*n_pixel))
  outputs = net(images)
  _, predicted = torch.min(outputs.data, 1)
  total += labels.size(0)                    
  correct += (predicted == labels).sum() 
print('Accuracy: %d %%' %
      (100 * correct / total))

批量大小为 10 时,每个枚举返回 10 x 图像大小的张量。如何将所有错误的分类保存到数组不正确的分类或错误的 img 中,并将它们的概率保存到字典中,以便以后使用 can plt.imshow 检查它们?

如果批量大小为 1,我可以使用这个:

if (predicted==labels).item()==0:
    incorrect_examples.append(images.numpy())

但是如果指定了批次大小(例如每批次 100 张图像),我应该如何保存错误的分类?

提前感谢您的任何回答。

【问题讨论】:

  • 也许尝试images[predicted==labels] 来获取错误的图像?

标签: pytorch imshow


【解决方案1】:

正如@zihaozhihao 的评论中已经说过的,images[predicted==labels] 应该做的工作。

换句话说,你会得到一个索引掩码,然后用这个掩码访问你想要的图像:

correct = 0
total = 0
incorrect_examples=[]
for (i, [images, labels]) in enumerate(test_loader):
    images = Variable(images.view(-1, n_pixel*n_pixel))
    outputs = net(images)
    _, predicted = torch.min(outputs.data, 1)
    total += labels.size(0)                    
    correct += (predicted == labels).sum() 
    print('Accuracy: %d %%' % (100 * correct / total))

    # if (predicted==labels).item()==0:
    #     incorrect_examples.append(images.numpy())

    idxs_mask = (predicted == labels).view(-1)
    incorrect_examples.append(images[idxs_mask].numpy()) 

view(-1) 将展平用于遮罩图像张量的批处理通道的遮罩。

在循环结束时(在循环之外),列表incorrect_examples 中的元素将具有[batch_size, n_pixel, n_pixel] 的形状,并且为方便起见,您可以通过连接它们将它们全部分组到一个张量中:

incorrect_images = torch.cat(incorrect_examples)
# incorrect_images.size() -> (n_incorrect_images, n_pixel, n_pixel)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2017-05-17
    • 2022-01-07
    • 2023-02-06
    • 2020-03-19
    • 1970-01-01
    • 2016-05-31
    相关资源
    最近更新 更多