Measure It Honestly: Validation, Test and Overfitting
A trained model is only useful if it is right on examples it has never seen, yet the easiest number to compute is how well it does on the examples it was trained on. That number cannot be trusted on its own. Measuring honestly means keeping some data aside, putting the network into the right state before measuring it, and reading the numbers for the moment a model starts learning its training data by heart instead of the task.
Why training accuracy proves little
Think of a student who prepares for an exam by learning the answers to last year's paper word for word. On last year's paper they score 100%. On a new paper with different questions they may score far less, because they learned the answers, not the subject. Their score on the paper they studied says almost nothing about the next one.
A model is in the same position. Training adjusts its weights again and again until its predictions fit the training examples, so its accuracy on those examples measures how well it was fitted to them. A network has many thousands of adjustable numbers, enough to come close to remembering individual examples: an oddly drawn digit, a mislabelled picture, a smudge that happens to appear in a few images of one class. All of that raises training accuracy and none of it helps on new data.
What a model is for is generalisation: being right on examples it never saw. The only way to see it is to measure on data the model was never trained on, often called held-out data. A model with 99% training accuracy and 97% on held-out data generalises well. A model with 99% training accuracy and 70% on held-out data has mostly memorised its training set, and the training number alone could never tell those two apart.
| Model | Accuracy on training data | Accuracy on held-out data | What it means |
|---|---|---|---|
| A | 99% | 97% | Learned the task |
| B | 99% | 70% | Mostly memorised its examples |
True or false?
If a model reaches 100% accuracy on its training data, it will also be close to 100% on new data.
False. The model was fitted to exactly those examples, so a perfect score on them can come from memorising them. Only data it never trained on shows how it does on new examples.
Two models with the same training accuracy can be very different in how useful they are.
True. One may have learned the task and the other may have memorised its examples. Their scores on held-out data tell them apart.
Three sets of data, three jobs
Measuring on held-out data means some labelled examples must never be used for training. In practice the labelled data is divided into three separate parts, each with its own job:
- the training set, the only part the model learns from;
- the validation set, set aside from the training data and measured after every epoch, to compare choices such as how many epochs to train or which learning rate to use;
- the test set, kept untouched until every choice is made, then measured once for the final number.
No example may appear in two of the parts. A validation or test example that is also in the training set is not new to the model, so measuring on it flatters the score in the same way the training accuracy does.
| Set | Used for | Measured |
|---|---|---|
| Training | Adjusting the weights | Every batch, by the training loop |
| Validation | Comparing choices | After every epoch |
| Test | One honest final estimate | Once, at the very end |
How big should each part be? There is no fixed rule, and the split is a trade: every example given to validation or test is one fewer to learn from. One common example is 70% for training, 15% for validation and 15% for test. Many public datasets already come with a training part and a test part chosen by their authors. Those test examples should stay the test set, so the validation set is cut out of the training part.
In PyTorch, torch.utils.data.random_split does the cut. It takes a dataset and a list of lengths, either whole counts that add up to the size of the dataset or fractions that add up to 1, and returns non-overlapping parts chosen at random. Here a dataset of 10,000 labelled examples becomes 8,000 for training and 2,000 for validation:
import torch
from torch.utils.data import DataLoader, random_split
# labelled_data: any dataset of (input, label) pairs, here 10,000 of them
generator = torch.Generator().manual_seed(42)
train_set, val_set = random_split(labelled_data, [8000, 2000], generator=generator)
train_loader = DataLoader(train_set, batch_size=64, shuffle=True)
val_loader = DataLoader(val_set, batch_size=1000)The generator has its own seed, so the split is the same every time the program runs on the same machine and library version. Without generator=, the split would draw from PyTorch's global random numbers. Then any change earlier in the program that uses more or fewer random numbers would also change which examples land in which part.
Each part is a Subset: a list of positions into the original dataset, not a copy of the data. Because it reads its examples from the original, each one is prepared exactly as before, and a Subset can be handed to a DataLoader like any dataset. Only the training loader shuffles, because the order of validation examples does not change a measurement.
True or false?
`random_split(data, [8000, 2000])` on a dataset of 10,000 examples can put the same example in both parts.
False. The parts never overlap: every example goes to exactly one of them.
If a dataset comes with a test part from its authors, the validation set should be taken from the training part.
True. The test part is kept for the final measurement, so the examples used to compare choices must come from somewhere else, and the training part is the only other source.
The validation set: where choices are made
Training involves decisions the training loss cannot settle: how many epochs, how large a learning rate, how big a hidden layer. The training loss keeps falling the longer you train, so it always votes for more. The validation set answers instead. After every epoch the model is measured on it, and the choice that gives the best validation result wins. The work goes round a loop until the validation numbers look good, and only then does the test set come in:
- Train on the training set
- Measure on the validation set
- Adjust a choice epochs, learning rate, size
- Measure once on the test set
- Train to Measure
- Measure to Adjust a choice
- Adjust a choice to Train: repeat
- Measure to Measure once: every choice made
The test set: one final number
Each choice made on the validation set nudges the model towards whatever happens to suit those particular examples. Suppose you try 20 learning rates and keep the one with the best validation accuracy, 97.6%. Part of that winning margin is real, and part of it is luck: among 20 tries, the winner is also the one whose mistakes happened to fall on the fewest validation examples. So 97.6% is now an optimistic estimate for new data.
The more often a set is used to decide something, the more the model is shaped to that set, much as a teacher who teaches to the test raises the test scores more than the pupils' knowledge. A set wears out with use.
That is why the test set is used once, after every choice is final. A number that no decision depended on is still an honest estimate of how the model will do on new examples. If you look at the test score, change something and measure again, the test set has become a second validation set and its number has lost that honesty.
True or false?
Measuring the test set after every epoch and stopping at the epoch with the best test accuracy gives an honest test score.
False. Picking the epoch by its test score is a choice made on the test set, so the test number becomes optimistic. The epoch should be picked on the validation set.
After many rounds of adjustments, the validation accuracy tends to overstate how well the model does on new data.
True. Every choice favoured what suited those validation examples, so the final validation number is slightly flattering. The untouched test set gives the honest estimate.
Measuring a network: evaluation mode and no gradients
Measuring a network means running it on the held-out examples and counting how many it gets right, without changing it. Two switches make sure the measurement is both correct and cheap.
The first is evaluation mode. Some kinds of layer behave differently while training than while predicting. A dropout layer is one example. On every training step it sets a random choice of its values to zero (about half of them, with its default setting), so the network cannot lean on any single one. When predicting, it must pass every value through, or the same image would get a different answer each time.
Every module has a stored flag, training, that is True when it is created. Calling model.eval() sets it to False for the network and every layer inside it, and model.train() sets it back to True. A network made only of linear layers and ReLU behaves the same in both modes. The PyTorch documentation still recommends switching every time, because a layer you use may behave differently in a later version, and a habit that is always followed cannot be forgotten on the network that needs it.
The second switch is turning gradient tracking off. While training, PyTorch records every operation on the parameters so it can work out the gradients, which costs time and memory. A measurement never calls backward(), so the record is wasted work. Inside with torch.no_grad(): nothing is recorded.
def evaluate(model, loader, loss_fn):
model.eval()
total_loss = 0.0
correct = 0
with torch.no_grad():
for inputs, labels in loader:
scores = model(inputs)
total_loss += loss_fn(scores, labels).item() * len(labels)
correct += (scores.argmax(1) == labels).sum().item()
count = len(loader.dataset)
return total_loss / count, correct / countThe loss function returns the average over one batch, so multiplying it by the batch size gives that batch's total. Adding up the totals and dividing by the number of examples then gives the true average, even when the last batch is smaller than the others. scores.argmax(1) picks the class with the highest score for each example, and comparing it with the labels gives one True or False per example, which sum() counts.
The two switches are independent: model.eval() does not turn off gradient tracking, and torch.no_grad() does not put the layers into evaluation mode. A measurement uses both. Evaluation mode also stays on until something turns it off, so a training loop that measures after every epoch calls model.train() at the start of each epoch:
for epoch in range(10):
model.train()
for inputs, labels in train_loader:
loss = loss_fn(model(inputs), labels)
loss.backward()
optimizer.step()
optimizer.zero_grad()
train_loss, train_acc = evaluate(model, train_loader, loss_fn)
val_loss, val_acc = evaluate(model, val_loader, loss_fn)
print(f"epoch {epoch + 1}: train {train_acc:.1%}, validation {val_acc:.1%}")Measuring the training set with the same function gives a training number taken the same way as the validation one, with the weights as they stand at the end of the epoch, so the two can be compared fairly. The numbers such a loop prints repeat exactly on one machine with one library version; on another machine or version they come out about the same, not identical, so compare your own results as approximate.
True or false?
Calling `model.eval()` stops PyTorch from recording operations for gradients.
False. Evaluation mode only changes how certain layers behave. Gradient tracking is turned off separately, with `torch.no_grad()`.
After `evaluate` returns, the model is still in evaluation mode until `model.train()` is called.
True. The mode is a stored flag. Nothing switches it back by itself, which is why the loop calls `model.train()` at the start of every epoch.
A network with only linear layers and ReLU gives the same predictions in training mode and evaluation mode.
True. Neither layer changes behaviour between the modes. Calling `eval()` and `train()` is still the recommended habit.
Overfitting: the gap between two curves
With a training measurement and a validation measurement after every epoch, you can draw both as curves, one point per epoch. At first they move together: the model is learning patterns that hold for any handwriting, any photo, any example of the task, so both losses fall. Later, once the general patterns are learned, the only way left to lower the training loss is to fit the details of the training examples themselves. The training loss keeps falling, but those details do not exist in the validation set, so the validation loss stops falling and may start to rise.
That is overfitting: the model keeps improving on its training data while it stops improving, or gets worse, on held-out data. It shows as a gap between the two curves that keeps growing. The two charts below use made-up numbers to show the two shapes.
loss against epoch
- training
- validation
loss against epoch
- training
- validation
On the left, the two curves keep a similar shape and a small, steady distance: the model does a little better on the data it trained on, as it always will, but what it learns carries over. On the right, they follow each other for the first few epochs and then part: from about epoch 5 on, each extra epoch makes the model better at its own training examples and worse at new ones. Reading the numbers epoch by epoch, the sign is the same: a training figure that keeps improving next to a validation figure that has stalled or turned back, with the difference between them widening.
The validation curve also tells you how long to train. The epoch where validation loss is lowest is the best choice of training length among those tried, and because that choice was made on the validation set, the test set is still needed for the final, honest number. Overfitting is more likely when the model is large compared to the amount of training data, or when the training examples are not a good enough sample of the data the model will meet.
True or false?
A model is overfitting only once its validation accuracy actually drops.
False. The sign is the growing gap: training keeps improving while validation stops improving or gets worse. Validation that has merely stalled while training races ahead already shows it.
A small, steady difference between training and validation loss is normal for a well-fit model.
True. A model nearly always does a little better on the examples it learned from. What signals overfitting is the difference growing epoch after epoch.