Sub topic 11
Evaluating on Held-Out Data
You should already understand PyTorch datasets, model training, epochs, and the difference between training and validation data. This chapter assumes that your classifier has been trained and that test_loader contains images never used to choose hyperparameters or update weights.
Why the test set must stay untouched
A held-out test set estimates how the classifier will perform on new images. Use the training set to update weights and the validation set to choose settings such as the learning rate, number of epochs, or augmentation. Keep the test set separate until these decisions are finished.
If you repeatedly inspect test results and change the model, the test set becomes part of the development process. Its score may then look better than performance on truly new data.
Accuracy is useful but incomplete
Accuracy is the fraction of predictions that are correct:
\text{accuracy}=\frac{\text{correct predictions}}{\text{all predictions}}It works well when classes have similar sizes and similar costs for mistakes. It can mislead when one class is much more common than the others. A model that always predicts the largest class may have high accuracy while failing every minority class.
A confusion matrix counts predictions by actual and predicted class. Its rows represent the true classes, and its columns represent the predicted classes. The diagonal contains correct predictions. Off-diagonal cells show which classes the model confuses.
For each class, inspect these measures:
| Measure | Meaning |
|---|---|
| Precision | Of the images predicted as this class, how many were correct |
| Recall | Of the real images in this class, how many were found |
| F1 score | A balance between precision and recall |
| Support | The number of test images in the class |
Calculate overall and per-class results
Run evaluation with model.eval() and torch.inference_mode(). The first disables training behavior such as dropout. The second avoids storing gradients, reducing memory use.
import torch
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
ConfusionMatrixDisplay,
)
import matplotlib.pyplot as plt
model.eval()
all_predictions = []
all_labels = []
with torch.inference_mode():
for images, labels in test_loader:
logits = model(images.to(device))
predictions = logits.argmax(dim=1).cpu()
all_predictions.extend(predictions.tolist())
all_labels.extend(labels.tolist())
accuracy = accuracy_score(all_labels, all_predictions)
print(f"test accuracy: {accuracy:.3f}")
print(classification_report(
all_labels,
all_predictions,
target_names=class_names,
zero_division=0,
))
matrix = confusion_matrix(
all_labels,
all_predictions,
labels=range(len(class_names)),
)
display = ConfusionMatrixDisplay(
confusion_matrix=matrix,
display_labels=class_names,
)
display.plot(xticks_rotation="vertical", cmap="Blues")
plt.tight_layout()
plt.show()The zero_division=0 setting handles a class for which the model makes no positive predictions. Treat that result as a warning, not as evidence of good performance.
Read the errors
Start with the largest off-diagonal cells. Look at the corresponding images and ask whether the labels are reliable, the classes are visually distinct, and the test images represent real use. A low recall for one class may indicate too few examples, inconsistent lighting, or a decision boundary that needs more fine-tuning.
Use a separate test set from the same source as deployment. If deployment images come from a different camera, location, or time period, create an additional external test set to measure that distribution shift.
Exercise
A classifier has 95% accuracy, but its confusion matrix shows that it never predicts the smallest class. Is the model acceptable?
Show answer
Usually not. Accuracy hides the minority-class failure. Check that class's recall, precision, F1 score, and support, then collect data or adjust training so the required classes are recognized.