如何测试Keras CNN图像分类模型?鸡与自然场景二分类模型全误判问题求助
Hey there! Let's work through your problem step by step and clarify how Keras handles model inputs and layer logic.
First: Fixing the "All Predictions Are 'Chicken'" Issue
The most likely culprit here is inconsistent data preprocessing between your training and prediction workflows—this is a super common pitfall for new Keras users!
1. You Forgot to Normalize Test Images
During training, you used ImageDataGenerator(rescale=1/255) to scale pixel values from the raw 0-255 range down to 0-1. But in your prediction code, you skipped this critical step! Your model was trained on normalized data, so feeding unprocessed 0-255 pixel values will completely throw off its feature detection and predictions.
2. Minor Input Shape & Variable Name Bugs
- You reused the variable name
image, which overwrites theimagemodule you imported (fromkeras.preprocessing.image). This can cause unexpected errors later on. - The
np.vstack([X])line is unnecessary—np.expand_dimsalready adds the batch dimension your model expects, so you can use the array directly.
Corrected Prediction Code
from tensorflow.keras.preprocessing import image import numpy as np import glob # Load test image paths sample = glob.glob('./sample/**/*.jpg', recursive=True) img_path = sample[0] # Load and resize image to match model input size img = image.load_img(img_path, target_size=(200, 200)) # Convert to array AND normalize (this is the key fix!) img_array = image.img_to_array(img) / 255.0 # Add batch dimension (model expects shape: (batch_size, 200, 200, 3)) img_array = np.expand_dims(img_array, axis=0) # Run prediction and interpret result prediction = model.predict(img_array) if prediction[0] > 0.5: print("Predicted: Chicken") else: print("Predicted: Natural Scene")
Understanding Keras Model Layers & Input Logic
Let’s break down your model’s structure and how inputs map to each layer:
Input Shape Basics
Your first layer defines input_shape=(200,200,3):
200,200: Height and width of your images (matches thetarget_sizeyou used inflow_from_directory)3: Number of color channels (RGB)- Keras always expects inputs to include a batch dimension (even for a single image). That’s why we use
np.expand_dimsto add an extra axis, resulting in a shape like(1, 200, 200, 3)(1 image in the batch).
Layer Breakdown
- Conv2D + MaxPool2D: These layers extract hierarchical image features (edges, textures, complex shapes).
MaxPool2Dreduces spatial dimensions to lower computation and prevent overfitting. - Flatten: Converts the 3D feature maps from convolution layers into a 1D array that can feed into fully connected dense layers.
- Dense Layers: The final
Dense(1, activation='sigmoid')outputs a value between 0 and 1, perfect for binary classification (0 = natural scene, 1 = chicken, based on your training setup).
Recommended Learning Resources (No External Links Needed!)
- Keras Official Docs - Model Basics: This section walks through Sequential models, layer types, and input shape requirements in plain language. It’s the best starting point for understanding how layers work together.
- Keras Official Docs - Image Preprocessing: Covers data generators, normalization, and how to ensure consistency between training and inference—exactly what you need to avoid preprocessing mismatches.
- Keras Binary Classification Tutorials: The official image classification examples (like the cats vs dogs tutorial) mirror your use case. They explain the end-to-end workflow, including training, validation, and prediction with proper preprocessing.
Additional Checks to Rule Out Other Issues
After fixing preprocessing, if predictions are still off:
- Verify your training/validation/test datasets are properly split with no overlap, and that each set has a representative mix of classes.
- Check for overfitting: If training accuracy is much higher than validation accuracy, you might need more training data, dropout layers, or data augmentation (using
ImageDataGenerator’s rotation/zoom features).
内容的提问来源于stack exchange,提问作者swordlordswamplord

