Regularization in Deep Networks
After this lesson, you will be able to:
- Apply weight decay correctly in deep networks, and know why it must be decoupled from the gradient (AdamW), not folded into L2 like the original Adam
- Use dropout the right way: invert-scale at training time, switch off at inference, and pick a sensible p for your network size and dataset
- Soften your training targets with label smoothing to stop your model from screaming '99.99% confident' when it should not be, and explain why this also calibrates probabilities
- Combine modern data augmentation tricks (Mixup, CutMix, RandAugment) and stochastic depth so your deep network actually generalizes instead of memorizing the training set
Before you start
Don't worry if the toolbox feels overwhelming at first — most projects start with weight decay + a couple of augmentations, and you only reach for the heavier tricks (Mixup, stochastic depth) when you actually have a deep enough network for them to matter.
#The Memorization Problem
A deep network with a few million parameters can fit a few thousand training images perfectly. That is not learning — that is a lookup table dressed up in tensor form. Regularization is what stops the model from settling for the lookup table and pushes it toward representations that transfer to new data.
#Weight Decay: L2, but Done Properly
λ‖w‖² to the loss and the optimizer pulls weights toward zero. In deep networks the same idea applies — every layer's weights are penalized for growing too large.L2 as a Gaussian prior is derived in MLE, MAP & Fisher Information, and ridge shrinkage in a closed-form model is derived in Convex Optimization, KKT & Lagrangian Duality. For a network trained by gradient steps the same penalty becomes a per-step shrinkage, which is where the name weight decay comes from.
Why putting L2 inside Adam's gradient gives a different result from this decoupled form is derived in Optimization Algorithms: SGD to AdamW.
weight_decay=0.01–0.1 is the default. For SGD on CNNs, weight_decay=5e-4 is the long-running ResNet/ViT recipe. Always use AdamW, not Adam-with-L2.#Dropout: Random Sub-network Ensembling
Interactive Lab
Sweep the regularization strength and watch train vs validation loss diverge — find the sweet spot where the model generalizes.
Inverted dropout works because the expected output equals the input, so the activation statistics match between training and evaluation and inference needs no rescaling. The derivation shows why the factor is exactly 1/(1-p).
Dropout is described as an ensemble of sub-networks. For a single linear layer that statement is exact, and the derivation below shows how.
Drag p up and the mask count to 500: the green bars keep matching the gold ticks for the average, the variance bars grow as a squared times p over (1 - p), and the ReLU gap stays open while the linear gap closes.
Your training accuracy is 78% and your validation accuracy is 85% — yes, validation is HIGHER than training. You have dropout=0.3 in the model. What's happening?
#Label Smoothing: Don't Be a Know-It-All
1.0 on the correct class and 0.0 on every other class. To do that, the logit for the correct class has to be infinitely larger than every other logit. Models try, and the result is over-confident, badly calibrated probabilities (every prediction is 99.999% something).In the targets above the true class gets 1 - epsilon and each other class gets epsilon over K - 1, so they sum to exactly 1. (PyTorch's label_smoothing option blends the one-hot vector with a uniform vector over all K classes instead, so the true class gets 1 - epsilon + epsilon over K. The ideas are the same.)
The code comment in the MathBlock computes (1 - epsilon) times the usual loss plus epsilon times a smooth loss. The next derivation shows that this blend is exactly cross-entropy against the smoothed target.
Label smoothing has two effects worth knowing:
-
Calibration: The model's predicted probabilities become closer to actual frequencies. A 90% prediction is right ~90% of the time, instead of the 99% confidence / 90% accuracy mismatch you get with one-hot. This is huge for production where downstream systems (alerts, thresholds, costs) depend on probabilities meaning what they say.
-
Tighter clusters: Müller, Kornblith, and Hinton 2019 showed label smoothing pulls all examples of the same class toward the same point in the penultimate layer — the embedding space gets cleaner clusters with bigger gaps. It also makes knowledge distillation worse (a known tradeoff).
0.1.#Early Stopping: Listen to Validation
Train until validation loss stops improving, then stop. That is early stopping. It is so simple it sounds trivial, but it is one of the most reliable regularizers ever invented — Goodfellow's textbook calls it "the most commonly used form of regularization in deep learning" and it has zero hyperparameter tuning beyond a patience value.
best_val_loss = float("inf")
patience, patience_counter = 5, 0
for epoch in range(max_epochs):
train_one_epoch(model, train_loader)
val_loss = evaluate(model, val_loader)
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), "best.pt") # checkpoint the best
patience_counter = 0
else:
patience_counter += 1
if patience_counter >= patience:
print(f"Early stop at epoch {epoch}, best val loss {best_val_loss:.4f}")
break
model.load_state_dict(torch.load("best.pt")) # restore the winner#Data Augmentation: The Quietly Strongest Regularizer
For images:
- Geometric: random crop (with resize), horizontal flip, rotation, perspective distortion, scaling
- Photometric: color jitter (brightness/contrast/saturation/hue), Gaussian blur, grayscale conversion
- Erasing: RandomErasing (Zhong et al. 2020) — black out a random rectangle, forces robustness to occlusion
- Learned policies: AutoAugment (RL-searched augmentation pipeline), RandAugment (just pick N random ops with magnitude M — works almost as well, far simpler), TrivialAugment (one random op, even simpler, often best)
For text: random token deletion, word swap, back-translation (translate to French and back), synonym replacement (NLPAug, TextAttack libraries).
For audio: time masking, frequency masking (SpecAugment), pitch shift, time stretch, additive noise.
The principle is universal: augment along the dimensions that should not change the label. Flipping a cat image horizontally is still a cat. Translating "the movie was great" to French and back is still positive sentiment. Anything that changes the label (rotating a "6" upside down to a "9") is a mistake.
#Mixup and CutMix: Convex Combinations of Examples
The code multiplies two losses by lambda and 1 - lambda. The derivation shows that this is the same as one cross-entropy against the mixed label.
x + F(x) become just x). The network has to learn to function with arbitrary subsets of layers — equivalent to training a shallow ensemble. Default in modern ViT and ConvNeXt training recipes.You train an MLP on a 200-row tabular dataset with dropout=0.5 between every layer. After 100 epochs, training accuracy is 60% and validation accuracy is 58%. What's the most likely problem?
The answer: dropout 0.5 zeroes half of every layer's activations every step. On a tiny dataset with a small network, this leaves so little signal that the model cannot even fit the training set. Drop dropout to 0.1 or remove it entirely; rely on weight decay + data augmentation instead. Regularization should match the gap between training and validation loss — if training loss is high, you don't have an overfitting problem and regularization is hurting you, not helping.
#Try It Yourself
This code needs PyTorch, and in places a GPU, so it cannot run on this page. Copy it to Google Colab to run it.
# Copy to Colab: needs torch, so it cannot run on this page.
# Implement dropout from scratch and verify the inverted-scaling math
import torch
import torch.nn as nn
import torch.nn.functional as F
# --- Manual dropout ---
def manual_dropout(x, p, training):
if not training or p == 0:
return x
mask = (torch.rand_like(x) > p).float()
return x * mask / (1 - p) # inverted scaling: keeps E[output] = E[input]
# --- Verify the expectation is preserved ---
torch.manual_seed(0)
x = torch.ones(10000)
out_train = manual_dropout(x, p=0.5, training=True)
out_eval = manual_dropout(x, p=0.5, training=False)
print(f"Training mode mean: {out_train.mean().item():.4f} (should be ~1.0)")
print(f"Eval mode mean: {out_eval.mean().item():.4f} (should be exactly 1.0)")
print(f"Training mode std: {out_train.std().item():.4f} (nonzero — random masking)")
print()
# --- Compare with PyTorch's built-in ---
torch.manual_seed(0)
official = F.dropout(x, p=0.5, training=True)
print(f"PyTorch official mean: {official.mean().item():.4f}")
print(f"Same scaling formula : (1-p) * 1/(1-p) = 1.0 in expectation\n")
# --- Mini training loop showing the train/eval mode switch ---
class TinyMLP(nn.Module):
def __init__(self, drop=0.5):
super().__init__()
self.fc1 = nn.Linear(20, 64)
self.dropout = nn.Dropout(drop)
self.fc2 = nn.Linear(64, 1)
def forward(self, x):
return self.fc2(self.dropout(F.relu(self.fc1(x))))
model = TinyMLP(drop=0.5)
batch = torch.randn(8, 20)
model.train()
out1 = model(batch)
out2 = model(batch)
print(f"In train mode, two forward passes with same input differ:")
print(f" ||out1 - out2|| = {(out1 - out2).norm().item():.4f} (nonzero — dropout active)")
model.eval()
out3 = model(batch)
out4 = model(batch)
print(f"In eval mode, two forward passes with same input match:")
print(f" ||out3 - out4|| = {(out3 - out4).norm().item():.4f} (zero — deterministic)")
print("\nCHALLENGE: Add label smoothing to a 3-class CE loss.")
print("Hint: nn.CrossEntropyLoss(label_smoothing=0.1) does it for you.")Notes for going further:
# Label smoothing built-in:
# loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1)
# logits = torch.randn(8, 3)
# targets = torch.randint(0, 3, (8,))
# loss = loss_fn(logits, targets)
# # Manual version:
# # log_probs = F.log_softmax(logits, dim=-1)
# # nll = -log_probs.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
# # smooth = -log_probs.mean(dim=-1).mean()
# # loss = 0.9 * nll + 0.1 * smoothWhat to check: Verify the manual dropout matches PyTorch's official scaling. Confirm train mode produces stochastic outputs and eval mode produces deterministic ones.
#Putting It Together: A Modern Regularization Stack
For a fresh CIFAR-10 ResNet from scratch in 2025, the typical recipe is:
- Data augmentation: random crop, horizontal flip, RandAugment(N=2, M=9), Mixup(alpha=0.2), random erasing
- Architecture-level: stochastic depth (linearly increasing drop probability with depth, max 0.1)
- Training-time noise: dropout=0.1 inside each block
- Loss / optimizer: cross-entropy with label_smoothing=0.1, AdamW with weight_decay=0.05
- Schedule: warmup 5 epochs, cosine decay over 200 epochs, early stopping with patience=20
For a fine-tuning task on a small custom dataset, dial almost all of this back: AdamW with weight_decay=0.01, light flip+crop augmentation, label_smoothing=0.1. Skip dropout (the pretrained model is already a heavy regularizer for your scale), skip Mixup (you don't have enough data for it to help).
#Key Takeaways
- Weight decay belongs in AdamW, not in the loss. Only AdamW applies decoupled weight decay correctly; vanilla Adam-with-L2 is broken because adaptive denominators warp the decay strength per parameter
- Dropout is inverted-scaled at training time so inference needs no special handling. But you MUST call
model.eval()before inference, or the random masks keep firing and your predictions become non-deterministic noise - Label smoothing fixes over-confident probabilities. Replacing one-hot targets with
(1-ε, ε/(K-1), ..., ε/(K-1))keeps logits bounded and produces calibrated outputs that downstream systems can actually trust - Data augmentation is usually the strongest regularizer in vision and audio. RandAugment + Mixup + horizontal flip will beat any architecture tweak, because it directly tells the model which transformations should not change the label
- Match regularization strength to your overfitting gap. Heavy regularization on a small dataset with a small model means you can't even fit the training set; start light, add only when validation accuracy plateaus while training keeps climbing
#Quick Check
You're training a transformer with Adam and `weight_decay=0.01` set on the optimizer. Why might switching to AdamW improve generalization without changing the value?