'Attribute Error on predicting the image 'DirectoryIterator' object has no attribute 'Filepath'

I am working on a CNN architecture with an image RGB dataset that belongs to two categories, i.e., crops and another one is grass. However, I am concerned about predicting the output. I think the problem is in the file path and facing an error that is

AttributeError: 'DirectoryIterator' object has no attribute 'Filepath'

Hereby I am including the code:

image_dir = Path('../content/dataset')

# Get file paths and labels

filepaths = list(image_dir.glob(r'**/*.jpg'))

labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))
filepaths = pd.Series(filepaths, name='Filepath').astype(str)

labels = pd.Series(labels, name='Label')

# Concatenate file paths and labels

image_df = pd.concat([filepaths, labels], axis=1)

# Shuffle the DataFrame and reset an index

image_df = image_df.sample(frac=1).reset_index(drop = True)

# Show the result

image_df.head(10)

Output:

Filepath    Label
0   ../content/dataset/crops/33.jpg crops
1   ../content/dataset/crops/11.jpg crops
2   ../content/dataset/crops/34.jpg crops
3   ../content/dataset/crops/20.jpg crops
4   ../content/dataset/crops/25.jpg crops
5   ../content/dataset/crops/1.jpg  crops
6   ../content/dataset/crops/38.jpg crops
7   ../content/dataset/grass/1109.jpg grass
8   ../content/dataset/crops/35.jpg crops
9   ../content/dataset/crops/26.jpg crops

#prediction the model
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(10, 10),
                        subplot_kw={'xticks': [], 'yticks': []})
for i, ax in enumerate(axes.flat):
    if i>=len(pred):
        break
    ax.imshow(plt.imread(test_data.Filepath.iloc[i]))
    ax.set_title(f"True: {test_data.Label.iloc[i]}\nPredicted: {pred[i]}")
plt.tight_layout()
plt.show()

Error:

ttributeError                            Traceback (most recent call last)
<ipython-input-90-70cc2082165d> in <module>()
      4     if i>=len(pred):
      5         break
----> 6     ax.imshow(plt.imread(test_data.Filepath.iloc[i]))
      7     ax.set_title(f"True: {test_data.Label.iloc[i]}\nPredicted: {pred[i]}")
      8 plt.tight_layout()

AttributeError: 'DirectoryIterator' object has no attribute 'Filepath'


Sources

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

Source: Stack Overflow

Solution Source