Deep learning in practice · lesson 8 of 13
Parts in this lesson
Atorch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.1)weight decay, decoupled from the gradient (lesson 7.3)
Bnn.Dropout(0.5)switches off each unit with probability 0.5 in training mode only
CF.pad(images, (1, 1, 1, 1))a border of zeros, so a window can slide one pixel each way

Regularisation for deep nets

Last updated

A network with 85,000 weights and 200 training images can learn every image by heart, and then it does worse on images it hasn't seen. This lesson makes that happen on purpose and tries the four standard remedies, one at a time: weight decay, dropout, data augmentation and early stopping. Then it shows what goes wrong if you forget that dropout must be switched off when you measure.

By the end of this lesson you can

  • Recognise overfitting from training and validation numbers
  • Add weight decay, dropout and data augmentation to a PyTorch model
  • Stop training at the best validation loss
  • Explain why dropout must be off during evaluation

Overfitting on 200 digits

Lesson 2.6 defined overfitting: a model that fits its training data better than the pattern behind it, so it scores well on what it has seen and worse on what it hasn't. A deep network is especially good at it, because it has so many weights. The network here has 64⋅256+256⋅256+256⋅10, plus 522 biases: 85,002 numbers, learning from only 200 digits.

This one script trains the same network five ways, 150 epochs each, and measures it on 500 other digits after every epoch. The first row, "nothing", is the plain network:

"""Overfitting on 200 digits, and four ways to fight it: weight decay, dropout, augmentation, early stopping."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X / 16, y, train_size=200, test_size=500, stratify=y, random_state=0)
X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_train, y_val = torch.tensor(y_train), torch.tensor(y_val)


def shift(xb):
    """Move each 8x8 image by up to one pixel in each direction, filling the edge with 0."""
    imgs = F.pad(xb.view(-1, 8, 8), (1, 1, 1, 1))
    dx, dy = torch.randint(0, 3, (2, len(xb)))
    return torch.stack([imgs[i, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))]).view(-1, 64)


def run(weight_decay=0.0, dropout=0.0, augment=False, epochs=150):
    torch.manual_seed(0)
    model = nn.Sequential(
        nn.Linear(64, 256), nn.ReLU(), nn.Dropout(dropout),
        nn.Linear(256, 256), nn.ReLU(), nn.Dropout(dropout),
        nn.Linear(256, 10),
    )
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=weight_decay)
    history = []
    for epoch in range(epochs):
        model.train()
        for idx in torch.randperm(200).split(32):
            xb = shift(X_train[idx]) if augment else X_train[idx]
            loss = F.cross_entropy(model(xb), y_train[idx])
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        model.eval()
        with torch.no_grad():
            train_acc = (model(X_train).argmax(1) == y_train).float().mean().item()
            val_loss = F.cross_entropy(model(X_val), y_val).item()
            val_acc = (model(X_val).argmax(1) == y_val).float().mean().item()
        history.append((train_acc, val_loss, val_acc))
    return history


print(f"{'':22} train acc  val acc  val loss")
runs = {
    "nothing": run(),
    "weight decay 0.1": run(weight_decay=0.1),
    "dropout 0.5": run(dropout=0.5),
    "shifted images": run(augment=True),
    "all three": run(weight_decay=0.1, dropout=0.5, augment=True),
}
for name, h in runs.items():
    train_acc, val_loss, val_acc = h[-1]
    print(f"{name:22} {train_acc:9.3f} {val_acc:8.3f} {val_loss:9.3f}")

# early stopping on the first run: keep the epoch with the lowest validation loss,
# and stop once 10 epochs in a row haven't beaten it
h = runs["nothing"]
best, wait = 0, 0
for epoch in range(1, len(h)):
    if h[epoch][1] < h[best][1]:
        best, wait = epoch, 0
    else:
        wait += 1
        if wait == 10:
            break
print(f"early stopping: lowest validation loss {h[best][1]:.3f} at epoch {best + 1}, stopped at epoch {epoch + 1},"
      f" validation accuracy {h[best][2]:.3f}")
print("nothing, validation loss at epochs 10, 25, 50, 100, 150:", " ".join(f"{h[e - 1][1]:.3f}" for e in (10, 25, 50, 100, 150)))
Terminal, in ml-local/7-8
(.venv) $ python regularise.py
                       train acc  val acc  val loss
nothing                    1.000    0.930     0.342
weight decay 0.1           1.000    0.934     0.315
dropout 0.5                1.000    0.930     0.304
shifted images             1.000    0.906     0.245
all three                  0.985    0.928     0.275
early stopping: lowest validation loss 0.255 at epoch 29, stopped at epoch 39, validation accuracy 0.922
nothing, validation loss at epochs 10, 25, 50, 100, 150: 0.387 0.274 0.274 0.316 0.342

Training accuracy 1.000: every one of the 200 digits right. Validation accuracy 0.930. The gap is the overfitting. The last line shows it happening over time: the validation loss falls to 0.274 by epoch 25, stays there to epoch 50, then rises, to 0.342 by epoch 150. The network kept getting more confident about its training digits, and more confidently wrong about some of the others.

Watch the validation loss rather than only the accuracy. Accuracy only changes when an answer flips; the loss sees confidence too, so it shows overfitting sooner.

Weight decay

Lesson 3.8 fought overfitting in linear models by penalising big weights: ridge regression adds λ2‖θ‖2 to the loss. Weight decay is the same idea for networks: every step, shrink every weight a little towards 0, as well as following the gradient:

θ←θ−η∇L−ηλθ

In words: the usual step, then take away a small fraction ηλ of each weight. A weight survives only if the gradient keeps pushing it back. Big weights let a network make sharp, confident distinctions between nearly identical inputs, which is what memorising looks like; weight decay makes those expensive. With AdamW, lesson 7.3's optimiser, it's the weight_decay argument.

With λ=0.1: validation accuracy 0.934, loss 0.315 against 0.342. Training accuracy is still 1.000. A small improvement, and nearly free.

Dropout

Dropout (Srivastava and others, 2014) switches off each hidden unit at random during training, with probability p, a fresh choice for every batch. A unit can't rely on any particular other unit being there, so the network can't build fragile chains that only fit the training set; it has to spread what it knows across many units.

The units that stay on are scaled up, so the next layer receives the same total on average:

a˜=m⊙a1−p,mj∼Bernoulli⁡(1−p)

In words: m is a random mask of 0s and 1s, one per unit; each mj is 1 with probability 1−p and 0 otherwise (a Bernoulli draw, like a biased coin). Multiply the layer's outputs by the mask (that's ⊙, item by item), then divide by 1−p. With p=0.5, half the units go silent and the other half count double. In evaluation mode, nothing is switched off and nothing is scaled, and because of that division during training, the sizes already match. This version is called "inverted dropout", and it's what nn.Dropout does.

Dropout flickerhidden units switched off at random, a new choice every step
×××2×2×2××××2×2×××2×2××inputshidden 1hidden 2outputs

Training step 1: 5 of 8 units off in hidden layer 1, 4 of 8 in hidden layer 2. Each unit is off with probability 0.5; the ones left on are multiplied by 1/(1 − 0.5) = 2.00, so on average the next layer receives the same total.

In the table, dropout 0.5 left validation accuracy at 0.930 but brought the loss down from 0.342 to 0.304: the same answers, held less overconfidently. Dropout helps most in big networks trained for long on lots of data, and it's common in the fully connected layers of larger models.

Data augmentation

The best cure for overfitting is more data. Data augmentation makes more from what you have: change each training example in a way that shouldn't change its label, a fresh change every time it's used. For images: shift, flip, rotate, crop, change the brightness. For these tiny 8×8 digits, the script's shift moves each image by up to one pixel in each direction:

"""One training digit, and the same digit moved by one pixel, as regularise.py's shift() does."""
import torch
from sklearn.datasets import load_digits
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
image = torch.tensor(X[0], dtype=torch.float32)  # pixel values 0 to 16
print(f"digit {y[0]}, pixel values 0 to 16:")
for row in image.view(8, 8).int().tolist():
    print("  " + " ".join(f"{v:2d}" for v in row))

padded = F.pad(image.view(8, 8), (1, 1, 1, 1))
right = padded[1:9, 0:8]                          # take the window one pixel to the left: the digit moves right
print("moved one pixel right:")
for row in right.int().tolist():
    print("  " + " ".join(f"{v:2d}" for v in row))
Terminal, in ml-local/7-8
(.venv) $ python augment.py
digit 0, pixel values 0 to 16:
   0  0  5 13  9  1  0  0
   0  0 13 15 10 15  5  0
   0  3 15  2  0 11  8  0
   0  4 12  0  0  8  8  0
   0  5  8  0  0  9  8  0
   0  4 11  0  1 12  7  0
   0  2 14  5 10 12  0  0
   0  0  6 13 10  0  0  0
moved one pixel right:
   0  0  0  5 13  9  1  0
   0  0  0 13 15 10 15  5
   0  0  3 15  2  0 11  8
   0  0  4 12  0  0  8  8
   0  0  5  8  0  0  9  8
   0  0  4 11  0  1 12  7
   0  0  2 14  5 10 12  0
   0  0  0  6 13 10  0  0
Augmentation stripone digit, and eight copies moved by one pixel
originalrightleftdownupdown rightdown leftup rightup left

Moved right: the same 0, with a row or column of zeros where the edge was. To a person all nine are the same digit; to the network they are nine different lists of 64 numbers, so training on them teaches it that a small shift doesn't change the answer. The "right" copy matches the one augment.py printed.

F.pad puts a border of zeros around the image, making it 10×10, and an 8×8 window cut from it is the image moved by one pixel. Starting the window one column to the left moves the digit one column right.

The results disagree with each other in an instructive way. Shifted images gave the lowest validation loss of any single method, 0.245, but also the lowest accuracy, 0.906. On an 8×8 image, a one-pixel shift is an eighth of its width: a big change, and some shifted digits push the edge of the digit off the image. The network learned to be less sure of itself, which the loss rewards, but it also lost some accuracy. For real photographs, where a shift of a few pixels is tiny, augmentation is one of the most effective tricks there is, and Stage 8 uses it on every image model. The lesson here is the general one: choose changes that really don't change the label.

Combining all three gave training accuracy 0.985, no longer perfect, and validation 0.928 with a loss of 0.275. Regularisers don't simply add up; each one makes the training task harder, and too much of that becomes underfitting.

Early stopping

The simplest regulariser costs nothing: stop at the right time. Measure the validation loss after every epoch, keep a copy of the model whenever it's the best so far, and stop once it hasn't improved for a while (the patience, here 10 epochs). This is early stopping.

The script's early stopping, run on the "nothing" network's history, found the lowest validation loss, 0.255, at epoch 29, and would have stopped at epoch 39 instead of running to 150. Validation accuracy there was 0.922. Its loss, 0.255, beats every row of the table except the shifted images, and it saved three quarters of the training time.

In a real training loop, "keep a copy" means saving the weights: best = copy.deepcopy(model.state_dict()) when the loss improves, and model.load_state_dict(best) at the end. Lesson 7.11 covers state_dict. Early stopping uses the validation set to make a decision, so, as in lesson 2.9, the final score must come from a test set it never touched.

Wrong way: dropout left on at test time

nn.Dropout checks the model's mode every time it runs. Forget model.eval() before measuring, and it keeps switching units off:

"""The wrong way: measuring a network that uses dropout without switching to model.eval()."""
import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
X, y = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)
X_train, y_train, X_val, y_val = X[:1200], y[:1200], X[1200:], y[1200:]

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Dropout(0.5), nn.Linear(256, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(30):
    model.train()
    for idx in torch.randperm(len(X_train)).split(32):
        loss = F.cross_entropy(model(X_train[idx]), y_train[idx])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

with torch.no_grad():
    # still in training mode: dropout switches off a random half of the hidden units on every call
    print("left in train mode, three measurements:",
          " ".join(f"{(model(X_val).argmax(1) == y_val).float().mean().item():.3f}" for _ in range(3)))
    print("the first image, scored twice:", model(X_val[:1]).argmax(1).item(), model(X_val[:1]).argmax(1).item(),
          "   its top score twice:", f"{model(X_val[:1]).max().item():.2f}", f"{model(X_val[:1]).max().item():.2f}")
    model.eval()
    print("after model.eval():                   ",
          " ".join(f"{(model(X_val).argmax(1) == y_val).float().mean().item():.3f}" for _ in range(3)))
Terminal, in ml-local/7-8
(.venv) $ python dropout_eval.py
left in train mode, three measurements: 0.911 0.916 0.923
the first image, scored twice: 7 7    its top score twice: 4.38 4.52
after model.eval():                    0.928 0.928 0.928

In training mode, three measurements of the same model on the same data give three different accuracies: 0.911, 0.916 and 0.923. Even one image gets a different score each time, 4.38 then 4.52. After model.eval(), it's 0.928 every time, higher than all three.

Nothing crashes, so nothing tells you. The symptoms are an accuracy that changes when you rerun the same evaluation, and a model that seems slightly worse than it is. The same switch also changes batch norm (lesson 7.7). Make it a habit: model.eval() and torch.no_grad() before measuring, model.train() before the next epoch.

Check what you learned

Training accuracy is 1.000, and every extra epoch makes the validation loss worse. What is happening?
With nn.Dropout(0.5) in training mode, what happens to a hidden unit that isn’t switched off?
You evaluate the same model on the same validation set twice and get 0.911, then 0.916. What’s the likely cause?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning