Keras
deep learning
image prediction
machine learning
neural networks

How to predict input image using trained model in Keras?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Predicting Input Image Using a Trained Model in Keras

Keras is a powerful and easy-to-use library for building, training, and evaluating deep learning models. Once you have trained a model, predicting the class or label of new input images is an essential step for utilizing your model in practical applications. This article will guide you through the technical details of using a trained Keras model to predict input images.

Prerequisites

To get started, you need the following:

  1. A trained Keras model, saved in either HDF5 format or using TensorFlow's SavedModel format.
  2. The Keras library installed in your Python environment.
  3. Additional libraries such as NumPy and PIL (or OpenCV) for handling and preprocessing images.

Loading a Trained Model

Keras provides straightforward methods to load a model from disk. The following example demonstrates loading a model that has been saved using Keras's model.save() function:

python
from tensorflow.keras.models import load_model

model = load_model('path/to/your_model.h5')

If your model was stored using the SavedModel format, the process remains the same since load_model() supports both formats.

Preprocessing Input Image

Before making predictions, input images must be preprocessed to match the input format expected by your model. Important preprocessing steps typically include:

  • Resizing the image to the input shape of your model.
  • Scaling pixel values (commonly to the range [0, 1]).
  • Converting the image into a NumPy array and adding an additional dimension to represent batch size.

Here's an example that uses the PIL library for image preprocessing:

python
1from PIL import Image
2import numpy as np
3
4def preprocess_image(image_path, target_size):
5    # Load the image using PIL
6    img = Image.open(image_path).convert('RGB')
7    # Resize the image
8    img = img.resize(target_size)
9    # Convert image to a NumPy array
10    img_array = np.array(img)
11    # Scale pixel values
12    img_array = img_array / 255.0
13    # Add batch dimension
14    img_array = np.expand_dims(img_array, axis=0)
15    return img_array
16
17preprocessed_image = preprocess_image('path/to/image.jpg', model.input_shape[1:3])

Making Predictions

Once the image is preprocessed, it is fed into the model to make predictions. Keras's predict() method is used to obtain predictions. The output will differ based on whether your model is a regression model or a classifier.

python
1predictions = model.predict(preprocessed_image)
2
3# For a classification task
4predicted_class = np.argmax(predictions, axis=1)  # Get the index of the highest probability class

Visualization of Prediction Results

For classification tasks, it is helpful to map predicted indices to their corresponding class labels for interpretation. Here's a simple example of how you might convert a class index to a human-readable label:

python
class_labels = ['cat', 'dog', 'bird']  # Example label list
predicted_label = class_labels[predicted_class[0]]
print(f"Predicted class: {predicted_label}")

Summary

Here's a concise summary of the key steps for predicting input images with a trained Keras model:

StepDescription
Load ModelUse load_model() to load the trained model from disk.
Preprocess ImageResize, scale, and convert image to NumPy array. Add batch dimension.
Make PredictionsUse the predict() method to obtain predictions.
Interpret ResultsMap predicted indices to class labels (for classifiers).

Additional Considerations

  • Batch Processing: If you have multiple images, you can preprocess them all together and pass them as a batch to the predict() method for efficient computation.
  • Custom Layers and Objects: When loading models with custom objects, use the custom_objects parameter of load_model() to define any layers or functions used during training.
  • Optimizations: Leveraging hardware acceleration (e.g., GPUs) can considerably speed up the prediction process.

With these guidelines, you should be well-equipped to utilize your trained Keras models for practical image classification or prediction tasks. Happy coding!


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.