Image Classification
Keras
TensorFlow
Misclassified Images
Machine Learning

Image classification with Keras on Tensorflow how to find which images are misclassified during training?

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

Tracking misclassified images during training is one of the fastest ways to improve image models. Aggregate metrics such as accuracy hide class-specific errors and labeling issues. A practical workflow records per-sample predictions, then saves and reviews mistakes each epoch or at checkpoints.

Collect Predictions and Compare with Ground Truth

After each epoch, run inference on a validation dataset and compare predicted class IDs with true labels. Store sample IDs or file paths so you can inspect exact failures.

python
1import numpy as np
2import tensorflow as tf
3
4
5def collect_misclassified(model, val_ds):
6    misclassified = []
7
8    for images, labels, paths in val_ds:
9        probs = model.predict(images, verbose=0)
10        preds = np.argmax(probs, axis=1)
11        labels_np = labels.numpy()
12
13        for i in range(len(preds)):
14            if preds[i] != labels_np[i]:
15                misclassified.append({
16                    "path": paths[i].numpy().decode("utf-8"),
17                    "true": int(labels_np[i]),
18                    "pred": int(preds[i]),
19                    "confidence": float(np.max(probs[i])),
20                })
21
22    return misclassified

This output can be serialized and reviewed after training or in dashboards.

Add a Keras Callback for Epoch-Level Reports

A callback lets you run this analysis automatically. Keep it lightweight to avoid large training slowdowns.

python
1import json
2from tensorflow import keras
3
4class MisclassificationLogger(keras.callbacks.Callback):
5    def __init__(self, val_ds, out_dir):
6        super().__init__()
7        self.val_ds = val_ds
8        self.out_dir = out_dir
9
10    def on_epoch_end(self, epoch, logs=None):
11        errors = collect_misclassified(self.model, self.val_ds)
12        out_path = f"{self.out_dir}/misclassified_epoch_{epoch + 1}.json"
13        with open(out_path, "w", encoding="utf-8") as f:
14            json.dump(errors, f, indent=2)
15        print(f"Saved {len(errors)} errors to {out_path}")

Use this callback only on validation data with fixed ordering so comparisons between epochs remain meaningful.

Visualize Mistakes to Find Systematic Patterns

Numerical logs are useful, but image grids make patterns obvious. Group errors by true class and predicted class to detect confusion clusters.

python
1import matplotlib.pyplot as plt
2from PIL import Image
3
4
5def show_errors(misclassified, n=9):
6    sample = misclassified[:n]
7    cols = 3
8    rows = (len(sample) + cols - 1) // cols
9
10    plt.figure(figsize=(10, 10))
11    for i, item in enumerate(sample, 1):
12        img = Image.open(item["path"]).convert("RGB")
13        plt.subplot(rows, cols, i)
14        plt.imshow(img)
15        plt.title(f"t={item['true']} p={item['pred']} c={item['confidence']:.2f}")
16        plt.axis("off")
17    plt.tight_layout()
18    plt.show()

Visual review often reveals data issues such as mislabeled files, poor crops, or class imbalance effects.

Turn Error Analysis into Iteration

Misclassification reports should feed concrete actions: relabel uncertain samples, add augmentations for weak classes, rebalance class weights, or collect targeted data. Keep a changelog linking each action to error-pattern evidence.

This process is more reliable than architecture changes made without error diagnostics.

Closing the Loop with Data and Training Updates

Misclassification logs are most valuable when they trigger concrete pipeline updates. Start by clustering mistakes by true class and predicted class to identify persistent confusion pairs. If one class is consistently confused with another, inspect image quality, annotation consistency, and augmentation coverage for both classes. Next, review confidence distribution for errors. High-confidence errors often indicate labeling issues or feature leakage, while low-confidence errors may indicate uncertain boundaries that need more representative data. Feed this analysis into targeted actions such as relabeling, class-balanced sampling, or specialized augmentations. After each change, compare confusion matrices and error galleries against the previous run. This disciplined loop turns misclassification tracking into measurable model improvement rather than passive logging.

python
1from collections import Counter
2
3def confusion_pairs(errors):
4    pairs = Counter((e["true"], e["pred"]) for e in errors)
5    return pairs.most_common(10)
6
7print(confusion_pairs([
8    {"true": 1, "pred": 2},
9    {"true": 1, "pred": 2},
10    {"true": 0, "pred": 1},
11]))

Common Pitfalls

  • Evaluating only aggregate metrics and skipping per-sample error analysis.
  • Logging errors without file paths, making later review difficult.
  • Comparing epoch outputs with shuffled validation datasets.
  • Saving too many high-resolution plots and slowing training significantly.

Summary

  • Capture per-sample predictions and mismatches on validation data.
  • Use callbacks for automatic epoch-level misclassification logs.
  • Visualize errors to identify systematic model weaknesses.
  • Convert error patterns into targeted data and training actions.
  • Keep validation order stable for meaningful longitudinal analysis.

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