Sub topic 16
Early stopping
This chapter assumes you know what training and validation error are, how a train/validation/test split works, and how to read a basic Keras fit call. Earlier chapters showed that a model overfits when it keeps improving on training data while getting worse on new data. Early stopping uses that signal directly. It halts training at the point where validation performance stops improving.
The idea
Iterative learners, such as neural networks and gradient boosting, improve their fit step by step. Early in training they pick up broad patterns. Later they start fitting noise in the training set. Training loss keeps falling, but validation loss reaches a minimum and then rises.
Early stopping watches validation loss after each epoch. When it has not improved for a set number of epochs, training stops. The weights are then rolled back to the best epoch.
Why it counts as regularisation
Early stopping limits how far the weights can move from their starting values. Small initial weights give a simple function, and training makes it more complex. Stopping early therefore caps the effective capacity of the model without adding a penalty term.
For linear models trained with gradient descent, this is close to an L2 penalty. Fewer epochs act like a larger alpha. The match is exact only under simplifying assumptions, but it explains why the two methods often give similar results.
The number of epochs becomes a hyperparameter that early stopping tunes for you. You set a generous maximum, and the validation curve picks the actual number.
A runnable example
The code below builds a small noisy classification problem so that overfitting appears. It trains a deliberately large network with the callback.
import numpy as np
from tensorflow import keras
rng = np.random.default_rng(0)
X = rng.normal(size=(600, 20)).astype("float32")
signal = X[:, 0] + 0.5 * X[:, 1]
y = (signal + rng.normal(0, 1.5, size=600) > 0).astype("float32")
X_train, y_train = X[:400], y[:400]
X_val, y_val = X[400:], y[400:]
model = keras.Sequential([
keras.layers.Input(shape=(20,)),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dense(128, activation="relu"),
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,
min_delta=1e-3,
restore_best_weights=True,
)
history = model.fit(
X_train, y_train,
validation_data=(X_val, y_val),
epochs=200,
batch_size=32,
callbacks=[early_stop],
verbose=0,
)
val_loss = history.history["val_loss"]
best_epoch = int(np.argmin(val_loss)) + 1
print("epochs run:", len(val_loss))
print("best epoch:", best_epoch)
print("best val_loss:", round(min(val_loss), 3))
print("final train_loss:", round(history.history["loss"][-1], 3))The run stops long before 200 epochs. The last training loss is usually well below the best validation loss, which shows the gap that early stopping avoided. Exact numbers vary with your TensorFlow version and hardware.
Choosing the settings
| Setting | What it does | Typical guidance |
|---|---|---|
| `monitor` | The metric to watch | Use `val_loss` by default. Use a metric such as `val_auc` only if it matches what you care about, and set `mode` to match. |
| `patience` | Epochs to wait after the last improvement | 3 to 10 for small problems. Larger values suit noisy validation curves. |
| `min_delta` | Smallest change that counts as improvement | Raises the bar so tiny fluctuations do not reset the counter. |
| `restore_best_weights` | Roll back to the best epoch | Set it to `True`. By default Keras keeps the final weights, which are `patience` epochs past the best. |
Patience trades off two errors. If it is too small, noise in the validation loss can stop training before the real minimum. If it is too large, you spend compute and, without restore_best_weights, keep overfitted weights.
Early stopping in scikit-learn
Several estimators have this built in.
MLPClassifierandMLPRegressor: setearly_stopping=True. The estimator holds outvalidation_fractionof the training data and stops aftern_iter_no_changeepochs without improvement.SGDClassifierandSGDRegressor: use the sameearly_stopping=Trueoption.HistGradientBoostingClassifier: setearly_stopping=Trueor"auto", which enables it when the sample count is above 10,000.GradientBoostingClassifier: setn_iter_no_change.
In each case the number of boosting rounds or epochs is chosen by the held-out portion, not fixed in advance.
Common errors
- Stopping on the test set. If you monitor test loss, the stopping point is tuned to the test data, and its score becomes optimistic. Monitor a validation set and keep the test set for one final evaluation.
- Reporting the stopping validation score as final. The validation set picked the best epoch, so its score is slightly optimistic. Report the test score instead.
- Reading noise as overfitting. Validation loss from a small validation set jumps around. Increase patience, enlarge the validation set, or use
min_delta. - Learning-rate schedules that interact with stopping. If the schedule lowers the learning rate late in training, validation loss can plateau and then improve again. A short patience would stop before that improvement.
- Leakage through the split. If
validation_splittakes the last part of the data, as Keras does, and your rows are ordered by class or time, the validation set is not representative. Shuffle first, or split by time on purpose.
When to use it, and when not
Early stopping is cheap and needs one extra hyperparameter. It also saves training time. Its costs are that it needs held-out data, which reduces what you train on, and that it ties the stopping point to a single split. With very small datasets, cross-validation with a fixed epoch count chosen from the average best epoch can be more stable. After choosing the epoch count, you can retrain on all training data for that many epochs.
For high-bias models, early stopping does not help. If training loss is also high, the model is underfitting, and stopping sooner makes it worse. Use it only once training error is low enough that the validation gap is the problem.
Exercise
Your model's training loss falls steadily for 100 epochs. Validation loss reaches its minimum at epoch 18, then rises slowly. You trained with EarlyStopping(monitor="val_loss", patience=10) and did not set restore_best_weights. At which epoch does training stop, and which weights does the model keep? Then name one change that fixes the problem.
Show answer
Training stops at epoch 28, which is 10 epochs after the best epoch (18). Without restore_best_weights=True, the model keeps the weights from epoch 28, which are already overfit. Set restore_best_weights=True to get the epoch 18 weights back.