Dropout and Other Network Regularisers
A network with a few hundred thousand parameters can memorise a few thousand training examples, labels and noise included. Every regulariser is a way to make memorising harder than learning the pattern: penalise large weights (weight decay), train a different random sub-network at each step (dropout, stochastic depth), refuse to let the model become infinitely confident (label smoothing), or show it more varied data (augmentation). Weight decay and the basic dropout mechanism are introduced in Weight Decay and Dropout, with a from-scratch network on the moons data, and the general theory of penalties in Regularization. This lesson collects the regularisers used in deep networks, implements the less familiar ones in NumPy, measures them honestly on a small Digits problem, and turns dropout into an uncertainty estimate (MC dropout).
The regularisers as formulas
Inverted dropout multiplies each activation by an independent mask, scaled so the expectation is unchanged:
At evaluation the layer is the identity. The mean is preserved, the variance is not: training sees noisier activations than inference.
Stochastic depth (DropPath) applies the same idea to whole residual branches: in a block , with probability the branch of an example is skipped, , and otherwise it is scaled by . Vision transformers and ConvNeXt use it with rising linearly from 0 at the first block to about 0.1 to 0.5 at the last.
Label smoothing replaces the one-hot target of class among classes by
so the cross-entropy is minimised by a finite logit gap instead of an infinite one.
Weight decay shrinks every weight a little at each step, ; with Adam use the decoupled form AdamW (the difference is explained in Adam and AdamW).
The mechanics in NumPy
import numpy as np
rng = np.random.default_rng(0)
def dropout(h, p, training):
"""Inverted dropout: drop units with probability p, scale the rest by 1/(1-p)."""
if not training or p == 0:
return h, None
mask = (rng.random(h.shape) >= p) / (1 - p)
return h * mask, mask # the backward pass multiplies by the same mask
h = rng.uniform(0, 2, (10_000, 50)) # activations of a layer for 10,000 examples
for p in (0.1, 0.5):
out, mask = dropout(h, p, True)
print(f"p={p}: zeros {float((out == 0).mean()):.3f} mean {h.mean():.3f} -> {out.mean():.3f}"
f" std {h.std():.3f} -> {out.std():.3f}")
def drop_path(branch, p, training):
"""Stochastic depth: drop the WHOLE residual branch of an example, not single units."""
if not training or p == 0:
return branch
keep = (rng.random((branch.shape[0], 1)) >= p) / (1 - p) # one draw per example
return branch * keep
x = np.ones((6, 4))
y = x + drop_path(np.full((6, 4), 0.5), 0.5, True) # residual block x + F(x)
print("drop_path, one row per example:", y[:, 0].tolist())
def smooth_targets(y, k, eps):
t = np.full((len(y), k), eps / k)
t[np.arange(len(y)), y] += 1 - eps
return t
def cross_entropy(logits, targets):
z = logits - logits.max(1, keepdims=True)
logp = z - np.log(np.exp(z).sum(1, keepdims=True))
return float(-(targets * logp).sum(1).mean())
print("smoothed target for class 2 of 4, eps=0.1:", smooth_targets(np.array([2]), 4, 0.1).round(3).tolist())
y = np.array([2])
for scale in (2, 5, 10, 20):
logits = np.array([[0.0, 0.0, scale, 0.0]]) # more and more confident in class 2
print(f"logit gap {scale:2d}: plain CE {cross_entropy(logits, np.eye(4)[y]):.4f}"
f" smoothed CE {cross_entropy(logits, smooth_targets(y, 4, 0.1)):.4f}")p=0.1: zeros 0.100 mean 1.000 -> 1.001 std 0.577 -> 0.694
p=0.5: zeros 0.499 mean 1.000 -> 1.002 std 0.577 -> 1.291
drop_path, one row per example: [2.0, 1.0, 2.0, 1.0, 2.0, 2.0]
smoothed target for class 2 of 4, eps=0.1: [[0.025, 0.025, 0.925, 0.025]]
logit gap 2: plain CE 0.3408 smoothed CE 0.4908
logit gap 5: plain CE 0.0200 smoothed CE 0.3950
logit gap 10: plain CE 0.0001 smoothed CE 0.7501
logit gap 20: plain CE 0.0000 smoothed CE 1.5000
With half of the activations are zeroed, the mean stays at 1.000 (1.002 with sampling noise) and the standard deviation more than doubles, from 0.577 to 1.291. For the extra noise is small (0.694). DropPath acts per example: in the residual output each row is either (branch dropped) or (branch kept and doubled). For label smoothing the target for class 2 of 4 with is . The plain cross-entropy keeps falling as the model grows more confident (0.0001 at a logit gap of 10), so training pushes the logits apart forever; of the four gaps the smoothed loss is lowest at 5 (0.3950) and rises again for overconfident logits (1.5000 at a gap of 20). The optimum is where the softmax reproduces the smoothed target, a gap of .
Measuring them on Digits
The experiment is set up to overfit: only the first 60 images of the course's Digits training split, an MLP with two hidden layers of 512 units (about 300,000 parameters for 60 examples), AdamW at learning rate 0.001, batch 32, 150 epochs. Every variant is trained with three seeds and evaluated on the 360 validation images (the test set is not used). Validation loss is the cross-entropy, which also punishes confident mistakes.
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))
X_small, y_small = X_tr[:60], y_tr[:60] # 60 images: a wide MLP memorises them
def shift(xb, gen): # augmentation: random shift by up to 1 pixel
imgs = nn.functional.pad(xb.view(-1, 1, 8, 8), (1, 1, 1, 1))
dx, dy = torch.randint(0, 3, (2, len(xb)), generator=gen)
return torch.stack([imgs[i, 0, dy[i]:dy[i] + 8, dx[i]:dx[i] + 8] for i in range(len(xb))]).view(-1, 64)
def run(seed, p=0.0, wd=0.0, smooth=0.0, augment=None, epochs=150):
torch.manual_seed(seed)
model = nn.Sequential(nn.Linear(64, 512), nn.ReLU(), nn.Dropout(p),
nn.Linear(512, 512), nn.ReLU(), nn.Dropout(p), nn.Linear(512, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=wd)
loss_fn = nn.CrossEntropyLoss(label_smoothing=smooth)
gen = torch.Generator().manual_seed(seed)
for epoch in range(epochs):
model.train()
for idx in torch.randperm(len(y_small), generator=gen).split(32):
xb = augment(X_small[idx], gen) if augment else X_small[idx]
loss = loss_fn(model(xb), y_small[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
train_acc = (model(X_small).argmax(1) == y_small).float().mean().item()
logits = model(X_va)
val_acc = (logits.argmax(1) == y_va).float().mean().item()
return train_acc, val_acc, nn.functional.cross_entropy(logits, y_va).item()
variants = {
"no regularisation": {},
"dropout 0.5": {"p": 0.5},
"weight decay 2.0": {"wd": 2.0},
"label smoothing 0.1": {"smooth": 0.1},
"shift augmentation": {"augment": shift},
"dropout + decay": {"p": 0.5, "wd": 2.0},
}
print("60 training images, 360 validation images, mean of seeds 0, 1, 2")
print(f"{'':21s}train acc val acc (min-max) val loss")
for name, kw in variants.items():
runs = torch.tensor([run(s, **kw) for s in (0, 1, 2)])
tr, va, nll = runs.mean(0).tolist()
lo, hi = runs[:, 1].min().item(), runs[:, 1].max().item()
print(f"{name:21s}{tr:9.3f} {va:.3f} ({lo:.3f}-{hi:.3f}) {nll:8.3f}")60 training images, 360 validation images, mean of seeds 0, 1, 2
train acc val acc (min-max) val loss
no regularisation 1.000 0.850 (0.844-0.858) 0.515
dropout 0.5 1.000 0.857 (0.850-0.861) 0.486
weight decay 2.0 1.000 0.864 (0.861-0.867) 0.412
label smoothing 0.1 1.000 0.883 (0.878-0.892) 0.572
shift augmentation 1.000 0.854 (0.842-0.861) 0.537
dropout + decay 1.000 0.860 (0.856-0.867) 0.419
Read it with the seed spread in mind: one validation image is 0.003 of accuracy, and the baseline alone ranges from 0.844 to 0.858 over three seeds.
- Every variant reaches 1.000 training accuracy. With 60 images nothing stops memorisation; the regularisers only change which memorising solution is found.
- Label smoothing gives the largest accuracy gain, 0.883 against 0.850, with all three seeds above the best baseline seed. Its validation loss is the worst, 0.572: with 10 classes the smoothed target of the true class is , so the model is trained never to be more confident than that, so the cross-entropy on correct answers stays higher. Accuracy and loss can disagree.
- Weight decay 2.0 has the best validation loss, 0.412 against 0.515, and a modest accuracy gain (0.864). Its main effect is smaller weights, so less extreme logits and fewer confidently wrong predictions.
- Dropout 0.5 and the shift augmentation are within the seed noise of the baseline on this problem (0.857 and 0.854). The Digits images are centred and tiny (), so a one-pixel shift is a large change that the validation images never show; augmentation helps only when it produces variation the real data has.
- Dropout + decay ends with about the loss of weight decay alone (0.419) and no further accuracy gain.
The honest summary: on a small, clean problem the regularisers are worth a few points at most, and you need several seeds to see them. Their effect is larger on big models trained for a long time, where dropout, stochastic depth, label smoothing and heavy augmentation are standard parts of the recipe (and in large language-model pretraining, where data is plentiful, dropout is usually switched off).
The same curve with the browser-runnable scikit-learn MLP: its alpha is an L2 penalty on the weights. Increase it and the weight norm falls, then the model underfits:
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.exceptions import ConvergenceWarning
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_small, y_small = X_tr[:60], y_tr[:60]
warnings.simplefilter("ignore", ConvergenceWarning)
print("alpha (L2) train acc val acc ||W||")
for alpha in (1e-4, 0.1, 1.0, 3.0, 10.0):
clf = MLPClassifier(hidden_layer_sizes=(256,), alpha=alpha, max_iter=300, random_state=0)
clf.fit(X_small, y_small)
wnorm = np.sqrt(sum((W ** 2).sum() for W in clf.coefs_))
print(f"{alpha:10g} {clf.score(X_small, y_small):10.3f} {clf.score(X_va, y_va):9.3f} {wnorm:7.2f}")alpha (L2) train acc val acc ||W||
0.0001 1.000 0.869 14.48
0.1 1.000 0.872 11.47
1 1.000 0.867 7.44
3 0.983 0.792 5.57
10 0.583 0.464 2.42
From to 1 the validation accuracy stays at 0.867 to 0.872 while the weight norm halves (14.48 to 7.44); at 3 the model can no longer fit its 60 images (0.983) and validation falls to 0.792; at 10 it underfits badly (0.464). Like every regulariser strength, is tuned on the validation set (Grid and Random Search).
MC dropout: uncertainty from the same network
At inference dropout is normally off. Monte Carlo dropout (Gal and Ghahramani, 2016) leaves it on and runs the input times: each pass uses a different sub-network, and the spread of the predictions estimates how unsure the model is. The prediction is the average,
and the predictive entropy (or the standard deviation of the passes) is the uncertainty score. In PyTorch put the model in eval mode, then switch only the nn.Dropout modules back to train mode, so that batch norm, if present, keeps using its running statistics. Here a dropout MLP () is trained on the full training split for 15 epochs:
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(256, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
gen = torch.Generator().manual_seed(0)
for epoch in range(15):
model.train()
for idx in torch.randperm(len(y_tr), generator=gen).split(64):
loss = nn.functional.cross_entropy(model(X_tr[idx]), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval() # standard prediction: dropout off
with torch.no_grad():
p_det = model(X_va).softmax(1)
def mc_predict(model, x, T=100):
model.eval()
for m in model.modules(): # switch ONLY the dropout layers back on
if isinstance(m, nn.Dropout):
m.train()
with torch.no_grad():
probs = torch.stack([model(x).softmax(1) for _ in range(T)]) # (T, N, classes)
model.eval()
return probs
probs = mc_predict(model, X_va)
p_mc = probs.mean(0)
entropy = -(p_mc * p_mc.clamp_min(1e-12).log()).sum(1) # predictive entropy
spread = probs.gather(2, p_mc.argmax(1).view(1, -1, 1).expand(100, -1, 1)).squeeze(2).std(0)
right = p_mc.argmax(1) == y_va
print(f"accuracy: dropout off {(p_det.argmax(1) == y_va).float().mean().item():.3f}"
f" MC average of 100 passes {right.float().mean().item():.3f}")
print(f"wrong predictions: {int((~right).sum())} of {len(y_va)}")
print(f"mean entropy right {entropy[right].mean().item():.3f} wrong {entropy[~right].mean().item():.3f}")
print(f"mean std of the top-class probability right {spread[right].mean().item():.3f} wrong {spread[~right].mean().item():.3f}")
order = entropy.argsort(descending=True)
print("errors among the 20 most uncertain:", int((~right[order[:20]]).sum()),
" among the 180 most certain:", int((~right[order[-180:]]).sum()))accuracy: dropout off 0.969 MC average of 100 passes 0.972
wrong predictions: 10 of 360
mean entropy right 0.215 wrong 0.978
mean std of the top-class probability right 0.054 wrong 0.210
errors among the 20 most uncertain: 6 among the 180 most certain: 0
The averaged prediction is as accurate as the deterministic one (0.972 against 0.969). The useful part is the uncertainty: the 10 wrong predictions have a mean entropy of 0.978, the right ones 0.215, and the standard deviation of the top-class probability across passes is 0.210 against 0.054. Sorting the validation images by entropy, 6 of the 20 most uncertain are errors, and none of the 180 most certain. That is a cheap way to route doubtful cases to a human, with the caveat that MC dropout estimates are often still overconfident on inputs far from the training data; check them with a calibration curve before relying on them.
Choosing and placing regularisers
| Regulariser | Typical setting | Where |
|---|---|---|
| Weight decay | AdamW 0.01 to 0.1 (larger on small data); not on biases and norm parameters | every model |
| Dropout | 0.1 to 0.5 after hidden layers of MLPs; 0.1 in transformers (attention weights, residual branches) | MLP heads, small data |
| DropPath | 0.1 to 0.5 at the last block, linear schedule | deep residual nets, ViT |
| Label smoothing | classification with many classes | |
| Data augmentation | transformations the real data shows | images, audio, text (image augmentation) |
| Early stopping | patience on validation loss | everything (Early Stopping) |
Pitfalls
- Forgetting
model.eval(). Dropout stays on and validation results become noisy and pessimistic. MC dropout is the one case where you want it on, and then only for dropout layers. - Dropout before batch norm. The variance of activations differs between training (with dropout) and inference (without), and BN's running variance is computed in training mode; the mismatch hurts. Put dropout after the last normalisation, or use it only in the head.
- Applying weight decay to everything. Decaying the of normalisation layers and the biases is rarely useful; pass parameter groups to the optimiser with
weight_decay=0.0for them. - Augmentations that change the label. Flipping a 6 makes a 9 lookalike; rotating text makes it unreadable. Augment only with transformations that keep the label.
- Judging with one seed. Differences of one or two points on a few hundred validation examples are often noise, as the baseline spread above shows.
- Label smoothing with calibration-sensitive outputs. It improves accuracy but distorts the probabilities; do not use smoothed models where the probabilities themselves matter without recalibrating them.
Practice
- With , what is the scale factor of kept units, and what is for ?
Answer
Kept units are multiplied by . The variance is : is 3.75 with probability 0.8 and 0 with probability 0.2, mean 3, and .
- Write a
DropPathmodule for PyTorch, used asx + self.drop_path(self.branch(x)).
Answer
class DropPath(nn.Module):
def __init__(self, p):
super().__init__()
self.p = p
def forward(self, x):
if not self.training or self.p == 0:
return x
shape = (x.shape[0],) + (1,) * (x.dim() - 1) # one draw per example
keep = torch.rand(shape, device=x.device) >= self.p
return x * keep / (1 - self.p)torchvision has the same thing as torchvision.ops.StochasticDepth(p, mode="row").
- Why do you switch only the dropout modules to train mode for MC dropout, not the whole model?
Answer
model.train() would also put batch-norm layers in training mode: they would normalise with the statistics of the evaluation batch and update their running statistics with evaluation data. Only the dropout randomness is wanted.
- In the Digits table, label smoothing had the best accuracy and the worst validation loss. How can both be true?
Answer
Accuracy only counts the arg-max. The smoothed model is trained to put about 0.91 on the right class, so even its confident correct predictions have a cross-entropy of about , and on harder examples its probabilities are spread further. The unsmoothed model is very confident when right (near 0 loss) and also when wrong; on balance its loss can be lower or higher, and here it was lower.
Test yourself
Why does inverted dropout divide the kept activations by ?
- To make training faster
- So the expected activation is unchanged and the layer can be the identity at evaluation
- To reduce the variance
- To prevent overfitting of the biases
What does stochastic depth (DropPath) drop?
- Single activations
- Whole residual branches, per example, so the block becomes the identity
- Entire training examples
- Layers of the optimiser state
With label smoothing and classes, what is the target probability of the true class?
- 1
- 0.9
- 0.925
- 0.975
In the MC dropout experiment, how were the uncertain predictions distributed?
- Errors were spread evenly
- 6 of the 20 most uncertain images were errors, none of the 180 most certain
- All errors had low entropy
- MC dropout lowered the accuracy to 0.5
On 60 Digits images, how much did dropout 0.5 change the mean validation accuracy over three seeds?
- From 0.850 to 0.857, within the seed noise
- From 0.850 to 0.95
- It fell to chance
- From 0.50 to 0.85