Keras中datagen.flow_from_directory分类模式标签错误求助
flow_from_directory Hey there! I’ve run into this exact label mapping issue with Keras’ flow_from_directory before—let’s fix it together. The root problem here is almost certainly how Keras sorts your class folders by default.
The Core Issue
By default, flow_from_directory sorts class folders alphabetically, not numerically. For your folder names 0, 1, ..., 9, 10, ..., 23, alphabetical order would put 10 right after 1, 11 after 10, and so on—instead of following the numerical sequence you expect. That means your folder 10 would get mapped to label index 2 (instead of 10), throwing off all your label correspondences.
How to Fix It
Here are two straightforward solutions, with the first being the easiest and most reliable:
1. Force the Correct Class Order with the classes Parameter
Manually specify the exact order of your classes in the flow_from_directory call. This overrides the default alphabetical sorting and ensures your folders 0 to 23 map to labels 0 to 23 correctly.
Here’s your modified code:
datagen = ImageDataGenerator(rescale=1./255, fill_mode='nearest') train_data = datagen.flow_from_directory( 'training-images', class_mode='categorical', target_size=(32,32), classes=[str(i) for i in range(24)] # This forces the numerical order ) # Always verify the mapping works! print("Current class-to-label mapping:") print(train_data.class_indices)
After running this, check the printed class_indices—you should see {'0': 0, '1': 1, ..., '23': 23} if everything’s set up right.
2. Rename Folders for Alphabetical-Numerical Match
If you prefer not to modify code, rename your folders to have leading zeros (e.g., 00, 01, ..., 09, 10, ..., 23). This way, alphabetical sorting will match numerical sorting. This is less efficient if you have a lot of folders, but it works too.
Quick Check to Confirm
Before training, always run print(train_data.class_indices) to double-check that each folder name maps to the label index you expect. If you see any unexpected mappings (like '10': 2), you’ll know the sorting issue is still present.
Also, make sure your training-images directory only contains the 24 class folders (0 to 23)—no extra subfolders or files in the root, as those would be treated as additional classes and mess up your labels.
内容的提问来源于stack exchange,提问作者Hassan_mohammad

