Sub topic 14
Analyzing errors and improving your data
This chapter assumes you have a trained classifier and a validation loader built with shuffle=False from ImageFolder, as in the earlier chapters. It also assumes you know what a confusion matrix is. The code below uses model, val_ds, val_loader, and device from those chapters.
Why errors beat more tuning
After the first fine-tuning run, a validation accuracy such as 91% tells you how often the model is wrong. It does not tell you why. Changing the learning rate or the architecture is a guess. Reading the mistakes is evidence.
In small custom datasets, many errors come from the data, not the model. Typical causes are wrong labels, near-identical classes, or training images that look unlike real use. Fixing these usually gains more than another hyperparameter search.
The working loop has four steps:
- Collect predictions for every held-out image.
- Find where the errors cluster, by class pair and by confidence.
- Look at the actual images and name the cause.
- Change the data, or the training setup, to match the cause.
Collect predictions with file paths
Keep the file path next to every prediction. Without it you cannot open the image that was misclassified. ImageFolder stores (path, class_index) pairs in .samples, and with shuffle=False the loader visits them in that order.
import torch
def collect_probs(model, loader, device):
model.eval()
chunks = []
with torch.inference_mode():
for images, _ in loader:
logits = model(images.to(device))
chunks.append(logits.softmax(dim=1).cpu())
return torch.cat(chunks)
probs = collect_probs(model, val_loader, device)
labels = torch.tensor(val_ds.targets)
confidence, preds = probs.max(dim=1)
paths = [path for path, _ in val_ds.samples]
assert len(paths) == len(labels) == len(preds)
print(f"accuracy: {(preds == labels).float().mean().item():.3f}")The assert guards against a mismatch between paths and predictions. If someone later turns on shuffling or drops the last batch, the paths no longer line up with the predictions. You would then be inspecting the wrong images without noticing.
Confusion matrix and per-class recall
A confusion matrix has one row per true class and one column per predicted class. Large numbers off the diagonal show which classes the model mixes up.
classes = val_ds.classes
n = len(classes)
cm = torch.bincount(labels * n + preds, minlength=n * n).view(n, n)
recall = cm.diag().float() / cm.sum(dim=1).clamp(min=1)
for name, r in zip(classes, recall):
print(f"{name:20s} recall {r.item():.3f}")
off_diag = cm.clone()
off_diag.fill_diagonal_(0)
counts, flat_idx = off_diag.flatten().topk(min(5, n * n))
print("\nMost confused (true -> predicted):")
for count, idx in zip(counts, flat_idx):
if count.item() == 0:
break
t, p = divmod(idx.item(), n)
print(f"{classes[t]} -> {classes[p]}: {count.item()}")Read the output in two ways:
- Per-class recall. A class with low recall is either hard, underrepresented, or poorly labeled. Compare it with how many training images it has.
- Asymmetric pairs. If many
huskyimages are calledwolfbut fewwolfimages are calledhusky, the model has learnedwolfas a broad class. That points to class balance or an overly generic class.
Treat small counts with care. With 10 validation images in a class, one mistake moves recall by 10 points.
Look at the confident errors first
Sort the wrong predictions by confidence. A wrong prediction made with 0.98 confidence is more informative than a wrong one made with 0.40. The first is often a label error or a real overlap between classes. The second is usually just a hard image.
wrong = (preds != labels).nonzero().squeeze(1)
order = confidence[wrong].argsort(descending=True)
worst = wrong[order][:20]
print(f"{len(wrong)} errors. Most confident first:")
for i in worst.tolist():
print(
f"{confidence[i].item():.2f} true={classes[labels[i]]:12s} "
f"pred={classes[preds[i]]:12s} {paths[i]}"
)Open the listed files and look at them. A contact sheet is faster than opening files one at a time:
import matplotlib.pyplot as plt
from PIL import Image
def show_errors(indices, cols=5):
rows = (len(indices) + cols - 1) // cols
fig, axes = plt.subplots(rows, cols, figsize=(3 * cols, 3.4 * rows))
axes = axes.flatten() if rows * cols > 1 else [axes]
for ax in axes:
ax.axis("off")
for ax, i in zip(axes, indices):
ax.imshow(Image.open(paths[i]).convert("RGB"))
ax.set_title(
f"true: {classes[labels[i]]}\npred: {classes[preds[i]]} "
f"({confidence[i]:.2f})",
fontsize=8,
)
plt.tight_layout()
plt.savefig("errors.png", dpi=120)
show_errors(worst.tolist()[:15])Name the cause
Go through the images and tag each one with a cause. A spreadsheet or a plain text file with path and tag is enough. After 30 to 50 images, a pattern usually appears.
| What you see | Likely cause | Typical fix |
|---|---|---|
| The model is right and the label is wrong | Label noise | Correct the label in the folder structure |
| The image contains two classes, or none | Ambiguous image | Remove it, or define a rule for such images |
| Two classes look the same to a human too | Overlapping class definitions | Merge the classes or write a clearer definition |
| One class has low recall and few training images | Too little data | Collect more images, or see the chapter on class imbalance |
| Errors share a background, lighting, or camera | Spurious cue | Add varied images, and strengthen augmentation |
| Validation images look unlike real-world photos | Distribution mismatch | Build the validation set from real deployment images |
| Near-identical images appear in train and validation | Leakage | Deduplicate, then re-split |
Label noise
Public and scraped datasets often have a few percent of wrong labels. If you find a confident error where the model is clearly right, fix the label. Do this in both training and validation data, since training noise hurts the model and validation noise distorts your measurement.
Spurious cues
A classifier can learn the background instead of the object. If all cow photos show grass and all boat photos show water, the model may use the background. The giveaway is that errors appear when the background changes. The fix is data: add cows on sand and boats on a trailer. Stronger augmentation on its own seldom removes a cue that is present in every image.
Leakage
Leakage means the same, or almost the same, image appears in both training and validation data. Common sources are burst photos, video frames, and the same product photographed several times. Validation accuracy is then too high, and the errors you see are not the model's real weak spots.
A cheap check is to hash the file contents and look for exact duplicates:
import hashlib
from collections import defaultdict
from pathlib import Path
def file_hash(path):
return hashlib.md5(Path(path).read_bytes()).hexdigest()
train_hashes = {file_hash(p) for p, _ in train_ds.samples}
dupes = [p for p, _ in val_ds.samples if file_hash(p) in train_hashes]
print(f"{len(dupes)} validation images are byte-identical to a training image")This finds only exact copies. Resized or re-compressed copies need perceptual hashing or an embedding-similarity search. For burst photos and video frames, split by source (the session, the video, or the product), not by individual image.
Apply fixes in a sensible order
- Fix labels and remove leakage first. These change what you are measuring, so any other change is hard to judge before they are fixed.
- Fix class definitions. Merging or sharpening classes costs nothing.
- Add data where recall is low. Target the classes and conditions you found, not the whole dataset. Fifty well-chosen images of the failing case often beat 500 random ones.
- Change training only for problems the data cannot explain. This includes stronger augmentation, a lower learning rate, or unfreezing more layers.
Change one thing per run and record the validation accuracy and per-class recall. If you change labels, add data, and alter augmentation at once, you cannot tell which change helped.
Common mistakes
- Shuffled validation loader. The paths no longer match predictions. Keep
shuffle=Falseand keep theassert. - Reading only accuracy. Overall accuracy hides a class with 40% recall when that class is small.
- Fixing labels in training only. The validation score then stays noisy, and you cannot see the improvement.
- Deleting hard images. Remove images that are wrong or ambiguous. Keep images that are merely difficult, or the score will look better than the model really is.
- Adding data from the validation distribution to training. Once an image goes into training, it can no longer be used for validation.
Exercise
Your validation accuracy is 94%. The confusion matrix shows that 12 of the 15 errors are sedan images predicted as coupe, and most of them have confidence above 0.95. You open them and find that 9 of the 12 are clearly coupes filed under sedan. What do you do, and what do you do next?
Show answer
The cause is label noise, not a model weakness. Move the 9 mislabeled images to the coupe folder. Also check whether similar mislabels exist in the training sedan folder, for example by listing the most confident sedan to coupe predictions on training images. For the 3 remaining errors, decide whether they are ambiguous (remove them or write a rule) or genuinely hard (keep them). Retrain, compare validation accuracy and per-class recall, and confirm the sedan/coupe confusion has shrunk. Do not change the learning rate or architecture first, since the evidence points to the data.