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.

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 shapeWhat it meansWhat to doWatch out
Both high and close togetherUnderfitting. The model is too weak or has not learned enoughMake the model bigger. Tune the learning rate (learning rate schedules). If dropout or penalties are strong, weaken themEarly stopping does not help. Waiting longer only lowers the loss a little
Both still going downNot trained long enoughTrain for more epochsIt is normal for early stopping not to stop
Training goes down, validation turns back up, the gap growsOverfitting. The model started to memorize the training dataEarly stopping with restore. Also look at dropout, weight decay and more dataStopping at the bottom does not close the gap. Closing it is the job of the other methods
Validation jumps up and down a lotThe learning rate is high, the batch is small, or the validation set is smallLower the learning rate or use a schedule. Use bigger batches or a bigger validation set. Raise the patienceA small patience gets fooled by one noisy jump and stops early
Validation is lower than trainingDropout and weight penalties are on only during training. Training loss is an average over the epoch, so it includes values from before the model improvedUsually leave itIf 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.

  1. 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.
  2. 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.
  3. 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.

EpochValidation lossBest so far (epoch)WaitedAction
11.001.00 (1)0Remember the first value and save the weights
20.800.80 (2)0New best. Save
30.700.70 (3)0New best. Save
40.720.70 (3)1No improvement. With p = 1 we would stop here
50.660.66 (5)0New best. Save and reset the count to 0
60.670.66 (5)1No improvement
70.690.66 (5)2No improvement
80.680.66 (5)3Lower 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

PropertyIn plain wordsIn the experiment
Training loss is not a fair report cardThe model has seen that data, so it almost always goes down. Validation loss tells you how it does on new dataOn "gap grows" the green line keeps falling to the end
Patience trades noise for timeSmall: stops early and saves time, but gets fooled by noise. Large: ignores noise, but runs longerCompare 1, 5 and 10 on "validation jumps"
With restore on, a big patience costs only timeYou use the best weights anyway, so waiting longer only costs timeOn "gap grows", patience 5 and 20 both pick epoch 24
Without restore you keep a model p epochs too lateThe weights at the stop are at least p epochs after the best onesSection 3, step ③: 0.83 instead of 0.76
The validation score looks a little too goodYou 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.

# 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

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 hereTextbook term
Loss per epoch, plottedLearning curve. Some books use the same name for score versus amount of training data
Loss on the training data, loss on held-out dataTraining loss, validation loss
One full pass over the training dataEpoch
Data kept asideValidation set, test set
Deciding when to stop from validation lossEarly stopping
How many times to wait, pPatience
Going back to the best weightsRestore best weights
Smallest drop that counts as bettermin_delta
Training state saved to a fileCheckpoint
Not learned enough, memorizingUnderfitting, overfitting
Methods that make a model memorize lessRegularization

Sources

← Weight decay and L1/L2 regularizationGrokking: generalizing long after memorizing →