Skip to content
LeetQuant
QR04 Regression and Numerical Optimisation

QR04 · Regression and Numerical Optimisation · Lesson 4 of 6

Ridge and Lasso

Closed-form ridge and its SVD shrinkage, why the lasso produces exact zeros (soft-thresholding), coordinate descent, choosing the penalty by cross-validation, and the elastic net.

20 min

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 12\tfrac12 in front of the residual sum of squares,

ridge: 12∥y−Xβ∥22+λ2∥β∥22,lasso: 12∥y−Xβ∥22+λ∥β∥1.\text{ridge: } \tfrac12\|y - X\beta\|_2^2 + \tfrac\lambda2\|\beta\|_2^2, \qquad \text{lasso: } \tfrac12\|y - X\beta\|_2^2 + \lambda\|\beta\|_1 .

Libraries scale differently (scikit-learn divides the residual term by nn), so a λ\lambda 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 yy 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 −X⊤(y−Xβ)+λβ-X^\top(y - X\beta) + \lambda\beta to zero gives

β^ridge=(X⊤X+λI)−1X⊤y.\hat\beta_{\text{ridge}} = (X^\top X + \lambda I)^{-1}X^\top y .

For λ>0\lambda > 0 the matrix X⊤X+λIX^\top X + \lambda I is positive definite, so ridge exists even when XX is rank-deficient or p>np > n. That was its original purpose: a fix for near-singular X⊤XX^\top X.

What it shrinks. Take the thin SVD X=UDV⊤X = UDV^\top with singular values djd_j. Then

β^ridge=∑jvj djdj2+λ uj⊤y,Xβ^ridge=∑juj dj2dj2+λ uj⊤y.\hat\beta_{\text{ridge}} = \sum_j v_j\,\frac{d_j}{d_j^2 + \lambda}\,u_j^\top y, \qquad X\hat\beta_{\text{ridge}} = \sum_j u_j\,\frac{d_j^2}{d_j^2 + \lambda}\,u_j^\top y .

OLS has 1/dj1/d_j in place of dj/(dj2+λ)d_j/(d_j^2 + \lambda). So ridge multiplies the OLS component along each principal direction by dj2/(dj2+λ)d_j^2/(d_j^2 + \lambda): directions with large djd_j (high-variance combinations of regressors, well determined by the data) are barely touched, while directions with small djd_j (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 ∑jdj2/(dj2+λ)\sum_j d_j^2/(d_j^2 + \lambda) runs from pp at λ=0\lambda = 0 down to 0.

Two readings. Ridge is the posterior mode (and mean) under a Gaussian prior β∼N(0,(σ2/λ)I)\beta \sim N(0, (\sigma^2/\lambda)I): the same shrinkage as the "shrink a noisy alpha towards zero" calculation, applied to all coefficients at once. And there is always some λ>0\lambda > 0 whose mean squared error is below OLS's (Hoerl and Kennard), because the bias enters at order λ2\lambda^2 while the variance falls at order λ\lambda.

Worked example

ridge with two correlated regressors

Two standardised regressors have X⊤X=(10.90.91)X^\top X = \begin{pmatrix} 1 & 0.9 \\ 0.9 & 1 \end{pmatrix} and X⊤y=(0.95,0.85)⊤X^\top y = (0.95, 0.85)^\top. Compute OLS and ridge with λ=0.1\lambda = 0.1, explain the change in the eigenbasis, and compare coefficient variances (errors with variance σ2\sigma^2, uncorrelated).

Show solution

OLS. det⁡=1−0.81=0.19\det = 1 - 0.81 = 0.19, so

β^OLS=10.19(1−0.9−0.91)(0.950.85)=10.19(0.185−0.005)≈(0.974−0.026).\hat\beta_{\text{OLS}} = \frac{1}{0.19}\begin{pmatrix} 1 & -0.9 \\ -0.9 & 1 \end{pmatrix}\begin{pmatrix} 0.95 \\ 0.85 \end{pmatrix} = \frac{1}{0.19}\begin{pmatrix} 0.185 \\ -0.005 \end{pmatrix} \approx \begin{pmatrix} 0.974 \\ -0.026 \end{pmatrix} .

Ridge. X⊤X+0.1IX^\top X + 0.1I has diagonal 1.1 and determinant 1.21−0.81=0.401.21 - 0.81 = 0.40:

β^ridge=10.40(1.1−0.9−0.91.1)(0.950.85)=10.40(0.280.08)=(0.700.20).\hat\beta_{\text{ridge}} = \frac{1}{0.40}\begin{pmatrix} 1.1 & -0.9 \\ -0.9 & 1.1 \end{pmatrix}\begin{pmatrix} 0.95 \\ 0.85 \end{pmatrix} = \frac{1}{0.40}\begin{pmatrix} 0.28 \\ 0.08 \end{pmatrix} = \begin{pmatrix} 0.70 \\ 0.20 \end{pmatrix} .

Eigenbasis. X⊤XX^\top X has eigenvalues d2=1.9d^2 = 1.9 along (1,1)/2(1, 1)/\sqrt2 (the sum of the regressors) and 0.10.1 along (1,−1)/2(1, -1)/\sqrt2 (their difference). The shrinkage factors are 1.9/2.0=0.951.9/2.0 = 0.95 and 0.1/0.2=0.50.1/0.2 = 0.5. OLS has coordinates 0.947/20.947/\sqrt2 on the sum and 1.000/21.000/\sqrt2 on the difference; ridge keeps 95% of the first and 50% of the second, giving 0.9/20.9/\sqrt2 and 0.5/20.5/\sqrt2, which map back to 0.92(1,1)+0.52(1,−1)=(0.70,0.20)\tfrac{0.9}{2}(1, 1) + \tfrac{0.5}{2}(1, -1) = (0.70, 0.20).

Variance. Along each direction OLS has variance σ2/d2\sigma^2/d^2 and ridge σ2d2/(d2+λ)2\sigma^2 d^2/(d^2 + \lambda)^2:

Directiond2d^2OLS varianceRidge variance
sum1.90.526σ20.526\sigma^20.475σ20.475\sigma^2
difference0.110σ210\sigma^22.5σ22.5\sigma^2

Each coefficient's variance falls from 5.26σ25.26\sigma^2 (the VIF of 1/(1−0.81)1/(1 - 0.81)) to 1.49σ21.49\sigma^2. The price is bias in the poorly identified difference direction, which is exactly where OLS was guessing.

Lasso: why exact zeros

The ℓ1\ell_1 penalty λ∑j∣βj∣\lambda\sum_j|\beta_j| has a kink at zero. Its subgradient there is the whole interval [−λ,λ][-\lambda, \lambda], so a coefficient can sit at exactly zero whenever the pull of the data on it is weaker than λ\lambda. The ridge penalty's derivative λβj\lambda\beta_j vanishes at zero, so ridge never zeroes anything. Geometrically, the ℓ1\ell_1 ball is a diamond whose corners lie on the axes, and the RSS ellipses usually first touch it at a corner.

Orthonormal case (X⊤X=IX^\top X = I). Then β^OLS=X⊤y\hat\beta_{\text{OLS}} = X^\top y and the objective separates into 12(βj−bj)2+λ∣βj∣\tfrac12(\beta_j - b_j)^2 + \lambda|\beta_j| per coordinate, with bjb_j the OLS estimate. The optimality condition βj−bj+λsj=0\beta_j - b_j + \lambda s_j = 0, with sj=sign⁡(βj)s_j = \operatorname{sign}(\beta_j) if βj≠0\beta_j \ne 0 and sj∈[−1,1]s_j \in [-1, 1] otherwise, gives soft-thresholding:

β^jlasso=Sλ(bj)=sign⁡(bj) (∣bj∣−λ)+.\hat\beta_j^{\text{lasso}} = S_\lambda(b_j) = \operatorname{sign}(b_j)\,(|b_j| - \lambda)_+ .

Compare ridge, bj/(1+λ)b_j/(1 + \lambda) (proportional shrinkage), and best-subset selection, which hard-thresholds (keeps bjb_j unchanged if ∣bj∣|b_j| exceeds a cut-off, else 0). Lasso both selects and shrinks: surviving coefficients are pulled towards zero by λ\lambda, which biases large effects. A common fix is the relaxed lasso: use the lasso to choose variables, then refit OLS on them.

General XX. 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 λ\lambda down, warm-starting each fit from the last. Above λmax⁡=max⁡j∣xj⊤y∣\lambda_{\max} = \max_j |x_j^\top y| every coefficient is zero.

Behaviour to know:

  • With p>np > n, the lasso selects at most nn 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 pp-values invalid; the selection already used the data.

Worked example

ridge, lasso and elastic net in the orthonormal case

With orthonormal regressors, OLS gives b=(3.0,−1.2,0.4,0.1)b = (3.0, -1.2, 0.4, 0.1). Compute ridge and lasso with λ=0.5\lambda = 0.5, and the elastic net 12∥y−Xβ∥2+λ1∥β∥1+λ22∥β∥22\tfrac12\|y - X\beta\|^2 + \lambda_1\|\beta\|_1 + \tfrac{\lambda_2}{2}\|\beta\|_2^2 with λ1=λ2=0.5\lambda_1 = \lambda_2 = 0.5.

Show solution

Ridge: divide by 1+λ=1.51 + \lambda = 1.5: (2.000,−0.800,0.267,0.067)(2.000, -0.800, 0.267, 0.067). Everything shrinks by a third; nothing reaches zero.

Lasso: subtract 0.5 from each absolute value, flooring at zero: (2.5,−0.7,0,0)(2.5, -0.7, 0, 0). The two small coefficients are eliminated and the large ones move by the same absolute amount.

Elastic net: per coordinate the objective is 12(β−b)2+λ1∣β∣+λ22β2\tfrac12(\beta - b)^2 + \lambda_1|\beta| + \tfrac{\lambda_2}{2}\beta^2, minimised by soft-thresholding and then proportional shrinkage, Sλ1(b)/(1+λ2)S_{\lambda_1}(b)/(1 + \lambda_2): (2.5,−0.7,0,0)/1.5=(1.667,−0.467,0,0)(2.5, -0.7, 0, 0)/1.5 = (1.667, -0.467, 0, 0).

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 λ=0\lambda = 0 this is OLS. The weakest coefficient goes first, then the second; here X⊤y=(13,10,3)X^\top y = (13, 10, 3), so λmax⁡=13\lambda_{\max} = 13 and at λ=12\lambda = 12 only the first survives, at (13−12)/4=0.25(13 - 12)/4 = 0.25. The values match scikit-learn's Lasso with alpha = lam / 6 (its objective divides the residual term by n=6n = 6).

Choosing λ

λ\lambda is a hyperparameter: in-sample fit always prefers λ=0\lambda = 0. Choose it by cross-validation:

  1. Fix a log-spaced grid from λmax⁡\lambda_{\max} down to about 10−3λmax⁡10^{-3}\lambda_{\max}.
  2. Split the data into KK 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.
  3. Average across folds to get a CV error curve and its standard error at each λ\lambda.
  4. Take the minimiser, or, by the one-standard-error rule, the largest λ\lambda 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 b/(1+λ)b/(1 + \lambda), lasso is sign⁡(b)(∣b∣−λ)+\operatorname{sign}(b)(|b| - \lambda)_+, and the reason is the kink of ∣β∣|\beta| 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 λ\lambda on time-series data.

Knowledge check

With orthonormal regressors, an OLS coefficient is b=1.2b = 1.2. Using the objective 12∥y−Xβ∥2+λ∥β∥1\tfrac12\|y - X\beta\|^2 + \lambda\|\beta\|_1 with λ=0.5\lambda = 0.5, 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: β^=(X⊤X+λI)−1X⊤y\hat\beta = (X^\top X + \lambda I)^{-1}X^\top y always exists, and multiplies each principal component of the OLS fit by dj2/(dj2+λ)d_j^2/(d_j^2 + \lambda), shrinking poorly identified directions the most. It is the Gaussian-prior posterior.
  • Lasso: in the orthonormal case sign⁡(b)(∣b∣−λ)+\operatorname{sign}(b)(|b| - \lambda)_+. 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 1+λ21 + \lambda_2 (orthonormal case); keeps correlated groups together.
  • Standardise, leave the intercept unpenalised, and choose λ\lambda 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).