Sub topic 16
Early stopping
Early stopping ends training when validation performance stops improving. It limits how long a model is allowed to fit the training data, so it acts as a regulariser. This chapter assumes you know what training and validation sets are, how overfitting appears as a gap between training and validation error, and how to train a neural network with Keras.
Why training longer can hurt
Iterative training methods, such as gradient descent, start with small, simple weights and move toward a fit of the training data. Early on, the model learns broad patterns that generalise. Later, it starts to fit noise in the training set.
Training loss usually keeps falling for the whole run. Validation loss falls at first, reaches a minimum, and then rises. The rise marks the start of overfitting. Early stopping halts training near that minimum.
How it works
You monitor a validation metric after every epoch, which is one full pass over the training data. Two settings control the rule:
- Patience is the number of epochs you wait without improvement before stopping. A value of 5 means "stop if there is no new best for 5 epochs in a row".
- Restore best weights returns the model to the epoch with the best validation score. Without it, you keep the weights from the last epoch, which is already past the minimum.
Patience matters because validation loss is noisy. A patience of 1 can stop on a random bump. A very large patience wastes time and lets the model overfit before you roll back.
Example in Keras
This model combines three regularisers: an L2 weight penalty, dropout, and early stopping. The code assumes X_train has 20 features and y_train holds 0/1 labels.
from tensorflow import keras
model = keras.Sequential([
keras.layers.Input(shape=(20,)),
keras.layers.Dense(64, activation="relu", kernel_regularizer=keras.regularizers.l2(1e-3)),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
early_stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True)
model.fit(X_train, y_train, validation_split=0.2, epochs=200, callbacks=[early_stop])Here epochs=200 is only an upper limit. Training normally ends much sooner. The callback watches val_loss, which Keras computes on the 20% of the training data held out by validation_split.
Common errors
- Stopping on the test set. If you monitor the test set, you choose the stopping point using test data. The test score is then optimistic. Always monitor a validation set and keep the test set for the final check.
- Forgetting
restore_best_weights=True. The model you keep is thenpatienceepochs worse than the best one. - Patience too small. Noisy validation loss ends training too early, and the model underfits.
- Reusing the validation score as the final estimate. The stopping epoch is chosen using the validation set, so that score is slightly optimistic.
- Interactions with other settings. Dropout makes validation loss noisier early on, and learning-rate schedules can improve loss late in training. Both may call for higher patience.
Exercise
A model trains for 200 epochs with early stopping on validation loss, patience 5, and restorebestweights=True. Validation loss is lowest at epoch 31. At which epoch does training stop, and which weights does the final model use?
Show answer
Training stops at epoch 36, after 5 epochs pass without a new best validation loss. The final model uses the weights from epoch 31, because restorebestweights=True returns the model to its best epoch.
Exercise
Why is it a mistake to use the test set as the monitored data for early stopping?
Show answer
The stopping point is then selected using test data, so the test set no longer gives an unbiased estimate of performance on new data. The reported score will be too optimistic. Use a separate validation set for stopping.