如何用Keras在Python中测试已训练ConvNet并预测自定义图片?
Got it, let's walk through exactly how to test your custom image like mycat.jpg with your trained Keras model—this is such a common step that tutorials often skip over, so I totally get why you're asking!
The key here is to match the preprocessing you used during training—your model expects input data in the exact same format as the images it was trained on. Here's a step-by-step guide with code:
Step 1: Prep Your Image (Critical!)
First, you need to load your image and transform it to match the input shape your model was trained on (e.g., if you used 150x150 images during training, you need to resize your cat pic to that size). You also need to apply the same scaling (like rescale=1./255) that you used in your ImageDataGenerator.
Here's the code for this:
from tensorflow.keras.preprocessing.image import load_img, img_to_array import numpy as np # Load the image and resize it to your model's input dimensions img = load_img('mycat.jpg', target_size=(150, 150)) # Replace (150,150) with your model's input size # Convert the image to a numpy array img_array = img_to_array(img) # Apply the same scaling as your training data (e.g., divide by 255) img_array = img_array / 255.0 # Add a batch dimension—Keras models expect input in shape (batch_size, height, width, channels) img_batch = np.expand_dims(img_array, axis=0)
Step 2: Load Your Trained Model
If your model isn't already loaded in memory, load it using:
from tensorflow.keras.models import load_model model = load_model('your_trained_model.h5') # Replace with your model's filename
Step 3: Run the Prediction
Now you can use model.predict() just like you tried—this will return an array of probabilities for each class your model was trained on:
predictions = model.predict(img_batch)
For example, if you trained a binary classifier (cat vs dog), predictions might look like [[0.03, 0.97]]—meaning 3% chance it's a cat, 97% chance it's a dog. For multi-class classification, you'll get a probability for each category.
Step 4: Map Predictions to Class Names
To make the output readable, you need to link the predicted indices back to actual class names. The easiest way is to save the class mapping from your training generator when you trained the model:
Save the class mapping during training:
# When you set up your training generator train_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( 'train_dir', target_size=(150, 150), class_mode='categorical' ) # Save the class indices to a file import json with open('class_indices.json', 'w') as f: json.dump(train_generator.class_indices, f)
Load and use it during prediction:
# Load the class mapping with open('class_indices.json', 'r') as f: class_indices = json.load(f) # Reverse the mapping to get class names from indices class_names = {v: k for k, v in class_indices.items()} # Get the predicted class index (the one with the highest probability) predicted_index = np.argmax(predictions[0]) predicted_class = class_names[predicted_index] predicted_probability = predictions[0][predicted_index] print(f"This image is most likely a {predicted_class} with a probability of {predicted_probability:.2f}")
Quick Notes to Avoid Mistakes
- Match preprocessing exactly: If you used other augmentations during training (like rotation, zoom), you don't apply those during prediction—only the scaling and resizing.
- Color channels: Make sure your image uses the same color space as training (e.g., RGB—
load_imguses RGB by default, which matches most Keras preprocessing). - Input shape: Double-check that your resized image matches the input shape of your model's first layer (e.g., if your model starts with
Conv2D(32, (3,3), input_shape=(150,150,3)), your image must be 150x150 with 3 channels).
内容的提问来源于stack exchange,提问作者Kegan.rodhe

