'labels and the predictions of multiclass images images Index Error: list index out of range

I am training a CNN with an dataset of images that consists of 2410 RGB images and belongs to two categories, i.e., crops and another is grass. After training the CNN model, it achieved an accuracy for train of 100% and for testing an accuracy of 75%. In addition to this, when I tried to display several images of the dataset with their labels and the predictions, I got an error that is

IndexError: list index out of range

My code:

# Display some pictures of the dataset with their labels and the predictions
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(10, 10),
                        subplot_kw={'xticks': [], 'yticks': []})

for i, ax in enumerate(axes.flat):
    ax.imshow(plt.imread(test_df.Filepath.iloc[i]))
    ax.set_title(f"True: {test_df.Label.iloc[i]}\nPredicted: {pred[i]}")
plt.tight_layout()
plt.show()

Error:

IndexError                                Traceback (most recent call last)
<ipython-input-25-6ebcd93c2050> in <module>()
      5 for i, ax in enumerate(axes.flat):
      6     ax.imshow(plt.imread(image_df.Filepath.iloc[i]))
----> 7     ax.set_title(f"True: {image_df.Label.iloc[i]}\nPredicted: {pred[i]}")
      8 plt.tight_layout()
      9 plt.show()

IndexError: list index out of range

How can I resolve this problem.

Error Image



Solution 1:[1]

It's hard to say for sure what is going wrong in your script without some more information regarding image_df (i.e. what shape your data is). But as the error indicates, it seems that you're trying to access a list index that is not in the list (trying to get the nth element from a list with less than n elements). When enumerating through axes.flat, image_df.Label needs to have a size equal to or larger than axes.flat in order for image_df.Label.iloc[i] to be valid. To find out what is happening exactly, you should find out what sizes these lists have.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander de Ranitz