如何使用Keras与Python加载、展示猫狗数据集图像及解决路径查询空列表问题
Hey there! Let's fix that empty list issue first, then walk through how to load and display the cat/dog images properly.
1. Why cats = list(train_dir.glob('cats/*')) returns an empty list?
The problem boils down to incorrect path hierarchy plus a tiny typo:
- The
cats_and_dogs_filtered.zipyou downloaded unzips into a root folder namedcats_and_dogs_filtered, which contains the actualtrainandvalidationsubfolders inside it. - In your code,
tf.keras.utils.get_filereturns the path to the extracted outer folder (like/root/.keras/datasets/cats_and_dogs_filterted), but you're looking fortraindirectly under this path—when in reality,trainlives one level deeper inside the innercats_and_dogs_filteredfolder. - Also, you misspelled the dataset name: the original is
cats_and_dogs_filtered(ends withr), but you usedcats_and_dogs_filterted(missing the finalr) inget_file, which adds to the path confusion.
Here's the fixed code:
import tensorflow as tf import pathlib import os # Fix the filename spelling to match the original dataset _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' data_dir = tf.keras.utils.get_file('cats_and_dogs_filtered', origin=_URL, extract=True) # Point to the actual dataset folder inside the extracted directory data_dir = pathlib.Path(data_dir).parent / 'cats_and_dogs_filtered' train_dir = data_dir / 'train' validation_dir = data_dir / 'validation' # Test if we can find cat images now cats = list(train_dir.glob('cats/*')) print(len(cats)) # Should output 1000—success!
Alternatively, you can dynamically find the inner folder using glob:
data_dir = pathlib.Path(data_dir) data_dir = next(data_dir.glob('cats_and_dogs_filtered'))
2. Loading and displaying cat/dog images with Keras & Python
Let's cover two common methods: loading a single image directly, and using Keras's ImageDataGenerator to batch-load and visualize the dataset.
Method 1: Load and display a single image
We'll use PIL and matplotlib for this—super straightforward:
import matplotlib.pyplot as plt from PIL import Image # Grab the first cat image path cat_img_path = cats[0] img = Image.open(cat_img_path) # Show the image plt.figure(figsize=(8, 8)) plt.imshow(img) plt.title('A Cute Cat!') plt.axis('off') # Hide axes for cleaner look plt.show()
Method 2: Batch-load and display images with ImageDataGenerator
ImageDataGenerator is Keras's go-to tool for handling image datasets—it handles resizing, scaling, and even data augmentation. Here's how to use it:
from tensorflow.keras.preprocessing.image import ImageDataGenerator # Initialize the generator (we'll scale pixel values to 0-1 first) train_datagen = ImageDataGenerator(rescale=1./255) # Load training data from the directory train_generator = train_datagen.flow_from_directory( train_dir, target_size=(150, 150), # Resize all images to 150x150 batch_size=32, class_mode='binary' # Binary classification (cat vs dog) ) # Get one batch of images and their labels images, labels = next(train_generator) # Display the first 9 images in the batch plt.figure(figsize=(10, 10)) for i in range(9): plt.subplot(3, 3, i+1) plt.imshow(images[i]) # Label based on the generator's class order (0 = cat, 1 = dog, alphabetical) plt.title('Cat' if labels[i] == 0 else 'Dog') plt.axis('off') plt.show()
Quick note: flow_from_directory automatically assigns labels based on subfolder names, sorted alphabetically—so cats gets label 0, dogs gets label 1.
Bonus: Add data augmentation (for better model training)
If you want to augment your data to improve model generalization, just tweak the ImageDataGenerator setup:
train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, # Rotate images up to 40 degrees width_shift_range=0.2, # Shift horizontally by 20% of width height_shift_range=0.2, # Shift vertically by 20% of height shear_range=0.2, # Shear transformation zoom_range=0.2, # Zoom in/out by 20% horizontal_flip=True, # Flip images horizontally fill_mode='nearest' # Fill in missing pixels after transformation )
For larger datasets, you can also use tf.data.Dataset (available in TensorFlow 2.4+) for faster loading and more control.
内容的提问来源于stack exchange,提问作者Osama Mohammed

