Module contents
Lesson 4 of 24Core 80 min

L2 regularization: ridge regression

Introduces regularization as explicit complexity control through a penalty on parameter norm. Derives the closed-form ridge solution, interprets it via the SVD as a filter shrinking low-variance directions, defines effective degrees of freedom, and connects it to a Gaussian prior (MAP estimation). Ends with closed-form leave-one-out cross-validation for choosing λ without retraining.

After this lesson you can

  • Derive the ridge solution and prove it exists and is unique for every λ > 0.
  • Express ridge using the SVD and explain each component's shrinkage factor d_j²/(d_j² + λ).
  • Calculate effective degrees of freedom df(λ) = tr(H_λ) and use them to compare models.
  • Interpret ridge as MAP estimation with a Gaussian prior and as least squares on augmented data.
  • Choose λ using closed-form LOOCV and generalized cross-validation.

Before you start

Motivation: exploding coefficients

In the previous lesson, a high-degree polynomial fitted to 15 points passed through them all and oscillated between them with enormous coefficients. Reducing degree fixed the problem, but degree is a coarse control: it takes only integer values, each step adds a whole column, and it does not transfer to non-polynomial models. This lesson introduces the other control, used throughout modern machine learning: keep all columns and charge for coefficient size.

The problem appears whenever some direction in parameter space is poorly determined by data. With X=UDV⊤\mat{X} = \mat{U}\mat{D}\mat{V}\T the singular value decomposition of the design matrix, of rank pp, and uncorrelated noise of variance σ2\sigma^2, the covariance of the ordinary least squares estimator (OLS) is

Cov⁡(β^MCO)=σ2(X⊤X)−1=σ2∑j=1pvjvj⊤dj2.\Cov(\hat{\vb{\beta}}_{\text{MCO}}) = \sigma^2(\mat{X}\T\mat{X})\inv = \sigma^2\sum_{j=1}^p \frac{\vb{v}_j\vb{v}_j\T}{d_j^2}.

The component of β^\hat{\vb{\beta}} along vj\vb{v}_j has variance σ2/dj2\sigma^2/d_j^2. Three situations make some djd_j small:

  • Collinearity. Two nearly proportional variables, such as total and LDL cholesterol in the diabetes data we will use (correlation 0.8970.897), leave almost no information about the difference in their effects.
  • pp close to nn. As the number of columns approaches the number of rows, the smallest singular value approaches zero (for a random n×pn\times p matrix with independent variance-1 entries and fixed p/np/n, dmin⁡/n→1−p/nd_{\min}/\sqrt n \to 1 - \sqrt{p/n}), and with p>np > n the null space of X\mat{X} has dimension at least p−np - n: infinitely many solutions.
  • Ill-conditioned bases. Powers x,x2,…,x15x, x^2, \dots, x^{15} on [0,1][0, 1] are nearly dependent: with 15 equally spaced points, the singular values of that already standardized and centered matrix fall from 1414 to 2×10−102\times 10^{-10} (and the last is exactly zero).

A cell shows the symptom. Two variables have correlation 0.980.98, n=30n = 30, true coefficients β=(1,1)\vb{\beta} = (1, 1), and noise σ=1\sigma = 1; the experiment is repeated 4,000 times with the same design and fresh noise.

[ ]Two almost identical variablesBrowser
import numpy as np

rng = np.random.default_rng(1)
n, rho, sigma, R = 30, 0.98, 1.0, 4000
Xraw = rng.normal(size=(n, 2)) @ np.linalg.cholesky([[1, rho], [rho, 1]]).T
X = (Xraw - Xraw.mean(0)) / Xraw.std(0)          # diseño fijo, estandarizado
G = X.T @ X
print(f"correlación muestral = {np.corrcoef(X.T)[0, 1]:.3f}   autovalores de XᵀX = {np.round(np.linalg.eigvalsh(G)[::-1], 2)}")

beta = np.array([1.0, 1.0])
Y = X @ beta + sigma * rng.normal(size=(R, n))   # R réplicas: una por fila
lam = 10.0
B_mco = np.linalg.solve(G, X.T @ Y.T).T
B_rid = np.linalg.solve(G + lam * np.eye(2), X.T @ Y.T).T
for nombre, B in [("MCO", B_mco), (f"ridge λ={lam:g}", B_rid)]:
    print(f"{nombre:12s} media = {np.round(B.mean(0), 3)}  desv. típica = {np.round(B.std(0), 3)}  "
          f"sd(b1+b2) = {(B[:, 0] + B[:, 1]).std():.3f}  sd(b1-b2) = {(B[:, 0] - B[:, 1]).std():.3f}  "
          f"P(b1 < 0) = {np.mean(B[:, 0] < 0):.3f}  E‖b-β‖² = {np.mean(((B - beta) ** 2).sum(1)):.3f}")
print("teórica MCO: sd(b_j) =", np.round(sigma * np.sqrt(np.diag(np.linalg.inv(G))), 3))

Least squares is unbiased (means 0.9890.989 and 1.0091.009), but each coefficient has standard deviation 1.031.03, equal to its value: in 16.5% of repetitions β^1\hat\beta_1 is negative. The output shows the problem: the sum β^1+β^2\hat\beta_1 + \hat\beta_2 is well estimated (deviation 0.180.18), the difference terribly (2.052.05). This is direction (1,−1)(1, -1), with eigenvalue 0.490.49 versus 59.559.5. With the penalty we will study and λ=10\lambda = 10, coefficients have 15% bias toward zero (0.8550.855 instead of 1), but their standard deviation falls to 0.090.09 and total squared error E∥β^−β∥2\E\norm{\hat{\vb{\beta}} - \vb{\beta}}^2 drops from 2.112.11 to 0.0580.058: 36 times less. Trading a little bias for much less variance is the whole idea.

Ridge: penalized and constrained forms

We use standardized variables (training mean 0 and standard deviation 1) and an intercept that is not penalized. Below, X∈Rn×p\mat{X} \in \R^{n\times p} is the already centered data matrix without a column of ones, and y\vb{y} is centered; the intercept is then yˉ\bar y (justified below).

The formula follows by setting the gradient to zero, −2X⊤(y−Xβ)+2λβ=0-2\mat{X}\T(\vb{y} - \mat{X}\vb{\beta}) + 2\lambda\vb{\beta} = \vb{0}. Showing the matrix is invertible and that this critical point is the global minimum for any nn, pp, and rank is the first guided exercise: the key is v⊤(X⊤X+λI)v=∥Xv∥2+λ∥v∥2≥λ∥v∥2\vb{v}\T(\mat{X}\T\mat{X} + \lambda\mat{I})\vb{v} = \norm{\mat{X}\vb{v}}^2 + \lambda\norm{\vb{v}}^2 \ge \lambda\norm{\vb{v}}^2. Hoerl and Kennard proposed the method for precisely the “non-orthogonal” problems in the motivation: adding λ\lambda to the diagonal of X⊤X\mat{X}\T\mat{X} moves it away from singularity.

The constrained form

Penalizing size is equivalent to limiting it. Let β^+=X+y\hat{\vb{\beta}}^+ = \mat{X}\pinv\vb{y} be the minimum-norm least-squares solution.

Proof

With reduced SVD X=∑j=1rdjujvj⊤\mat{X} = \sum_{j=1}^r d_j\vb{u}_j\vb{v}_j\T and cj=uj⊤yc_j = \vb{u}_j\T\vb{y}, the spectral formula in the next section gives ∥β^λ∥2=∑jdj2cj2/(dj2+λ)2\norm{\hat{\vb{\beta}}_\lambda}^2 = \sum_j d_j^2c_j^2/(d_j^2 + \lambda)^2. Since X⊤y=∑jdjcjvj≠0\mat{X}\T\vb{y} = \sum_j d_jc_j\vb{v}_j \neq \vb{0}, some cjc_j is nonzero and every term is continuous and decreasing in λ\lambda, strictly so for that jj. As λ→0+\lambda \to 0^+ the sum tends to ∑jcj2/dj2=∥β^+∥2\sum_j c_j^2/d_j^2 = \norm{\hat{\vb{\beta}}^+}^2, and as λ→∞\lambda \to \infty, to 0. By the intermediate value theorem, for every tt in the interval there is a unique λt\lambda_t with ∥β^λt∥=t\norm{\hat{\vb{\beta}}_{\lambda_t}} = t.

The constrained problem is convex and β=0\vb{\beta} = \vb{0} is strictly feasible, so the Karush–Kuhn–Tucker conditions are necessary and sufficient (the inequality version of Lagrange multipliers). With Lagrangian ∥y−Xβ∥2+μ(∥β∥2−t2)\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \mu(\norm{\vb{\beta}}^2 - t^2), they require X⊤Xβ+μβ=X⊤y\mat{X}\T\mat{X}\vb{\beta} + \mu\vb{\beta} = \mat{X}\T\vb{y}, μ≥0\mu \ge 0 and μ(∥β∥2−t2)=0\mu(\norm{\vb{\beta}}^2 - t^2) = 0. If μ=0\mu = 0, β\vb{\beta} would be a least-squares solution with norm ≤t<∥β^+∥\le t < \norm{\hat{\vb{\beta}}^+}, impossible because β^+\hat{\vb{\beta}}^+ has minimum norm. Thus μ>0\mu > 0, β=β^μ\vb{\beta} = \hat{\vb{\beta}}_\mu and ∥β^μ∥=t\norm{\hat{\vb{\beta}}_\mu} = t, namely μ=λt\mu = \lambda_t. This point satisfies the conditions, so it is a solution, and the only one because any other would also have to satisfy them.

∎

If t≥∥β^+∥t \ge \norm{\hat{\vb{\beta}}^+}, the constraint is inactive and the problem returns least squares. The constrained form gives a geometric picture: contours of ∥y−Xβ∥2\norm{\vb{y} - \mat{X}\vb{\beta}}^2 are ellipses centered on β^MCO\hat{\vb{\beta}}_{\text{MCO}}, the constraint is a ball, and the solution is the point where the first ellipse touches the ball.

InteractiveLoss contours and the L2 ball
  • loss contour tangent to the disk
  • disk ∥β∥≤t\norm{\vb{\beta}} \le t
  • ridge path as λ\lambda varies
  • well-determined axis (eigenvalue 1+∣ρ∣1 + \abs{\rho})
  • poorly determined axis (eigenvalue 1−∣ρ∣1 - \abs{\rho})
1.11 (50 % of OLS)
0.80
λ\lambda yielding that radius (per observation)1.116
β^λ\hat{\vb{\beta}}_\lambda(0.92, 0.63)
Factor in the well-determined direction62 %
Factor in the poorly determined direction15 %
Increase in training MSE1.083
Eigenvalues of R\mat{R}1.80 and 0.20
The poorly determined component (aqua) retains 15 % and the well-determined one (orange), 62 %: ridge shrinks most where the data are least informative.
Two standardized variables with correlation ρ\rho: ellipses are mean-squared-error contours centered at β^MCO\hat{\vb{\beta}}_{\text{MCO}}, with axes along eigenvectors of correlation matrix R\mat{R}; the disk is ∥β∥≤t\norm{\vb{\beta}} \le t. The ridge solution (magenta) is the tangency point, and the dashed curve is its complete path as λ\lambda varies. Reduce tt and read both factors: which component of β^MCO\hat{\vb{\beta}}_{\text{MCO}} shrinks first? Set ρ=0\rho = 0 and compare the path. Then move ρ\rho to 0.950.95 and drag β^MCO\hat{\vb{\beta}}_{\text{MCO}} along the aqua axis.

The figure uses the simplest model showing the phenomenon: X⊤X/n=R=[1ρρ1]\mat{X}\T\mat{X}/n = \mat{R} = \begin{bmatrix} 1 & \rho \\ \rho & 1 \end{bmatrix}, with eigenvalues 1±∣ρ∣1 \pm \abs{\rho} and λ\lambda measured per observation. Initially (ρ=0.8\rho = 0.8, tt halfway), the component of β^MCO\hat{\vb{\beta}}_{\text{MCO}} on the poorly determined axis retains 15%, and that on the well-determined axis 62%. Without correlation the ellipses are circles, both factors coincide, and the path is a straight segment to the origin: ridge only shrinks proportionally. With positive correlation, the path first falls almost parallel to the aqua axis toward diagonal β1=β2\beta_1 = \beta_2 (the well-determined direction through the origin) and only then follows it down toward 0\vb{0}. This is the previous cell’s geometry: the difference β1−β2\beta_1 - \beta_2, barely constrained by data, is sacrificed first.

Why the intercept is not penalized

If you penalized bb, adding a constant cc to every response would not shift predictions by cc: the fit would depend on the origin used to measure yy (Celsius and Kelvin would give different curves). Without penalizing bb, for each fixed β\vb{\beta} the best bb is the mean of yi−xi⊤βy_i - \vb{x}_i\T\vb{\beta}, and substituting it is exactly the centering theorem from linear regression: ridge without an intercept on centered data remains, with b^=yˉ−xˉ⊤β^λ\hat b = \bar y - \bar{\vb{x}}\T\hat{\vb{\beta}}_\lambda. This is what scikit-learn’s Ridge does with fit_intercept=True.

Why standardization is needed

Least squares is scale-equivariant: multiplying column jj by c≠0c \neq 0 divides its coefficient by cc without changing predictions. Ridge is not, because the penalty measures βj\beta_j in the variable’s units: the same effect on yy costs λβj2\lambda\beta_j^2 in one unit and something different in another. Standardization puts all variables on the same scale before charging, so λ∥β∥2\lambda\norm{\vb{\beta}}^2 penalizes effects per standard deviation, making them comparable. Coefficients in original units are recovered afterward with wj=w~j/sjw_j = \tilde w_j/s_j. The units exercise shows how the penalty becomes unbalanced otherwise.

The closed-form solution and its limits

Three consequences of the formula (X⊤X+λI)−1X⊤y(\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\vb{y} are worth keeping in mind.

Conditioning. Eigenvalues of X⊤X+λI\mat{X}\T\mat{X} + \lambda\mat{I} are dj2+λd_j^2 + \lambda (and λ\lambda in null-space directions), so its condition number is (d12+λ)/(dmin⁡2+λ)≤1+d12/λ(d_1^2 + \lambda)/(d_{\min}^2 + \lambda) \le 1 + d_1^2/\lambda. Ridge addresses both the statistical problem (variance) and numerical problem (nearly singular system). Even so, in practice X⊤X\mat{X}\T\mat{X} is not formed: use SVD or the augmented-data trick below with QR.

The limit λ→0+\lambda \to 0^+ is the minimum-norm solution, not an arbitrary least-squares solution: in the spectral formula, dj/(dj2+λ)→1/djd_j/(d_j^2 + \lambda) \to 1/d_j in directions with dj>0d_j > 0, and null-space directions never enter. When X\mat{X} lacks full rank, this determines which solution you obtain. The cell duplicates the s1 column of the diabetes data: rank remains 10 with 11 columns.

[ ]λ → 0 and a repeated columnBrowser
import numpy as np
from sklearn.datasets import load_diabetes

X, y = load_diabetes(return_X_y=True, scaled=False)
Z = (X - X.mean(0)) / X.std(0)
yc = y - y.mean()
Z2 = np.column_stack([Z, Z[:, 4]])          # s1 repetida
print("rango:", np.linalg.matrix_rank(Z2), "  columnas:", Z2.shape[1])
b_min = np.linalg.pinv(Z2) @ yc
print("norma mínima: s1 =", round(b_min[4], 3), "  copia =", round(b_min[10], 3))
for lam in [10.0, 1.0, 1e-2, 1e-4, 1e-6]:
    b = np.linalg.solve(Z2.T @ Z2 + lam * np.eye(11), Z2.T @ yc)
    print(f"λ = {lam:7.0e}: s1 = {b[4]:8.3f}  copia = {b[10]:8.3f}  ‖β_λ − X⁺y‖ = {np.linalg.norm(b - b_min):.1e}")
b_mco = np.linalg.lstsq(Z, yc, rcond=None)[0]
print("MCO sin la copia: s1 =", round(b_mco[4], 3), "  la mitad:", round(b_mco[4] / 2, 3))

For each λ\lambda, ridge divides the effect of s1 equally between both copies, and distance to X+y\mat{X}\pinv\vb{y} falls proportionally to λ\lambda: from 8.6×10−28.6\times 10^{-2} at λ=10−2\lambda = 10^{-2} to 8.6×10−68.6\times 10^{-6} at λ=10−6\lambda = 10^{-6}. Equal division is no accident: the problem is symmetric in the copies and has a unique solution, so that solution must be symmetric. Something similar happens with highly correlated but nonidentical variables, and ridge tends to give them similar coefficients (the “grouping effect”); lasso in the next lesson tends instead to keep one. This limit is also the starting point for the minimum-norm interpolator and double descent.

When p≫np \gg n, solve an n×nn \times n system. From X⊤(XX⊤+λI)=(X⊤X+λI)X⊤\mat{X}\T(\mat{X}\mat{X}\T + \lambda\mat{I}) = (\mat{X}\T\mat{X} + \lambda\mat{I})\mat{X}\T, multiplying by both inverses yields

β^λ=X⊤(XX⊤+λIn)−1y.\hat{\vb{\beta}}_\lambda = \mat{X}\T(\mat{X}\mat{X}\T + \lambda\mat{I}_n)\inv\vb{y}.

With p=105p = 10^5 variables and n=500n = 500 examples, the left-hand form inverts a 105×10510^5\times 10^5 matrix and the right-hand form a 500×500500\times 500 one. Moreover, β^λ\hat{\vb{\beta}}_\lambda is written as a combination of examples and predictions need only dot products x⊤xi\vb{x}\T\vb{x}_i: replacing them with a kernel gives kernel ridge regression.

Spectral view: a filter on principal components

Write the reduced SVD X=UDV⊤\mat{X} = \mat{U}\mat{D}\mat{V}\T, with U∈Rn×r\mat{U} \in \R^{n\times r} and V∈Rp×r\mat{V} \in \R^{p\times r} having orthonormal columns, D=diag⁡(d1,…,dr)\mat{D} = \diag(d_1, \dots, d_r), d1≥⋯≥dr>0d_1 \ge \dots \ge d_r > 0, and r=rank⁡Xr = \rank\mat{X}. In the same first guided exercise you will prove that

β^λ=Vdiag⁡(djdj2+λ)U⊤y=∑j=1rdjdj2+λ (uj⊤y) vj.\hat{\vb{\beta}}_\lambda = \mat{V}\diag\Big(\frac{d_j}{d_j^2 + \lambda}\Big)\mat{U}\T\vb{y} = \sum_{j=1}^r \frac{d_j}{d_j^2 + \lambda}\,(\vb{u}_j\T\vb{y})\,\vb{v}_j.

Predictions on training data are then

y^λ=Xβ^λ=∑j=1ruj dj2dj2+λ⏟fj(λ) uj⊤y=Hλy,Hλ=Udiag⁡(fj)U⊤.\hat{\vb{y}}_\lambda = \mat{X}\hat{\vb{\beta}}_\lambda = \sum_{j=1}^r \vb{u}_j\,\underbrace{\frac{d_j^2}{d_j^2 + \lambda}}_{f_j(\lambda)}\,\vb{u}_j\T\vb{y} = \mat{H}_\lambda\vb{y}, \qquad \mat{H}_\lambda = \mat{U}\diag(f_j)\mat{U}\T.

What are these directions? Because data are centered, zj=Xvj=djuj\vb{z}_j = \mat{X}\vb{v}_j = d_j\vb{u}_j is the data’s jjth principal component, with sample variance dj2/nd_j^2/n. The vj\vb{v}_j are axes of the ellipses in the previous figure, eigenvectors of X⊤X\mat{X}\T\mat{X} supplied by the spectral theorem. Ridge shrinks high-variance components little and low-variance ones strongly, with a soft cutoff at dj=λd_j = \sqrt{\lambda}, where fj=1/2f_j = 1/2 exactly.

Principal component regression (PCR) does the same with a hard cutoff: retain the first kk (fj=1f_j = 1) and discard the rest (fj=0f_j = 0). Ridge is the continuous version and does not require choosing an integer. Notice what does not appear in fjf_j: the response. Neither ridge nor PCR checks whether signal in y\vb{y} lies in high-variance components; both assume it does.

InteractiveShrinkage by singular value
Design-matrix singular values djd_j (log scale)
10⁻¹⁰10⁻⁸10⁻⁶10⁻⁴10⁻²10⁰10²0√λ123456789101112131415
Shrinkage factors fj=dj2/(dj2+λ)f_j = d_j^2/(d_j^2 + \lambda)
00.51123456789101112131415
  • ridge: continuous factor fjf_j
  • principal components: keep the first kk
  • line d=λd = \sqrt{\lambda}, where fj=1/2f_j = 1/2
−3.00 (λ = 1e−3)
Effective degrees of freedom df(λ)\mathrm{df}(\lambda)5.19 of 14
Components with fj≥1/2f_j \ge 1/25
Principal components with the same dfk = 5
f1f_1 (highest variance)1.0000
f14f_{14} (smallest nonzero variance)3.5e−17
The 8 lowest-variance directions are nearly switched off (fj<0.05f_j < 0.05), while high-variance directions are nearly intact: the cutoff is at dj≈λ=0.032d_j \approx \sqrt{\lambda} = 0.032.
Above, singular values djd_j of the standardized design matrix on a log scale, with line d=λd = \sqrt{\lambda}; below, ridge factors fjf_j and, in orange, the hard principal-component cutoff with the same degrees of freedom. Start with the degree-15 polynomial: its singular values fall almost an order of magnitude per component, and as λ\lambda increases the bars switch off one by one from right to left. Switch to diabetes: with more similar singular values, the cutoff is much more gradual. For which λ\lambda is df\mathrm{df} exactly half its maximum?

With the polynomial and λ=10−3\lambda = 10^{-3} (the initial state), λ=0.032\sqrt{\lambda} = 0.032: the first four components (dj≥0.35d_j \ge 0.35) pass almost entirely, the fifth (d5=0.09d_5 = 0.09) retains 89%, the sixth (d6=0.021d_6 = 0.021) 30%, and the rest under 2%. The factors sum to 5.195.19: the degree-15 polynomial with that penalty behaves like a model with about five parameters. In diabetes singular values range from 42.242.2 to 1.91.9: the last component (d102=3.8d_{10}^2 = 3.8) is halved at λ≈4\lambda \approx 4, the ninth (d92=34.6d_9^2 = 34.6) at several tens, and the first eight (dj2d_j^2 between 192 and 1779) require λ\lambda in the hundreds or thousands.

Bias, variance, and the Hoerl–Kennard theorem

Now suppose the model y=Xβ+ε\vb{y} = \mat{X}\vb{\beta} + \vb{\varepsilon} with Eε=0\E\vb{\varepsilon} = \vb{0}, Cov⁡ε=σ2I\Cov\vb{\varepsilon} = \sigma^2\mat{I}, and fixed rank-pp X\mat{X}, and let αj=vj⊤β\alpha_j = \vb{v}_j\T\vb{\beta} be coordinates of the true β\vb{\beta} in the eigenbasis. The spectral formula gives, component by component,

E[vj⊤β^λ]=fj αj,Var⁡(vj⊤β^λ)=σ2dj2(dj2+λ)2,\E[\vb{v}_j\T\hat{\vb{\beta}}_\lambda] = f_j\,\alpha_j, \qquad \Var(\vb{v}_j\T\hat{\vb{\beta}}_\lambda) = \sigma^2\frac{d_j^2}{(d_j^2 + \lambda)^2},

and summing, the mean squared error

ECM(λ)=E∥β^λ−β∥2=σ2∑j=1pdj2(dj2+λ)2⏟varianza+λ2∑j=1pαj2(dj2+λ)2⏟sesgo2.\mathrm{ECM}(\lambda) = \E\norm{\hat{\vb{\beta}}_\lambda - \vb{\beta}}^2 = \underbrace{\sigma^2\sum_{j=1}^p \frac{d_j^2}{(d_j^2 + \lambda)^2}}_{\text{varianza}} + \underbrace{\lambda^2\sum_{j=1}^p \frac{\alpha_j^2}{(d_j^2 + \lambda)^2}}_{\text{sesgo}^2}.

Variance falls with λ\lambda and bias rises. At λ=0\lambda = 0 variance is σ2∑j1/dj2\sigma^2\sum_j 1/d_j^2, dominated by the smallest djd_j.

Proof

Differentiate term by term:

ddλ σ2dj2(dj2+λ)2=−2σ2dj2(dj2+λ)3,ddλ λ2αj2(dj2+λ)2=2λαj2dj2(dj2+λ)3.\frac{\mathrm{d}}{\mathrm{d}\lambda}\,\frac{\sigma^2d_j^2}{(d_j^2 + \lambda)^2} = -\frac{2\sigma^2d_j^2}{(d_j^2 + \lambda)^3}, \qquad \frac{\mathrm{d}}{\mathrm{d}\lambda}\,\frac{\lambda^2\alpha_j^2}{(d_j^2 + \lambda)^2} = \frac{2\lambda\alpha_j^2d_j^2}{(d_j^2 + \lambda)^3}.

Summing, ECM′(λ)=2∑jdj2(λαj2−σ2)/(dj2+λ)3\mathrm{ECM}'(\lambda) = 2\sum_j d_j^2(\lambda\alpha_j^2 - \sigma^2)/(d_j^2 + \lambda)^3. If λ<σ2/max⁡jαj2\lambda < \sigma^2/\max_j\alpha_j^2 (with σ2/0=∞\sigma^2/0 = \infty), all parenthesized terms are negative, as is the derivative. In particular ECM′(0)=−2σ2∑jdj−4<0\mathrm{ECM}'(0) = -2\sigma^2\sum_j d_j^{-4} < 0.

∎

The theorem establishes existence: a good λ\lambda depends on unknown β\vb{\beta} and σ2\sigma^2, so it must be chosen from data (as we will see with cross-validation). The gain depends on where β\vb{\beta} lies relative to the eigenaxes, and the cell calculates it with the exact formula for the first cell’s design.

[ ]Ridge bias, variance, and MSEBrowser
import numpy as np
import matplotlib.pyplot as plt

# continúa la celda «Dos variables casi iguales»: X, G, sigma, B_rid
w, V = np.linalg.eigh(G)
w, V = w[::-1], V[:, ::-1]                      # d_j² de mayor a menor

def ecm_teorico(lam, beta):
    a = V.T @ beta
    var = sigma**2 * np.sum(w / (w + lam) ** 2)
    sesgo2 = lam**2 * np.sum(a**2 / (w + lam) ** 2)
    return var, sesgo2

lams = np.logspace(-2, 3, 501)
for b in [np.array([1.0, 1.0]), np.array([np.sqrt(2), 0.0]), np.array([1.0, -1.0])]:
    tot = np.array([sum(ecm_teorico(l, b)) for l in lams])
    k = tot.argmin()
    print(f"β = {np.round(b, 3)}  α² = {np.round((V.T @ b) ** 2, 3)}  ECM(MCO) = {sum(ecm_teorico(0, b)):.3f}  "
          f"λ* = {lams[k]:.3g}  ECM(λ*) = {tot[k]:.3f}  cociente = {tot[k] / sum(ecm_teorico(0, b)):.3f}")
v10, s10 = ecm_teorico(10.0, np.array([1.0, 1.0]))
print(f"λ = 10 y β = (1, 1): teórico {v10 + s10:.3f} (varianza {v10:.3f}, sesgo² {s10:.3f});"
      f" Monte Carlo de la primera celda {np.mean(((B_rid - 1.0) ** 2).sum(1)):.3f}")

partes = np.array([ecm_teorico(l, np.array([1.0, -1.0])) for l in lams])
plt.loglog(lams, partes[:, 0], label="varianza")
plt.loglog(lams, partes[:, 1], label="sesgo²")
plt.loglog(lams, partes.sum(1), "k", label="ECM")
plt.axhline(sum(ecm_teorico(0, np.array([1.0, -1.0]))), color="gray", ls="--", label="ECM de MCO")
plt.xlabel("λ"); plt.title("β = (1, −1): la señal en la dirección mal determinada"); plt.legend(); plt.show()

All three β\vb{\beta} have the same norm, 2\sqrt 2, and least squares has the same error, 2.072.07, because its variance does not depend on β\vb{\beta}. Ridge, by contrast, depends greatly on signal location. If β=(1,1)\vb{\beta} = (1, 1) lies entirely in the well-determined direction (α2=(2,0)\alpha^2 = (2, 0)), the best λ\lambda reduces error by 98%: what is switched off is almost entirely noise. If it lies entirely in the poorly determined direction, β=(1,−1)\vb{\beta} = (1, -1), the improvement is only about half (ratio 0.4970.497), because shrinking that direction also destroys signal. Even then improvement exists, as the theorem guarantees. Formula and simulation agree: both give 0.0580.058 at λ=10\lambda = 10.

Effective degrees of freedom

How many parameters does a ridge fit “use”? Counting coefficients does not help: there are pp for every λ\lambda. A useful definition measures how much the fit adapts to data.

The second equality is the trace of Udiag⁡(fj)U⊤\mat{U}\diag(f_j)\mat{U}\T, which by cyclicity is tr⁡(diag⁡(fj)U⊤U)=∑jfj\tr(\diag(f_j)\mat{U}\T\mat{U}) = \sum_j f_j. The formula shows the properties: df\mathrm{df} is continuous and strictly decreasing, approaches rr as λ→0+\lambda \to 0^+ (least squares: trace of a rank-rr projection), and approaches 0 as λ→∞\lambda \to \infty. Add 1 for an intercept. Note that Hλ\mat{H}_\lambda is no longer a projection: its eigenvalues fjf_j lie strictly between 0 and 1, and Hλ2≠Hλ\mat{H}_\lambda^2 \neq \mat{H}_\lambda.

Why this definition? Because it measures training error’s optimism exactly. If ynuevo\vb{y}^{\text{nuevo}} are new responses at the same xi\vb{x}_i, independent of y\vb{y}, then E(yinuevo−y^i)2−E(yi−y^i)2=2Cov⁡(yi,y^i)\E(y_i^{\text{nuevo}} - \hat y_i)^2 - \E(y_i - \hat y_i)^2 = 2\Cov(y_i, \hat y_i) because the other terms coincide. Summing and dividing by nn,

E[error de prediccioˊn en los xi]=E[error de entrenamiento]+2σ2n df.\E[\text{error de predicción en los } \vb{x}_i] = \E[\text{error de entrenamiento}] + \frac{2\sigma^2}{n}\,\mathrm{df}.

A high-df\mathrm{df} model can fit training better but pays 2σ2/n2\sigma^2/n for each degree of freedom, whether they are called polynomial coefficients or shrinkage factors. Thus df\mathrm{df} lets us compare models from different families on the same scale. In the lab, ridge on a degree-15 polynomial with df=4.49\mathrm{df} = 4.49 has risk 0.1260.126, between the unpenalized degree-4 polynomial (df=4\mathrm{df} = 4, risk 0.1330.133) and degree 5 (df=5\mathrm{df} = 5, risk 0.1240.124): the continuous control does what the discrete one does, without choosing a basis.

The coefficient path

As λ\lambda varies from 00 to ∞\infty, β^λ\hat{\vb{\beta}}_\lambda traces a curve from β^+\hat{\vb{\beta}}^+ to 0\vb{0}: the ridge path (or ridge trace, as Hoerl and Kennard called it). Three properties should not be confused:

  • The norm decreases; coefficients need not. ∥β^λ∥\norm{\hat{\vb{\beta}}_\lambda} is monotone (proved above), but each β^j\hat\beta_j combines components shrinking at different rates and can increase in absolute value or change sign. In diabetes, coefficient s3 goes from 4.84.8 with OLS to −9.0-9.0 at λ=50\lambda = 50.
  • Training error increases. ∥y−y^λ∥2=∑j(1−fj)2cj2+∥(I−UU⊤)y∥2\norm{\vb{y} - \hat{\vb{y}}_\lambda}^2 = \sum_j (1 - f_j)^2c_j^2 + \norm{(\mat{I} - \mat{U}\mat{U}\T)\vb{y}}^2 and each 1−fj=λ/(dj2+λ)1 - f_j = \lambda/(d_j^2 + \lambda) increases with λ\lambda.
  • No coefficient becomes zero. β^λ,j=ej⊤(X⊤X+λI)−1X⊤y\hat\beta_{\lambda,j} = \vb{e}_j\T(\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\vb{y} is a linear function of y\vb{y}, not identically zero except in degenerate cases, so it vanishes only on a hyperplane of y\vb{y} values, which has probability zero if noise has a density. Ridge shrinks but does not select variables.

Bayesian interpretation and augmented data

The penalty has a probabilistic interpretation explaining what ridge assumes and where λ\lambda comes from.

p(β∣y)∝p(y∣β) p(β)p(\vb{\beta} \given \vb{y}) \propto p(\vb{y} \given \vb{\beta})\,p(\vb{\beta})
Bayes' theorem; the normalization constant does not depend on β.
1/5

This interpretation gives λ\lambda meaning. A broad prior (large τ\tau: little belief that coefficients are small) yields small λ\lambda; much noise (large σ\sigma: each point is less informative) yields large λ\lambda. And λ=σ2/τ2\lambda = \sigma^2/\tau^2 makes sense only if all coefficients share the same prior scale, another way of saying standardization is needed. Two clarifications: the full posterior, with covariance, is Bayesian linear regression; ridge keeps its center. And covariance σ2(X⊤X+λI)−1\sigma^2(\mat{X}\T\mat{X} + \lambda\mat{I})\inv describes uncertainty about β\vb{\beta} given data, not the estimator’s frequentist variability, which is the smaller σ2(X⊤X+λI)−1X⊤X(X⊤X+λI)−1\sigma^2(\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\mat{X}(\mat{X}\T\mat{X} + \lambda\mat{I})\inv.

Augmented data. Add pp fictitious observations: row λ ej\sqrt{\lambda}\,\vb{e}_j with response 0, for j=1,…,pj = 1, \dots, p. With

X~=[Xλ Ip],y~=[y0p],∥y~−X~β∥2=∥y−Xβ∥2+λ∥β∥2,\tilde{\mat{X}} = \begin{bmatrix} \mat{X} \\ \sqrt{\lambda}\,\mat{I}_p \end{bmatrix}, \qquad \tilde{\vb{y}} = \begin{bmatrix} \vb{y} \\ \vb{0}_p \end{bmatrix}, \qquad \norm{\tilde{\vb{y}} - \tilde{\mat{X}}\vb{\beta}}^2 = \norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}^2,

ridge is ordinary least squares on augmented data. Each fictitious row is a “witness” stating βj=0\beta_j = 0 with weight λ\sqrt\lambda; with λ>0\lambda > 0, X~\tilde{\mat{X}} has full rank pp even if X\mat{X} does not. This is the prior idea written as data, with a practical advantage: any stable least-squares routine (QR, lstsq) solves ridge without forming X⊤X\mat{X}\T\mat{X}.

Choosing λ: closed-form cross-validation

All of the above leaves λ\lambda free. The standard choice estimates prediction error for every value on a grid using cross-validation and selects the best. With KK folds one retrains KK times per λ\lambda; with leave-one-out cross-validation (LOOCV), nn times. For ridge, and generally any linear fit from penalized least squares, LOOCV comes for free from the full fit.

The proof, in the second guided exercise, has an elegant idea: replacing yiy_i by the prediction made for it by the model without ii does not change that model. The result is closed-form leave-one-out cross-validation:

LOOCV(λ)=1n∑i=1n(yi−y^i1−hii)2,GCV(λ)=1n∑i=1n(yi−y^i)2(1−tr⁡(H)/n)2,\mathrm{LOOCV}(\lambda) = \frac1n\sum_{i=1}^n\Big(\frac{y_i - \hat y_i}{1 - h_{ii}}\Big)^2, \qquad \mathrm{GCV}(\lambda) = \frac{\frac1n\sum_{i=1}^n(y_i - \hat y_i)^2}{\big(1 - \tr(\mat{H})/n\big)^2},

where tr⁡H=1+df(λ)\tr\mat{H} = 1 + \mathrm{df}(\lambda) with the intercept. Once the SVD is calculated, each λ\lambda costs O(nr)\bigO(nr): an entire grid costs less than one retraining.

hii=∂y^i/∂yih_{ii} = \partial\hat y_i/\partial y_i is example ii‘s leverage: how much its own prediction moves if its response moves, the same quantity as in regression diagnostics. A point with hiih_{ii} near 1 pulls the fit toward itself, making its residual eie_i deceptively small; dividing by 1−hii1 - h_{ii} undoes the deception.

InteractiveThe leave-one-out shortcut
Degree-15 ridge with λ=10−3.00\lambda = 10^{-3.00}: full fit and without point 15
Leverages hiih_{ii} (hat-matrix diagonal) and their mean (1+df)/n(1 + \mathrm{df})/n
00.51mean 0.413
  • fit with all 15 points and residual eie_i
  • fit without point ii and its residual
  • sin⁡(2πx)\sin(2\pi x)
−3.00 (λ = 1e−3)
15 (x = 1.000)
df(λ)\mathrm{df}(\lambda)5.19
Leverage hiih_{ii}0.993
Full-fit residual eie_i−0.014
Formula ei/(1−hii)e_i / (1 - h_{ii})−1.9816
Refitting without the point−1.9816
LOOCV (mean of all 15)0.391
GCV0.120
hii=0.993h_{ii} = 0.993: the fit nearly passes through the point (small eie_i), but without it the curve moves far away. Dividing by 1−hii=0.0071 - h_{ii} = 0.007 recovers that error.
Degree-15 ridge on the 15 lab points. Orange is the full fit; dashed magenta is retrained without the marked point. The last two readouts compare that retraining's residual with the formula ei/(1−hii)e_i/(1 - h_{ii}), which uses only the full fit. Below, each point's leverage hiih_{ii} and its mean, used by GCV. Start at x=1x = 1: why is its residual so small and its leave-one-out residual so large? Try a central point and move λ\lambda toward 10−810^{-8} and 1010.

At λ=10−3\lambda = 10^{-3}, the point at x=1x = 1 has hii=0.993h_{ii} = 0.993: x15x^{15} is practically equal at all points except the last few (it is 0.330.33 at the penultimate, x=13/14x = 13/14, and 11 at x=1x = 1), so once standardized it acts almost as an indicator for that point, and the fit follows it with little penalty cost. Its residual is ei=−0.014e_i = -0.014 and its leave-one-out residual −1.98-1.98: over a hundred times larger. Points two through eleven have hiih_{ii} between 0.240.24 and 0.330.33, and the point at x=0x = 0 has 0.7440.744: the endpoints are influential.

GCV: the rotation-invariant version

Generalized cross-validation (GCV) replaces each hiih_{ii} with its mean tr⁡(H)/n\tr(\mat{H})/n. Golub, Heath and Wahba (1979) proposed it as a rotation-invariant version of ordinary cross-validation (Allen’s PRESS): if you rotate the problem (without an intercept) by an orthogonal matrix, y↦Qy\vb{y} \mapsto \mat{Q}\vb{y} and X↦QX\mat{X} \mapsto \mat{Q}\mat{X}, ridge coefficients do not change but hiih_{ii} and LOOCV do; GCV does not. Two practical readings:

  • Since (1−x)−2≈1+2x(1 - x)^{-2} \approx 1 + 2x for small xx, GCV≈1nRSS (1+2 tr⁡H/n)\mathrm{GCV} \approx \frac1n\mathrm{RSS}\,(1 + 2\,\tr\mat{H}/n): training error plus a degrees-of-freedom penalty, related to the earlier optimism 2σ2df/n2\sigma^2\mathrm{df}/n.
  • When leverages differ greatly, as with the polynomial, LOOCV and GCV can differ considerably, and GCV may have spurious minima near λ=0\lambda = 0, where the fit nearly interpolates and numerator and denominator both approach zero. You will see this in the lab.

The one-standard-error rule

The validation curve is a noisy estimate, and so is its minimum. The one-standard-error rule (Hastie, Tibshirani and Friedman, section 7.10) chooses the simplest model, here the largest λ\lambda, whose estimated error is no more than one standard error above the minimum. With LOOCV, a reasonable standard error is the standard deviation of the nn squares (ei/(1−hii))2(e_i/(1 - h_{ii}))^2 divided by n\sqrt n; it is not exact because those terms are dependent, but gives the right scale.

InteractiveRidge path and validation error
Standardized coefficients versus λ\lambda
10⁻²10⁻¹10⁰10¹10²10³10⁴10⁵−50050
Leave-one-out mean squared error (closed form) ± one standard error
10⁻²10⁻¹10⁰10¹10²10³10⁴10⁵40006000
  • bmi
  • s5
  • s1
  • s2
  • other variables
  • LOOCV and ±1 SE band
0.00 (λ = 1)
df(λ)\mathrm{df}(\lambda)8.75 of 10
LOOCV ± SE3627 ± 959
∥β^λ∥\norm{\hat{\vb{\beta}}_\lambda}71.49
Coefficient of bmi19.62
Coefficient of s552.19
Coefficient of s1−20.06
Coefficient of s2−12.42
λmin⁡\lambda_{\min} (df)7.9 (6.56)
1 SE rule (df)79 (2.61)
Between λ=0.01\lambda = 0.01 and the current λ\lambda, the following changed sign: s2. Ridge shrinks the norm, not each coefficient separately.
scikit-learn diabetes data: 10 standardized clinical variables and disease progression one year later. Above, standardized coefficients against λ\lambda (the four most interesting variables in color); below, LOOCV calculated by the closed formula, with a one-standard-error band. The cursor synchronizes both panels. Start with the first 40 patients: the curve has a clear U and the minimum (solid line) and one-standard-error rule (dashed) choose very different models. How many degrees of freedom does each have? Follow s1 and s2 left: what do two variables with correlation 0.90.9 do without a penalty? Switch to all 442 patients: how much does ridge improve on least squares there?

For the first 40 patients, LOOCV drops from 49504950 at λ=0.01\lambda = 0.01 (nearly least squares) to 32543254 at λmin⁡=7.9\lambda_{\min} = 7.9, with df=6.56\mathrm{df} = 6.56 out of 10; the one-standard-error rule chooses λ=79\lambda = 79 and df=2.61\mathrm{df} = 2.61, at the cost of LOOCV 40554055. Standard error at the minimum is enormous, 820820: with 40 patients the curve is poorly determined and the difference between criteria is a decision, not a fact. With all 442 patients ridge barely improves prediction (30003000 versus 30023002 for least squares, λmin⁡=1.8\lambda_{\min} = 1.8): with n=442n = 442 and p=10p = 10, variance is already small. What changes greatly are the coefficients of s1 and s2.

Lab: ridge from scratch with SVD and closed-form LOOCV

The plan: one SVD of the standardized matrix, the entire λ\lambda grid from it, and checks against each interpretation in the lesson (linear system, augmented data, posterior mean, and scikit-learn).

[ ]Ridge by SVD: one decomposition for the entire gridBrowser
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge

datos = load_diabetes(scaled=False)
X, y = datos.data, datos.target
nombres = datos.feature_names
n, p = X.shape
mu, s = X.mean(0), X.std(0)
Z = (X - mu) / s                     # estandarizada (desviación típica poblacional, como StandardScaler)
ybar = y.mean()
yc = y - ybar
print(f"n = {n}, p = {p}, correlación(s1, s2) = {np.corrcoef(X[:, 4], X[:, 5])[0, 1]:.3f}")

U, d, Vt = np.linalg.svd(Z, full_matrices=False)
uy = U.T @ yc
print("valores singulares d_j:", np.round(d, 2))
print(f"número de condición de Z: {d[0] / d[-1]:.1f}")

def ridge_svd(lams):
    """Coeficientes (una fila por λ) y factores de encogimiento, con una sola SVD."""
    lams = np.atleast_1d(lams).astype(float)
    F = d**2 / (d**2 + lams[:, None])
    return (F / d * uy) @ Vt, F

lam = 50.0
B, F = ridge_svd(lam)
b = B[0]
b_solve = np.linalg.solve(Z.T @ Z + lam * np.eye(p), Z.T @ yc)
Zaum = np.vstack([Z, np.sqrt(lam) * np.eye(p)])
yaum = np.concatenate([yc, np.zeros(p)])
b_aum = np.linalg.lstsq(Zaum, yaum, rcond=None)[0]
b_sk = Ridge(alpha=lam).fit(Z, y).coef_
s2, t2 = 2500.0, 50.0                # σ² y τ² con σ²/τ² = 50
b_post = np.linalg.solve(Z.T @ Z / s2 + np.eye(p) / t2, Z.T @ yc / s2)
print(f"λ = {lam:g}: |SVD - solve| = {np.abs(b - b_solve).max():.1e}  |SVD - aumentados| = {np.abs(b - b_aum).max():.1e}  "
      f"|SVD - sklearn| = {np.abs(b - b_sk).max():.1e}  |SVD - media posterior| = {np.abs(b - b_post).max():.1e}")

b_mco = ridge_svd(0.0)[0][0]
print(f"{'':6s}{'MCO':>9s}{'λ=50':>9s}")
for j in range(p):
    print(f"{nombres[j]:6s}{b_mco[j]:9.2f}{b[j]:9.2f}")
print(f"‖β‖: MCO {np.linalg.norm(b_mco):.2f}  ridge {np.linalg.norm(b):.2f}   df(50) = {F.sum():.2f}")

All four routes agree to 10−1310^{-13}: linear system, least squares on augmented data, posterior mean with σ2/τ2=50\sigma^2/\tau^2 = 50, and Ridge. The table shows what the penalty does with moderate λ\lambda (df=7.51\mathrm{df} = 7.51). Least squares gives s1 (total cholesterol) −37.7-37.7 and s2 (LDL) +22.7+22.7: two variables correlated at 0.8970.897 with large opposite effects that largely cancel. At λ=50\lambda = 50 they become −3.62-3.62 and −3.52-3.52, almost equal: the grouping effect. Variables outside that conflict, such as bmi (24.7→23.124.7 \to 23.1) or bp (15.4→14.215.4 \to 14.2), barely move, and s3 changes sign (4.8→−9.04.8 \to -9.0). The norm drops from 65.565.5 to 37.637.6.

Now validation. The cell calculates LOOCV, its standard error, and GCV for 141 λ\lambda values from the same SVD, and compares them with actual LOOCV, retraining 442 times.

[ ]Closed-form LOOCV and GCV versus retraining n timesBrowser
import time

lams = np.logspace(-2, 5, 141)

def loo_gcv(U, d, yc, lams):
    n = len(yc)
    uy = U.T @ yc
    F = d**2 / (d**2 + lams[:, None])         # una fila por λ
    Yhat = (F * uy) @ U.T
    H = 1 / n + F @ (U**2).T                   # diagonales de H_λ, con el término independiente
    R = yc - Yhat
    E = R / (1 - H)                            # residuos dejando uno fuera
    df = F.sum(1)
    cv = (E**2).mean(1)
    se = (E**2).std(1, ddof=1) / np.sqrt(n)
    gcv = (R**2).mean(1) / (1 - (df + 1) / n) ** 2
    return cv, se, gcv, df, E

t0 = time.perf_counter()
cv, se, gcv, df, E = loo_gcv(U, d, yc, lams)
t_cerrada = time.perf_counter() - t0

def loo_explicita(lam):
    e = np.empty(n)
    for i in range(n):
        m = np.ones(n, bool); m[i] = False
        Zi, yi = Z[m], y[m]
        zm, ym = Zi.mean(0), yi.mean()           # el término independiente se reestima sin el ejemplo i
        bi = np.linalg.solve((Zi - zm).T @ (Zi - zm) + lam * np.eye(p), (Zi - zm).T @ (yi - ym))
        e[i] = y[i] - (ym + (Z[i] - zm) @ bi)
    return e

for lam in [0.1, 10.0, 1000.0]:
    t0 = time.perf_counter(); e = loo_explicita(lam); t_exp = time.perf_counter() - t0
    k = np.argmin(np.abs(lams - lam))
    print(f"λ = {lam:g}: máx |fórmula - reentrenando| = {np.abs(E[k] - e).max():.1e}   LOOCV = {np.mean(e**2):.1f}")
print(f"tiempo: forma cerrada para {len(lams)} λ, {1000 * t_cerrada:.0f} ms; reentrenar {n} veces para un λ, {1000 * t_exp:.0f} ms")

def resumen(cv, se, gcv, df, etiqueta):
    i = cv.argmin()
    j = np.max(np.nonzero(cv <= cv[i] + se[i])[0])
    g = gcv.argmin()
    print(f"{etiqueta}: LOOCV(λ=0.01) = {cv[0]:.0f}   λ_min = {lams[i]:.3g} (df {df[i]:.2f}, LOOCV {cv[i]:.0f} ± {se[i]:.0f})   "
          f"regla 1 ET: λ = {lams[j]:.3g} (df {df[j]:.2f}, LOOCV {cv[j]:.0f})   GCV: λ = {lams[g]:.3g}")

resumen(cv, se, gcv, df, "442 pacientes")
Z40 = (X[:40] - X[:40].mean(0)) / X[:40].std(0)
y40 = y[:40] - y[:40].mean()
U40, d40, _ = np.linalg.svd(Z40, full_matrices=False)
resumen(*loo_gcv(U40, d40, y40, lams)[:4], "40 pacientes ")
print(f"varianza de y: {y.var():.0f}")

The formula reproduces retrained LOOCV to 10−1210^{-12} and is much faster: timings depend on the machine, but the closed form evaluates 141 λ\lambda values in less time than 442 retrainings for one. The criteria agree with the figure’s preview. With all 442 patients, the minimum is at λ=1.78\lambda = 1.78 with df=9.59\mathrm{df} = 9.59, and GCV chooses 3.163.16: nearly least squares. Validation error is around 3000 versus yy variance 5930, so the linear model explains slightly less than half. With 40 patients the penalty matters, and the one-standard-error rule takes the model to df=2.61\mathrm{df} = 2.61.

Ridge on polynomial features

The second lab revisits the previous lesson’s problem: f(x)=sin⁡(2πx)f(x) = \sin(2\pi x), 15 equally spaced points in [0,1][0, 1] and noise σ=0.3\sigma = 0.3 (here with NumPy seed 0). Instead of reducing degree, keep it at 15 and vary λ\lambda. Pipeline order matters: powers first, then standardization, so each power has variance 1 before penalization. Since ff is known, risk is calculated exactly: σ2+∫01(f^−f)2\sigma^2 + \int_0^1(\hat f - f)^2.

[ ]Fixed degree 15, λ as the complexity controlBrowser
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge, LinearRegression

f = lambda x: np.sin(2 * np.pi * x)
rng = np.random.default_rng(0)
x = np.linspace(0, 1, 15)
y = f(x) + 0.3 * rng.normal(size=15)
xg = np.linspace(0, 1, 2001)
riesgo = lambda pred: 0.09 + np.mean((pred(xg) - f(xg)) ** 2)    # σ² + ∫(f̂ − f)², por cuadratura

def modelo(lam):
    return make_pipeline(PolynomialFeatures(15, include_bias=False), StandardScaler(), Ridge(alpha=lam))

def df_de(m, lam):
    Zt = m[:2].transform(x[:, None])
    dd = np.linalg.svd(Zt - Zt.mean(0), compute_uv=False)
    return np.sum(dd**2 / (dd**2 + lam))

ajustes = {}
for lam in [1e-10, 1e-6, 1e-3, 1e-2, 1e-1, 1, 10]:
    m = modelo(lam).fit(x[:, None], y)
    ajustes[lam] = m
    pred = lambda t, m=m: m.predict(t[:, None])
    print(f"λ = {lam:6.0e}  df = {df_de(m, lam):5.2f}  ECM entrenamiento = {np.mean((pred(x) - y) ** 2):.4f}  "
          f"riesgo = {riesgo(pred):.3f}  ‖β‖ = {np.linalg.norm(m[-1].coef_):9.3g}")
for M in [3, 4, 5, 6]:
    m = make_pipeline(PolynomialFeatures(M, include_bias=False), LinearRegression()).fit(x[:, None], y)
    print(f"grado {M} sin penalizar: riesgo = {riesgo(lambda t: m.predict(t[:, None])):.3f}")

for lam, estilo in [(1e-10, ":"), (1e-2, "-"), (10, "--")]:
    plt.plot(xg, ajustes[lam].predict(xg[:, None]), estilo, label=f"λ = {lam:g}")
plt.plot(xg, f(xg), color="gray", lw=1, label="sin(2πx)")
plt.scatter(x, y, color="k", zorder=3)
plt.ylim(-2, 2); plt.legend(); plt.title("Polinomio de grado 15 con tres penalizaciones"); plt.show()

The table is the previous lesson’s validation curve traversed with a continuous control. At λ=10−10\lambda = 10^{-10} the fit nearly interpolates (training error 0.00060.0006), has df=9.70\mathrm{df} = 9.70, coefficient norm 5880 and risk 0.2280.228, more than twice the noise. Between λ=10−6\lambda = 10^{-6} and 10−210^{-2} risk stays at 0.1240.124 to 0.1260.126, near the minimum possible σ2=0.09\sigma^2 = 0.09 plus approximation error for a sine with few degrees of freedom, and df\mathrm{df} falls from 7.37.3 to 4.44.4. At λ=10\lambda = 10 the model can no longer follow the sine (df=1.72\mathrm{df} = 1.72, risk 0.2510.251). The best unpenalized polynomial (degree 5) reaches 0.1240.124: ridge matches the best degree choice without choosing it.

It remains to choose λ\lambda from data. The cell reuses loo_gcv on the polynomial, examines endpoint leverages, and also calculates honest LOOCV, which re-estimates standardization inside each fold (the closed formula treats standardization as fixed).

[ ]LOOCV, GCV, and polynomial leveragesBrowser
P = np.vander(x, 16, increasing=True)[:, 1:]                 # x, ..., x^15
mu_p, s_p = P.mean(0), P.std(0)
Zp = (P - mu_p) / s_p
Up, dp, Vtp = np.linalg.svd(Zp - Zp.mean(0), full_matrices=False)
r = np.sum(dp > 1e-13 * dp[0])                                # rango numérico (14: 15 puntos centrados)
Up, dp, Vtp = Up[:, :r], dp[:r], Vtp[:r]
lp = np.logspace(-10, 2, 121)
yc_p = y - y.mean()
cv_p, se_p, gcv_p, df_p, E_p = loo_gcv(Up, dp, yc_p, lp)
H_p = 1 / 15 + (dp**2 / (dp**2 + lp[:, None])) @ (Up**2).T

def predictor(lam):
    c = Vtp.T @ (dp / (dp**2 + lam) * (Up.T @ yc_p))
    return lambda t: y.mean() + ((np.vander(t, 16, increasing=True)[:, 1:] - mu_p) / s_p - Zp.mean(0)) @ c

for nombre, crit in [("LOOCV", cv_p), ("GCV", gcv_p)]:
    k = crit.argmin()
    print(f"{nombre:5s} global: λ = {lp[k]:.2g}  df = {df_p[k]:.2f}  criterio = {crit[k]:.3f}  riesgo = {riesgo(predictor(lp[k])):.3f}")
locales = [k for k in range(1, len(lp) - 1) if gcv_p[k] < gcv_p[k - 1] and gcv_p[k] < gcv_p[k + 1]]
print("mínimos locales de la GCV en λ =", [f"{lp[k]:.2g}" for k in locales])
for lam in [1e-3, 1e-2]:
    k = np.argmin(np.abs(np.log10(lp / lam)))
    print(f"λ = {lam:g}: h_ii en x = 0 y x = 1: {H_p[k, 0]:.3f}, {H_p[k, -1]:.3f}   media (1 + df)/n = {(1 + df_p[k]) / 15:.3f}   "
          f"LOOCV = {cv_p[k]:.3f}   GCV = {gcv_p[k]:.3f}")
    print(f"   en x = 1: residuo e_i = {E_p[k, -1] * (1 - H_p[k, -1]):.3f}   residuo dejando uno fuera = {E_p[k, -1]:.3f}")

# LOOCV honesta: el escalado se ajusta sin el ejemplo i
cv_dentro = np.zeros(len(lp))
for i in range(15):
    m = np.arange(15) != i
    Pi = P[m]
    mi, si = Pi.mean(0), Pi.std(0)
    Zi = (Pi - mi) / si
    zb = Zi.mean(0)
    Ui, di, Vti = np.linalg.svd(Zi - zb, full_matrices=False)
    ki = di > 1e-13 * di[0]
    C = (np.where(ki, di / (di**2 + lp[:, None]), 0.0) * (Ui.T @ (y[m] - y[m].mean()))) @ Vti
    cv_dentro += (y[i] - y[m].mean() - C @ ((P[i] - mi) / si - zb)) ** 2 / 15
k = cv_dentro.argmin()
print(f"LOOCV con el escalado dentro de cada pliegue: λ = {lp[k]:.2g}  df = {df_p[k]:.2f}  criterio = {cv_dentro[k]:.3f}  "
      f"riesgo = {riesgo(predictor(lp[k])):.3f}")

Three results, all from the output:

  • LOOCV chooses well. Its minimum is at λ=0.0079\lambda = 0.0079 with df=4.49\mathrm{df} = 4.49 and true risk 0.1260.126, within 0.0020.002 of the best table value.
  • GCV’s global minimum is spurious. It is at λ=2×10−10\lambda = 2\times 10^{-10}, with df=9.52\mathrm{df} = 9.52, criterion 0.0070.007 (below the noise itself, 0.090.09, already an alarm), and risk 0.2300.230. GCV has a second local minimum at the same λ=0.0079\lambda = 0.0079 as LOOCV. The reason is as before: with 15 points and rank 14, decreasing λ\lambda approaches interpolation, training error and (1−tr⁡H/n)2(1 - \tr\mat{H}/n)^2 both approach zero, and their ratio can fall. Inspect the whole curve and restrict the grid to df\mathrm{df} clearly below nn.
  • Leverages vary greatly. At λ=10−3\lambda = 10^{-3}, the point at x=1x = 1 has hii=0.993h_{ii} = 0.993 versus a mean of 0.4130.413; this explains why LOOCV (0.3910.391) and GCV (0.1200.120) differ so much there, exactly when GCV’s rotational invariance ceases to be a virtue.

Honest LOOCV chooses λ=0.02\lambda = 0.02 (df=4.15\mathrm{df} = 4.15, risk 0.1280.128): here treating standardization as fixed barely changes the choice. That is not always true, and in any case the closed-form curve validates a fit with standardization already decided from all data, rather than the complete procedure (standardizing and fitting).

With scikit-learn

Ridge solves this lesson’s problem with the same convention: sum of squares plus alpha times ∥w∥2\norm{\vb{w}}^2, with unpenalized intercept. RidgeCV, with cv=None (the default), calculates exact closed-form LOOCV for the whole grid, as we did. Watch other classes’ conventions: ElasticNet and SGDRegressor average the loss, 12n∥y−Xw∥2+α2∥w∥2\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 + \frac{\alpha}{2}\norm{\vb{w}}^2, and their α\alpha corresponds to alpha =nα= n\alpha in Ridge.

[ ]Ridge, RidgeCV, and the alpha conventionBrowser
import warnings
from sklearn.linear_model import RidgeCV, ElasticNet
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = datos.data, datos.target                          # de nuevo diabetes (las celdas del polinomio reutilizaron y)
rcv = RidgeCV(alphas=lams).fit(Z, y)
print(f"RidgeCV: alpha_ = {rcv.alpha_:.3g}   best_score_ = {rcv.best_score_:.0f}   (nuestro λ_min = {lams[cv.argmin()]:.3g}, LOOCV {cv.min():.0f})")
print("coeficientes iguales a los de ridge_svd:", np.allclose(rcv.coef_, ridge_svd(rcv.alpha_)[0][0]))

# el mismo modelo dentro de un Pipeline, sobre los datos sin escalar
pipe = make_pipeline(StandardScaler(), RidgeCV(alphas=lams)).fit(X, y)
w_orig = pipe[-1].coef_ / pipe[0].scale_                 # de vuelta a las unidades originales
print("coeficientes en unidades originales (bmi, bp):", np.round(w_orig[[2, 3]], 3))

a = 0.1
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    en = ElasticNet(alpha=a, l1_ratio=0.0, tol=1e-12, max_iter=100000).fit(Z, y)
print(f"ElasticNet(alpha={a}, l1_ratio=0) frente a Ridge(alpha={n * a:g}): máx diferencia = "
      f"{np.abs(en.coef_ - Ridge(alpha=n * a).fit(Z, y).coef_).max():.1e}")

best_score_ is LOOCV with sign reversed (scikit-learn maximizes scores), and RidgeCV chooses the same λ=1.78\lambda = 1.78. A Pipeline with StandardScaler is the correct way to deliver the model: it standardizes with training parameters and applies them to new data. But internal LOOCV of RidgeCV inside that Pipeline still sees data already scaled using all examples: for an honest estimate of the complete procedure, put the entire Pipeline into external cross-validation (nested cross-validation).

Common mistakes

Exercises

QuizFrom meters to centimeters
You fit ridge without standardization. One variable, a length, changes from meters to centimeters; everything else, including λ\lambda, stays the same. What happens to the effective penalty on that variable's effect?
NumericEffective degrees of freedom
A centered design matrix has singular values d=(10,1,0.1)d = (10, 1, 0.1). Calculate df(λ)\mathrm{df}(\lambda) for λ=1\lambda = 1.
NumericWhich λ gives one degree of freedom?
With singular values d=(3,1)d = (3, 1), for which λ>0\lambda > 0 is df(λ)=1\mathrm{df}(\lambda) = 1?
NumericA prior's λ
You model y∣β∼N(Xβ,σ2I)y \given \vb{\beta} \sim \Normal(\mat{X}\vb{\beta}, \sigma^2\mat{I}) with σ=2\sigma = 2 and use the prior β∼N(0,τ2I)\vb{\beta} \sim \Normal(\vb{0}, \tau^2\mat{I}) with τ=0.5\tau = 0.5. Which ridge λ\lambda (in the form ∥y−Xβ∥2+λ∥β∥2\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}^2) gives the MAP estimator?
NumericEvaluating GCV
A ridge fit with intercept on n=50n = 50 examples has residual sum of squares RSS=40\mathrm{RSS} = 40 and df(λ)=9\mathrm{df}(\lambda) = 9 (excluding the intercept). Calculate GCV(λ)\mathrm{GCV}(\lambda).
NumericA misleading residual
In a ridge fit, example ii has residual ei=yi−y^i=0.05e_i = y_i - \hat y_i = 0.05 and leverage hii=0.95h_{ii} = 0.95. What is its leave-one-out residual, yi−f^(−i)(xi)y_i - \hat f^{(-i)}(\vb{x}_i)?
QuizWhat the ridge path does
Let X\mat{X} be centered with X⊤y≠0\mat{X}\T\vb{y} \neq \vb{0}. As λ\lambda increases from 0, which statements are always true?

More than one answer may be correct.

QuizSignal in the wrong direction
In a particular problem, almost all the relationship between x\vb{x} and yy lies in the principal component with least variance: ∣ur⊤y∣\abs{\vb{u}_r\T\vb{y}} is large and the other ∣uj⊤y∣\abs{\vb{u}_j\T\vb{y}} are small. You choose λ\lambda by cross-validation. What do you expect?
QuizThe same model with twice the data
You duplicate your training dataset by copying every row twice (same xi\vb{x}_i and yiy_i). Which λ′\lambda' gives exactly the same ridge coefficients as λ\lambda on the original data?
QuizLOOCV and GCV on the polynomial
For the degree-15 polynomial with λ=10−3\lambda = 10^{-3}, LOOCV is 0.3910.391 and GCV 0.1200.120. Why?
ProofExistence, uniqueness, and spectral formula
Prove: For every λ>0\lambda > 0, X⊤X+λI\mat{X}\T\mat{X} + \lambda\mat{I} is positive definite, ridge has a unique minimizer and, with reduced SVD X=UDV⊤\mat{X} = \mat{U}\mat{D}\mat{V}\T (r=rank⁡Xr = \rank\mat{X}), β^λ=Vdiag⁡(dj/(dj2+λ))U⊤y\hat{\vb{\beta}}_\lambda = \mat{V}\diag\big(d_j/(d_j^2 + \lambda)\big)\mat{U}\T\vb{y}.
0
Let J(β)=∥y−Xβ∥2+λ∥β∥2J(\vb{\beta}) = \norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}^2 for arbitrary X∈Rn×p\mat{X} \in \R^{n\times p}, without assumptions on nn, pp, or rank.

Step 1 of 4. Why is X⊤X+λI\mat{X}\T\mat{X} + \lambda\mat{I} positive definite?

ProofThe leave-one-out validation identity
Prove: For the linear fit y^=Hy\hat{\vb{y}} = \mat{H}\vb{y} obtained by minimizing J(β;y)=∑k=1n(yk−xk⊤β)2+β⊤ΩβJ(\vb{\beta}; \vb{y}) = \sum_{k=1}^n (y_k - \vb{x}_k\T\vb{\beta})^2 + \vb{\beta}\T\mat{\Omega}\vb{\beta} with fixed positive-semidefinite Ω\mat{\Omega} and invertible X⊤X+Ω\mat{X}\T\mat{X} + \mat{\Omega} (ridge with unpenalized intercept is the case Ω=diag⁡(0,λI)\mat{\Omega} = \diag(0, \lambda\mat{I}) with a column of ones in X\mat{X}), we have yi−y^i(−i)=(yi−y^i)/(1−hii)y_i - \hat y_i^{(-i)} = (y_i - \hat y_i)/(1 - h_{ii}), where y^i(−i)=xi⊤β^(−i)\hat y_i^{(-i)} = \vb{x}_i\T\hat{\vb{\beta}}^{(-i)} and β^(−i)\hat{\vb{\beta}}^{(-i)} minimizes J−iJ_{-i}, the same sum without term ii (assume J−iJ_{-i} also has a unique minimizer).
0
Fix ii and let y∗\vb{y}^* be y\vb{y} with component ii replaced by y^i(−i)\hat y_i^{(-i)}.

Step 1 of 4. How does β^(−i)\hat{\vb{\beta}}^{(-i)} relate to the full problem with data y∗\vb{y}^*?

CodeRidge path and LOOCV with one SVD
Implement ridge_path(X, y, lambdas), returning (coefs, loocv): coefs of shape (len(lambdas), p) with ridge coefficients for each λ\lambda (with an unpenalized intercept, as in scikit-learn's Ridge(alpha=λ), and without standardization), and loocv of shape (len(lambdas),) with leave-one-out mean squared error. Center X and y, make one call to np.linalg.svd, and calculate everything else from it. It must also work with p>np > n.
import numpy as np

def ridge_path(X, y, lambdas):
  """Coeficientes ridge (una fila por lambda) y LOOCV, con una sola SVD."""
  X = np.asarray(X, dtype=float)
  y = np.asarray(y, dtype=float)
  lambdas = np.asarray(lambdas, dtype=float)
  n, p = X.shape
  # tu código: centra, una SVD, factores f_j, coeficientes, h_ii y residuos dejando uno fuera
  coefs = np.zeros((len(lambdas), p))
  loocv = np.zeros(len(lambdas))
  return coefs, loocv
Shift+Enter to run

Summary

Key idea
Ridge minimizes ∥y−Xβ∥2+λ∥β∥2\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}^2 and, in the SVD basis, multiplies each principal component of the fit by dj2/(dj2+λ)d_j^2/(d_j^2 + \lambda): it leaves high-variance directions almost intact and switches off those barely determined by data, trading a little bias for much less variance.
  • The solution (X⊤X+λI)−1X⊤y(\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\vb{y} exists and is unique for every λ>0\lambda > 0, regardless of rank; it equals least squares constrained to a ball ∥β∥≤t\norm{\vb{\beta}} \le t, and as λ→0+\lambda \to 0^+ approaches the minimum-norm solution.
  • Standardize variables and leave the intercept unpenalized: ridge is not scale-equivariant and the penalty should treat an effect of one standard deviation equally across variables.
  • Some λ>0\lambda > 0 always has lower mean squared error than least squares (Hoerl and Kennard); the gain depends on whether signal lies in well-determined directions.
  • Effective degrees of freedom df(λ)=tr⁡Hλ=∑jfj\mathrm{df}(\lambda) = \tr\mat{H}_\lambda = \sum_j f_j measure complexity on the parameter-count scale, and training-error optimism is 2σ2df/n2\sigma^2\mathrm{df}/n.
  • Ridge is MAP estimation with prior N(0,τ2I)\Normal(\vb{0}, \tau^2\mat{I}) and λ=σ2/τ2\lambda = \sigma^2/\tau^2, and least squares on augmented data with pp rows λ ej\sqrt\lambda\,\vb{e}_j.
  • LOOCV comes from a single fit, ei/(1−hii)e_i/(1 - h_{ii}); GCV replaces hiih_{ii} with their mean. With one SVD, the whole λ\lambda grid costs less than one retraining. Always plot the curve: with unequal leverage the criteria disagree and GCV can have spurious minima.
  • Coming next: lasso replaces the L2 ball with L1 and does zero coefficients; neural-network weight decay is an iterative version of this penalty; Tikhonov regularization is the same filter for inverse problems; and double descent studies what happens as λ→0\lambda \to 0 when p>np > n.