Sub topic 11
Evaluating on held-out data
This chapter assumes you have a fine-tuned classifier and the val_tfms, train_ds, model, device and num_classes objects from the earlier chapters. It also assumes you know what accuracy is. You will learn to measure how well the model will do on images it has never seen, and to read the result for more than one number.
Why held-out data matters
Training accuracy measures memory as much as skill. A model that has seen an image dozens of times can label it correctly without learning anything that transfers. Only images the model has not trained on estimate real-world performance.
You need two held-out sets, and they do different jobs.
| Split | Used for | How often you look at it |
|---|---|---|
| Train | Updating weights | Every step |
| Validation | Choosing epochs, learning rates, augmentation, unfreezing depth | Many times |
| Test | One final, honest estimate | Once, at the end |
Every decision you make based on validation results leaks a little information from the validation set into your choices. After many rounds, validation accuracy is slightly optimistic. The test set is the check that has not been used to make any choice.
Evaluation setup
Evaluation must differ from training in three ways.
- Call
model.eval(). This switches off dropout and makes batch normalization use its stored running statistics instead of the current batch's statistics. Skipping it gives noisy, lower results. - Disable gradient tracking with
torch.inference_mode()ortorch.no_grad(). This saves memory and time. - Use the deterministic transform (
Resize,CenterCrop,Normalize), never the random augmentation. Random crops make results change from run to run and test the model on images unlike real inputs.
Also set shuffle=False. Shuffling does not corrupt predictions if you collect labels and predictions in the same loop, but a fixed order makes it possible to map errors back to file names later.
from torch.utils.data import DataLoader
from torchvision import datasets
# val_tfms is the deterministic transform defined in the data-loading chapter.
test_ds = datasets.ImageFolder("data/test", transform=val_tfms)
test_loader = DataLoader(test_ds, batch_size=32, shuffle=False, num_workers=4)
assert test_ds.classes == train_ds.classes, "class folders differ between splits"The assertion catches a quiet failure. ImageFolder assigns label indices by sorting folder names. If the test folder is missing a class, the indices shift and every metric is wrong without any error message.
Collecting predictions
Computing a running accuracy, as run_epoch does, is fine for monitoring. For a proper evaluation, store every label, prediction and confidence so you can compute any metric afterwards.
import torch
@torch.inference_mode()
def collect_predictions(model, loader, device):
model.eval()
labels_all, preds_all, conf_all = [], [], []
for images, labels in loader:
probs = model(images.to(device)).softmax(dim=1)
conf, preds = probs.max(dim=1)
labels_all.append(labels)
preds_all.append(preds.cpu())
conf_all.append(conf.cpu())
return torch.cat(labels_all), torch.cat(preds_all), torch.cat(conf_all)
y_true, y_pred, conf = collect_predictions(model, test_loader, device)
accuracy = (y_true == y_pred).float().mean().item()
print(f"test accuracy {accuracy:.3f} on {len(y_true)} images")Accuracy and its uncertainty
Accuracy is the fraction of images classified correctly. It is easy to read, but two things limit it.
First, it hides class structure. If 90% of your test images are one class, a model that always predicts that class scores 90%. Always compare accuracy with the share of the largest class.
Second, it is noisy on small sets. With n test images and accuracy p, the standard error is roughly sqrt(p * (1 - p) / n), and a 95% interval is about 1.96 times that.
| Test images | Accuracy | Approximate 95% interval |
|---|---|---|
| 100 | 0.90 | ±5.9 points |
| 200 | 0.90 | ±4.2 points |
| 1000 | 0.90 | ±1.9 points |
If two models differ by one point on 200 images, you cannot say which is better. Do not tune toward differences smaller than the noise.
The confusion matrix
A confusion matrix has one row per true class and one column per predicted class. Cell (i, j) counts images of true class i predicted as class j. The diagonal holds correct predictions. Large off-diagonal cells show which classes the model mixes up.
from sklearn.metrics import confusion_matrix, classification_report
cm = confusion_matrix(y_true, y_pred, labels=list(range(num_classes)))
print(cm)
print(classification_report(
y_true, y_pred,
labels=list(range(num_classes)),
target_names=train_ds.classes,
digits=3,
zero_division=0,
))Passing labels explicitly keeps the matrix the right size even if some class is never predicted. Without it, scikit-learn only includes classes that appear.
To find the worst confusions quickly, rank the off-diagonal cells:
import numpy as np
off_diag = cm.copy()
np.fill_diagonal(off_diag, 0)
order = np.dstack(np.unravel_index(np.argsort(-off_diag, axis=None), off_diag.shape))[0]
for i, j in order[:5]:
if off_diag[i, j] > 0:
print(f"{off_diag[i, j]:3d} x true {train_ds.classes[i]} -> predicted {train_ds.classes[j]}")Per-class precision, recall and F1
The classification report gives three numbers per class. Each answers a different question.
- Precision: of the images the model labeled as this class, how many were right? Low precision means the class attracts false alarms.
- Recall: of the images that truly belong to this class, how many did the model find? Low recall means the class is being missed.
- F1: the harmonic mean of precision and recall, which is low if either is low.
Which one matters depends on the use. A classifier that flags damaged parts for removal needs high recall on the "damaged" class. One that triggers an expensive action needs high precision.
The report also prints two averages. Macro average takes the unweighted mean across classes, so a weak rare class pulls it down. Weighted average weights by class size and tracks accuracy. Report macro F1 alongside accuracy whenever your classes are unequal in size.
Data leakage
Leakage means information from held-out images reaches training. It produces high held-out scores that collapse in production. Image datasets leak in three common ways.
- Duplicates and near-duplicates. The same photo downloaded twice, or resized copies, can land in both train and test. Hash files or compare small image fingerprints before splitting.
- Grouped images. Frames from one video, or many photos of the same object or patient, are nearly identical. Split by group, not by individual file, so a group lives in only one split.
- Preprocessing fitted on all data. Computing normalization statistics or choosing augmentation from the full dataset is a mild form of leakage. Using the fixed ImageNet mean and standard deviation, as this tutorial does, avoids it.
A warning sign is validation accuracy that is near-perfect after one epoch on a hard problem. Look for leakage before celebrating.
Calibration and confidence
You also collected the confidence of each prediction. A model is calibrated if, among predictions made with 80% confidence, about 80% are right. Fine-tuned networks are often overconfident. Check it cheaply by comparing confidence with correctness:
correct = (y_true == y_pred)
bins = [0.0, 0.5, 0.7, 0.9, 1.0001]
for lo, hi in zip(bins[:-1], bins[1:]):
mask = (conf >= lo) & (conf < hi)
if mask.any():
print(f"conf {lo:.1f}-{min(hi, 1.0):.1f}: n={mask.sum().item():4d}, "
f"accuracy {correct[mask].float().mean().item():.3f}")If the highest bin is far below its stated confidence, do not treat softmax outputs as probabilities when you set a rejection threshold. Pick the threshold from this table instead.
Common errors
| Symptom | Likely cause |
|---|---|
| Accuracy changes between identical runs | Random augmentation in the evaluation transform, or the model is still in train mode |
| Accuracy far below validation during training | Different transform, class indices shifted, or `eval()` not called |
| Per-class numbers look scrambled | Class folders differ between splits, so label indices do not match |
| Test accuracy far below validation | Validation overused for tuning, or a small test set |
| Test accuracy above 99% on a hard task | Leakage between splits |
Exercise
Your test set has 400 images, 380 of them from class "cat" and 20 from class "fox". The model scores 0.95 accuracy. Why is this not yet good news, and which two numbers would you look at next?
Show answer
A model that always predicts "cat" also scores 380/400 = 0.95, so the accuracy may reflect only the class imbalance. Look at the per-class recall for "fox" (and its precision), or the macro-averaged F1, together with the confusion matrix row for "fox". If fox recall is low, the model is missing the rare class.
Exercise
You tried 15 augmentation settings and kept the one with the best accuracy on the validation set, which reached 0.93. Why should you expect the test accuracy to be a little lower, and what should you do?
Show answer
Choosing the best of many settings on the same validation set selects partly for luck, so 0.93 is optimistically biased. Run the chosen model on the untouched test set once and report that number. Do not go back and adjust the setup based on the test result.