You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试Keras CNN图像分类模型?鸡与自然场景二分类模型全误判问题求助

Troubleshooting Your Keras Image Classification Issue & Learning Resources

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 the image module you imported (from keras.preprocessing.image). This can cause unexpected errors later on.
  • The np.vstack([X]) line is unnecessary—np.expand_dims already 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 the target_size you used in flow_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_dims to 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). MaxPool2D reduces 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).
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:22:39