AI Logic

Regularization

Early Stopping

Updated:

Example learning curves and stopping point. The horizontal axis is epochs and the vertical axis is loss. The training loss keeps decreasing, while the validation loss decreases and then starts to rise. The weights are saved at the point of minimum validation loss (the best model), training stops at epoch 46 after 10 epochs without improvement (patience = 10), and the saved best weights are restored. The dashed curve shows what happens if training continues

Background and overview

Early Stopping is a regularization method that stops training when the validation loss stops improving and returns the weights from the best point so far. The meaning of the term and where it is used are summarized in the glossary entry Early Stopping. This article explains it in detail as a regularization method: the criteria for when to stop, patience (how long to wait), how to keep the best model, and its relationship to L2 regularization.

When a large model is trained for a long time, the training loss keeps decreasing, but the validation loss starts to rise at some point. The figure above illustrates this; it marks the onset of overfitting. Section 7.8 of the textbook Deep Learning (Goodfellow et al., 2016) notes that this behavior appears reliably across experiments and introduces Early Stopping as "probably the most commonly used form of regularization in deep learning," because it is both effective and simple.

Early Stopping changes neither the loss function nor the model architecture. The only thing it changes is "how many steps to train." Therefore, it does not disturb training dynamics even when combined with other regularization. On the other hand, the actual validation loss is not a smooth U-shape but goes up and down in small fluctuations. Deciding at which point it has "stopped improving" is the crux of this method.

Procedure (the basic method with patience)

The commonly used method is explained following Algorithm 7.1 of Deep Learning. Two values must be set in advance: the evaluation interval nn (in steps) and the number of times to wait pp (patience).

  1. Set the best validation loss vv to ∞\infty and the number of non-improvements jj to 0.
  2. Train for nn steps.
  3. Measure the loss v′v' on the validation data.
  4. If v′<vv' < v (it improved), set v←v′v \leftarrow v', save the current weights θ∗\theta^* and the number of steps so far i∗i^*, and reset jj to 0.
  5. If it did not improve, increment jj by 1.
  6. Repeat steps 2–5 while j<pj < p. Stop when jj reaches pp.
  7. Return the saved best weights θ∗\theta^*, not the final weights.

In the figure above, validation is performed every epoch with p=10p = 10. After the validation loss reaches its minimum at the yellow point, it fails to go below that value 10 times in a row, so training stops there. The weights at the stopping point have already overfit somewhat, so the weights from the best point are restored.

Patience is a "wait" that prevents stopping too early because of small ups and downs in the validation loss. Stopping after a single worsening misses cases where the loss decreases again afterward. A larger value misses fewer such cases but lengthens training.

When to stop (stopping criteria)

Prechelt (1998) showed that the actual validation loss does not change smoothly. In an example with the glass classification dataset (Glass), there were 16 local minima in the validation loss before full-blown overfitting began at epoch 400. The best stopping point was at epoch 205; compared with stopping at the first deep minimum (epoch 45), training took about 7 times longer, while the validation loss improved by only 1.1%.

Prechelt therefore grouped stopping criteria into three classes and compared them on a large scale. Eva(t)E_{\text{va}}(t) is the validation error at epoch tt, Eopt(t)E_{\text{opt}}(t) is the lowest validation error up to that point, and Etr(t)E_{\text{tr}}(t) is the training error.

  1. GL (stop when the generalization loss exceeds a threshold): Measures how many percent the validation error has worsened from its minimum so far. Stop when GL(t)>αGL(t) > \alpha. GL(t)=100(Eva(t)Eopt(t)−1)GL(t) = 100 \left( \frac{E_{\text{va}}(t)}{E_{\text{opt}}(t)} - 1 \right)
  2. PQ (generalization loss divided by training progress): Measures whether the training error is still changing a lot within a strip of kk epochs. While the training error is decreasing quickly, a worsening of the validation error is considered recoverable, so stopping is made harder. Stop when GL(t)/Pk(t)>αGL(t)/P_k(t) > \alpha. Pk(t)=1000(∑t′=t−k+1tEtr(t′)k⋅min⁡t−k+1≤t′≤tEtr(t′)−1)P_k(t) = 1000 \left( \frac{\sum_{t'=t-k+1}^{t} E_{\text{tr}}(t')}{k \cdot \min_{t-k+1 \le t' \le t} E_{\text{tr}}(t')} - 1 \right)
  3. UP (stop when the validation error rises in successive strips): Measure the validation error at the end of each kk-epoch strip, and stop when it has risen relative to the previous strip ss times in a row. The size of the increase is ignored.

The paper uses a strip length of k=5k = 5. Whichever criterion triggers the stop, the result is the weights from the point of lowest validation error so far (keeping one copy of the weights is enough for this).

The method commonly written in PyTorch training loops, "stop if the minimum has not been updated for patience consecutive times" (the procedure in the previous section), is like GL in comparing against the minimum so far, and like UP in waiting for a number of times instead of stopping immediately.

Trade-off between speed and performance of criteria (experiments)

Prechelt compared a total of 1296 training runs over 12 tasks (real-world data from the Proben1 benchmark collection), 12 fully connected network architectures, and 14 criteria. The data was split into 50% training, 25% validation, and 25% test. The table below shows a subset. Training time and test error are ratios relative to criterion GL2GL_2.

CriterionTraining time (GL2GL_2 = 1)Test error (GL2GL_2 = 1)Rate of reaching the best result
UP2UP_20.7661.02458.7%
GL1GL_10.8231.01068.0%
GL2GL_21.0001.00072.3%
UP4UP_41.5660.99766.6%
GL5GL_52.0130.99177.2%
PQ3PQ_33.0950.98880.0%

"Rate of reaching the best result" is the fraction of runs in which the criterion was among those that found the lowest validation error among the criteria examined in that run.

  • Criteria that stop later are slightly better: Within the range examined, test error decreased by about 4% (1.024 → 0.988) at the cost of about 4 times the training time (0.766 → 3.095).
  • Even fast criteria are often sufficient: Even the fastest criterion reached the same result as the best in about 60% of runs. Even the slowest criterion did so in about 80%.
  • By the time training stops, extra training has already happened: Even with the fastest criterion, about one fifth of the total training time was spent after passing the best point. With slow criteria, training ran about twice as long as necessary.

Based on these results, Prechelt recommends the following choices.

  • If a small performance gain (e.g., 4%) is not worth a large increase in training time (e.g., 4×), use a fast criterion.
  • If training several times and picking the best (i.e., to raise the probability of reaching a good result), use a GL criterion.
  • To improve the average quality of a single run, use PQ when overfitting is small, and UP otherwise.

Relationship to L2 regularization (why it is regularization)

Section 7.8 of Deep Learning explains why Early Stopping acts as regularization as follows. If only τ\tau steps are taken with a learning rate ϵ\epsilon, the weights can move only within a limited region around their initial values. ϵτ\epsilon\tau serves as a measure of the effective capacity of the model.

Furthermore, for a linear model with a quadratic approximation of the loss, the book shows that Early Stopping is equivalent to L2 regularization (Weight Decay).

  1. Let w∗w^* be the optimal weights without regularization, and H=QΛQ⊤H = Q \Lambda Q^\top the Hessian of the loss (Λ\Lambda is the diagonal matrix of eigenvalues λi\lambda_i).
  2. Starting from 0 and taking τ\tau steps of gradient descent with learning rate ϵ\epsilon, the weights become (Eq. (7.40)) Q⊤w(τ)=[I−(I−ϵΛ)τ]Q⊤w∗Q^\top w^{(\tau)} = \left[ I - (I - \epsilon\Lambda)^{\tau} \right] Q^\top w^*
  3. On the other hand, the optimal weights w~\tilde{w} under L2 regularization of strength α\alpha can be written as (Eq. (7.42)) Q⊤w~=[I−(Λ+αI)−1α]Q⊤w∗Q^\top \tilde{w} = \left[ I - (\Lambda + \alpha I)^{-1} \alpha \right] Q^\top w^*
  4. Comparing 2 and 3, if the values are chosen so that (I−ϵΛ)τ=(Λ+αI)−1α(I - \epsilon\Lambda)^{\tau} = (\Lambda + \alpha I)^{-1}\alpha, the two give the same weights. When the eigenvalues are small, this condition becomes approximately (Eqs. (7.44) and (7.45)) τ≈1ϵα,α≈1τϵ\tau \approx \frac{1}{\epsilon\alpha}, \qquad \alpha \approx \frac{1}{\tau\epsilon}

In other words, the number of training steps τ\tau plays a role like the inverse of the L2 regularization strength. The longer the training, the weaker the regularization. In both cases, weights along directions of high curvature of the loss (directions the data clearly demands) are learned early and to a large extent, while weights along directions of low curvature remain small.

However, Early Stopping does not merely limit the number of steps; it chooses the stopping point by monitoring the validation loss. As a result, it effectively tries many regularization strengths automatically within a single training run. This is the advantage of Early Stopping over L2 regularization, whose strength must be determined by retraining many times with different values.

Practical considerations

Keep the validation data used to choose the stopping point separate from the test data used to measure final performance. Stopping based on the test data amounts to selecting for the test data, making test scores look better than the true performance. Also, if the validation data is small, the validation loss fluctuates more and the stopping point becomes unstable.

  • Always save the best weights: The weights at the stopping point have overfit by the amount of patience. The copy of the best weights can be kept in CPU memory or on disk rather than GPU memory. Writes happen only occasionally and are never read during training, so this has almost no effect on training speed (Deep Learning, Section 7.8).
  • Switch to model.eval() for each validation: When there are layers that behave differently in training and inference, such as Dropout and batch normalization, call model.eval() before validation and model.train() when returning to training. Forgetting this makes the validation loss fluctuate and shifts the stopping point.
  • Keep the cost of validation down: Validation is performed many times between training steps and takes time. The cost can be reduced by making the validation set smaller than the training set or by validating less often, although both make the stopping point coarser.
  • The validation data can be returned to training later: The validation data reduces the amount of data available for training. Deep Learning introduces two approaches. One is to retrain on all the data for the number of steps i∗i^* determined by Early Stopping, although there is no rule for whether to match the number of "steps" or "epochs" now that there is more data. The other is to continue training from the stopped weights on all the data until the validation loss falls below the training loss at the stopping point; this may never reach the target and never terminate.
  • Combine it with other regularization: Early Stopping can be used alone or together with Weight Decay, Dropout, and others. Even with regularization that modifies the loss, it is rare for generalization to be best exactly where the training loss is minimized.

Comparison with other regularization methods

Early Stopping and regularization methods commonly used with it, compared from the same perspectives.

MethodWhat is modifiedExtra computationHow the strength is chosen
Early StoppingTraining lengthEvaluation on validation data, a copy of the weightsDetermined automatically within one run by monitoring validation loss
Weight DecayWeight updates (shrinking weights)Almost noneTrain many times with different values and compare
DropoutNetwork (dropping units)Almost none (training becomes slower)Train many times with different values and compare
MixupTraining data (mixing inputs and labels)Additions and shufflingTrain many times with different values and compare
  • Add it first: Early Stopping can be added without changing the training procedure, so it is convenient to include it first even when using other regularization.
  • Its strength is easy to set: With Weight Decay, too strong a setting can trap the model in a bad solution with overly small weights. Early Stopping does not change training dynamics, so such failures are unlikely (Deep Learning, Section 7.8).
  • Unusable without validation data: When data is so scarce that no validation set can be held out, rely on other regularization.

PyTorch example

Show code
python
import copy
import torch
import torch.nn as nn


class EarlyStopping:
    """Stop if the validation loss fails to improve on its minimum for patience consecutive times (Deep Learning, Algorithm 7.1)"""

    def __init__(self, patience=10, min_delta=0.0):
        self.patience = patience      # Number of times to wait p
        self.min_delta = min_delta    # Improvements smaller than this do not count
        self.best = float("inf")      # Best validation loss v
        self.best_state = None        # Best weights θ*
        self.best_epoch = 0           # Epoch of the best point i*
        self.count = 0                # Number of non-improvements j

    def step(self, val_loss, model, epoch):
        if val_loss < self.best - self.min_delta:
            self.best = val_loss
            self.best_epoch = epoch
            self.count = 0
            # The weight copy may be kept on the CPU
            self.best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
        else:
            self.count += 1
        return self.count >= self.patience   # Stop if True


def generalization_loss(val_losses):
    """Prechelt's GL(t) = 100 (E_va(t) / E_opt(t) − 1)"""
    return 100 * (val_losses[-1] / min(val_losses) - 1)


model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Dropout(0.2), nn.Linear(256, 10))
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
stopper = EarlyStopping(patience=10)

# Dummy training and validation data (use a DataLoader in practice)
x_train, y_train = torch.randn(512, 1, 28, 28), torch.randint(0, 10, (512,))
x_val, y_val = torch.randn(128, 1, 28, 28), torch.randint(0, 10, (128,))

for epoch in range(1, 201):
    model.train()                       # Train with Dropout enabled
    optimizer.zero_grad()
    loss = criterion(model(x_train), y_train)
    loss.backward()
    optimizer.step()

    model.eval()                        # Always switch to eval before validation
    with torch.no_grad():
        val_loss = criterion(model(x_val), y_val).item()

    if stopper.step(val_loss, model, epoch):
        print(f"Stopped at epoch {epoch}. Best was epoch {stopper.best_epoch}")
        break

# Restore the best weights, not the final ones
model.load_state_dict(stopper.best_state)

FAQ

Q. How large should patience be?
A.

Choose it based on how much the validation loss fluctuates and how much training time is available. The larger the fluctuations, the larger the value should be so that small ups and downs do not stop training early. In Prechelt's experiments, criteria that stopped later gave slightly better test error but much longer training (about 4% improvement for about 4 times the time). Start with a small value and increase it if time allows.

Q. Should I use the weights at the stopping point or the best weights?
A.

Use the best weights. At the stopping point, training has progressed by the amount of patience past the best point, and overfitting has begun. Therefore, save the weights from the point of minimum validation loss and restore them when training finishes.

Q. How does this differ from the glossary entry on Early Stopping?
A.

The glossary entry briefly summarizes the meaning of the term and where it is used. This article explains it in detail as a regularization method: stopping criteria (GL, PQ, UP, and patience), how to keep the best weights, why it works like L2 regularization, and practical considerations.

References

  1. L. Prechelt, "Early Stopping — But When?," in Neural Networks: Tricks of the Trade, LNCS 1524, Springer, 1998, pp. 55–69.
  2. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016. Section 7.8: Early Stopping.