Machine Learning
Image Processing
Model Prediction
Neural Networks
Computer Vision

How to run prediction using image as input for a saved model?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Running prediction on a SavedModel with image input requires consistent preprocessing, shape management, and signature usage. Most runtime errors come from mismatch between model’s expected tensor shape/dtype and actual image pipeline output.

Core Sections

1) Load SavedModel and inspect signature

python
1import tensorflow as tf
2
3model = tf.saved_model.load("./saved_model")
4print(model.signatures.keys())
5infer = model.signatures["serving_default"]
6print(infer.structured_input_signature)

Always inspect signature before building inference wrapper.

2) Decode and preprocess image

python
1img_bytes = tf.io.read_file("cat.jpg")
2img = tf.image.decode_jpeg(img_bytes, channels=3)
3img = tf.image.resize(img, [224, 224])
4img = tf.cast(img, tf.float32) / 255.0
5img = tf.expand_dims(img, axis=0)  # batch dimension

3) Run inference

python
outputs = infer(input_1=img)  # key name must match signature
print(outputs)

If key differs, adapt call to actual signature input key.

4) Postprocess predictions

python
probs = tf.nn.softmax(outputs["logits"], axis=-1)
class_id = tf.argmax(probs, axis=-1).numpy()[0]

Ensure output key names ("logits", etc.) match model export.

Validation and Deployment Readiness

After applying the solution in this topic, use a repeatable verification sequence so fixes remain stable across environments and future refactors. The most reliable pattern is: reproduce baseline behavior, apply one focused change, then re-run the same checks and compare outputs. This avoids false confidence from incidental improvements.

A compact verification loop:

bash
1# 1) baseline capture
2./run_case.sh > before.txt
3
4# 2) apply targeted fix from this guide
5# keep the diff focused and minimal
6
7# 3) verify and compare
8./run_case.sh > after.txt
9diff -u before.txt after.txt

If your repository includes automated tests, convert the reproduced issue into a regression test immediately. This transforms one-time troubleshooting into long-term protection and catches behavior drift early during upgrades.

bash
1# example quality gates
2./lint.sh
3./test.sh
4./smoke.sh

Run at least one edge-case pass in addition to nominal-path checks. Real-world failures often appear on boundary inputs: empty payloads, null values, large datasets, malformed encodings, unusual locale/timezone settings, or high-concurrency requests. Document expected behavior for those edge cases so reviewers and on-call engineers can reproduce outcomes quickly.

Validate environment parity before rollout. A fix that succeeds locally can fail in staging/production due to version mismatches, architecture differences, network policies, or filesystem semantics. Capture runtime/tool metadata alongside test evidence.

bash
1python --version
2node --version
3java -version
4git rev-parse --short HEAD

Define rollback criteria before deployment. Identify which metrics/logs indicate success or regression, and document the rollback command path. This operational discipline reduces incident duration and prevents repeated firefighting for the same class of issue.

Finally, isolate behavior changes from unrelated formatting or dependency churn. Smaller, focused commits are easier to review, bisect, and revert safely. If normalization or tooling updates are required, ship them separately to keep risk controlled.

Common Pitfalls

  • Ignoring signature input names and passing wrong keyword argument.
  • Missing batch dimension for single-image inference.
  • Feeding uint8 tensors when model expects normalized floats.
  • Using wrong resize/crop preprocessing compared to training pipeline.
  • Misreading output tensor keys without signature inspection.

Summary

Image prediction with a SavedModel is reliable when signature inspection and preprocessing are explicit. Match input key, shape, dtype, and normalization exactly to training expectations. Most failures are pipeline mismatches, not model corruption.

A practical long-term safeguard is to keep one regression test for the core behavior and one edge-case test for boundary inputs (empty values, malformed payloads, or large datasets). Run both in CI on every dependency/runtime upgrade. This catches compatibility drift early and prevents repeated production incidents that otherwise look unrelated. When possible, attach a short runbook entry with exact verification commands so teammates can reproduce outcomes quickly during troubleshooting.

Include this check in your release checklist and rerun it after any library/runtime upgrade. A small, repeatable smoke test here usually prevents subtle regressions that are expensive to diagnose later in production.


Course illustration
Course illustration

All Rights Reserved.