【问题标题】:Display misclassified images in pytorch在 pytorch 中显示错误分类的图像
【发布时间】:2020-10-13 15:38:31
【问题描述】:

我是 pytorch 和 numpy 的新手,所以这可能是一个愚蠢的问题。我希望看到一些被我的网络错误分类的图像,带有正确的标签和预测的标签。这是我的代码

valid_and_test_set = torchvision.datasets.MNIST("./mnist", train=False, download=True)
dataset_valid, dataset_test = torch.utils.data.random_split(valid_and_test_set,[5000, 5000])
dataset_test.dataset.transform = transform #transform is composed by unsqueeze, normalize, view and gaussian noise with randn
dataset_test.dataset.target_transform = OneHot() #OneHot return the label
dataloader_test = torch.utils.data.DataLoader(dataset_test.dataset, batch_size=5000, num_workers=num_workers, pin_memory=True)

def test(dataset, dataloader):
    net.eval()  
    with torch.no_grad():
        for batch in dataloader:
            inputs = batch[0]
            inputs = inputs.to(device, non_blocking=True)
            outputs = net(inputs)
            predictions = torch.argmax(outputs, dim=1)
            return predictions

提前谢谢你

【问题讨论】:

    标签: numpy matplotlib pytorch tensorboard


    【解决方案1】:

    至少有两种方法可以做到这一点。

    一个是存储在评估期间被错误分类的图像(运行测试数据)并绘制它们。这显示here

    另一种方法是使用 TensorBoard。这在我看来是相当优雅的,你可以找到它的综合指南here

    【讨论】:

      【解决方案2】:
      def test(dataset, dataloader):
          net.eval()
          with torch.no_grad():
              for batch in dataloader:
                  inputs = batch[0]
                  label=batch[1]
                  inputs = inputs.to(device, non_blocking=True)
                  outputs = net(inputs)
                  predictions = torch.argmax(outputs, dim=1)
                  for sampleno in range(batch[0].shape[0]):
                      if(label[sampleno]!=predictions[sampleno]):
                          print("Actual Lable")
                          print(label[sampleno])
                          print("Predicted Label")
                          print(predictions[sampleno])
                          showimg(inputs[sampleno].cpu())
                  return predictions
      

      你可以这样写showing()函数

      def showimg(model):
          model=np.reshape(model.numpy(),[28,28]) # For 1D Vector
          
          #If you normalize the image then use Next three-line
          #Otherwise skip that
          mean=np.array([0.485, 0.456, 0.406] )
          std=np.array([0.229, 0.224, 0.225])
          model=(model*std+mean)
          
      
      
          #print(model)
      
          cv2.imshow("ABC", model)
          
          #waits for user to press any key
          #(this is necessary to avoid Python kernel form crashing)
          cv2.waitKey(0)
      
          #closing all open windows
          cv2.destroyAllWindows()
      

      【讨论】:

      • 训练函数中的“数据”变量是什么?
      • 修改了那个变量。
      【解决方案3】:

      我收到这个错误,不知道这是什么意思

      ValueError                                Traceback (most recent call last)
       in 
          288 
          289         # test on validation
      --> 290         predictions = test(dataset_valid, dataloader_valid)
          291         accuracy_valid = 100. * predictions.eq(dataset_valid.dataset.targets[dataset_valid.indices].to(device)).sum().float() / len(dataset_valid)
          292 
      
       in test(dataset, dataloader)
          236                     print("Predicted Label")
          237                     print(predictions[sampleno])
      --> 238                     showimages(inputs[sampleno].cpu())
          239             return predictions
          240 
      
       in showimages(model)
          240 
          241 def showimages(model):
      --> 242     model=np.transpose(model.numpy(),(1,2,0))
          243 
          244     
      
      <__array_function__ internals> in transpose(*args, **kwargs)
      
      ~/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py in transpose(a, axes)
          649 
          650     """
      --> 651     return _wrapfunc(a, 'transpose', axes)
          652 
          653 
      
      ~/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
           59 
           60     try:
      ---> 61         return bound(*args, **kwds)
           62     except TypeError:
           63         # A TypeError occurs if the object does have such a method in its
      
      ValueError: axes don't match array
      

      【讨论】:

      • 您的input input[sampleno] 的大小是多少?
      • torch.Size([5000, 784]) 和 torch.Size([784])。问题是这是灰度的,而你使用的是 RGB(我认为)
      • Ow 好的,我为 3D 数组(RGB 图像)做了这个,但在你的情况下,输入是一个向量,我修改了我的答案。我想这次它会起作用
      • 快完成了,我在 plt.imshow 上遇到了无效形状 (1, 28, 28) 的错误(我不得不使用它,因为我在 Debian 上遇到了 OpenCV 问题)
      • 在使用plt.inshow之前使用np.squeeze()函数
      猜你喜欢
      • 2020-07-20
      • 2020-05-23
      • 1970-01-01
      • 2019-08-06
      • 2015-07-28
      • 2019-05-06
      • 2021-12-11
      • 2021-04-08
      • 1970-01-01
      相关资源
      最近更新 更多