Early stopping: restore the model you selected
提前停止
Run a checkpoint-aware controller and distinguish patience, improvement thresholds, stopped parameters and restored parameters.
early-stoppingStop at one point, return to another
A training curve can keep improving after the validation curve has passed its best point. An early-stopping rule waits long enough to avoid reacting to every fluctuation, but waiting means the final parameters may already be worse than an earlier checkpoint. “Stopped automatically” and “restored the best model” are separate behaviors.
Deep Learning, Section 7.8 and Algorithm 7.1 describes checking validation performance, saving improving parameters and returning the saved model after patience runs out. The archived Keras 2 EarlyStopping API exposes separate controls for the monitored quantity, improvement threshold, patience, warm-up and restoration; its documented default for restore_best_weights is false.
We will execute a tiny training loop that really stops and really returns an earlier parameter. It makes the checkpoint decision visible without relying on a plot that only suggests where one might stop.
A training target and a validation target disagree
Use a scalar predictor θ. One synthetic training observation has target 2; a separate validation observation has target 1. The losses and gradient-descent trajectory from θ₀=0 at rate 1/4 are:
The recurrence follows by subtracting one quarter of the training gradient θ−2. Subtracting the training optimum 2 on both sides shows the remaining distance shrinks by 3/4 each step, giving the closed form. No validation gradient is used for training.
At epochs 1 and 2, θ is 1/2 and 7/8. Validation loss falls to 1/8 and then 1/128. At epochs 3 and 4, θ becomes 37/32 and 175/128, while validation loss rises to 25/2048 and 2209/32768. Training loss continues to decrease throughout.
Define improvement and patience precisely
Our monitor minimizes a nonnegative validation loss v. It accepts a new checkpoint only when the loss is more than δ below the best previously accepted loss b. Otherwise it increments the consecutive unsuccessful-check count c:
STOP denotes termination. Here δ is nonnegative and p is a positive patience count. The first observation initializes b and a snapshot. This strict inequality means a tie does not reset patience; an improvement of exactly δ does not reset it either. With positive δ, the accepted checkpoint need not be the raw minimum observed loss. This is our declared policy, not a claim of exact compatibility with every framework callback.
We observe the untrained baseline at epoch zero and then after every training step. With δ=0 and p=2, epoch 2 becomes the best checkpoint, epochs 3 and 4 consume patience, and training ends at epoch 4. Returning θ=175/128 would return the last model. Restoring θ=7/8 returns the selected one, whose validation loss is 1/128.
Why training time can act like regularization
For this one-dimensional quadratic only, a ridge-penalized optimum can match the early iterate:
Differentiate the penalized objective to get (1+λ)θ−2=0, then solve for the λ that matches θₜ. At t=2, λ=9/7 yields θ=7/8. This original calculation illustrates implicit shrinkage along this trajectory. It is not a universal equivalence between early stopping and one scalar L 2 penalty in a multidimensional or nonlinear model.
Store the selected state and stop computing
The complete Python 3.12 program uses immutable fractions as snapshots. It checks before changing monitor state that epochs increase, losses are nonnegative bounded rationals and the monitor has not already stopped. Patience is limited to 1–32 checks; the run has a separate maximum epoch budget. Both patience exhaustion and budget exhaustion return the selected checkpoint, including the untrained baseline if that remains selected.
from fractions import Fraction as F
def scalar(x):
if type(x) not in (int,F) or abs(x)>1000:raise ValueError('bounded rational required')
return F(x)
class EarlyStop:
def __init__(self, patience=2, min_delta=0):
if type(patience) is not int or not 1<=patience<=32:raise ValueError('patience must be 1 through 32')
delta=scalar(min_delta)
if delta<0:raise ValueError('nonnegative min_delta required')
self.patience,self.delta=patience,delta
self.best=None;self.snapshot=None;self.bad=0;self.last=-1;self.stopped=False
def observe(self, epoch, theta, metric):
if self.stopped:raise ValueError('monitor already stopped')
if type(epoch) is not int or not self.last<epoch<=64:raise ValueError('strictly increasing epoch required')
theta,metric=scalar(theta),scalar(metric)
if metric<0:raise ValueError('nonnegative loss required')
if self.best is None or metric<self.best-self.delta:
self.best=metric;self.snapshot=(epoch,theta);self.bad=0
else:self.bad+=1
self.last=epoch;self.stopped=self.bad>=self.patience
return self.stopped
def train(max_epochs=20, patience=2, min_delta=0):
if type(max_epochs) is not int or not 0<=max_epochs<=64:raise ValueError('epoch budget must be 0 through 64')
monitor=EarlyStop(patience,min_delta);theta=F(0);trace=[]
monitor.observe(0,theta,(theta-1)**2/2)
for epoch in range(1,max_epochs+1):
theta-=F(1,4)*(theta-2)
train_loss=(theta-2)**2/2;val_loss=(theta-1)**2/2
stopped=monitor.observe(epoch,theta,val_loss)
trace.append((epoch,theta,train_loss,val_loss))
if stopped:break
return dict(trace=trace,last_theta=theta,restored_theta=monitor.snapshot[1],
best_epoch=monitor.snapshot[0],best_loss=monitor.best,
reason='patience' if monitor.stopped else 'budget')
if __name__=='__main__':
result=train()
for epoch,theta,loss,val in result['trace']:
print('epoch:',epoch,'theta:',theta,'train:',loss,'validation:',val)
for key in ('reason','last_theta','restored_theta','best_epoch','best_loss'):print(key+':',result[key])
Actual output:
epoch: 1 theta: 1/2 train: 9/8 validation: 1/8
epoch: 2 theta: 7/8 train: 81/128 validation: 1/128
epoch: 3 theta: 37/32 train: 729/2048 validation: 25/2048
epoch: 4 theta: 175/128 train: 6561/32768 validation: 2209/32768
reason: patience
last_theta: 175/128
restored_theta: 7/8
best_epoch: 2
best_loss: 1/128
Only four parameter updates occur in the default run; later states are not precomputed and then hidden. Tests check the literal trajectory and restored loss, a plateau, exact-threshold behavior, the zero-epoch budget and invalid observations. Scalar work is O(T) for T completed updates; this teaching trace uses O(T) storage. For P model parameters, one in-memory checkpoint generally needs O(P) storage, apart from the trace and training state.
A validation set is a decision input
Repeatedly inspecting validation results and choosing training duration makes the validation set part of model selection. It cannot also provide an untouched final test estimate. Trying many architectures and stopping policies against a small validation set can select its noise. The two-observation example proves how the controller behaves; it does not estimate real-world generalization.
Patience counts validation checks in our rule. If validation happens every five epochs, patience two does not mean two epochs. A noisy metric may need a longer patience, an explicit smoothing rule or repeated evaluation; each changes the selection procedure and should be recorded.
A checkpoint for inference needs the selected model parameters and relevant non-parameter state, such as normalization statistics. To resume training faithfully, optimizer moments, scheduler position and random-generator state may also matter. This scalar example has none of those additional states, so restoring a fraction is sufficient only here.
Monitor direction also matters: smaller loss is better, whereas an accuracy monitor commonly wants larger values. The present controller supports minimization only, has no warm-up or baseline target, and does not clone the Keras API. Nonfinite metrics are rejected rather than silently treated as ordinary bad epochs.
Which model will be returned?
- With patience two in the default run, what are the stopping epoch and selected epoch?
Answer 1: Stop at epoch 4; select epoch 2.
- What loss does restoring the selected parameter recover?
Answer 2: Validation loss 1/128 at θ=7/8.
- Under our strict policy, does an improvement of exactly min_delta reset patience?
Answer 3: No. It must exceed min_delta.
- What ridge coefficient matches the second iterate in this scalar example?
Answer 4: λ=9/7, because 2/(1+9/7)=7/8.
Checkpoint selection is part of the algorithm
The textbook supplies the validation-and-checkpoint procedure; the archived API illustrates that restoration and stopping have separate controls. The exact trajectory, scalar ridge calculation, monitor and tests are original, with no Keras execution or reproduced benchmark claim.
Read training, validation and test splits before interpreting the selected score. Compare weight decay for an explicit update intervention and epochs and steps for the unit of patience and training budget.
Make a prediction, then check
Which parameter does the default controller return?
Learning objectives
- Execute a stopping rule with explicit checkpoint restoration.
- Separate validation selection from untouched test evaluation.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 7: Regularization for Deep Learning
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - EarlyStopping — Keras 2 API
Keras contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Decay paths, exact dropout distributions, checkpoint restoration and batch-normalization derivatives/state are checked against literal references, analytic identities and finite differences. Three examples use the standard library; BatchNorm uses NumPy1.26.4.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Deep Learning — Chapter 7: Regularization for Deep Learning · Section7.8 printed241–245, Algorithm7.1 printed244: validation checks, saved improving parameters and patience; scalar ridge relation derived independently.
- EarlyStopping — Keras 2 API · ArchivedKeras2 signature and argument descriptions: monitor/min_delta/patience/warm-up/restore_best_weights defaultFalse; strict comparator is our policy, not an API equivalence claim.
Related topics