关于Keras猫狗分类教程的疑问:Image Generator如何识别标签?
Hey there! Let's break down how Keras' ImageGenerator figures out those cat and dog labels—it's a clever folder structure trick that makes labeling totally automatic, no manual tagging required.
The Key: Folder Names = Labels
First, let's recap the folder structure the tutorial uses (this is the critical piece):
training/ ├─ cats/ │ ├─ cat001.jpg │ ├─ cat002.jpg │ └─ ... └─ dogs/ ├─ dog001.jpg ├─ dog002.jpg └─ ...
The exact same structure applies to the validation/ directory too.
How flow_from_directory Does the Magic
When you use train_datagen.flow_from_directory() (the method the tutorial uses to load data), here's what happens under the hood:
- It scans the root directory you specify (like
'training'). - It looks for direct subfolders of that root directory—each subfolder name becomes a class label.
- Every image inside the
cats/subfolder gets automatically tagged with thecatslabel; every image indogs/gets thedogslabel.
Let's tie this to the code snippet from the tutorial (expanded to show the key part):
# Training data generator setup train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # Load training data from directory train_generator = train_datagen.flow_from_directory( 'training', # Root directory for training images target_size=(150, 150), # Resize all images to this size batch_size=32, class_mode='binary' # Since we have 2 classes (cat/dog) )
- The
class_mode='binary'parameter tells Keras to convert the two labels into a binary format (0 and 1). By default, Keras assigns labels based on alphabetical order of the subfolder names. Socats(comes beforedogsalphabetically) becomes0, anddogsbecomes1. - You can verify this by printing
train_generator.class_indices—it will output{'cats': 0, 'dogs': 1}.
Extra Notes to Keep in Mind
- No manual labels needed: You don't have to create CSV files or add labels to filenames—just organize your images into subfolders named after their classes.
- Multi-class support: If you were working with more than two classes (e.g., cats, dogs, birds), you'd just add a
birds/subfolder, setclass_mode='categorical', and Keras would handle one-hot encoded labels automatically. - Validation set consistency: The
validationdirectory uses the exact same structure, so the validation generator will recognize labels the same way—this ensures your model evaluates on correctly labeled validation data.
Does that make sense now? If you have any follow-up questions about how this interacts with model training or data augmentation, feel free to ask!
内容的提问来源于stack exchange,提问作者vidit02100

