How to run prediction with a pretrained Keras application model

Pretrained Keras Applications models are ready-made image classifiers with weights trained on ImageNet. Running one inference pass confirms that image loading, preprocessing, backend selection, and decoded output line up before adding custom data or serving code.

MobileNetV2 keeps the smoke test small while using the same Keras Applications pattern as larger models. A local image is resized to the model input size, converted to a NumPy batch, processed with the matching mobilenet_v2.preprocess_input() helper, and passed to model.predict().

Decoded class names come from the ImageNet classifier head. They are meaningful only when the model is loaded with weights=“imagenet” and include_top=True, so feature-extraction or custom-head models should check tensor shapes or custom labels instead of calling decode_predictions().

Steps to run prediction with a pretrained Keras application model:

  1. Save one RGB photo as sample.jpg beside the script.

    Use a real photo of an object or scene for readable class names. Generated or abstract images can still prove the tensor path, but the decoded labels may not describe the image well.

  2. Create predict_mobilenet.py with the MobileNetV2 model, preprocessing helper, and decoder.
    import os
    import sys
     
    os.environ.setdefault("KERAS_BACKEND", "tensorflow")
     
    import numpy as np
    import keras
    from keras.applications.mobilenet_v2 import (
        MobileNetV2,
        decode_predictions,
        preprocess_input,
    )
     
    image_path = sys.argv[1] if len(sys.argv) > 1 else "sample.jpg"
     
    model = MobileNetV2(weights="imagenet")
    image = keras.utils.load_img(image_path, target_size=(224, 224))
    array = keras.utils.img_to_array(image)
    batch = np.expand_dims(array, axis=0)
    inputs = preprocess_input(batch.copy())
    predictions = model.predict(inputs, verbose=0)
     
    print(f"image array shape: {array.shape}")
    print(f"model input shape: {inputs.shape}")
    print(f"prediction shape: {predictions.shape}")
     
    top_predictions = decode_predictions(predictions, top=3)[0]
    for rank, (_, label, score) in enumerate(top_predictions, start=1):
        print(f"{rank}. {label}: {score:.3f}")

    KERAS_BACKEND must be selected before importing keras. The script uses setdefault() so a shell-level backend choice can still override it.

  3. Run the script against the image.
    $ python predict_mobilenet.py sample.jpg
    image array shape: (224, 224, 3)
    model input shape: (1, 224, 224, 3)
    prediction shape: (1, 1000)
    1. African_elephant: 0.849
    2. tusker: 0.037
    3. Indian_elephant: 0.009

    The first run downloads the MobileNetV2 ImageNet weights into the Keras model cache. Scores change with the input image; the shown transcript used an elephant photo.

  4. Confirm that the output includes a one-image batch, a 1000-class prediction vector, and decoded class rows.

    decode_predictions() expects ImageNet classifier output. If include_top=False or a custom classifier head is used, verify the tensor shape and map class indices with the labels from that model.