如何使用Keras基于训练好的MNIST模型进行预测?
Hey there! Awesome work getting your model trained and saved with solid accuracy—let’s break down exactly how to feed new handwritten digit images into it for predictions. Here’s a step-by-step guide with code:
Step 1: Load Your Saved Model
First, you’ll need to load the hand_written.h5 model you saved. Make sure you have the necessary Keras imports available:
from keras.models import load_model import numpy as np # Load the trained model model = load_model('hand_written.h5')
Step 2: Prepare Your New Input Data
Your model expects input data in the exact same format as the training data. That means following these rules:
- The image must be a 28x28 pixel grayscale image (no color channels)
- Pixel values need to be normalized to the range [0, 1] (divided by 255)
- The input shape should include a batch dimension (even for single images, Keras expects this)
Example: Preprocess a Numpy Array Image
Let’s say you have a numpy array new_digit representing your 28x28 grayscale image (pixel values from 0 to 255). Here’s how to format it:
# Normalize pixel values to [0,1] new_digit = new_digit.astype('float32') / 255 # Add the single color channel dimension (shape becomes (28,28,1)) new_digit = np.expand_dims(new_digit, axis=-1) # Add the batch dimension (shape becomes (1,28,28,1)) new_digit = np.expand_dims(new_digit, axis=0)
Example: Load and Preprocess an Image File
If you’re working with a PNG/JPG file, use PIL to resize and convert it to the right format:
from PIL import Image # Load image and convert to grayscale img = Image.open('my_handwritten_digit.png').convert('L') # Resize to match MNIST's 28x28 size img = img.resize((28, 28)) # Convert to numpy array new_digit = np.array(img) # Apply the same preprocessing steps new_digit = new_digit.astype('float32') / 255 new_digit = np.expand_dims(new_digit, axis=-1) new_digit = np.expand_dims(new_digit, axis=0)
Step 3: Run Prediction and Interpret Results
Once your data is preprocessed, use model.predict() to get the model’s output. The result will be a 1x10 array of probabilities (one for each digit 0-9). To get the predicted digit, take the index of the highest probability with np.argmax():
# Get prediction probabilities (verbose=0 hides unnecessary output) predictions = model.predict(new_digit, verbose=0) # Extract the predicted digit predicted_digit = np.argmax(predictions) print(f"Predicted Digit: {predicted_digit}") print(f"Probability for each digit: {predictions[0]}")
Quick Typo Note on Your Training Code
I spotted a tiny typo in your original code: x_tset=x_test.astype('float32') should be x_test=x_test.astype('float32'). It doesn’t affect your trained model since you normalized x_test correctly afterward, but just something to fix if you re-run training later!
内容的提问来源于stack exchange,提问作者Arjun

