ImageDataGenerator
Keras
deep learning
image prediction
machine learning

Predicting a single image with Keras' ImageDataGenerator

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

Introduction

Single image inference in Keras looks simple, but accuracy depends on preprocessing consistency more than model call syntax. Most incorrect predictions come from wrong shape, wrong normalization, or wrong label mapping. ImageDataGenerator can be used for one image, but direct preprocessing is often clearer for production inference.

Match Training Preprocessing Exactly

Before writing inference code, confirm what preprocessing was used during training:

  • image size
  • color mode
  • scaling strategy
  • model specific preprocessing function

If training used rescale=1.0/255.0, do the same in inference. If training used an application specific function such as preprocess_input, reuse that exact function.

Direct Single Image Prediction Pattern

For one image, direct array preparation is explicit and easy to debug.

python
1import numpy as np
2import tensorflow as tf
3from tensorflow.keras.preprocessing import image
4
5model = tf.keras.models.load_model("model.h5")
6
7img = image.load_img("sample.jpg", target_size=(224, 224), color_mode="rgb")
8arr = image.img_to_array(img).astype("float32") / 255.0
9arr = np.expand_dims(arr, axis=0)
10
11pred = model.predict(arr)
12print(pred)

The batch dimension is required, even for one sample.

Using ImageDataGenerator for One Image

You can still use ImageDataGenerator if you want parity with an existing generator pipeline.

python
1import numpy as np
2from tensorflow.keras.preprocessing import image
3from tensorflow.keras.preprocessing.image import ImageDataGenerator
4
5img = image.load_img("sample.jpg", target_size=(224, 224))
6arr = image.img_to_array(img)
7arr = np.expand_dims(arr, axis=0)
8
9datagen = ImageDataGenerator(rescale=1.0/255.0)
10flow = datagen.flow(arr, batch_size=1, shuffle=False)
11
12pred = model.predict(flow, steps=1)
13print(pred)

For strict single image use cases, direct array code is usually easier to reason about. Generators shine more when processing many images.

Convert Model Output to Human Labels

Prediction array interpretation depends on the final activation.

Softmax multi class example:

python
1import numpy as np
2
3class_names = ["cat", "dog", "horse"]
4probs = model.predict(arr)[0]
5idx = int(np.argmax(probs))
6print("label:", class_names[idx])
7print("confidence:", float(probs[idx]))

Sigmoid binary example:

python
score = float(model.predict(arr)[0][0])
label = "positive" if score >= 0.5 else "negative"
print(label, score)

Wrong output interpretation can look like a model bug even when the model is fine.

Build a Reusable Inference Helper

A helper function prevents subtle preprocessing drift between scripts and services.

python
1import numpy as np
2from tensorflow.keras.preprocessing import image
3
4def prepare_image(path, size=(224, 224)):
5    img = image.load_img(path, target_size=size, color_mode="rgb")
6    arr = image.img_to_array(img).astype("float32") / 255.0
7    return np.expand_dims(arr, axis=0)
8
9x = prepare_image("sample.jpg")
10pred = model.predict(x)

Keep helper versioned with the model artifact. If model preprocessing changes, update helper and bump model metadata together.

Evaluate Confidence and Top Candidates

Top one prediction is often not enough for diagnostics. Inspect top three probabilities to understand uncertainty.

python
1probs = model.predict(arr)[0]
2indices = np.argsort(probs)[::-1][:3]
3for i in indices:
4    print(i, float(probs[i]))

For user facing features, define confidence thresholds. Low confidence results may need fallback behavior or manual review.

Common Pitfalls

A common mistake is forgetting np.expand_dims, which causes shape mismatch at runtime.

Another frequent issue is preprocessing mismatch. Using divide by 255 during inference when training used model specific preprocess_input can significantly reduce accuracy.

Teams also accidentally keep augmentation enabled during inference when reusing a training generator configuration. Augmentation should be disabled for deterministic prediction.

Finally, class index mapping can drift. Save label order from training and load that mapping for inference.

Summary

  • Single image prediction works best when preprocessing matches training exactly.
  • 'ImageDataGenerator can handle one image, but direct array preprocessing is simpler.'
  • Always include batch dimension before calling model.predict.
  • Interpret outputs according to final activation and saved class mapping.
  • Most inference errors are data pipeline mismatches, not model architecture issues.

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
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
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