AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⌬Neural Networks
  1. Neurons and Activation Functions
  2. Multilayer Perceptrons and Backpropagation
  3. Training Hyperparameters: Epochs, Learning Rate, Batch Size and More
  4. Optimizers: SGD, Momentum, RMSProp, Adam/AdamW and LR Schedules
  5. Regularization, Normalization and Initialization
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Neural Networks

Regularization, Normalization and Initialization

The toolkit that makes deep networks generalize and train stably: weight decay, dropout, early stopping, data augmentation, batch and layer normalization, and principled weight initialization.

Intermediate~30 min·6 references
Key terms
RegularisationDropoutWeight decayEarly stoppingData augmentationBatch normalizationLayer normalizationWeight initialization

Modern networks have far more parameters than training examples — they can memorise even randomly labelled data (Zhang et al., 2016). Two families of techniques keep them useful. [[regularization|Regularization]] discourages memorisation so the model generalizes to new data. Normalization and initialization keep the signals and gradients flowing through many layers at a healthy scale so that training works at all. This lesson covers the standard tools in both families and their knobs[1].

≈
A team where anyone might be absent
Dropout is like a team where, every day, a random half of the members are absent. Nobody can rely on one star colleague, so everyone learns to be useful on their own and knowledge is spread out — the team becomes robust. Weight decay is a small tax on large weights: the model can still use big weights, but only if they really pay for themselves. Early stopping is leaving the exam-prep session before you start memorising the answer key.

Weight decay (L2 regularization)

L′(w) = L(w) + (λ/2)·‖w‖² ⇒ w ← (1 − ηλ)·w − η·∇L(w)
Each SGD step first shrinks every weight by a factor (1 − ηλ), then applies the usual gradient step. For Adam, use the decoupled form (AdamW).
In words: “add a penalty proportional to the squared size of the weights to the loss; the gradient of that penalty is λw, so every update first shrinks each weight by the factor (1 − ηλ) and then takes the usual gradient step.” Weights decay toward zero unless the data keep pushing them up, which favours simpler, smoother models and reduces Overfitting.
Symbols(hover a symbol in the formula)
L′(w)
the regularized loss that is actually minimized
L(w)
the original data loss
λ
lambda — Weight decay strength, e.g. 10⁻⁴ to 10⁻²; the /2 is there so the penalty's gradient is simply λw
‖w‖²
squared L2 norm: the sum of all weights squared, w₁² + w₂² + …
⇒
“which leads to” (take the gradient of L′ and plug it into gradient descent)
w
the weights
←
update the weights
ηλ
η times λ: the fraction by which every weight shrinks per step
η
Learning rate
∇L(w)
Gradient of the original data loss
·
multiplication
▸Worked example
w = 2, λ = 0.01, η = 0.1, data gradient ∇L(w) = 0.5 Penalty added to the loss: (λ/2)·‖w‖² = 0.005 · 4 = 0.02 Shrink factor: 1 − ηλ = 1 − 0.001 = 0.999 w ← 0.999 · 2 − 0.1 · 0.5 = 1.998 − 0.05 = 1.948 (same as w − η·(0.5 + λw) = 2 − 0.1 · 0.52 = 1.948) If the data stop pushing (∇L = 0): w = 2 · 0.999ⁿ → after 1,000 steps ≈ 0.735

Weight decay prefers solutions with small weights, which tend to be smoother functions that change gently with the input — less able to thread through every noisy training point. It is cheap, almost always helps a little, and is on by default in most modern recipes (AdamW)[1].

knobWeight decay λ
What it is
Strength of the pull of every weight toward zero.
↑ If you increase it
Less overfitting and a smaller train/val gap; too high and the model underfits — both losses rise and predictions flatten.
↓ If you decrease it
More capacity to fit the training set; at 0, only other regularizers (or early stopping) prevent memorisation.
Typical values
SGD: 1e-4–5e-4. AdamW: 0.01–0.1. Exclude biases and normalization parameters.

Dropout

training: h̃ = (m ⊙ h) / (1 − p), mᵢ ~ Bernoulli(1 − p) inference: h̃ = h
“Inverted dropout”: each unit is zeroed with probability p and the survivors are scaled up by 1/(1 − p), so the expected activation is unchanged and inference needs no rescaling.
In words: “during training, multiply each activation by a random 0-or-1 mask (1 with probability 1 − p) and divide the survivors by 1 − p; at inference, use the activations unchanged.” Randomly removing units stops neurons from relying on specific partners, and the division keeps the average activation equal in both modes.
Symbols(hover a symbol in the formula)
training
the mode used while learning (model.train() in PyTorch)
inference
the mode used for predictions (model.eval()): Dropout is switched off
h̃
“h-tilde”: the activations after dropout, passed to the next layer
h
the layer's activations (a vector)
m
random mask vector of 0s and 1s, drawn fresh for every example and step
mᵢ
mask entry for unit i
⊙
element-wise product: units whose mask is 0 become 0
p
drop probability, e.g. 0.1–0.5 (the p in nn.Dropout(p))
~
“is drawn from” a probability distribution
Bernoulli
a biased coin flip: 1 with probability 1 − p, 0 with probability p
▸Worked example
p = 0.5, so survivors are scaled by 1/(1 − 0.5) = 2 h = (2, 1, 4, 3) sum 10 Training, mask m = (1, 0, 1, 0): m ⊙ h = (2, 0, 4, 0) → h̃ = (4, 0, 8, 0) sum 12 Next step, mask (0, 1, 0, 1): h̃ = (0, 2, 0, 6) sum 8 On average over masks E[h̃ᵢ] = (1 − p) · hᵢ / (1 − p) = hᵢ, so the sum averages 10 Inference: h̃ = h = (2, 1, 4, 3) — no mask, no scaling

Dropout (Srivastava et al., 2014) randomly removes units during training[2]. Each mini-batch trains a different “thinned” sub-network that shares weights with all the others; at test time the full network acts like an average of this huge ensemble. It prevents units from co-adapting (relying on very specific partners) and was a key ingredient of AlexNet. Remember to switch it off for evaluation (model.eval()).

knobDropout rate p
What it is
Probability of zeroing each unit during training (PyTorch nn.Dropout(p)). Note: some papers use the keep probability instead.
↑ If you increase it
Stronger regularization and less overfitting, but noisier and slower training; too high (≥ 0.7) and the network underfits.
↓ If you decrease it
Faster convergence and less noise; at 0 there's no dropout. Large pretrained models fine-tuned on lots of data often use 0–0.1.
Typical values
0.5 for large fully connected layers (classic); 0.1 in Transformers; 0.1–0.2 on inputs; often lower in CNNs that use BatchNorm.

Early stopping and data augmentation

[[early-stopping|Early stopping]] monitors the validation loss each epoch, remembers the best checkpoint, and stops when there has been no improvement for patience epochs. It effectively tunes the number of epochs for free and limits how far weights can travel from their initialization — it behaves like a form of L2 regularization[1]. [[data-augmentation|Data augmentation]] creates new, label-preserving variations of training examples: random crops, flips, rotations, colour jitter for images; noise, time-stretching or SpecAugment-style masking for audio; synonym replacement or back-translation for text. It is often the single most effective regularizer for vision, because it teaches invariances the model would otherwise have to learn from more data.

knobEarly stopping patience
What it is
How many epochs (or evaluations) without improvement in validation loss to tolerate before stopping.
↑ If you increase it
More robust to noisy validation curves and temporary plateaus (e.g. before an LR drop), but wastes compute after the true optimum.
↓ If you decrease it
Stops sooner and saves compute, but may quit on a random bump before the model has really converged.
Typical values
5–20 epochs; scale with how noisy the validation loss is. Pair with a small min_delta.
knobAugmentation strength
What it is
How aggressive the random transformations are (crop scale range, rotation angle, jitter amount, probability of each transform).
↑ If you increase it
Stronger regularization and more robustness; too strong and examples stop looking like their label (a rotated “6” becomes a “9”), so the model underfits and training slows.
↓ If you decrease it
Faster training, closer fit to the training distribution, more overfitting on small datasets.
Typical values
Images: random resized crop + horizontal flip as a baseline; stronger policies (RandAugment, mixup) for long training runs.

Batch normalization

x̂ = (x − μ_B) / √(σ²_B + ε) y = γ · x̂ + β
μ_B and σ²_B are the mean and variance of each feature/channel over the current mini-batch; γ and β are learned scale and shift. At inference, running averages collected during training replace the batch statistics.
In words: “for each feature, subtract the batch mean and divide by the batch standard deviation, giving values with mean 0 and variance 1; then let the network rescale them with γ and shift them with β.” Normalizing keeps each layer's inputs in a stable range so training tolerates larger learning rates; γ and β let the network undo the normalization if another scale works better.
Symbols(hover a symbol in the formula)
x̂
“x-hat”: the normalized value (mean 0, variance 1 across the batch)
x
one feature's (or channel's) value for one example in the mini-batch
μ_B
mu — mean of that feature over the mini-batch
σ²_B
sigma squared — variance of that feature over the mini-batch
√
square root: turns the variance into a standard deviation
ε
small constant (PyTorch: 10⁻⁵) against division by zero
γ
gamma — learned scale, initialized to 1
β
beta — learned shift, initialized to 0 (not the momentum β)
y
output of the Batch normalization layer
·
multiplication
▸Worked example
One feature, batch of 4 examples: x = (2, 4, 6, 8) μ_B = (2 + 4 + 6 + 8) / 4 = 5 σ²_B = (9 + 1 + 1 + 9) / 4 = 5 → √5 ≈ 2.236 (ε is negligible) x̂ = (−3, −1, 1, 3) / 2.236 = (−1.342, −0.447, 0.447, 1.342) ← mean 0, variance 1 With learned γ = 2, β = 0.5: y = 2·x̂ + 0.5 = (−2.183, −0.394, 1.394, 3.183)

Batch normalization (Ioffe & Szegedy, 2015) normalizes each channel's activations to zero mean and unit variance across the batch, then lets the network rescale them[3]. It allows much higher learning rates, makes training less sensitive to initialization and adds a mild regularizing noise (each example's normalization depends on its batch-mates). The original motivation, “reducing internal covariate shift”, has been questioned: Santurkar et al. (2018) argue its main benefit is a smoother loss landscape. Its weak spots: it depends on the batch size (poor below ~8–16), behaves differently in train and eval mode, and is awkward for variable-length sequences.

Layer normalization (and friends)

Layer normalization (Ba et al., 2016) uses the same formula, but computes μ and σ² over the features of a single example instead of over the batch[4]. It therefore works identically for batch size 1, in training and inference, and for each token of a sequence — which is why it is the standard in RNNs and Transformers. RMSNorm (Zhang & Sennrich, 2019) drops the mean subtraction and is used in many recent LLMs; GroupNorm normalizes over groups of channels and is popular for detection/segmentation with small batches.

BatchNormLayerNormRMSNorm
Statistics computed overThe batch (per channel)Features of one exampleFeatures of one example (RMS only)
Depends on batch size?YesNoNo
Train ≠ eval behaviour?Yes (running stats)NoNo
Typical useCNNs (ResNet)Transformers, RNNsRecent LLMs (e.g. LLaMA)

Weight initialization

Initial weights must be random (to break symmetry) and correctly scaled. If they are too large, activations and gradients grow layer by layer and explode; too small and they shrink to nothing (Vanishing (and exploding) gradient). Glorot & Bengio (2010) derived a scale that keeps the variance of activations and gradients roughly constant across layers for tanh/sigmoid networks[5]; He et al. (2015) corrected it for ReLU, which zeroes half its inputs and so needs twice the variance[6].

Xavier/Glorot: Var(w) = 2 / (n_in + n_out) He/Kaiming: Var(w) = 2 / n_in
Example: a ReLU layer with n_in = 512 → He std = √(2/512) = 0.0625. Biases usually start at 0.
In words: “draw each initial weight at random, with mean 0 and a variance of 2 divided by the number of connections.” Xavier averages fan-in and fan-out so signals keep their size both forward and backward (good for tanh/sigmoid); He uses only fan-in with a factor 2 because ReLU zeroes about half of its inputs. Either way: the wider the layer, the smaller the initial weights.
Symbols(hover a symbol in the formula)
Xavier/Glorot
Weight initialization of Glorot & Bengio (2010), for tanh/sigmoid layers (nn.init.xavier_normal_)
He/Kaiming
initialization of He et al. (2015), for ReLU layers (nn.init.kaiming_normal_)
Var(w)
variance of the random initial weights (mean 0; std = √Var)
n_in
fan-in: number of inputs feeding each neuron
n_out
fan-out: number of outputs (neurons) of the layer
▸Worked example
Layer with n_in = 512 inputs and n_out = 256 outputs Xavier: Var = 2 / (512 + 256) = 2/768 ≈ 0.0026 → std ≈ 0.051 He: Var = 2 / 512 ≈ 0.0039 → std = 0.0625 Why it matters (ReLU net; each layer multiplies the signal variance by ½ · n_in · Var(w)): He: ½ · 512 · (2/512) = 1 → the signal keeps its size layer after layer std 0.01: ½ · 512 · 0.0001 ≈ 0.026 → after 10 layers 0.026¹⁰ ≈ 10⁻¹⁶: the signal vanishes
knobInitialization scale
What it is
The standard deviation (or uniform range) used to draw initial weights, usually set by a scheme like Xavier or He.
↑ If you increase it
Activations grow with depth: saturated tanh/sigmoid units, exploding ReLU activations and gradients, loss NaN in deep nets.
↓ If you decrease it
Activations shrink toward zero with depth; gradients vanish and the network learns very slowly or not at all.
Typical values
He (Kaiming) for ReLU-family; Xavier for tanh/sigmoid/linear. PyTorch layers default to a scaled uniform init — fine for most models.
python
import torch
import torch.nn as nn

class Net(nn.Module):
    def __init__(self, d_in, d_hidden=256, n_classes=10, p_drop=0.3):
        super().__init__()
        self.body = nn.Sequential(
            nn.Linear(d_in, d_hidden), nn.BatchNorm1d(d_hidden), nn.ReLU(), nn.Dropout(p_drop),
            nn.Linear(d_hidden, d_hidden), nn.BatchNorm1d(d_hidden), nn.ReLU(), nn.Dropout(p_drop),
            nn.Linear(d_hidden, n_classes),
        )
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.kaiming_normal_(m.weight, nonlinearity="relu")   # He init
                nn.init.zeros_(m.bias)

    def forward(self, x):
        return self.body(x)

model = Net(d_in=784)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)

model.train()   # dropout ON; BatchNorm uses batch stats and updates running stats
# ... training loop with early stopping (see the hyperparameters lesson) ...

model.eval()    # dropout OFF; BatchNorm uses running stats
with torch.no_grad():
    preds = model(x_val).argmax(dim=1)
Dropout, BatchNorm, He initialization and AdamW weight decay together. The train() / eval() switch changes the behaviour of dropout and BatchNorm.
python
import torch
from torchvision.transforms import v2

train_tf = v2.Compose([
    v2.RandomResizedCrop(224, scale=(0.08, 1.0)),   # random crop + resize
    v2.RandomHorizontalFlip(),
    v2.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
    v2.ToImage(), v2.ToDtype(torch.float32, scale=True),
    v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
val_tf = v2.Compose([            # no randomness for validation!
    v2.Resize(256), v2.CenterCrop(224),
    v2.ToImage(), v2.ToDtype(torch.float32, scale=True),
    v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
A standard image-augmentation pipeline with torchvision transforms v2. Augment the training set only.
!
Common pitfalls
Watch out for these:
  • Forgetting `model.eval()` before validation/inference: dropout stays on and BatchNorm uses the current batch — predictions become random-ish and depend on batch composition.
  • BatchNorm with tiny batches (1–4): statistics are too noisy; use GroupNorm/LayerNorm, or freeze BN statistics when fine-tuning.
  • Augmenting the validation or test set with random transforms: your metrics become noisy and biased.
  • Weight decay on BatchNorm/LayerNorm γ and on biases: usually harmless but can hurt; most recipes exclude them.
  • Stacking every regularizer at maximum on a small model: it underfits. Add regularization only when you see overfitting.
✓
What to reach for first
Overfitting? In rough order of reliability: more (or augmented) data → weight decay + early stopping → dropout → a smaller model. Training unstable or not starting? Check the learning rate and warmup → add normalization (BatchNorm for CNNs, LayerNorm for Transformers) → check initialization → add residual connections (next module).
▸Go deeper: dropout as an ensemble, and where to put LayerNorm

A layer with n units has 2ⁿ possible dropout masks, so dropout trains an exponential number of weight-sharing sub-networks. Srivastava et al. show that scaling the weights at test time approximates the geometric mean of their predictions (exactly for a single linear-softmax layer)[2]. Running several stochastic forward passes with dropout on (“MC dropout”) gives a cheap uncertainty estimate.

The original Transformer applied LayerNorm after each residual addition (Post-LN). Xiong et al. (2020) showed that putting it before each sub-layer (Pre-LN) keeps gradients well-behaved at initialization, so training can often use a shorter (or no) warmup — most modern LLMs use Pre-LN or Pre-RMSNorm.

Quiz

1.
Your model has 98% training accuracy and 71% validation accuracy. Which change is LEAST likely to help?
2.
You evaluate a model with dropout and BatchNorm but forget model.eval(). What do you observe?
3.
Why do Transformers use LayerNorm rather than BatchNorm?
4.
You use plain N(0, 1) initialization for a 20-layer ReLU MLP with 512 units per layer. What is the likely result?
5.
With dropout p = 0.2 (inverted dropout), what happens to the surviving activations during training?
Score: 0/5

References

  1. [1]
    Deep Learning — Chapter 7: Regularization for Deep Learning
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  2. [2]
    Dropout: A Simple Way to Prevent Neural Networks from Overfitting
    PaperSrivastava et al.2014jmlr.org
  3. [3]
    Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
    PaperIoffe & Szegedy2015arxiv.org
  4. [4]
    Layer Normalization
    PaperBa, Kiros & Hinton2016arxiv.org
  5. [5]
    Understanding the difficulty of training deep feedforward neural networks
    PaperGlorot & Bengio2010proceedings.mlr.press
  6. [6]
    Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
    PaperHe et al.2015arxiv.org
← Previous
Optimizers: SGD, Momentum, RMSProp, Adam/AdamW and LR Schedules
Next → · Training Results & Evaluation
Reading Loss & Accuracy Curves