Overfitting and regularisation

Learning curves, and methods that keep a network from memorising its training runs.

Outcome: Read training and validation curves; use early stopping, weight decay and dropout; tune hyperparameters on the validation set only.

Builds on Normalising and the training loop

The training loss and the validation loss, plotted against the training step, are the learning curves. Three patterns cover most cases. Both fall together: the network is still learning. Both stay high: it is usually underfitting, and the remedies are longer training or a larger model; if neither helps, the cause may be scatter in the data or a missing input. Training keeps falling while validation flattens and rises: it is overfitting, fitting the noise and the peculiarities of its training runs, as the high-degree polynomials did in train, validation and test.

Remedies for overfitting

Early stopping. A copy of the weights is kept whenever the validation loss reaches a new low; training stops when it has not improved for a set number of epochs, and the weights roll back to that copy.

Weight decay. Each step shrinks every weight slightly, which tends to favour smoother functions. AdamW with a small weight_decay applies the shrinking directly to the weights, separately from the gradient step, not as a term in the loss (Loshchilov and Hutter 2019, who showed that the two coincide for plain SGD but not for Adam).

Dropout. During training, a random fraction of a layer’s outputs is set to zero, so the network cannot rely on any one neuron (Srivastava et al. 2014). It is common in classification and used more sparingly in regression, where its effect depends on where it is placed (Kong et al. 2022, on image super-resolution).

More data. Usually the surest cure (Goodfellow et al. 2016, chapter 7), and for a surrogate that means more runs, not more points per run. Points of one run are strongly related, so 36 training runs of 2,000 points each are closer to 36 examples than to 72,000. Where the physics has a symmetry (a mirror plane, a periodic sector), mirrored or rotated copies of runs are extra data at no solver cost, provided the symmetry holds exactly.

A smaller model. Fewer or narrower layers. Parameter counts are only a rough guide, though: large networks often generalise well (Belkin et al. 2019). The validation curve decides, not the count.

Example 4-6 is the loop of Example 4-5 with weight decay and early stopping. It drops the cosine schedule, whose length was set by a fixed number of epochs, and allows up to 2,000 epochs, of which early stopping uses only as many as it needs.

Example 4-6. Weight decay and early stopping in the training loop, in PyTorch
import copy
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from aircraft import MLP, load_runs, scale_designs, split_runs

# Data, scaling and model as in the loop of 4.3.
torch.manual_seed(0)
d = load_runs()
tr, va, _, _ = split_runs(d)
Xn, mu, sd = scale_designs(d, tr)
y = d["CL"][:, None]
ym, ys = y[tr].mean(), y[tr].std()
T = lambda a: torch.tensor(a, dtype=torch.float32)
X_tr, y_tr = T(Xn[tr]), T((y[tr] - ym) / ys)
X_val, y_val = T(Xn[va]), T((y[va] - ym) / ys)
loader = DataLoader(TensorDataset(X_tr, y_tr),
                    batch_size=8, shuffle=True)
# Dropout would go in the layers of MLP:
#   nn.Linear(2, width), nn.SiLU(), nn.Dropout(0.1), ...
model = MLP()
loss_fn = nn.MSELoss()
opt = torch.optim.AdamW(model.parameters(), lr=3e-3,1
                        weight_decay=1e-4)

best, waited, patience = float("inf"), 0, 502
for epoch in range(2000):
    model.train()
    for xb, yb in loader:
        loss = loss_fn(model(xb), yb)
        opt.zero_grad()
        loss.backward()
        opt.step()
    model.eval()
    with torch.no_grad():
        val_loss = loss_fn(model(X_val), y_val).item()
    if val_loss < best:
        # A new best: keep a copy of the weights.
        best, best_epoch, waited = val_loss, epoch, 0
        best_state = copy.deepcopy(model.state_dict())3
    else:
        waited += 1
        if waited >= patience:
            break
# Roll back to the best epoch.
model.load_state_dict(best_state)4
print(f"stopped after epoch {epoch}, best epoch {best_epoch},"
      f" val RMSE {ys * best ** 0.5:.4f} in CL")
  1. AdamW shrinks every weight by a small fraction at each step, set by weight_decay and the learning rate, separately from the gradient step.
  2. patience: how many epochs without a new best validation loss to wait before stopping, here 50.
  3. state_dict() returns the live weight tensors, which keep changing as training goes on; deepcopy freezes a copy.
  4. The weights roll back to the copy from the best epoch, not the last one.

Example 4-6 prints stopped after epoch 269, best epoch 219, val RMSE 0.0004 in CL. The stop says only that 50 epochs brought no new best; whether the validation loss was flat or rising by then is read from the learning curves. The weights kept are those of epoch 219.