Regularization
Weight decay, dropout, and batch normalization: preventing overfitting and stabilizing deep networks.
The Training Loop article showed that a model can achieve low training loss while performing poorly on held-out data. The Building Blocks section introduced the operations that make deep networks expressive. Expressiveness is double-edged: a network with enough capacity can memorize training data rather than learning the underlying pattern. Regularization refers to techniques that constrain the network to generalize better.
Overfitting Revisited
Overfitting occurs when the network fits the noise in the training set. As the model grows more complex — more layers, more neurons, more parameters — it can assign a unique response to each training example without capturing the systematic relationship between inputs and outputs. The training loss decreases while the validation loss plateaus or rises.
Three complementary techniques address this: weight decay constrains parameter magnitudes, dropout randomly deactivates neurons during training, and batch normalization stabilizes the distribution of activations across layers.
Weight Decay
Weight decay penalizes large weights by adding a regularization term to the loss:
where is the sum of squared weights across all parameters and controls the strength of the penalty. The gradient of the regularization term is , so the update rule becomes:
The second term shrinks every weight toward zero at each step. Small weights mean the network cannot make sharp predictions based on individual features; it must spread its reliance across many inputs, which discourages memorization.
Connection to AdamW. The Optimizers article showed that AdamW applies this decay directly to the weights, bypassing Adam's adaptive denominator. This is precisely the term above, applied as a separate step after the gradient update. A typical weight decay coefficient is –.
L1 regularization uses the sum of absolute values instead: . Its gradient is , which pushes weights exactly to zero, producing sparse models. L1 is less common in deep learning but useful when explicit sparsity is desired.
Dropout
Dropout is a training-time technique: during the forward pass, each activation is independently set to zero with probability , the dropout rate. The remaining activations are scaled up by to preserve the expected magnitude:
This is inverted dropout: the scaling happens during training so that no adjustment is needed at inference. During evaluation, all activations pass through unchanged and the expected value is preserved by construction.
Example. With and input , a possible dropped output is:
The two zeroed positions receive no gradient signal in this step, and the three surviving values are scaled by .
Why dropout helps. Each training step uses a different randomly sampled sub-network. With neurons and independent masking, there are up to possible sub-networks sharing the same weights. The full network at inference implicitly averages over all of them. No single neuron can rely on specific other neurons always being present, so each must learn independently useful features rather than co-adapting as a group.
Dropout rates of – are typical for transformer attention and feed-forward blocks. Rates of were used in early deep MLPs. Dropout is less effective in convolutional layers, where batch normalization is generally preferred.
Batch Normalization
Each training step updates the weights of every layer simultaneously. As early layers change, the distribution of their outputs, which serves as input to later layers, shifts continuously. Later layers must constantly adapt to a moving target, slowing convergence. This is internal covariate shift.
Batch normalization (BatchNorm) normalizes the inputs to each layer across the current batch before passing them forward. For a batch of examples and a single feature channel, the four steps are:
The normalized has zero mean and unit variance within the batch. The learnable parameters and (initialized to and ) allow the network to undo the normalization if that turns out to be optimal, making BatchNorm an identity transformation when necessary.
Example. For the batch :
The normalized values have mean and standard deviation . With and , the layer output is unchanged.
BatchNorm is typically placed between the linear transformation and the activation: the sequence is , then BatchNorm, then ReLU.
Benefits. Beyond reducing internal covariate shift, BatchNorm acts as a regularizer because the normalization statistics introduce noise proportional to the batch variance. It also enables higher learning rates without divergence, and reduces sensitivity to weight initialization.
Train and Eval Modes
Both dropout and batch normalization behave differently during training and evaluation:
- Dropout: active during training (random masking), disabled during evaluation (identity).
- BatchNorm: during training, uses the current batch's and . During evaluation, uses running statistics accumulated as exponential moving averages over all training batches, since a single test example has no meaningful batch statistics.
This is why the training loop must call model.train() before each training epoch and model.eval() before validation. Failing to switch modes is a common source of bugs: a model left in training mode at inference sees stochastic dropout and noisy batch statistics rather than the stable, deterministic behavior it should produce.
Guidelines
| Technique | When to use | Typical value |
|---|---|---|
| Weight decay | Almost always | – |
| Dropout | MLPs, transformers | – |
| Batch normalization | CNNs, deep MLPs |
These techniques are not mutually exclusive. A typical deep network uses weight decay (via AdamW), batch normalization after each linear layer, and dropout at selected positions. The exact combination depends on the architecture.
In Code
import torch
import torch.nn as nn
# Dropout
dropout = nn.Dropout(p=0.4)
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
# Training mode: zeroes each element independently with probability p,
# and scales the survivors by 1/(1-p) so the expected value is unchanged
dropout.train()
print(dropout(x)) # tensor([1.667, 0., 5.000, 6.667, 0.]) (example, random each call)
# Eval mode: the input passes through unchanged, deterministic
dropout.eval()
print(dropout(x)) # tensor([1., 2., 3., 4., 5.])
# Batch normalization
bn = nn.BatchNorm1d(num_features=4) # normalizes each of the 4 features over the batch
bn.train()
x_batch = torch.tensor([[1., 3., 5., 7.], # batch of 4 examples, 4 features each
[2., 4., 6., 8.],
[3., 5., 7., 9.],
[4., 6., 8., 10.]])
y = bn(x_batch)
print(y.mean(0)) # ≈ tensor([0., 0., 0., 0.]) — each feature is centered
print(y.std(0)) # ≈ tensor([1., 1., 1., 1.]) — and has unit variance
bn.eval() # switches to the running statistics collected during training
# Regularized MLP combining all three
model = nn.Sequential(
nn.Linear(784, 256),
nn.BatchNorm1d(256),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, 128),
nn.BatchNorm1d(128),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(128, 10),
)
# The third regularizer: weight decay, built into AdamW
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
model.train() # enables dropout and batch statistics, on every layer at once
# ... training loop ...
model.eval() # disables dropout, switches to running statistics
# ... validation / inference ...
With activation functions, linear layers, and regularization in place, the Building Blocks section is complete. The next section applies these components to a specific domain: images. Convolutional networks exploit the spatial structure of images with a specialized operation — the convolution — that replaces the fully connected linear layer for feature extraction from local regions.