Regularization and generalization
Three views of one idea: constraint, shrinkage and prior
Regularization is how you keep a flexible model from memorizing noise, and it is the same idea whether it appears as a penalty term in ridge regression, as weight decay in a transformer (4.7 Regularization in deep nets), as a KL term in RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI) or as early stopping. Seeing it three ways — geometry, shrinkage, Bayesian prior — makes every later instance obvious, and the modern twist (double descent) explains why billion-parameter models generalize at all.
You'll be able to
- Derive the ridge closed form and explain, via the SVD, which directions it shrinks and why it fixes collinearity
- Explain why the L1 penalty produces sparse solutions, geometrically and via soft-thresholding
- Show that L2 and L1 regularization are MAP estimation under Gaussian and Laplace priors
- Explain why early stopping, data augmentation and noise injection act as regularizers
- Describe the classical U-curve, the interpolation threshold and double descent
- Tune λ with cross-validation and read a regularization path
Key ideas
- Regularization is anything that lowers test error without lowering training error; the classical form adds λ·Ω(w) to the empirical risk.
- Ridge: w_λ = (XᵀX + λI)⁻¹Xᵀy; always invertible; via the SVD it shrinks direction j by σⱼ²/(σⱼ²+λ), damping the noisy low-variance directions most.
- Lasso soft-thresholds coefficients (subtract λ/2, zero the small ones) and selects features; the diamond-shaped ℓ₁ ball's corners are why.
Show 5 more key ideas
- Penalty ⇔ constraint (Lagrange duality) ⇔ prior: Gaussian prior gives ridge with λ = σ²/τ², Laplace prior gives lasso.
- Early stopping ≈ ridge with λ ≈ 1/(ηt): low-curvature (noisy) directions never get fitted.
- More data, augmentation (encoding invariances) and noise injection are regularizers without penalty terms.
- Double descent: test error peaks at the interpolation threshold and falls again for over-parameterized models because gradient descent finds min-norm, smooth interpolants.
- Tune λ on a log grid with cross-validation, standardize features, never penalize the intercept, and read the regularization path.
Suggested path through this lesson
What regularization is
Any modification to a learning algorithm intended to reduce its test error but not its training error is regularization. The classical form adds a penalty on the parameters to the empirical risk (3.1 What is learning? ERM, generalization and the ML workflow):
with controlling how much you care about small weights versus fitting the data. encodes a belief about what good solutions look like: says "small", says "small and mostly zero". We will see the same objective through three lenses — a constraint, a shrinkage operator and a Bayesian prior — and then meet regularizers that are not penalties at all.
Ridge regression: the closed form and what it shrinks
Add the squared norm to least squares (3.2 Linear regression; the intercept is left unpenalized and features are standardized first):
The eigenvalues of are (squared singular values of , 1.3 Eigen-things, SVD and low rank); adding lifts every one to , so the matrix is always invertible — ridge is the fix for collinear or more-features-than-rows design matrices. The SVD shows exactly what changes. Least squares projects onto the column space: . Ridge gives
Each direction is kept with a shrinkage factor : near 1 for directions in which the data vary a lot (well-determined), near 0 for directions with tiny , where the least-squares solution was mostly fitting noise and had huge variance. Ridge trades a little bias for a large reduction in variance (3.5 Evaluating models: metrics, validation and the bias–variance trade-off) precisely where variance was the problem. In the special case of orthonormal columns every coefficient is shrunk by the same factor, .
Lasso: why gives zeros
Replace the penalty by . There is no closed form in general (the norm is not differentiable at zero; coordinate descent or LARS solve it), but with orthonormal columns the problem separates per coordinate and the solution is soft-thresholding:
where is the least-squares coefficient. Ridge divides every coefficient; lasso subtracts a constant and sets small ones to exactly zero. Worked example: with . Ridge: . Lasso (threshold ): — the third feature is dropped. Lasso therefore performs feature selection, which is why it is used when you suspect most features are irrelevant; ridge is preferred when many features matter a little, and the elastic net mixes the two and handles groups of correlated features gracefully.
The geometric reason is the one from 1.1 Vectors, dot products and norms: the penalized problem is equivalent (by Lagrange duality, 1.10 Optimization: from gradient descent to Adam) to minimizing the loss subject to . The loss's elliptical contours expand until they first touch the constraint region. The ball is round, so the touching point is generic — no coordinate is special. The ball is a diamond whose corners sit on the axes, and an ellipse is far more likely to hit a corner than a flat face; at a corner some coordinates are exactly zero. In high dimensions the ball is almost all corners.
The Bayesian view: regularizers are priors
Return to the probabilistic model of 3.2 Linear regression, , and add a prior belief that weights are small: . The log posterior (1.7 Probability II: Bayes, independence, MLE and MAP) is
Maximizing it (the MAP estimate) is minimizing : ridge with . Noisy data (large ) or a strong prior (small ) mean more shrinkage, which is exactly right. A Laplace prior , sharply peaked at zero, gives lasso with . Every penalty is a prior and every prior is a penalty; when you meet weight decay in a transformer (4.7 Regularization in deep nets) or the KL penalty toward a reference policy in RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI), you are looking at a prior saying "stay close to what we already believed".
Regularizers that are not penalties
Early stopping. Run gradient descent on least squares from and stop after steps. In the eigenbasis of (eigenvalues ) the -th component of the iterate is : high-curvature directions converge in a few steps, low-curvature ones (small , the noisy directions) barely move. That is the same ordering of shrinkage as ridge, and matching the factors gives the correspondence . Stopping when validation error turns up is the most used regularizer in deep learning (4.7 Regularization in deep nets).
Data. More relevant data lowers variance directly (3.5 Evaluating models: metrics, validation and the bias–variance trade-off). Augmentation manufactures more data by applying transformations the label should be invariant to — flips, crops and color shifts for images (5.4 Transfer learning and training CNNs in practice), synonym swaps for text — and is the strongest regularizer in computer vision. Noise injection on inputs is, to second order, equivalent to an penalty on the weights (Bishop, 1995), and dropout (4.7 Regularization in deep nets) is noise injection on hidden units. Simpler models and fewer features are regularization by hypothesis-space design (3.1 What is learning? ERM, generalization and the ML workflow).
Complexity versus data, and double descent
The classical story: as capacity grows, training error falls monotonically while test error follows a U — the sweet spot sits before the model can interpolate (fit every training point). The interactive demo shows this U: raise the polynomial degree on noisy data and watch test error fall, then explode. The modern story adds a chapter. If you keep increasing capacity past the interpolation threshold (parameters data points), test error often falls again — double descent (Belkin et al., 2019; Nakkiran et al., 2019). At the threshold there is exactly one interpolating solution and it must contort wildly to hit every noisy point, so variance peaks; beyond it, infinitely many interpolants exist and gradient descent from small initialization finds the minimum-norm one, which is smooth — an implicit regularization with no penalty term. This is why heavily over-parameterized networks generalize, and it reframes the practical recipe: use a model far larger than the data would classically justify, then regularize (weight decay, augmentation, early stopping) and tune by validation.
Choosing λ
Sweep on a logarithmic grid (e.g., to ), cross-validate (3.5 Evaluating models: metrics, validation and the bias–variance trade-off), and plot the regularization path — coefficients versus — to see which features survive. Pick the minimum validation error or, if you value simplicity, the one-standard-error rule: the largest whose error is within one standard error of the best. Always standardize features first (the penalty treats all coordinates alike) and never penalize the intercept.
from sklearn.linear_model import RidgeCV, LassoCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np
alphas = np.logspace(-4, 2, 30)
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=alphas, cv=5)).fit(X, y)
lasso = make_pipeline(StandardScaler(), LassoCV(alphas=alphas, cv=5)).fit(X, y)
ridge[-1].alpha_, lasso[-1].alpha_, (lasso[-1].coef_ != 0).sum() # chosen λ's and surviving features
Where this shows up later
- Weight decay, dropout, augmentation and early stopping in deep nets are these ideas at scale — 4.7 Regularization in deep nets; AdamW's decoupled weight decay is ridge done right — 4.5 Optimizers and learning-rate schedules.
- Double descent and grokking are the modern generalization puzzles — 4.7 Regularization in deep nets, 7.9 Scaling laws and compute-optimal training; "bigger model plus regularization" is the LLM recipe — 8.1 The LLM lifecycle and model landscape.
- The KL penalty in RLHF and DPO is a prior toward the reference model — 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI; LoRA's low rank is a structural regularizer — 8.2 Fine-tuning and PEFT.
- Sparsity from returns in sparse autoencoders for interpretability — 8.11 Interpretability: what is happening inside.
Common pitfalls (5)
- Regularizing unstandardized features, so the penalty hits small-unit features hardest for no reason.
- Penalizing the intercept, which biases predictions toward zero even when the target mean is far from it.
- Picking λ on the test set; use cross-validation and keep the test set for the final number.
- Concluding from the classical U-curve that a model with more parameters than data points must overfit.
- Using lasso with groups of correlated features and expecting stable selection; it picks one arbitrarily — use elastic net.
Recap: all 8 key points
- Regularization is anything that lowers test error without lowering training error; the classical form adds λ·Ω(w) to the empirical risk.
- Ridge: w_λ = (XᵀX + λI)⁻¹Xᵀy; always invertible; via the SVD it shrinks direction j by σⱼ²/(σⱼ²+λ), damping the noisy low-variance directions most.
- Lasso soft-thresholds coefficients (subtract λ/2, zero the small ones) and selects features; the diamond-shaped ℓ₁ ball's corners are why.
- Penalty ⇔ constraint (Lagrange duality) ⇔ prior: Gaussian prior gives ridge with λ = σ²/τ², Laplace prior gives lasso.
- Early stopping ≈ ridge with λ ≈ 1/(ηt): low-curvature (noisy) directions never get fitted.
- More data, augmentation (encoding invariances) and noise injection are regularizers without penalty terms.
- Double descent: test error peaks at the interpolation threshold and falls again for over-parameterized models because gradient descent finds min-norm, smooth interpolants.
- Tune λ on a log grid with cross-validation, standardize features, never penalize the intercept, and read the regularization path.
Watch
Why adding a penalty lowers variance, with pictures.
Read
Try it live
Interactive demo
runs in your browserExercises
- Shrinkage by hand
With orthonormal features and least-squares coefficients , compute ridge and lasso solutions for . Expected: ridge divides by ; lasso subtracts and zeroes the third coefficient for .
- Ridge fixes collinearity
Build with two nearly identical columns plus noise and fit OLS and ridge (λ = 1) on 20 bootstrap resamples. Expected: OLS coefficients on the twin columns swing between huge positive and negative values; ridge coefficients are stable and split the effect.
- Regularization path
On the diabetes dataset (
sklearn.datasets.load_diabetes), fitlasso_pathover a log grid and plot coefficients vs λ; mark the λ chosen byLassoCVand by the one-standard-error rule. Expected: features drop out one by one; the 1-SE model is sparser. - Early stopping equals ridge
Run gradient descent on least squares with a tiny learning rate from zero and record every 10 steps. For each snapshot find the ridge λ whose solution is closest in Euclidean distance. Expected: the best λ decreases roughly like .
- See double descent
Fit random-feature regression (random ReLU features of a 1-D input) to 50 noisy points with 5, 20, 45, 50, 55, 100, 500 features using min-norm least squares (
np.linalg.pinv). Plot test error vs feature count. Expected: a peak near 50 features and lower error on both sides.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →