Skip to content
Building Blocks

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:

Ltotal=Ltask+λ2∥W∥F2L_{\text{total}} = L_{\text{task}} + \frac{\lambda}{2} \|\mathbf{W}\|_F^2

where ∥W∥F2=∑ijWij2\|\mathbf{W}\|_F^2 = \sum_{ij} W_{ij}^2 is the sum of squared weights across all parameters and λ>0\lambda > 0 controls the strength of the penalty. The gradient of the regularization term is λW\lambda \mathbf{W}, so the update rule becomes:

W←W−η ∂Ltask∂W−ηλW\mathbf{W} \leftarrow \mathbf{W} - \eta\,\frac{\partial L_{\text{task}}}{\partial \mathbf{W}} - \eta \lambda \mathbf{W}

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 −ηλW-\eta \lambda \mathbf{W} term above, applied as a separate step after the gradient update. A typical weight decay coefficient is λ=0.01\lambda = 0.01–0.10.1.

L1 regularization uses the sum of absolute values instead: λ∥W∥1=λ∑ij∣Wij∣\lambda \|\mathbf{W}\|_1 = \lambda \sum_{ij} |W_{ij}|. Its gradient is λsign⁡(W)\lambda \operatorname{sign}(\mathbf{W}), 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 pp, the dropout rate. The remaining activations are scaled up by 11−p\frac{1}{1-p} to preserve the expected magnitude:

hidrop={hi1−pwith probability 1−p0with probability ph_i^{\text{drop}} = \begin{cases} \dfrac{h_i}{1 - p} & \text{with probability } 1 - p \\ 0 & \text{with probability } p \end{cases}

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 p=0.4p = 0.4 and input h=[1.0, 2.0, 3.0, 4.0, 5.0]\mathbf{h} = [1.0,\ 2.0,\ 3.0,\ 4.0,\ 5.0], a possible dropped output is:

hdrop=[1.67, 0, 5.0, 6.67, 0]\mathbf{h}^{\text{drop}} = [1.67,\ 0,\ 5.0,\ 6.67,\ 0]

The two zeroed positions receive no gradient signal in this step, and the three surviving values are scaled by 10.6≈1.67\frac{1}{0.6} \approx 1.67.

training (p = 0.4)inferencexx2 of 5 neurons randomly zeroed during training; all active at inference

Why dropout helps. Each training step uses a different randomly sampled sub-network. With nn neurons and independent masking, there are up to 2n2^n 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 p=0.1p = 0.1–0.30.3 are typical for transformer attention and feed-forward blocks. Rates of p=0.5p = 0.5 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 BB examples and a single feature channel, the four steps are:

μB=1B∑i=1BxiσB2=1B∑i=1B(xi−μB)2\mu_B = \frac{1}{B} \sum_{i=1}^B x_i \qquad \sigma^2_B = \frac{1}{B} \sum_{i=1}^B (x_i - \mu_B)^2 x^i=xi−μBσB2+εyi=γ x^i+β\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma^2_B + \varepsilon}} \qquad y_i = \gamma\,\hat{x}_i + \beta

The normalized x^i\hat{x}_i has zero mean and unit variance within the batch. The learnable parameters γ\gamma and β\beta (initialized to 11 and 00) 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 x=[1, 3, 5, 7]x = [1,\ 3,\ 5,\ 7]:

μB=4σB2=5x^≈[−1.34, −0.45, 0.45, 1.34]\mu_B = 4 \qquad \sigma^2_B = 5 \qquad \hat{x} \approx [-1.34,\ -0.45,\ 0.45,\ 1.34]

The normalized values have mean 00 and standard deviation 11. With γ=1\gamma = 1 and β=0\beta = 0, the layer output is x^\hat{x} unchanged.

BatchNorm is typically placed between the linear transformation and the activation: the sequence is z=Wx+b\mathbf{z} = \mathbf{W}\mathbf{x} + \mathbf{b}, 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 μB\mu_B and σB2\sigma^2_B. 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

TechniqueWhen to useTypical value
Weight decayAlmost alwaysλ=0.01\lambda = 0.01–0.10.1
DropoutMLPs, transformersp=0.1p = 0.1–0.50.5
Batch normalizationCNNs, deep MLPsε=10−5\varepsilon = 10^{-5}

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.