Bias, variance and regularisation¶
A model's error on new data comes from three places: it is too simple to represent the truth (bias), it reacts to the accidents of the particular training set (variance), and the world is noisy. Regularisation is the deliberate act of accepting a little bias to buy a large cut in variance; double descent is the modern discovery that the story has a second act.
10,000 ft
The question behind all of machine learning is generalisation: why should a model fitted to some examples work on examples it has never seen? The bias–variance decomposition is the classical answer and the most useful mental model a practitioner owns: it explains underfitting and overfitting, why more data helps, why ensembles work, and why every successful learning system includes some form of regularisation, from ridge regression's penalty in 1970 to weight decay, dropout, data augmentation and early stopping in today's networks (deep-learning regularisation). Then, around 2018–2019, practitioners' habit of training huge networks to zero training error forced a revision: test error can fall again after the point of perfect fit, "double descent", which connects this page to learning theory and scaling laws.
2,000 ft
Imagine retraining the same procedure on many independent training sets from the same world. Bias is how far the average of those fitted models is from the truth; variance is how much the individual fits scatter around that average. For squared error, expected test error = bias² + variance + irreducible noise, exactly. Making the model more flexible lowers bias and raises variance; more data lowers variance; regularisation (a penalty such as \(\lambda\lVert\mathbf{w}\rVert^2\), or early stopping, or averaging many models) raises bias slightly and lowers variance a lot. You choose the amount by validation. In heavily over-parameterised models the classical U-shaped curve can turn into a double descent, because among the many perfect fits the training algorithm picks a smooth one.
Ground level¶
Underfitting and overfitting, seen¶
Take points from a smooth curve plus noise, and fit polynomials of increasing degree. Degree 1 is a straight line through a wave: it misses the shape no matter how much data you give it (high bias, underfitting). Degree 3 follows the wave. Degree 14 through 15 points threads every point exactly, including the noise, and swings wildly between them (high variance, overfitting): training error is zero and test error is enormous. Drag the degree and watch training and test error part ways:
Training error is always optimistic, because the model has seen those points. Test error, measured on data the fit never touched, is the quantity you care about; metrics, validation and leakage is about measuring it honestly.
The decomposition in numbers¶
A simulation makes bias and variance concrete. The world: \(y = \sin(2\pi x) + \varepsilon\), \(\varepsilon\sim\mathcal{N}(0, 0.3^2)\), 15 training points at fixed, evenly spaced \(x\). We draw 2,000 independent noisy training sets, fit a polynomial of each degree to every one, and measure on a dense grid how far the average fit is from the truth (bias²) and how much the fits scatter around their average (variance). The code is in Build it.
| degree | bias² | variance | expected test MSE (= bias² + variance + 0.09) |
|---|---|---|---|
| 1 | 0.2103 | 0.0111 | 0.3114 |
| 3 | 0.0055 | 0.0205 | 0.1160 |
| 5 | 0.0000 | 0.0309 | 0.1210 |
| 9 | 0.0000 | 0.0627 | 0.1528 |
| 12 | 0.0002 | 0.4801 | 0.5703 |
| 14 | 0.0471 | 66.81 | 66.95 |
Read it column by column. Bias falls to essentially zero by degree 5: a quintic can bend like a sine wave on \([0,1]\). Variance rises steadily and then explodes as the number of parameters approaches the number of points; at degree 14 (15 parameters, 15 points) the fit interpolates, and the noise in each training set is amplified into huge oscillations near the ends. (The small non-zero bias² at degree 14 is Monte Carlo leakage of that enormous variance into the estimated average.) The best degree, 3, is not the one with the lowest bias: it is the best trade. The noise floor of \(\sigma^2 = 0.09\) is the same in every row; no model can beat it.
Bias and variance belong to a procedure, not to a fitted model
A single fitted curve has an error, not a bias and a variance. Bias and variance describe the learning procedure (model family + fitting method + training-set size) across the training sets it might have been given. That is why "more data" reduces variance without changing the model, and why averaging models trained on different resamples (bagging, random forests) reduces variance without changing bias.
Regularisation: buy variance with bias¶
Restricting the model family (choosing degree 3) is one way to control variance, but it is coarse: features come and go in whole units. Regularisation instead keeps the flexible family and adds a preference for "simple" parameter values to the training objective:
\(\lambda \ge 0\) is a continuous dial. At \(\lambda = 0\) you have the unregularised fit; as \(\lambda \to \infty\) the weights are forced to zero (a constant model). Somewhere in between is the best trade, found by cross-validation. The same degree-14 polynomial that scored 66.95 above, refitted with a ridge penalty:
| λ | bias² | variance | expected test MSE |
|---|---|---|---|
| 0.0001 | 0.0190 | 23.76 | 23.87 |
| 0.01 | 0.0033 | 0.2178 | 0.3111 |
| 0.1 | 0.0042 | 0.0641 | 0.1583 |
| 1 | 0.0328 | 0.0262 | 0.1490 |
| 10 | 0.2773 | 0.0080 | 0.3753 |
A U-curve again, now in \(\lambda\): from 66.95 to 0.149, close to the best hand-picked degree (0.116), without choosing the degree at all. Bias rises monotonically with \(\lambda\) and variance falls monotonically; the sum has a minimum.
Ridge (L2): shrink everything a little¶
Ridge regression (Hoerl and Kennard, 1970; the same idea as Tikhonov regularisation in numerical analysis) uses \(\Omega(\mathbf{w}) = \lVert\mathbf{w}\rVert_2^2 = \sum_j w_j^2\). The loss stays a quadratic, so there is a closed form:
Adding \(\lambda\) to the diagonal makes the matrix invertible even when \(X^\top X\) is singular (collinear features, or more features than rows), which is what Hoerl and Kennard were after.
By hand. On the five-point example from linear regression, with \(x\) centred (so the intercept is unpenalised and stays \(\bar y = 4\)), the one-feature ridge slope is
\(\lambda = 0\) gives the OLS slope \(0.9\); \(\lambda = 10\) halves it to \(0.45\); \(\lambda\to\infty\) flattens the line to \(\hat y = 4\). The penalty acts like \(\lambda\) phantom data points that all vote for a zero slope.
Where the shrinkage lands. Write the SVD \(X = UDV^\top\) with singular values \(d_j\). Then OLS fitted values are \(\sum_j \mathbf{u}_j(\mathbf{u}_j^\top\mathbf{y})\), while ridge's are
Each principal direction of the inputs is shrunk by the factor \(d_j^2/(d_j^2+\lambda)\): directions where the data vary a lot (\(d_j^2 \gg \lambda\)) pass almost untouched, directions with little spread, where the estimate is noisiest, are shrunk hardest. Ridge does not treat features equally; it treats directions of evidence according to how much evidence there is. The sum of those factors, \(\mathrm{df}(\lambda) = \sum_j d_j^2/(d_j^2+\lambda)\), is the effective degrees of freedom: \(p\) at \(\lambda = 0\) (the trace of the hat matrix in linear regression), falling smoothly to 0.
Lasso (L1): shrink some things to exactly zero¶
The lasso (Tibshirani, 1996) uses \(\Omega(\mathbf{w}) = \lVert\mathbf{w}\rVert_1 = \sum_j |w_j|\). It has no closed form in general, but it does something ridge never does: it sets many weights to exactly zero, performing feature selection and estimation in one convex problem.
By hand, the orthonormal case. If the columns of \(X\) are orthonormal and we minimise \(\tfrac12\lVert\mathbf{y}-X\mathbf{w}\rVert^2 + \lambda\lVert\mathbf{w}\rVert_1\), the problem separates per coordinate and the answer is soft-thresholding of the OLS coefficients:
whereas ridge with \(\tfrac12\lVert\mathbf{y}-X\mathbf{w}\rVert^2 + \tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2\) gives \(\hat w_j/(1+\lambda)\). Take OLS coefficients \((3.0, 0.8, -0.3)\) and \(\lambda = 0.5\): lasso returns \((2.5, 0.3, 0)\); ridge returns \((2.0, 0.533, -0.2)\). Lasso subtracts a constant and clips at zero, killing the small coefficient; ridge divides by a constant, keeping every coefficient alive and hitting the large ones hardest in absolute terms.
Why corners make zeros. Write the penalised problem in constrained form: minimise the squared error subject to \(\Omega(\mathbf{w}) \le t\). The loss's level sets are ellipses centred on the OLS solution; the answer is where the smallest ellipse first touches the constraint region. The L2 ball is round, so the first contact is almost never on an axis. The L1 ball is a diamond (a cross-polytope in higher dimensions) whose corners stick out along the axes, so the first contact is very often a corner, where some coordinates are exactly zero.
Lasso's weaknesses follow from the same geometry: among a group of highly correlated features it tends to pick one arbitrarily, and it can select at most \(n\) features when \(p > n\). The elastic net (Zou and Hastie, 2005) mixes the penalties, \(\lambda_1\lVert\mathbf{w}\rVert_1 + \lambda_2\lVert\mathbf{w}\rVert_2^2\), keeping sparsity while sharing weight across correlated groups.
The wider family of regularisers¶
Anything that restricts the effective flexibility of the fitted model, or averages away its sensitivity to the particular sample, regularises. The same trade appears under many names:
| Regulariser | Where you meet it | How it cuts variance |
|---|---|---|
| L2 penalty / weight decay | ridge, logistic regression, AdamW in every LLM | shrinks weights, mostly along low-evidence directions |
| L1 penalty | lasso, sparse models | zeros out features |
| Early stopping | gradient-trained models | stops before fitting the noise; for least squares it is approximately ridge with \(\lambda \approx 1/(\eta t)\) (see The maths) |
| Fewer features / lower degree / smaller model | everything | restricts the hypothesis class |
| Data augmentation | vision, speech, text | adds plausible variations, encoding invariances |
| Dropout, noise injection | neural networks | trains an implicit ensemble; noise on inputs is equivalent to an L2-like penalty for linear models |
| Bagging and ensembling | random forests, model averaging | averaging \(B\) fits with correlation \(\rho\) cuts variance from \(\sigma^2\) to \(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\) |
| Priors | Bayesian models | the penalty is the negative log-prior (MAP) |
| Pre-training | foundation models | starts from parameters that already encode broad structure, so fine-tuning needs fewer bits from the small dataset |
Double descent: when the U-curve breaks¶
The classical picture says: as capacity grows past the sweet spot, test error rises, and a model that fits the training data perfectly is badly overfitted. Modern deep learning flatly contradicts it. Zhang et al. (2016) showed that standard image networks can fit random labels perfectly, so they have enough capacity to memorise anything, yet the same networks trained on real labels generalise well. Belkin, Hsu, Ma and Mandal (2019) reconciled the two pictures with the double descent curve: test error follows the classical U up to the interpolation threshold (where the model has just enough capacity to fit the training data exactly), peaks there, and then falls again as capacity grows further. Nakkiran et al. (2019) found it in deep networks as a function of model size, of training epochs, and even of dataset size (more data can briefly hurt).
You can see it in plain linear regression. Let the truth use 400 weak features, give the model the first \(p\) of them, train on \(n = 40\) points, and use the minimum-norm least-squares fit whenever \(p > n\) (Build it):
| model features \(p\) | 5 | 20 | 35 | 40 = n | 45 | 60 | 100 | 200 | 400 |
|---|---|---|---|---|---|---|---|---|---|
| test MSE | 1.42 | 2.46 | 9.18 | 111.95 | 10.00 | 3.49 | 1.81 | 1.35 | 1.18 |
Why the peak? At \(p = n\) there is exactly one interpolating solution, and to thread every noisy point it must use whatever directions the data offer, including those with tiny singular values: the noise is divided by near-zero numbers. Past the threshold there are infinitely many interpolators and the minimum-norm one spreads the fit across many directions, each carrying only a little noise; extra features act as an implicit ridge penalty. Gradient descent from zero finds exactly this minimum-norm solution (linear regression: the maths), which is one reason over-parameterised networks trained by gradient descent generalise. The peak is also fragile: an optimally tuned ridge penalty removes it. What survives is the lesson that "number of parameters" is a poor measure of capacity; what matters is the effective complexity of the solution the algorithm actually returns. Learning theory takes this further.
First principles¶
Why must there be a trade-off at all? A finite training set contains a finite amount of information. A model with many free parameters must spend that information pinning each one down; spread thin, each estimate is noisy (variance). A model with few parameters pins them down well, but if the truth is not in its family, no amount of data closes the gap (bias). Learning theory names the two parts estimation error and approximation error. Every inductive bias (linearity, smoothness, sparsity, translation invariance in CNNs) is a bet that the truth lies in, or near, a small part of the space, so that fewer bits of data are needed to find it. When the bet is right, you win twice: low bias and low variance.
Unbiased is not best. It is tempting to think an unbiased estimator is the honest one. Stein's paradox says otherwise: when estimating three or more means at once from Gaussian observations, the obvious unbiased estimate (use each observation as its own mean) is inadmissible: James and Stein (1961) gave an estimator that shrinks all of them towards a common point and has lower total squared error for every possible value of the true means. Shrinkage borrows strength across coordinates. Ridge regression is the same idea applied to regression weights, and the Gauss–Markov guarantee for OLS (best among unbiased linear estimators) leaves exactly this loophole open.
A penalty is a prior. Put a Gaussian prior \(\mathbf{w}\sim\mathcal{N}(\mathbf{0}, \tau^2 I)\) on the weights and maximise the posterior instead of the likelihood: the negative log-posterior is the squared error plus \(\frac{\sigma^2}{\tau^2}\lVert\mathbf{w}\rVert^2\), so ridge is MAP estimation with \(\lambda = \sigma^2/\tau^2\). A Laplace prior \(p(w_j)\propto e^{-|w_j|/b}\) gives the lasso. Strong regularisation means a confident prior; weak regularisation, a vague one. The Bayesian view also tells you what to do with \(\lambda\) in principle (integrate over it, or maximise the marginal likelihood) and connects this page to MLE, MAP and Bayes.
What breaks if you ignore it. Without any regularisation, a model with as many effective parameters as data points has no reason to prefer the smooth curve over the wild one that also passes through every point. Something must express the preference; if you do not choose it explicitly (penalty, prior, architecture), you inherit whatever implicit preference the optimiser has, which for gradient descent happens to be a good one in many settings and an awful one in others.
The maths¶
Setting. Data \(y = f(\mathbf{x}) + \varepsilon\) with \(\mathbb{E}[\varepsilon] = 0\), \(\operatorname{Var}(\varepsilon) = \sigma^2\), noise independent across examples. A training set \(\mathcal{D}\) is random; the fitted predictor \(\hat f_{\mathcal{D}}\) is therefore random. Write \(\bar f(\mathbf{x}) = \mathbb{E}_{\mathcal{D}}[\hat f_{\mathcal{D}}(\mathbf{x})]\) for the average prediction.
Averaging over test inputs \(\mathbf{x}\) gives the decomposition of expected test MSE used in the tables above.
Derivation: the bias–variance decomposition
Fix \(\mathbf{x}\) and drop it from the notation. Write \(y - \hat f = (f - \bar f) + (\bar f - \hat f) + \varepsilon\). Square and take expectations over \(\mathcal{D}\) and the test noise \(\varepsilon\):
The cross terms vanish: \(\mathbb{E}_{\mathcal{D}}[\bar f - \hat f] = 0\) by the definition of \(\bar f\); \(\mathbb{E}[\varepsilon] = 0\); and the test noise \(\varepsilon\) is independent of the training set, so \(\mathbb{E}[(\bar f - \hat f)\varepsilon] = \mathbb{E}[\bar f - \hat f]\,\mathbb{E}[\varepsilon] = 0\). What remains is bias² + variance + \(\sigma^2\). The decomposition is exact for squared error; for 0–1 loss and cross-entropy there are analogous but non-additive versions.
Ridge: bias and variance in closed form. With fixed design and \(\mathbf{y} = X\mathbf{w} + \boldsymbol\varepsilon\), let \(A_\lambda = (X^\top X + \lambda I)^{-1}X^\top X\). Then
In the eigenbasis of \(X^\top X\) (eigenvalues \(s_j = d_j^2\)), coordinate \(j\) has bias factor \(\frac{\lambda}{s_j+\lambda}\) and variance \(\sigma^2\frac{s_j}{(s_j+\lambda)^2}\), compared with OLS's zero bias and variance \(\sigma^2/s_j\). For a small eigenvalue \(s_j\), OLS variance \(\sigma^2/s_j\) is huge while ridge's is at most \(\sigma^2/(4\lambda)\). Hoerl and Kennard proved that there is always some \(\lambda > 0\) with lower total mean-squared error than OLS.
Derivation: lasso soft-thresholding via subgradients
With orthonormal columns (\(X^\top X = I\)) and \(\hat{\mathbf{w}} = X^\top\mathbf{y}\) the OLS solution, \(\tfrac12\lVert\mathbf{y}-X\mathbf{w}\rVert^2 = \tfrac12\lVert\mathbf{w} - \hat{\mathbf{w}}\rVert^2 + \text{const}\), so the lasso problem splits into one-dimensional problems \(\min_{w}\;\tfrac12(w-\hat w)^2 + \lambda|w|\). The objective is convex; \(w^\ast\) is optimal iff \(0\) lies in its subdifferential \(w - \hat w + \lambda\,\partial|w|\), where \(\partial|w| = \{\operatorname{sign}(w)\}\) for \(w\ne0\) and \([-1,1]\) at \(0\).
- If \(w^\ast > 0\): \(w^\ast = \hat w - \lambda\), consistent only when \(\hat w > \lambda\).
- If \(w^\ast < 0\): \(w^\ast = \hat w + \lambda\), consistent only when \(\hat w < -\lambda\).
- If \(w^\ast = 0\): need \(\hat w \in [-\lambda, \lambda]\).
Together: \(w^\ast = \operatorname{sign}(\hat w)(|\hat w| - \lambda)_+\). For general \(X\), coordinate descent applies this update one coordinate at a time on partial residuals, which is how glmnet and scikit-learn solve the lasso.
Early stopping is approximately ridge. Gradient descent on \(\frac{1}{2}\lVert\mathbf{y} - X\mathbf{w}\rVert^2\) from \(\mathbf{w}_0 = \mathbf{0}\) with step \(\eta\) gives, in eigen-coordinate \(j\),
Both are filters that pass high-\(s_j\) directions and suppress low-\(s_j\) ones; for small \(\eta s_j\), \(1 - (1-\eta s_j)^t \approx 1 - e^{-\eta t s_j}\), which behaves like \(\frac{s_j}{s_j+\lambda}\) with \(\lambda \approx 1/(\eta t)\). Training longer is weaker regularisation.
Effective degrees of freedom of a linear smoother \(\hat{\mathbf{y}} = S\mathbf{y}\) is \(\operatorname{tr}(S)\). For ridge, \(\operatorname{tr}\big(X(X^\top X+\lambda I)^{-1}X^\top\big) = \sum_j \frac{d_j^2}{d_j^2+\lambda}\). For the lasso, the expected number of non-zero coefficients is an unbiased estimate of its degrees of freedom (a result of Zou, Hastie and Tibshirani).
Minimum-norm interpolation. For \(p > n\) with full row rank, \(\hat{\mathbf{w}} = X^\top(XX^\top)^{-1}\mathbf{y} = X^+\mathbf{y}\), which equals \(\lim_{\lambda\to 0^+}\hat{\mathbf{w}}_{\text{ridge}}(\lambda)\): "ridgeless" regression. Its variance is \(\sigma^2\operatorname{tr}\big((XX^\top)^{-1}\big)\) (times feature covariance terms), which blows up as the smallest eigenvalue of \(XX^\top\) approaches 0, as it does near \(p = n\) for random designs: the double-descent peak. Hastie, Montanari, Rosset and Tibshirani (2019) give exact asymptotic curves.
In practice¶
- Standardise features before any penalty; otherwise \(\lambda\) punishes features according to their units. Do not penalise the intercept.
- Choose \(\lambda\) by cross-validation on a log grid (e.g. \(10^{-4}\) to \(10^{4}\)). The one-standard-error rule picks the most regularised model whose CV error is within one standard error of the best; it trades a statistically invisible loss for a simpler model.
- Ridge by default when many features each matter a little or are correlated; lasso when you believe few matter and want selection; elastic net when both. In scikit-learn:
RidgeCV,LassoCV,ElasticNetCV; logistic regression'sCis \(1/\lambda\). - Diagnose with learning curves. Plot training and validation error against training-set size. Both high and close together: bias, so add capacity or features. Large gap: variance, so add data or regularisation.
- Weight decay in deep learning is L2 regularisation (decoupled from the adaptive step in AdamW); typical LLM pre-training uses weight decay around 0.1 (optimisers).
- Lasso-selected features are not "the true causes". With correlated predictors the selected set is unstable across resamples; check stability before telling a story about it.
Common misconceptions¶
More parameters always means more overfitting
Capacity is not the parameter count. A heavily regularised or implicitly regularised model with millions of parameters can have lower variance than a 15-parameter polynomial interpolating 15 points. Double descent is the sharpest demonstration.
Overfitting means training error is low
Overfitting means the gap between training and test error is large and test error is worse than a simpler or more regularised alternative would give. Low training error with low test error is just a good model.
Regularisation is only for small datasets
Every frontier model is trained with weight decay and often with data augmentation or dropout; the right amount shrinks as data grows, but rarely to zero.
Build it¶
1. The bias–variance decomposition by simulation. NumPy only; runs in about two seconds.
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x) # the truth we pretend not to know
sigma, n, trials = 0.3, 15, 2000
x_test = np.linspace(0, 1, 200)
x_train = np.linspace(0, 1, n) # fixed inputs; only the noise is redrawn
def design(x, degree): # Legendre basis on [-1, 1]: well conditioned
return np.polynomial.legendre.legvander(2 * x - 1, degree)
def fit_predict(x, y, degree, lam=0.0):
A, B = design(x, degree), design(x_test, degree)
P = lam * np.eye(degree + 1); P[0, 0] = 0 # don't penalise the intercept
w = np.linalg.solve(A.T @ A + P, A.T @ y) if lam else np.linalg.lstsq(A, y, rcond=None)[0]
return B @ w
def decompose(degree, lam=0.0):
preds = np.empty((trials, x_test.size))
for t in range(trials): # many noisy training sets, same world
x = x_train
preds[t] = fit_predict(x, f(x) + rng.normal(0, sigma, n), degree, lam)
bias2 = np.mean((preds.mean(0) - f(x_test)) ** 2)
var = np.mean(preds.var(0))
return bias2, var, bias2 + var + sigma**2
print("degree bias² variance expected test MSE")
for deg in (1, 3, 5, 9, 12, 14):
b, v, e = decompose(deg)
print(f"{deg:>4} {b:8.4f} {v:9.4f} {e:12.4f}")
print("\ndegree 14 (15 parameters, 15 points) with ridge penalty λ:")
for lam in (1e-4, 1e-2, 1e-1, 1.0, 10.0):
b, v, e = decompose(14, lam)
print(f" λ={lam:<6g} bias²={b:.4f} var={v:.4f} test MSE={e:.4f}")
Output:
degree bias² variance expected test MSE
1 0.2103 0.0111 0.3114
3 0.0055 0.0205 0.1160
5 0.0000 0.0309 0.1210
9 0.0000 0.0627 0.1528
12 0.0002 0.4801 0.5703
14 0.0471 66.8109 66.9481
degree 14 (15 parameters, 15 points) with ridge penalty λ:
λ=0.0001 bias²=0.0190 var=23.7586 test MSE=23.8675
λ=0.01 bias²=0.0033 var=0.2178 test MSE=0.3111
λ=0.1 bias²=0.0042 var=0.0641 test MSE=0.1583
λ=1 bias²=0.0328 var=0.0262 test MSE=0.1490
λ=10 bias²=0.2773 var=0.0080 test MSE=0.3753
2. Double descent in ordinary least squares.
import numpy as np
rng = np.random.default_rng(0)
n, D, sigma, trials = 40, 400, 0.5, 200
w_true = rng.normal(0, 1, D); w_true /= np.linalg.norm(w_true) # signal spread over all D features
print(" p test MSE (model sees the first p of", D, "features; n =", n, ")")
for p in (5, 10, 20, 30, 35, 38, 40, 42, 45, 60, 100, 200, 400):
errs = []
for _ in range(trials):
X = rng.normal(0, 1, (n, D)); y = X @ w_true + rng.normal(0, sigma, n)
w = np.linalg.lstsq(X[:, :p], y, rcond=None)[0] # min-norm solution if p > n
Xt = rng.normal(0, 1, (500, D))
errs.append(np.mean((Xt[:, :p] @ w - Xt @ w_true) ** 2) + sigma**2)
tag = " <- p = n: interpolation threshold" if p == n else ""
print(f"{p:>4} {np.median(errs):9.3f}{tag}")
Output:
p test MSE (model sees the first p of 400 features; n = 40 )
5 1.418
10 1.638
20 2.464
30 4.524
35 9.177
38 18.791
40 111.951 <- p = n: interpolation threshold
42 22.563
45 9.999
60 3.485
100 1.807
200 1.353
400 1.176
The peak sits exactly at \(p = n\), and with all 400 features the over-parameterised interpolator (1.18) beats every under-parameterised model. For reference, predicting zero everywhere scores \(\lVert\mathbf{w}\rVert^2 + \sigma^2 = 1.25\): the signal is weak and spread thin, the regime in which this effect is strongest.
Things to try
- In snippet 1, draw the \(x\) positions at random for each training set instead of fixing them. Variance at high degree becomes far larger and heavier-tailed: random designs put points near the ends sparsely, where polynomials swing.
- Add
n = 60and rerun: which column of the table changes, and which does not? - In snippet 2, replace
lstsqwith ridge at \(\lambda = 1\) and confirm the peak disappears. - Implement the lasso by coordinate descent with soft-thresholding; plot the coefficient paths as \(\lambda\) decreases and note the order in which features enter.
- Bag 50 degree-9 fits on bootstrap resamples and measure how much variance falls; compare with the \(\rho\sigma^2 + (1-\rho)\sigma^2/B\) formula.
Check yourself¶
Training error 2%, validation error 25%. Bias or variance problem? Name three remedies.
Variance (large gap). Remedies: more training data; stronger regularisation (larger \(\lambda\), weight decay, dropout, augmentation, early stopping); a simpler model or fewer features; bagging/ensembling. Also check for leakage between training and validation if the gap is suspicious in the other direction.
Training error 20%, validation 21%, and a human expert gets 3%. What now?
High bias: the model underfits. Increase capacity (more features, interactions, a more flexible model), reduce regularisation, train longer. More data alone will not help much: both errors are already close.
Why does the ridge penalty shrink coefficients along small-singular-value directions the most, and why is that what you want?
The shrinkage factor is \(d_j^2/(d_j^2+\lambda)\). Small \(d_j\) means the data barely vary along that direction, so the OLS estimate there is \(\sigma^2/d_j^2\)-noisy; shrinking it costs little bias (the data could not see it anyway) and saves a lot of variance.
OLS coefficients \((1.2, -0.4, 0.1)\), orthonormal design. Give the lasso solution at \(\lambda = 0.3\) and the ridge solution at \(\lambda = 1\) (with the conventions on this page).
Lasso: \((0.9, -0.1, 0)\). Ridge: divide by \(1 + 1 = 2\): \((0.6, -0.2, 0.05)\).
Show that ridge regression is MAP estimation with a Gaussian prior, and find \(\lambda\) in terms of the noise and prior variances.
\(-\log p(\mathbf{w}\mid\mathbf{y}) = \frac{1}{2\sigma^2}\lVert\mathbf{y}-X\mathbf{w}\rVert^2 + \frac{1}{2\tau^2}\lVert\mathbf{w}\rVert^2 + \text{const}\). Multiply by \(2\sigma^2\): \(\lVert\mathbf{y}-X\mathbf{w}\rVert^2 + \frac{\sigma^2}{\tau^2}\lVert\mathbf{w}\rVert^2\), so \(\lambda = \sigma^2/\tau^2\): noisier data or a tighter prior means more shrinkage.
Why does bagging reduce variance but not bias? When does it fail to help?
The average of \(B\) predictors has the same expectation as one (same bias) but variance \(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\), where \(\rho\) is the correlation between members. It helps most for high-variance, low-bias learners (deep trees) and barely at all for stable ones (linear regression, where bootstrap fits are highly correlated), or when \(\rho\) is close to 1.
Hard: explain the double-descent peak at \(p = n\) in terms of the smallest singular value of the design matrix.
The interpolating solution's variance scales with \(\sum_j 1/d_j^2\) over the non-zero singular values. For a random \(n\times p\) design, the smallest singular value is near zero when \(p\approx n\) (square random matrices are nearly singular) and grows away from zero as \(p\) moves away from \(n\) in either direction. Below \(n\), least squares is unique and gets better-conditioned as \(p\) falls; above \(n\), the min-norm solution sees \(n\) singular values that grow with \(p\) (the \(n\times n\) Gram matrix \(XX^\top\) is a sum of more and more independent terms). So noise amplification peaks at \(p = n\); any ridge penalty caps it at \(1/\lambda\).
Go deeper¶
Papers
- Neural Networks and the Bias/Variance Dilemma — Geman, Bienenstock and Doursat, Neural Computation, 1992. The paper that brought the decomposition into machine learning; sections 2–3.
- Ridge Regression: Biased Estimation for Nonorthogonal Problems — Hoerl and Kennard, 1970. The existence theorem: some \(\lambda > 0\) always beats OLS in MSE.
- Regression Shrinkage and Selection via the Lasso — Tibshirani, 1996. The lasso, its geometry and the diamond picture.
- Regularization and Variable Selection via the Elastic Net — Zou and Hastie, 2005. Why lasso struggles with correlated groups and the fix.
- Understanding Deep Learning Requires Rethinking Generalization — Zhang, Bengio, Hardt, Recht and Vinyals, 2016. Networks fit random labels; read the randomisation tests.
- Reconciling modern machine-learning practice and the classical bias–variance trade-off — Belkin, Hsu, Ma and Mandal, PNAS, 2019 (arXiv). The double-descent curve and its proposed mechanism.
- Deep Double Descent: Where Bigger Models and More Data Hurt — Nakkiran et al., 2019. Model-wise, epoch-wise and sample-wise double descent in real networks.
- Surprises in High-Dimensional Ridgeless Least Squares Interpolation — Hastie, Montanari, Rosset and Tibshirani, 2019. Exact asymptotics for the setting of snippet 2.
Videos and lectures
- Lecture 08: Bias-Variance Tradeoff and Lecture 12: Regularization — Yaser Abu-Mostafa, Caltech. The cleanest lecture treatment, with learning curves.
- Bias and Variance, Ridge and Lasso — StatQuest. Short visual intuitions for each idea.
Articles and blog posts
- The Bias Variance Tradeoff and Double Descent — Amazon MLU-Explain. Interactive explainers for both acts of the story.
- Lecture 12: Bias Variance Tradeoff — Kilian Weinberger, Cornell. The decomposition derived carefully, with the diagnosis recipe.
Courses and books
- The Elements of Statistical Learning — Hastie, Tibshirani and Friedman. Section 3.4 (shrinkage) and chapter 7 (model assessment, effective degrees of freedom).
- Statistical Learning with Sparsity — Hastie, Tibshirani and Wainwright (free PDF). Everything about the lasso and its descendants.
Code
- scikit-learn linear models —
Ridge,Lasso,ElasticNetand their CV variants, with the coordinate-descent solver.
Where this leads¶
- Metrics, validation and leakage — how to measure test error honestly and pick \(\lambda\) without fooling yourself.
- Decision trees, random forests and boosting — bagging as variance reduction and boosting as bias reduction, in practice.
- Learning theory: PAC, VC and double descent — formal bounds on the estimation error, and their modern revisions.
- Regularisation in deep learning — weight decay, dropout and augmentation at scale.
- MLE, MAP and Bayes — the probabilistic reading of every penalty on this page.