Measure on the Test Set and Read the Mistakes
When a classifier is finished, two questions remain: how well will it do on photos it has never seen, and where exactly does it go wrong? One honest number answers the first, measured on a test set that played no part in building the model. The second needs more than a number: a table of which classes are mistaken for which, a score per class, and a look at the wrongly classified photos themselves.
Why the validation score flatters the model
During training, the validation set is the judge of every choice: which epoch to keep, which learning rate to use, whether an augmentation helped, how many layers to unfreeze. Each time a choice is kept because the validation accuracy went up, a little knowledge about those particular images flows into the model. After many such choices, the model fits the validation set slightly better than it fits photos in general, and the validation accuracy is no longer a fair measurement of new data. It is optimistic.
The effect is the same as a teacher who practises the exact questions of the exam: the class scores well, and the score says less about what the class has learned. Picking the best of several epochs by validation accuracy already does this in a small way, because some of that best epoch's lead is luck on those images.
The cure is a third set, the test set, kept apart from every decision. It is used once, after every choice is final, and its accuracy is the number reported as the model's performance.
- Training set fits the weights
- Validation set guides every choice
- All choices final
- Test set measured once
- Training set to Validation set: train, then score
- Validation set to All choices final: keep the best
- All choices final to Test set: one run
Once the test set is used, it is tempting to adjust something and measure again. That second measurement turns the test set into another validation set: the change was kept or dropped because of its score, so the score is optimistic in the same way. A test set wears out with repeated use, and the only way to get a fresh, fair measurement after that is a new set of photos the model has never been judged on.
The measurement itself runs with the same evaluation setup as validation, in three parts. The model is switched to evaluation mode with model.eval(), so that layers such as batch normalisation and dropout behave as in real use. Gradient tracking is switched off with torch.inference_mode(), since nothing is trained. And every photo gets the same fixed preprocessing as for validation, never the random training augmentations.
The first two switches are independent of each other: inference_mode() does not put the model in evaluation mode, and eval() does not stop gradients, so both are needed.
For each photo, the softmax of the class scores gives probabilities that add up to one. The class with the highest probability is the prediction, and that probability is the model's confidence in it.
import torch
def predict(model, loader):
model.eval()
labels, preds, confs = [], [], []
with torch.inference_mode():
for images, targets in loader:
probs = torch.softmax(model(images), dim=1)
conf, pred = probs.max(dim=1)
labels.append(targets)
preds.append(pred)
confs.append(conf)
return torch.cat(labels), torch.cat(preds), torch.cat(confs)With a loader that does not shuffle, position i in these three tensors is image i of the test set, which later leads straight back to the photo behind each mistake.
True or false?
After choosing the best epoch by validation accuracy, that validation accuracy is a fair estimate of accuracy on new photos.
False. The epoch was chosen because it scored highest on those images, so part of its score is a fit to them. Only a set untouched by the choice gives a fair estimate.
Measuring on the test set, changing the learning rate because of the result and measuring again makes the second test accuracy optimistic.
True. The change was kept because of the test score, so the test set has started to guide choices, just like a validation set.
Wrapping the evaluation in torch.inference_mode() also switches the model to evaluation mode.
False. The two are independent. inference_mode() only stops gradient tracking; model.eval() is still needed for layers such as batch normalisation and dropout.
The confusion matrix: which class is taken for which
The test accuracy is the share of test images classified correctly. It says how many mistakes there are, but not which ones. A confusion matrix counts them by kind: it is a table with one row for each true class and one column for each predicted class, and the cell in row i, column j counts the test images of class i that the model called class j.
Take a small example: a classifier of three animals, tested on 100 photos of cats, 100 of dogs and 20 of foxes.
| True class | cat | dog | fox | Row total |
|---|---|---|---|---|
| cat | 92 | 6 | 2 | 100 |
| dog | 5 | 93 | 2 | 100 |
| fox | 3 | 8 | 9 | 20 |
| Column total | 100 | 107 | 13 | 220 |
Three readings come straight from the table:
- The diagonal (92, 93, 9) holds the correct predictions. Their sum divided by all images is the accuracy: 194 of 220, about 88%.
- Each row adds up to the number of test images of that true class, and shows where that class's images went. The fox row says most foxes that were missed were taken for dogs.
- Each column adds up to everything the model predicted as that class, and shows where those predictions came from. The dog column holds 107 predictions, 14 of them wrong.
An off-diagonal cell names a specific confusion, and that is what makes the matrix useful: a fox mistaken for a dog is a different problem from a fox mistaken for a cat, and it points to what to look at next.
The matrix can be counted from the labels and predictions with plain tensor operations. Each pair (true, predicted) is turned into one cell number, and torch.bincount counts how often each cell number occurs:
def confusion_matrix(labels, preds, num_classes):
cell = labels * num_classes + preds
counts = torch.bincount(cell, minlength=num_classes * num_classes)
return counts.reshape(num_classes, num_classes)scikit-learn's sklearn.metrics.confusion_matrix(y_true, y_pred) uses the same layout, true class in the rows and predicted class in the columns. Not every source does: some textbooks and course materials put the true class in the columns instead. Before reading any confusion matrix, check which axis is which.
True or false?
In a confusion matrix with the true class in the rows, each row adds up to the number of test images of that class.
True. Every image of a class lands in exactly one cell of its row, wherever its prediction went.
A column total shows how many test images truly belong to that class.
False. A column collects everything predicted as that class, right and wrong. The true count of a class is its row total.
Precision and recall for each class
The matrix holds the counts; two shares per class turn them into scores that can be compared. Both start from the correct predictions of the class, its diagonal cell, and divide it by a different total.
- Precision asks: of all the images the model called this class, what share really were? It divides by the column total. A low precision means the model uses this answer too readily.
- Recall asks: of all the images that really are this class, what share did the model find? It divides by the row total. A low recall means the class is often missed.
Precision of class c diagonal cell over its column total
Recall of class c diagonal cell over its row total
For the fox class in the example, precision is \( 9 / 13 \approx 0.69 \): of the 13 photos the model called foxes, 9 were. Recall is \( 9 / 20 = 0.45 \): of the 20 real foxes, the model found fewer than half. The same arithmetic for every class gives this picture:
- cat
- dog
- fox
- precision
- recall
The overall accuracy of 88% looks healthy, yet more than half of the foxes are missed. The single number hides this because it is an average weighted by class size. Accuracy equals the recall of each class, weighted by how many test images that class has, so a large class counts for much and a small one for little. Cats and dogs together have 200 of the 220 images, so the fox recall of 45% barely moves the total. The smaller and rarer a class, the less its weakness shows in the accuracy, and the more it matters to read the scores class by class.
The two scores also fail in opposite directions. The dog class has a recall of 0.93 but a lower precision of 0.87, because the model sends doubtful foxes to "dog": dogs are found, at the price of many false dog answers. Low recall in one class and low precision in another often turn out to be the same confusion, seen from its row and from its column.
With the matrix as a float tensor, both scores for every class take one line each:
cm = confusion_matrix(labels, preds, num_classes).float()
correct = cm.diag()
precision = correct / cm.sum(dim=0) # column totals
recall = correct / cm.sum(dim=1) # row totals
accuracy = correct.sum() / cm.sum()A class the model never predicts has a column total of zero, so its precision is 0 divided by 0, which gives nan: there are no predictions of it to be right or wrong.
scikit-learn computes the same scores with precision_score and recall_score. With more than two classes, they need average=None to return one value per class instead of a single average. Its classification_report prints, for every class in one table, the precision, the recall, the F1 score and the support (the number of true images of that class).
True or false?
A model with 95% test accuracy can still miss most of the images of one class.
True. Accuracy weights each class by its number of images. A small class can have a low recall and still change the total very little.
Precision and recall of a class are two names for the same share.
False. Both use the correct predictions of the class, but precision divides by everything predicted as the class (its column) and recall by everything that truly is the class (its row).
If a model calls a class very rarely and is right each time, that class has high precision but may have low recall.
True. Its few predictions are all right, so precision is high, but most of its real images went to other classes, so recall is low.
Reading the mistakes, most confident first
The matrix says which confusions happen; only the photos say why. The wrongly classified images are the ones where the prediction differs from the label. Sorting them by the model's confidence, highest first, puts the most informative cases at the top: an image the model called a dog with probability 0.98 while its label says fox is either a striking failure of the model or a sign that something is wrong with the label.
wrong = (preds != labels).nonzero().flatten()
order = confs[wrong].argsort(descending=True)
for i in wrong[order][:12].tolist():
print(i, class_names[labels[i]], "->", class_names[preds[i]],
f"{confs[i]:.2f}")Each line names a test image by its position, so the photo itself can be opened and looked at. Looking at a few dozen of them, most mistakes fall into one of three kinds, and each kind calls for a different response.
| Kind | What the photo shows | What it means |
|---|---|---|
| Wrong label | The model is right: the photo shows the predicted class, and the label is a mistake | The model is better than its score; fix the label |
| Truly ambiguous | Both classes are in the photo, or it is too small, dark or cropped for anyone to tell | No model can be reliably right; the classes or the data may need a clearer rule |
| Real weakness | A clear photo of the labelled class that the model gets wrong | A gap in what the model learned, for example an unusual angle or background |
Wrong labels are more common than one might expect. A study of ten widely used benchmark test sets estimated that on average at least 3.3% of their labels are wrong, and at least 6% in the ImageNet validation set (Northcutt, Athalye and Mueller, 2021). Errors at that rate are enough to change which of two models looks better.
A confident mistake is still only a candidate. In the same study, the images flagged automatically as likely label errors were checked by people, and only about half of them really were mislabelled. The confidence ranks the photos worth looking at; a person looking at the photo decides which kind of mistake it is.
The confidence itself needs care. Softmax probabilities always lie between 0 and 1 and add up to one over the classes, so they rank the predictions well, but a probability of 0.98 is not a measured 98% chance of being right. Use it to decide which photos to look at first, not as a promise about how often the model is right.
Counting the kinds turns the reading into a judgement. Mistakes that are mostly wrong labels mean the test accuracy understates the model. Mistakes that are mostly ambiguous photos mean the model is close to what the data allows. Mistakes that cluster in one confusion, on clear photos of the same sort, are the real weakness, and they show what kind of photos the model needs to see more of. Any such change starts a new round of choices, judged again on the validation set, while the test set keeps its single, final measurement.
True or false?
A wrong prediction made with probability 0.99 proves that the test label is wrong.
False. It makes the image worth checking, nothing more. In a study of label errors, only about half of the automatically flagged images were confirmed as mislabelled by people.
Sorting the wrong predictions by confidence is useful even though softmax probabilities are not calibrated chances of being right.
True. The order still separates the answers the model was sure of from the close calls, and the sure but wrong ones are the most informative to look at.
Fixing wrong labels in the test set can raise the measured test accuracy without changing the model.
True. Where the model was right and the label wrong, a corrected label turns a counted mistake into a correct prediction.