Buying variance with bias
OLS is unbiased, and when regressors are many, noisy or correlated, its variance is huge: coefficients swing between samples and predict badly out of sample. Penalised regression pulls coefficients towards zero. That adds bias but can cut variance by much more, lowering mean squared error. The earlier bias–variance lesson introduced the idea; this one works through the mechanics.
The objective: derive ridge in closed form and see what it shrinks, understand why the lasso sets coefficients exactly to zero, compute both in the orthonormal case, and choose the penalty properly.
Convention for this lesson: both objectives put in front of the residual sum of squares,
Libraries scale differently (scikit-learn divides the residual term by ), so a from one source is not directly comparable with another. Two rules hold for both methods: standardise the regressors first (the penalty is not scale-invariant), and do not penalise the intercept (centre and the regressors, or leave the intercept out of the penalty).
Ridge: closed form and SVD shrinkage
The ridge objective is a strictly convex quadratic. Setting its gradient to zero gives
For the matrix is positive definite, so ridge exists even when is rank-deficient or . That was its original purpose: a fix for near-singular .
What it shrinks. Take the thin SVD with singular values . Then
OLS has in place of . So ridge multiplies the OLS component along each principal direction by : directions with large (high-variance combinations of regressors, well determined by the data) are barely touched, while directions with small (where OLS divides by almost zero) are shrunk hard. Principal-components regression keeps or drops directions outright; ridge shrinks smoothly.
The effective degrees of freedom runs from at down to 0.
Two readings. Ridge is the posterior mode (and mean) under a Gaussian prior : the same shrinkage as the "shrink a noisy alpha towards zero" calculation, applied to all coefficients at once. And there is always some whose mean squared error is below OLS's (Hoerl and Kennard), because the bias enters at order while the variance falls at order .
Worked example
ridge with two correlated regressors
Two standardised regressors have and . Compute OLS and ridge with , explain the change in the eigenbasis, and compare coefficient variances (errors with variance , uncorrelated).
Show solutionHide solution
OLS. , so
Ridge. has diagonal 1.1 and determinant :
Eigenbasis. has eigenvalues along (the sum of the regressors) and along (their difference). The shrinkage factors are and . OLS has coordinates on the sum and on the difference; ridge keeps 95% of the first and 50% of the second, giving and , which map back to .
Variance. Along each direction OLS has variance and ridge :
| Direction | OLS variance | Ridge variance | |
|---|---|---|---|
| sum | 1.9 | ||
| difference | 0.1 |
Each coefficient's variance falls from (the VIF of ) to . The price is bias in the poorly identified difference direction, which is exactly where OLS was guessing.
Lasso: why exact zeros
The penalty has a kink at zero. Its subgradient there is the whole interval , so a coefficient can sit at exactly zero whenever the pull of the data on it is weaker than . The ridge penalty's derivative vanishes at zero, so ridge never zeroes anything. Geometrically, the ball is a diamond whose corners lie on the axes, and the RSS ellipses usually first touch it at a corner.
Orthonormal case (). Then and the objective separates into per coordinate, with the OLS estimate. The optimality condition , with if and otherwise, gives soft-thresholding:
Compare ridge, (proportional shrinkage), and best-subset selection, which hard-thresholds (keeps unchanged if exceeds a cut-off, else 0). Lasso both selects and shrinks: surviving coefficients are pulled towards zero by , which biases large effects. A common fix is the relaxed lasso: use the lasso to choose variables, then refit OLS on them.
General . No closed form, but the problem is convex. Coordinate descent cycles through coordinates, soft-thresholding each against the partial residual; it is what glmnet and scikit-learn use. The whole path is cheap to compute from large down, warm-starting each fit from the last. Above every coefficient is zero.
Behaviour to know:
- With , the lasso selects at most variables (when the solution is unique).
- Among a group of highly correlated regressors it tends to pick one, somewhat arbitrarily, and the pick changes between samples. Do not read the selected set as "the true drivers".
- Variable selection makes naive post-lasso -values invalid; the selection already used the data.
Worked example
ridge, lasso and elastic net in the orthonormal case
With orthonormal regressors, OLS gives . Compute ridge and lasso with , and the elastic net with .
Show solutionHide solution
Ridge: divide by : . Everything shrinks by a third; nothing reaches zero.
Lasso: subtract 0.5 from each absolute value, flooring at zero: . The two small coefficients are eliminated and the large ones move by the same absolute amount.
Elastic net: per coordinate the objective is , minimised by soft-thresholding and then proportional shrinkage, : .
Read across: ridge keeps every variable, lasso selects, elastic net selects and shrinks further. In general (non-orthonormal) designs the elastic net's ridge part also makes it keep correlated regressors together, sharing the coefficient, instead of choosing one.
Coordinate descent in a few lines
import math
def soft(z, t):
return math.copysign(max(abs(z) - t, 0.0), z)
def lasso_cd(X, y, lam, sweeps=200):
"""Minimise 0.5*||y - Xb||^2 + lam*||b||_1 by coordinate descent."""
n, p = len(X), len(X[0])
b = [0.0] * p
r = list(y) # residual y - Xb
sq = [sum(X[i][j] ** 2 for i in range(n)) for j in range(p)]
for _ in range(sweeps):
for j in range(p):
# correlation of column j with the partial residual (b_j left out)
z = sum(X[i][j] * (r[i] + X[i][j] * b[j]) for i in range(n))
new = soft(z, lam) / sq[j]
for i in range(n):
r[i] -= X[i][j] * (new - b[j])
b[j] = new
return b
X = [[1, 0, 1], [0, 1, 1], [1, 1, 0], [-1, 0, 1], [0, -1, -1], [-1, -1, 0]]
y = [3, 1, 4, -2, -1, -4]
for lam in [0.0, 1.0, 3.0, 12.0]:
print(lam, [round(v, 4) for v in lasso_cd(X, y, lam)])
0.0 [2.75, 1.0, 0.25]
1.0 [2.5, 1.0, 0.0]
3.0 [2.1667, 0.6667, 0.0]
12.0 [0.25, 0.0, 0.0]
At this is OLS. The weakest coefficient goes first, then the second; here , so and at only the first survives, at . The values match scikit-learn's Lasso with alpha = lam / 6 (its objective divides the residual term by ).
Choosing λ
is a hyperparameter: in-sample fit always prefers . Choose it by cross-validation:
- Fix a log-spaced grid from down to about .
- Split the data into folds (5 or 10). For each fold, fit the whole path on the other folds and record the prediction error on the held-out fold.
- Average across folds to get a CV error curve and its standard error at each .
- Take the minimiser, or, by the one-standard-error rule, the largest whose CV error is within one standard error of the minimum: a simpler model that is statistically indistinguishable.
Pitfalls: standardise using the training fold's means and standard deviations only, or the held-out fold leaks into the fit; any variable screening must be redone inside each fold; and with time series, random folds leak the future, so use walk-forward or purged folds as in the bias–variance lesson. Information criteria (AIC, BIC using the effective degrees of freedom) are cheaper alternatives.
Which method? Many small effects, correlated regressors, prediction the goal: ridge. A few real effects among many candidates, interpretability wanted: lasso. Groups of correlated candidates where you still want sparsity: elastic net.
Interview angle
"Why does the lasso give zeros and ridge doesn't?" Answer with the orthonormal case: ridge is , lasso is , and the reason is the kink of at zero (or the corners of the diamond). Follow-ups to expect: why standardise, why not penalise the intercept, what happens with two identical regressors (ridge splits the coefficient equally; lasso's solution is not unique: any same-signed split with the same total is optimal), and how you would choose on time-series data.
Knowledge check
With orthonormal regressors, an OLS coefficient is . Using the objective with , what is the lasso coefficient?
Knowledge check
Along which directions does ridge regression shrink the OLS fit the most?
Knowledge check
Before running the lasso without standardising, you change one regressor's units from thousands of dollars to dollars (its values become 1,000 times larger). What happens to that regressor?
Key takeaways
- Ridge: always exists, and multiplies each principal component of the OLS fit by , shrinking poorly identified directions the most. It is the Gaussian-prior posterior.
- Lasso: in the orthonormal case . The kink at zero gives exact zeros; it selects and shrinks, and picks arbitrarily among correlated regressors. Fit it by coordinate descent along a path.
- Elastic net: soft-threshold then divide by (orthonormal case); keeps correlated groups together.
- Standardise, leave the intercept unpenalised, and choose by cross-validation done properly (fold-internal scaling, time-aware folds, one-standard-error rule).
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).