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
- 11Linear regression model and least-squares fittingLeast squares as Gaussian maximum likelihoodCentering, standardization and the interceptPolynomial regressionValidation curve
- 02Singular value decompositionSpectral theoremProjection matrixTrace
- 05Prior, likelihood and posteriorMaximum a posteriori estimatorRegression diagnostics: residuals, leverage and influence
- 06Lagrange multipliersLagrangian
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 the singular value decomposition of the design matrix, of rank , and uncorrelated noise of variance , the covariance of the ordinary least squares estimator (OLS) is
The component of along has variance . Three situations make some small:
- Collinearity. Two nearly proportional variables, such as total and LDL cholesterol in the diabetes data we will use (correlation ), leave almost no information about the difference in their effects.
- close to . As the number of columns approaches the number of rows, the smallest singular value approaches zero (for a random matrix with independent variance-1 entries and fixed , ), and with the null space of has dimension at least : infinitely many solutions.
- Ill-conditioned bases. Powers on are nearly dependent: with 15 equally spaced points, the singular values of that already standardized and centered matrix fall from to (and the last is exactly zero).
A cell shows the symptom. Two variables have correlation , , true coefficients , and noise ; the experiment is repeated 4,000 times with the same design and fresh noise.
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 and ), but each coefficient has standard deviation , equal to its value: in 16.5% of repetitions is negative. The output shows the problem: the sum is well estimated (deviation ), the difference terribly (). This is direction , with eigenvalue versus . With the penalty we will study and , coefficients have 15% bias toward zero ( instead of 1), but their standard deviation falls to and total squared error drops from to : 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, is the already centered data matrix without a column of ones, and is centered; the intercept is then (justified below).
The formula follows by setting the gradient to zero, . Showing the matrix is invertible and that this critical point is the global minimum for any , , and rank is the first guided exercise: the key is . Hoerl and Kennard proposed the method for precisely the “non-orthogonal” problems in the motivation: adding to the diagonal of moves it away from singularity.
The constrained form
Penalizing size is equivalent to limiting it. Let be the minimum-norm least-squares solution.
Proof
With reduced SVD and , the spectral formula in the next section gives . Since , some is nonzero and every term is continuous and decreasing in , strictly so for that . As the sum tends to , and as , to 0. By the intermediate value theorem, for every in the interval there is a unique with .
The constrained problem is convex and is strictly feasible, so the Karush–Kuhn–Tucker conditions are necessary and sufficient (the inequality version of Lagrange multipliers). With Lagrangian , they require , and . If , would be a least-squares solution with norm , impossible because has minimum norm. Thus , and , namely . This point satisfies the conditions, so it is a solution, and the only one because any other would also have to satisfy them.
∎If , the constraint is inactive and the problem returns least squares. The constrained form gives a geometric picture: contours of are ellipses centered on , the constraint is a ball, and the solution is the point where the first ellipse touches the ball.
The figure uses the simplest model showing the phenomenon: , with eigenvalues and measured per observation. Initially (, halfway), the component of 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 (the well-determined direction through the origin) and only then follows it down toward . This is the previous cell’s geometry: the difference , barely constrained by data, is sacrificed first.
Why the intercept is not penalized
If you penalized , adding a constant to every response would not shift predictions by : the fit would depend on the origin used to measure (Celsius and Kelvin would give different curves). Without penalizing , for each fixed the best is the mean of , and substituting it is exactly the centering theorem from linear regression: ridge without an intercept on centered data remains, with . This is what scikit-learn’s Ridge does with fit_intercept=True.
Why standardization is needed
Least squares is scale-equivariant: multiplying column by divides its coefficient by without changing predictions. Ridge is not, because the penalty measures in the variable’s units: the same effect on costs in one unit and something different in another. Standardization puts all variables on the same scale before charging, so penalizes effects per standard deviation, making them comparable. Coefficients in original units are recovered afterward with . The units exercise shows how the penalty becomes unbalanced otherwise.
The closed-form solution and its limits
Three consequences of the formula are worth keeping in mind.
Conditioning. Eigenvalues of are (and in null-space directions), so its condition number is . Ridge addresses both the statistical problem (variance) and numerical problem (nearly singular system). Even so, in practice is not formed: use SVD or the augmented-data trick below with QR.
The limit is the minimum-norm solution, not an arbitrary least-squares solution: in the spectral formula, in directions with , and null-space directions never enter. When 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.
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 , ridge divides the effect of s1 equally between both copies, and distance to falls proportionally to : from at to at . 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 , solve an system. From , multiplying by both inverses yields
With variables and examples, the left-hand form inverts a matrix and the right-hand form a one. Moreover, is written as a combination of examples and predictions need only dot products : replacing them with a kernel gives kernel ridge regression.
Spectral view: a filter on principal components
Write the reduced SVD , with and having orthonormal columns, , , and . In the same first guided exercise you will prove that
Predictions on training data are then
What are these directions? Because data are centered, is the data’s th principal component, with sample variance . The are axes of the ellipses in the previous figure, eigenvectors of supplied by the spectral theorem. Ridge shrinks high-variance components little and low-variance ones strongly, with a soft cutoff at , where exactly.
Principal component regression (PCR) does the same with a hard cutoff: retain the first () and discard the rest (). Ridge is the continuous version and does not require choosing an integer. Notice what does not appear in : the response. Neither ridge nor PCR checks whether signal in lies in high-variance components; both assume it does.
With the polynomial and (the initial state), : the first four components () pass almost entirely, the fifth () retains 89%, the sixth () 30%, and the rest under 2%. The factors sum to : the degree-15 polynomial with that penalty behaves like a model with about five parameters. In diabetes singular values range from to : the last component () is halved at , the ninth () at several tens, and the first eight ( between 192 and 1779) require in the hundreds or thousands.
Bias, variance, and the Hoerl–Kennard theorem
Now suppose the model with , , and fixed rank- , and let be coordinates of the true in the eigenbasis. The spectral formula gives, component by component,
and summing, the mean squared error
Variance falls with and bias rises. At variance is , dominated by the smallest .
Proof
Differentiate term by term:
Summing, . If (with ), all parenthesized terms are negative, as is the derivative. In particular .
∎The theorem establishes existence: a good depends on unknown and , so it must be chosen from data (as we will see with cross-validation). The gain depends on where lies relative to the eigenaxes, and the cell calculates it with the exact formula for the first cell’s design.
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 have the same norm, , and least squares has the same error, , because its variance does not depend on . Ridge, by contrast, depends greatly on signal location. If lies entirely in the well-determined direction (), the best reduces error by 98%: what is switched off is almost entirely noise. If it lies entirely in the poorly determined direction, , the improvement is only about half (ratio ), because shrinking that direction also destroys signal. Even then improvement exists, as the theorem guarantees. Formula and simulation agree: both give at .
Effective degrees of freedom
How many parameters does a ridge fit “use”? Counting coefficients does not help: there are for every . A useful definition measures how much the fit adapts to data.
The second equality is the trace of , which by cyclicity is . The formula shows the properties: is continuous and strictly decreasing, approaches as (least squares: trace of a rank- projection), and approaches 0 as . Add 1 for an intercept. Note that is no longer a projection: its eigenvalues lie strictly between 0 and 1, and .
Why this definition? Because it measures training error’s optimism exactly. If are new responses at the same , independent of , then because the other terms coincide. Summing and dividing by ,
A high- model can fit training better but pays for each degree of freedom, whether they are called polynomial coefficients or shrinkage factors. Thus lets us compare models from different families on the same scale. In the lab, ridge on a degree-15 polynomial with has risk , between the unpenalized degree-4 polynomial (, risk ) and degree 5 (, risk ): the continuous control does what the discrete one does, without choosing a basis.
The coefficient path
As varies from to , traces a curve from to : the ridge path (or ridge trace, as Hoerl and Kennard called it). Three properties should not be confused:
- The norm decreases; coefficients need not. is monotone (proved above), but each combines components shrinking at different rates and can increase in absolute value or change sign. In diabetes, coefficient
s3goes from with OLS to at . - Training error increases. and each increases with .
- No coefficient becomes zero. is a linear function of , not identically zero except in degenerate cases, so it vanishes only on a hyperplane of 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 comes from.
This interpretation gives meaning. A broad prior (large : little belief that coefficients are small) yields small ; much noise (large : each point is less informative) yields large . And 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 describes uncertainty about given data, not the estimator’s frequentist variability, which is the smaller .
Augmented data. Add fictitious observations: row with response 0, for . With
ridge is ordinary least squares on augmented data. Each fictitious row is a “witness” stating with weight ; with , has full rank even if 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 .
Choosing λ: closed-form cross-validation
All of the above leaves free. The standard choice estimates prediction error for every value on a grid using cross-validation and selects the best. With folds one retrains times per ; with leave-one-out cross-validation (LOOCV), 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 by the prediction made for it by the model without does not change that model. The result is closed-form leave-one-out cross-validation:
where with the intercept. Once the SVD is calculated, each costs : an entire grid costs less than one retraining.
is example ‘s leverage: how much its own prediction moves if its response moves, the same quantity as in regression diagnostics. A point with near 1 pulls the fit toward itself, making its residual deceptively small; dividing by undoes the deception.
At , the point at has : is practically equal at all points except the last few (it is at the penultimate, , and at ), so once standardized it acts almost as an indicator for that point, and the fit follows it with little penalty cost. Its residual is and its leave-one-out residual : over a hundred times larger. Points two through eleven have between and , and the point at has : the endpoints are influential.
GCV: the rotation-invariant version
Generalized cross-validation (GCV) replaces each with its mean . 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, and , ridge coefficients do not change but and LOOCV do; GCV does not. Two practical readings:
- Since for small , : training error plus a degrees-of-freedom penalty, related to the earlier optimism .
- When leverages differ greatly, as with the polynomial, LOOCV and GCV can differ considerably, and GCV may have spurious minima near , 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 , 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 squares divided by ; it is not exact because those terms are dependent, but gives the right scale.
s1 and s2 left: what do two variables with correlation 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 at (nearly least squares) to at , with out of 10; the one-standard-error rule chooses and , at the cost of LOOCV . Standard error at the minimum is enormous, : 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 ( versus for least squares, ): with and , 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 grid from it, and checks against each interpretation in the lesson (linear system, augmented data, posterior mean, and scikit-learn).
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 : linear system, least squares on augmented data, posterior mean with , and Ridge. The table shows what the penalty does with moderate (). Least squares gives s1 (total cholesterol) and s2 (LDL) : two variables correlated at with large opposite effects that largely cancel. At they become and , almost equal: the grouping effect. Variables outside that conflict, such as bmi () or bp (), barely move, and s3 changes sign (). The norm drops from to .
Now validation. The cell calculates LOOCV, its standard error, and GCV for 141 values from the same SVD, and compares them with actual LOOCV, retraining 442 times.
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 and is much faster: timings depend on the machine, but the closed form evaluates 141 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 with , and GCV chooses : nearly least squares. Validation error is around 3000 versus 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 .
Ridge on polynomial features
The second lab revisits the previous lesson’s problem: , 15 equally spaced points in and noise (here with NumPy seed 0). Instead of reducing degree, keep it at 15 and vary . Pipeline order matters: powers first, then standardization, so each power has variance 1 before penalization. Since is known, risk is calculated exactly: .
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 the fit nearly interpolates (training error ), has , coefficient norm 5880 and risk , more than twice the noise. Between and risk stays at to , near the minimum possible plus approximation error for a sine with few degrees of freedom, and falls from to . At the model can no longer follow the sine (, risk ). The best unpenalized polynomial (degree 5) reaches : ridge matches the best degree choice without choosing it.
It remains to choose 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).
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 with and true risk , within of the best table value.
- GCV’s global minimum is spurious. It is at , with , criterion (below the noise itself, , already an alarm), and risk . GCV has a second local minimum at the same as LOOCV. The reason is as before: with 15 points and rank 14, decreasing approaches interpolation, training error and both approach zero, and their ratio can fall. Inspect the whole curve and restrict the grid to clearly below .
- Leverages vary greatly. At , the point at has versus a mean of ; this explains why LOOCV () and GCV () differ so much there, exactly when GCV’s rotational invariance ceases to be a virtue.
Honest LOOCV chooses (, risk ): 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 , 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, , and their corresponds to alpha in Ridge.
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 . 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
More than one answer may be correct.
Step 1 of 4. Why is positive definite?
Step 1 of 4. How does relate to the full problem with data ?
ridge_path(X, y, lambdas), returning (coefs, loocv): coefs of shape (len(lambdas), p) with ridge coefficients for each (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 .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, loocvSummary
- The solution exists and is unique for every , regardless of rank; it equals least squares constrained to a ball , and as 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 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 measure complexity on the parameter-count scale, and training-error optimism is .
- Ridge is MAP estimation with prior and , and least squares on augmented data with rows .
- LOOCV comes from a single fit, ; GCV replaces with their mean. With one SVD, the whole 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 when .