How to display incorrect samples predicted by the model?

I have written a snipet that should output 10 images that were misclassified by my model.

fig = plt.figure(figsize=(20, 8))

for idx in np.arange(10):
    ax = fig.add_subplot(2, 10/2, idx+1, xticks=[], yticks=[])
    #std = np.array([0.229, 0.224, 0.225])
    #mean = np.array([0.485, 0.456, 0.406])
    img = incorrect_examples[idx][idx]
    img = img/2 + 0.5
    img = np.clip(img, 0, 1)
    ax.imshow(img)
    ax.set_title(f"{classes[pred[idx]]}: x%\n (label: {classes[target[idx]]})",
                 color=("green" if pred[idx] == target[idx].item() else "red"))

I get the following error:

---> 10     ax.imshow(img)
     11     ax.set_title(f"{classes[pred[idx]]}: x%\n (label: {classes[target[idx]]})",
     12                  color=("green" if pred[idx] == target[idx].item() else "red"))

4 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py in set_data(self, A)
    697                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
    698             raise TypeError("Invalid shape {} for image data"
--> 699                             .format(self._A.shape))
    700 
    701         if self._A.ndim == 3:

TypeError: Invalid shape (1, 3, 224, 224) for image data
1 Like

That first dimension should be squeezed out as an image should have 3 dimensions: number of channels, height, and width. (i.e. (3, 224, 224)).

Try img = img.squeeze() before calling ax.imshow(img)

Tried it. I get this:

img = incorrect_examples[0][idx]
----> 9     img = img.squeeze(0)
     10     img = img/2 + 0.5
     11     img = np.clip(img, 0, 1)

ValueError: cannot select an axis to squeeze out which has size not equal to one
1 Like

What’s the shape? print(img.shape)

Ideally you want something like this:
image

Okay thanks I got rid of the problem.

1 Like

But I still cant get the images to be disp[layed in group. Can you provide me with a boiler code that will help me display 10 images.
The incorrect_examples is a (list) array of images which can be accessed by incorrect_examples[0][idx]

1 Like

Be sure to mark the correct answer in case others run into this too!

If you have a list of image tensors you can use this handy util from torchvision: torchvision.utils.make_grid torchvision.utils — Torchvision 0.10.0 documentation (pytorch.org).

It takes in a list of image tensors and makes a nice grid of images for you, one of the most convienent utils I’ve used for displaying multiple images.

Here’s an example:

1 Like

Cool, I will check it out. Thank you.

1 Like