Regularization
Regularization trades a little training fit for better generalization: penalize large weights (L2/L1), inject noise (dropout, augmentation, label smoothing) or stop before the model memorizes (early stopping).
Analogy: Packing for a flight with a strict weight limit: you bring only what you really need. The penalty forces the model to explain the data with fewer, smaller weights instead of memorizing every quirk.
How it works
- It cuts variance at the price of a little bias; the best regularizer is still more data.
- L2 shrinks all weights smoothly; L1 drives many to exactly zero, so it selects features.
- Dropout zeroes random activations in training and uses every unit at inference, like averaging thinned networks.
- Early stopping keeps the best validation checkpoint and stops after N epochs without improvement.
- Tune each strength (λ, p, ε, patience) on validation, never on test.
Check yourself
Answer to mark it learned; your answers aren't scored.
Offline evaluation of your PyTorch classifier was fine. In the serving code, the same image gets noticeably different class probabilities on every call, and accuracy is lower. Most likely cause?
Go deeper
Full explanation
Regularization constrains a model so it learns the signal, not the noise in its training set. It cuts variance at the price of a little bias (see Supervised learning, bias–variance & overfitting); the best regularizer is still more data.
- L2 / weight decay: add λ·Σw² to the loss. Shrinks all weights smoothly toward zero, giving a smoother function. With Adam, use AdamW (decoupled decay), not L2 inside the loss.
- L1 (lasso): add λ·Σ|w|. Its constant pull drives many weights to exactly zero, so it selects features. Elastic net mixes L1 and L2.
- Dropout: in training, zero each activation with probability p and scale the survivors by 1/(1−p); at inference use every unit. Like averaging many thinned networks.
- Early stopping: track validation loss, keep the best checkpoint, stop after N epochs without improvement.
- Data augmentation: crops, flips, noise, paraphrases. More varied data teaches the invariances you care about.
- Label smoothing: train on soft targets (1−ε on the true class, ε spread across all classes) so the model can't push logits toward infinity.
Tune each strength (λ, p, ε, patience) on validation, never on test.
Code Dropout, label smoothing, AdamW decay, L1 and early stopping (PyTorch)
import torch, torch.nn as nn
import torchvision.transforms as T
# Augmentation: a new random variant of each 28x28 image every epoch (train set only)
augment = T.Compose([T.RandomAffine(degrees=10, translate=(0.1, 0.1)), T.ToTensor()])
model = nn.Sequential(
nn.Flatten(), nn.Linear(28 * 28, 512), nn.ReLU(),
nn.Dropout(p=0.3), # zeroes 30% of activations, train mode only
nn.Linear(512, 10),
)
loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1) # true class target 0.91, others 0.01
# AdamW: decoupled weight decay (L2-style shrink) applied outside the adaptive step
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)
def l1(m, lam=1e-6): # optional L1 term: pushes weights to exactly 0
return lam * sum(p.abs().sum() for p in m.parameters())
best, patience, bad = float("inf"), 5, 0
for epoch in range(100):
model.train() # dropout ON
for x, y in train_loader: # dataset built with transform=augment
loss = loss_fn(model(x), y) + l1(model)
opt.zero_grad(); loss.backward(); opt.step()
model.eval() # dropout OFF for evaluation
with torch.no_grad():
val = sum(loss_fn(model(x), y).item() for x, y in val_loader) / len(val_loader)
if val < best: # early stopping: keep the best checkpoint
best, bad = val, 0
torch.save(model.state_dict(), "best.pt")
else:
bad += 1
if bad >= patience: break
model.load_state_dict(torch.load("best.pt"))Real example
A product-photo classifier (ResNet-50, 20k images, 50 classes) reaches 99% train / 78% validation accuracy, and validation loss starts rising at epoch 12 while train loss keeps falling. You add random crops and flips, weight decay, label smoothing 0.1 and early stopping with patience 5. Train accuracy drops to ~90% and validation rises to ~86%: the gap shrinks from 21 to ~4 points. The lower train score is the point: the model stopped memorizing backgrounds and started learning products.
Trade-offs +3 · −4
+ You gain
- Cheap: usually one hyperparameter and one line of code each.
- Composable: augmentation, weight decay and early stopping stack well.
- L1 yields sparse, more interpretable models and doubles as feature selection.
− You pay
- Every knob is another hyperparameter; too much regularization causes underfitting.
- Dropout slows convergence and can clash with BatchNorm (variance shift between train and eval).
- Label smoothing makes models worse teachers for knowledge distillation (Müller et al., 2019).
- None of it fixes a train/production mismatch; it only fights memorizing noise.
Use it when
Whenever validation lags training. Start with early stopping and weight decay; add augmentation for vision, audio or text, dropout in big dense layers, and L1 when you need a few interpretable features.
Avoid it when
When you're underfitting (train error already high): remove regularization and add capacity. Huge-data pretraining often drops dropout entirely: PaLM trained with none, using 0.1 only for fine-tuning.
Numbers to know 4
- Dropout paper: keep hidden units with p 0.5–0.8 (drop 20–50%), inputs ~0.8; original Transformer: dropout 0.1.
- Label smoothing ε = 0.1 in Inception-v3 and the original Transformer.
- Weight decay: 0.1 with AdamW in LLM pretraining (GPT-3, LLaMA); 1e-4 with SGD in the ResNet recipe.
- Early-stopping patience of ~5–10 epochs is a common rule of thumb.
Common pitfalls 4
- Forgetting
model.eval()at inference: dropout stays on and predictions turn noisy. - Decaying biases and LayerNorm/BatchNorm weights; standard recipes exclude them from weight decay.
- Augmentations that change the label (a 6 rotated 180° is a 9), or augmented copies leaking across train and validation.
- Early stopping on a noisy metric with patience 1, or choosing the epoch by looking at the test set.
Interview questions 3
Answer out loud first, then reveal.
L1 vs L2: why does L1 give sparse weights?Show answer
Look at the penalty's gradient. L2's is 2λw: proportional to the weight, so the pull fades as w approaches zero and weights end up small but rarely exactly zero. L1's is λ·sign(w): a constant pull however small the weight, so any weight whose data gradient is weaker than λ gets pinned at exactly zero. Geometrically, the L1 ball is a diamond with corners on the axes, and the loss contours usually touch it at a corner. I default to L2, use L1 for feature selection, and elastic net when features are correlated.
Why does dropout work, and what changes at inference?Show answer
Each step drops a random subset of units, so the network can't rely on fragile co-adapted features and has to spread information redundantly. It approximates averaging an exponential number of thinned subnetworks that share weights. At inference I keep every unit; with inverted dropout, which PyTorch uses, survivors were already scaled by 1/(1−p) during training, so the only change is calling model.eval(). Trade-offs: slower convergence, and I avoid putting it right before BatchNorm. In LLM pretraining on huge data it's often off entirely.
Your fine-tune on 2k examples overfits after one epoch. What do you do?Show answer
Data is the first lever: I check for duplicates and leakage, then add or augment examples, for example paraphrases or human-reviewed synthetic data. Then I cut effective capacity: LoRA instead of full fine-tuning, a lower learning rate, fewer epochs, and early stopping with validation run several times per epoch. Weight decay and LoRA dropout help at the margin. I judge by a task metric, not only validation loss, since loss can rise from overconfidence while accuracy still improves.