Early stopping and reading learning curves
You cannot know in advance how many epochs to train. Too few and the model has not learned enough. Too many and it memorizes the training data and gets new data wrong. Plot training loss and validation loss together and you can see which side you are on, and decide when to stop.
Short answer. A learning curve plots training loss and validation loss at every epoch. The height of the two lines and the gap between them tell you whether the model has not learned enough, has started to memorize, or is training with too much noise. Early stopping is a rule: stop training when the validation loss has not beaten its best value for p epochs in a row, then go back to the weights from the best epoch. p is called the patience.
Pick a curve shape with the buttons above, and change the patience from 1 to 20 with the slider or the number box. The curves are made up: smooth curves plus noise from a fixed seed, so they are the same every time you open the page. This is a small stand-in, not a real model being trained. In real training you cannot see the future, so the faint part after the stop and the "lowest" circle would not be there.
Try this. ① At the start (gap grows, patience 5) training stops at epoch 29 and restores the weights from epoch 24 (validation loss 0.76). The lowest point over all 60 epochs is also epoch 24, and 31 epochs were not run. ② With patience 1 it stops at epoch 14 and goes back to epoch 13 (0.93). With patience 3 it stops at epoch 22 and goes back to epoch 19 (0.79). Both stop before the bottom. With patience 20 it runs to epoch 44, but the restored epoch is still 24. ③ On "Validation jumps", patience 1 stops at epoch 4 (1.6). Patience 5 stops at epoch 29 and picks epoch 24 (0.56). Patience 10 stops at epoch 52 and picks epoch 42 (0.43). ④ On "Both high", from patience 8 up it never stops, and even after all epochs the validation loss is 0.97. ⑤ On "Validation lower", the blue line stays under the green line for all 60 epochs.
Definitions
The text below uses made-up learning curves. These are the textbook definitions. The ideas on this page are rules, so they are written in words instead of formulas.
- epoch
- One pass of training that uses every example in the training data once, from start to end.
- training loss, validation loss
- The training loss is the loss measured on the training data, which is used to change the weights. The validation loss is the loss measured on validation data that is held out and not used for training. Performance on unseen data is estimated with the validation loss.
- learning curve
- A graph of the training loss and the validation loss against the epoch. Some books use the term for a graph of the score against the number of training examples.
- early stopping
- A rule that does not fix the number of epochs in advance. Training stops when the validation loss has not improved on its lowest value so far for a set number of epochs in a row. After stopping, you use the weights from the epoch with the lowest validation loss, not the last weights.
- patience
- The number of epochs p that early stopping waits before it stops. Training stops after p epochs in a row that do not improve on the lowest validation loss so far, and the count goes back to 0 whenever a new lowest value appears.
- checkpoint
- A file that saves the state of training (such as the weights) partway through. In early stopping, you save one each time the validation loss reaches a new lowest value, and after stopping you go back to those weights.
1. What learning curves and early stopping are
The loss is one number for how wrong the model is. Lower is better. An epoch is one full pass over the training data. At the end of each epoch you measure the loss in two ways.
- Training loss: the loss on the data the model trains on. The model changes its weights to fit this data, so it almost always goes down.
- Validation loss: the loss on data kept aside and never trained on (the validation set). It tells you how well the model does on data it has not seen. How to split the data is on the data splitting page.
Plot both losses at every epoch and join the dots: that is a learning curve. Training loss alone always looks good. You need the validation loss next to it to tell learning apart from memorizing (overfitting).
Early stopping is a rule that uses the validation loss to decide when to stop. You do not fix the number of epochs in advance. You stop when the validation loss stops getting better. Then you use the weights from the epoch with the best validation loss, not the last weights.
2. Reading the curve shapes: what to do when
The four buttons in the experiment are shapes you will see often. Each one means something different and calls for a different fix. Early stopping is the answer for only one of them.
| Curve shape | What it means | What to do | Watch out |
|---|---|---|---|
| Both high and close together | Underfitting. The model is too weak or has not learned enough | Make the model bigger. Tune the learning rate (learning rate schedules). If dropout or penalties are strong, weaken them | Early stopping does not help. Waiting longer only lowers the loss a little |
| Both still going down | Not trained long enough | Train for more epochs | It is normal for early stopping not to stop |
| Training goes down, validation turns back up, the gap grows | Overfitting. The model started to memorize the training data | Early stopping with restore. Also look at dropout, weight decay and more data | Stopping at the bottom does not close the gap. Closing it is the job of the other methods |
| Validation jumps up and down a lot | The learning rate is high, the batch is small, or the validation set is small | Lower the learning rate or use a schedule. Use bigger batches or a bigger validation set. Raise the patience | A small patience gets fooled by one noisy jump and stops early |
| Validation is lower than training | Dropout and weight penalties are on only during training. Training loss is an average over the epoch, so it includes values from before the model improved | Usually leave it | If the gap is large, check that the validation data is not easier and does not overlap the training data (data splitting) |
Both reasons for "validation lower than training" are written in the Keras FAQ (see sources). Validation loss is measured with the model as it is at the end of the epoch, while training loss is the average over the batches of the epoch, so the higher values from early batches are mixed in.
3. How the rule is built
"Stop when the validation loss stops getting better" sounds simple, but done naively it gets fooled by noise. We fix the rule one step at a time on the "gap grows" curve from the experiment. In the formula, val[t] is the validation loss at epoch t, t* is the epoch with the lowest validation loss so far, and w[t*] is the weights saved at that epoch.
- Stop at the first rise:
val[t] > val[t−1] → stop. The simplest rule. At epoch 14 the validation loss is 1, up from 0.93 the epoch before, so we stop there. But the bottom is at epoch 24 (0.76). Why it fails: validation loss is noisy, so it goes up now and then even while it is still falling. One rise is not proof that we passed the bottom. - Wait p times:
t − t* ≥ p → stop. Compare with the best value so far, not with the previous epoch, and stop after p epochs in a row that do not beat it. A new best resets the count to 0. With p = 5, epoch 24 is the best, and epochs 25 to 29 are all above 0.76, so we stop at epoch 29. Why: a noisy rise or two is soon covered by a new best. The count only reaches p when we really passed the bottom. - Go back to the best:
w ← w[t*]. The weights at epoch 29 are 5 epochs past the bottom, with validation loss 0.83. So we go back to the weights saved at epoch 24 (0.76). Why: while we waited, the model had already started to memorize. Keeping the weights from the stop means keeping a model that got worse while we waited.
The finished rule is the same as algorithm 7.1 in section 7.8 of the textbook Deep Learning (see sources). The book describes p as "the number of times to observe worsening validation set error before giving up". It copies the parameters every time the validation error improves and returns that copy at the end.
Try this. Each time you press "Next", a piece is added to the formula (orange background) and the stop moves in the picture. In step ① training stops at epoch 14, and the empty circle (epoch 24) is far to the right. In step ② the stop moves to epoch 29 and the orange band says "waited 5". In step ③ the purple arrow goes back from epoch 29 to epoch 24.
4. Follow it by hand
Say the validation loss from epoch 1 on is 1.00, 0.80, 0.70, 0.72, 0.66, 0.67, 0.69, 0.68, 0.70. The patience is p = 3.
| Epoch | Validation loss | Best so far (epoch) | Waited | Action |
|---|---|---|---|---|
| 1 | 1.00 | 1.00 (1) | 0 | Remember the first value and save the weights |
| 2 | 0.80 | 0.80 (2) | 0 | New best. Save |
| 3 | 0.70 | 0.70 (3) | 0 | New best. Save |
| 4 | 0.72 | 0.70 (3) | 1 | No improvement. With p = 1 we would stop here |
| 5 | 0.66 | 0.66 (5) | 0 | New best. Save and reset the count to 0 |
| 6 | 0.67 | 0.66 (5) | 1 | No improvement |
| 7 | 0.69 | 0.66 (5) | 2 | No improvement |
| 8 | 0.68 | 0.66 (5) | 3 | Lower than the previous 0.69, but higher than 0.66. Waited 3 = p, so stop |
After stopping, go back to the weights from epoch 5 (0.66). Epoch 9 is never run. As epoch 8 shows, you compare with the best value, not the previous one. With p = 1 you would stop at epoch 4 and use epoch 3 (0.70).
5. Key properties
| Property | In plain words | In the experiment |
|---|---|---|
| Training loss is not a fair report card | The model has seen that data, so it almost always goes down. Validation loss tells you how it does on new data | On "gap grows" the green line keeps falling to the end |
| Patience trades noise for time | Small: stops early and saves time, but gets fooled by noise. Large: ignores noise, but runs longer | Compare 1, 5 and 10 on "validation jumps" |
| With restore on, a big patience costs only time | You use the best weights anyway, so waiting longer only costs time | On "gap grows", patience 5 and 20 both pick epoch 24 |
| Without restore you keep a model p epochs too late | The weights at the stop are at least p epochs after the best ones | Section 3, step ③: 0.83 instead of 0.76 |
| The validation score looks a little too good | You picked the stop using the validation set, so its score is flattered by that choice. Measure the final score on a separate test set | (data splitting) |
6. Checkpoints: saving the weights to a file
A checkpoint is the state of training saved to a file. It has two uses.
- Keep the best model. Save the weights every time the validation loss hits a new best, then load that file after stopping. The
w[t*]in section 3 is this file. For a big model you can keep it on disk instead of in memory. You only write it on a new best and never read it during training, so a slow place to store it barely slows training down (Deep Learning, section 7.8). - Resume after a crash. If training stops halfway, start again from the last checkpoint. For this you must save not only the weights but also the optimizer state (for example the averages Adam keeps) and the epoch number, so it picks up exactly where it left off.
# PyTorch: early stopping and checkpoints written by hand
best, wait = float("inf"), 0
for epoch in range(100):
train_one_epoch(model)
val = evaluate(model) # validation loss
if val < best:
best, wait = val, 0
torch.save(model.state_dict(), "best.pt") # new best: checkpoint
else:
wait += 1
if wait >= patience:
break # waited p times
model.load_state_dict(torch.load("best.pt", weights_only=True)) # go back to the best weights
# Keras: restore_best_weights is False by default. Without it you keep the weights from the stop
early = keras.callbacks.EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True)
model.fit(x, y, validation_data=(x_val, y_val), epochs=100, callbacks=[early])
In Keras the default patience is 0, and min_delta sets the smallest drop that counts as an improvement (see sources). The experiment on this page counts any drop at all as an improvement (min_delta = 0).
Where it is used
- Choosing the number of epochs for a neural network. Instead of guessing how many epochs to run, let the validation loss decide. Deep Learning calls early stopping probably the most commonly used form of regularization in deep learning.
- Saving training time. Epochs that no longer help are not run. The starting setup of experiment ① skipped 31 of 60 epochs.
- Checking that training is healthy. Even without early stopping, plotting the learning curve and reading its shape with the table in section 2 tells you what to change next.
Frequently asked questions
Should I stop on validation loss or on accuracy?
Usually validation loss. Keras EarlyStopping also watches validation loss (val_loss) by default. If there is another score you really care about, you can watch that instead. For a score where higher is better, such as accuracy, flip the direction of what counts as an improvement.
How big should the patience be?
There is no fixed value. The more the validation loss jumps around, the bigger it should be. On the noisy curve on this page, a patience of 1 stops at epoch 4, while 10 runs to epoch 52 and picks epoch 42 with a validation loss of 0.43. If you restore the best weights, a bigger patience never makes the validation loss worse. It only costs more time.
If I use early stopping, do I still need dropout or weight decay?
They do different jobs. Early stopping only decides when to stop. Dropout and weight decay make the model memorize less while it trains. The textbook Deep Learning says early stopping can be used alone or together with other regularization.
Words
| Plain words used here | Textbook term |
|---|---|
| Loss per epoch, plotted | Learning curve. Some books use the same name for score versus amount of training data |
| Loss on the training data, loss on held-out data | Training loss, validation loss |
| One full pass over the training data | Epoch |
| Data kept aside | Validation set, test set |
| Deciding when to stop from validation loss | Early stopping |
| How many times to wait, p | Patience |
| Going back to the best weights | Restore best weights |
| Smallest drop that counts as better | min_delta |
| Training state saved to a file | Checkpoint |
| Not learned enough, memorizing | Underfitting, overfitting |
| Methods that make a model memorize less | Regularization |
Sources
- Ian Goodfellow, Yoshua Bengio, Aaron Courville, Deep Learning, chapter 7 (Regularization), section 7.8 Early Stopping. The U-shaped validation curve, algorithm 7.1 (patience p, saving the best parameters), "most commonly used form of regularization", using it with other regularization, the cost of storing a copy.
- Keras documentation: EarlyStopping (monitor, patience, min_delta, restore_best_weights and their defaults).
- Keras documentation: FAQ, "Why is my training loss much higher than my testing loss?" (dropout and penalties only during training, training loss as an epoch average).
- PyTorch documentation: Saving and Loading Models (saving and loading a state_dict, checkpoints for resuming training).
← Weight decay and L1/L2 regularizationGrokking: generalizing long after memorizing →