Ridge Regression and L2 Regularization
Imagine fitting a linear model with 50 correlated features to only 30 training examples. The Normal Equations and Closed-Form Solution break down. The feature matrix is rank-deficient or nearly so. Ordinary least squares returns wild, unstable coefficients. These coefficients memorize noise instead of signal. This is not a rare pathology. It is the default state of affairs in genomics, text classification, and any pipeline with more engineered features than observations. Ridge regression fixes this by adding a penalty on the size of the coefficients. This trades a small amount of bias for a large reduction in variance. The idea is old. It appears in numerical analysis as Tikhonov regularization decades before it entered statistics. But it remains one of the most-used tools in applied machine learning. It is cheap, differentiable, and has a closed form. It reliably improves generalization when features are correlated or numerous. The big picture is a direct application of the The Bias–Variance Tradeoff. Unconstrained least squares is unbiased but can have enormous variance. This happens when the design matrix is ill-conditioned. Ridge regression shrinks coefficients toward zero, introducing bias. But it often produces a large drop in variance. This lowers total expected test error. This is the same shrinkage principle that underlies ensembling, early stopping, and weight decay in neural networks. This article derives the ridge objective and its closed-form solution. It explains geometrically and algebraically why the penalty stabilizes the estimate. It works a full numerical example by hand. It previews how the L2 penalty differs from the L1 penalty used in Lasso Regression and L1 Sparsity.
- Ridge regression adds an L2 penalty λ‖w‖² to the least-squares loss to shrink coefficients toward zero.
- The closed form is w = (XᵀX + λI)⁻¹Xᵀy, always invertible for λ > 0, unlike plain OLS.
- Shrinkage reduces variance at the cost of some bias, often lowering total test error.
- λ controls model complexity; it is chosen by cross-validation, not by training-set fit.
- Ridge keeps all features (no coefficient is driven exactly to zero) — contrast with Lasso's sparsity.
- Ridge is equivalent to a Gaussian prior on weights in a Bayesian Maximum Likelihood Estimation view.
Ridge regression trades a controlled amount of bias for a reduction in variance by penalizing the squared magnitude of the coefficients, stabilizing least-squares estimation when features are correlated or numerous.
The idea
Ordinary least squares (OLS) chooses weights w to minimize the residual sum of squares ``` L(w) = ‖y − Xw‖² ``` Ridge regression modifies this objective by adding a penalty proportional to the squared L2 norm of the weight vector: ``` L_ridge(w) = ‖y − Xw‖² + λ‖w‖² ``` Here λ ≥ 0 is the regularization strength, a hyperparameter that is not learned from the training loss directly — it is chosen by validation. When λ = 0, ridge regression reduces exactly to OLS. As λ → ∞, every coefficient is forced toward zero and the model collapses to predicting a constant. The penalty term ‖w‖² = w₁² + w₂² + ... + wₚ² is called the L2 penalty or Tikhonov regularization; the resulting shrinkage of coefficients toward zero is called ridge shrinkage. Crucially, the bias term (intercept) is conventionally excluded from the penalty — we want to shrink the slopes that describe feature effects, not force predictions toward zero regardless of the data's mean. In practice this is handled by centering y and each column of X before fitting, so the intercept can be recovered separately and the penalty applies only to the centered coefficients. The name "ridge" comes from the geometry of the solution: adding λI to XᵀX is literally adding a ridge along the diagonal of the matrix before inverting it, which pushes the matrix's eigenvalues away from zero and away from singularity. This single algebraic modification is what makes ridge regression well-defined even when OLS is not — for example, when the number of features p exceeds the number of examples n, or when features are perfectly collinear.
How it works
Step 1 — Center (and optionally scale) the data. Subtract the mean of y and the mean of each column of X. If features are on different scales, standardize each column to unit variance — otherwise the penalty λ‖w‖² unfairly punishes large-scale features more than small-scale ones, since a coefficient's contribution to ‖w‖² depends on the units of its feature.
Step 2 — Form the penalized normal equations. Differentiate the ridge loss with respect to w and set the gradient to zero: ``` ∇_w L_ridge = -2Xᵀ(y - Xw) + 2λw = 0 ⟹ XᵀXw + λw = Xᵀy ⟹ (XᵀX + λI)w = Xᵀy ``` Step 3 — Solve the linear system. ``` w* = (XᵀX + λI)⁻¹ Xᵀy ``` This is the ridge estimator. Unlike the OLS normal equations, (XᵀX + λI) is guaranteed invertible for any λ > 0, because adding λI shifts every eigenvalue of the positive semi-definite matrix XᵀX up by λ, making all eigenvalues strictly positive.
Step 4 — Select λ by cross-validation. Fit the model for a grid of λ values, evaluate held-out error (e.g., via k-fold cross-validation), and pick the λ that minimizes validation error. This step is essential: λ is a hyperparameter controlling the bias-variance tradeoff, and it cannot be tuned by minimizing training loss (training loss is always minimized at λ = 0). ``` function FIT_RIDGE(X, y, lambda):
# X: n-by-p design matrix (rows = examples), y: n-vector of targets x_mean <- column_means(X) y_mean <- mean(y) X_c <- X - x_mean # center features y_c <- y - y_mean # center target I <- identity_matrix(p) A <- transpose(X_c) X_c + lambda I # p-by-p, SPD for lambda > 0 b <- transpose(X_c) * y_c # p-vector w <- SOLVE_LINEAR_SYSTEM(A, b) # e.g. Cholesky decomposition of A intercept <- y_mean - dot(x_mean, w) return (intercept, w) function PREDICT_RIDGE(intercept, w, x_new): return intercept + dot(w, x_new) function CHOOSE_LAMBDA(X, y, lambda_grid, k): best_lambda <- None best_score <- +infinity for lambda in lambda_grid: score <- K_FOLD_CV_ERROR(X, y, lambda, k) # average squared error over folds if score < best_score: best_score <- score best_lambda <- lambda return best_lambda ``` The linear system `A w = b` is solved with Cholesky decomposition rather than by explicitly forming the matrix inverse, both for numerical stability and speed — A is symmetric positive definite whenever λ > 0, which is exactly the setting Cholesky is designed for.
Complexity & correctness
Time complexity. Forming XᵀX costs O(np²) (multiplying an n×p matrix by its transpose). Adding λI is O(p²) and negligible. Solving the p×p system A w = b via Cholesky decomposition costs O(p³). Total training cost is ``` O(np² + p³) ``` which is identical to OLS via the normal equations — the ridge penalty adds no asymptotic overhead, only a diagonal shift. If p ≫ n, an equivalent dual formulation solves an n×n system instead, costing O(n²p + n³); this dual form is exactly the bridge to Kernels and the Kernel Trick, since it expresses the solution purely in terms of inner products XXᵀ. Prediction on a new point costs O(p) per query.
Space complexity. Storing X costs O(np); storing XᵀX (or the Cholesky factor) costs O(p²). Total space is O(np + p²).
Correctness — why (XᵀX + λI) is always invertible. XᵀX is symmetric and positive semi-definite: for any vector v, vᵀ(XᵀX)v = ‖Xv‖² ≥ 0, so all its eigenvalues are ≥ 0. If M has eigenvalue μ ≥ 0 with eigenvector v, then M + λI has eigenvalue μ + λ with the same eigenvector. Since μ ≥ 0 and λ > 0, every eigenvalue of XᵀX + λI is strictly positive, so the matrix is positive definite and therefore invertible. This holds regardless of whether X has full column rank — ridge regression is well-posed even when p > n or columns are exactly collinear, precisely the situations where plain OLS fails.
Correctness — the objective is strictly convex, so the closed form is the unique global minimum. The ridge loss L_ridge(w) = ‖y − Xw‖² + λ‖w‖² is a sum of a convex quadratic (the squared error, convex but only strictly convex along directions where X has rank) and a strictly convex quadratic λ‖w‖² (for λ > 0, strictly convex in every direction). The sum of a convex function and a strictly convex function is strictly convex, so L_ridge has a unique minimizer everywhere, and setting the gradient to zero (as derived above) finds it exactly.
Why shrinkage reduces variance — the bias-variance decomposition. Write the ridge estimator in terms of the eigendecomposition of XᵀX = QΛQᵀ, with eigenvalues d₁ ≥ ... ≥ dₚ ≥ 0. One can show ``` w_ridge = Q diag( d_j / (d_j + λ) ) Qᵀ w_OLS ``` Each OLS component along eigenvector qⱼ is shrunk by the factor dⱼ/(dⱼ + λ) ∈ (0, 1]. Directions with small eigenvalue dⱼ (high-variance, poorly determined directions, exactly where OLS is unstable) are shrunk the most, because dⱼ/(dⱼ + λ) → 0 as dⱼ → 0. Directions with large eigenvalue (well-determined by the data) are barely shrunk. This is exactly the desired behavior: ridge regression suppresses the noisy, ill-determined components of the OLS solution while preserving the well-determined ones, which lowers estimator variance far more than it increases bias whenever the design matrix is ill-conditioned.
Tradeoffs, stated honestly. Ridge never sets a coefficient to exactly zero (unlike Lasso's L1 penalty), so it does not perform feature selection — it shrinks but does not sparsify. Ridge also requires choosing λ, adding a hyperparameter search (though a single cheap trick, generalized cross-validation, can select λ without refitting from scratch for each candidate). And centering/scaling is not optional bookkeeping — skipping it silently distorts which features get penalized most.
Worked example
Consider a tiny regression problem with one feature (already centered, so no intercept needed), n = 4 examples:
| x | y |
|---|---|
| 1 | 2.1 |
| 2 | 3.9 |
| 3 | 6.2 |
| 4 | 7.8 |
First, center x and y. Mean of x is 2.5, mean of y is 5.0.
| xᶜ = x − 2.5 | yᶜ = y − 5.0 |
|---|---|
| −1.5 | −2.9 |
| −0.5 | −1.1 |
| 0.5 | 1.2 |
| 1.5 | 2.8 |
Compute the sufficient statistics: ``` Sxx = Σ(xᶜ)² = 2.25 + 0.25 + 0.25 + 2.25 = 5.0 Sxy = Σ(xᶜ · yᶜ) = (−1.5)(−2.9) + (−0.5)(−1.1) + (0.5)(1.2) + (1.5)(2.8) = 4.35 + 0.55 + 0.60 + 4.20 = 9.70 ``` OLS solution (λ = 0): w_OLS = Sxy / Sxx = 9.70 / 5.0 = 1.94.
Ridge solution at λ = 1: ``` w_ridge = Sxy / (Sxx + λ) = 9.70 / (5.0 + 1) = 9.70 / 6.0 ≈ 1.6167 ``` Ridge solution at λ = 5: ``` w_ridge = 9.70 / (5.0 + 5) = 9.70 / 10.0 = 0.97 ``` Observe the shrinkage factor Sxx/(Sxx+λ) directly: at λ=1 it is 5/6 ≈ 0.833, at λ=5 it is 5/10 = 0.5. This matches the general formula dⱼ/(dⱼ+λ) derived above, with p=1 so d₁ = Sxx = 5.
| λ | shrinkage factor | ŵ | Intercept (recovered) |
|---|---|---|---|
| 0 | 1.000 | 1.940 | 5.0 − 2.5(1.940) = 0.150 |
| 1 | 0.833 | 1.617 | 5.0 − 2.5(1.617) = 0.958 |
| 5 | 0.500 | 0.970 | 5.0 − 2.5(0.970) = 2.575 |
| 50 | 0.0909 | 0.176 | 5.0 − 2.5(0.176) = 4.559 |
As λ grows, the fitted slope shrinks toward zero and the intercept (which is unpenalized) drifts toward the unconditional mean of y, since the model relies less and less on x to explain y. In a real application, λ = 1 vs. λ = 5 vs. λ = 50 would be compared not by inspecting coefficients but by k-fold cross-validation error on held-out points — the "right" λ depends on how noisy the true relationship is, which the training data alone under-determines.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Penalizing the intercept | Applying λ‖w‖² to the bias term forces predictions toward zero regardless of y's mean | Center y and X first; fit intercept separately, unpenalized |
| Not standardizing features | A feature measured in millimeters vs. meters gets penalized very differently | Standardize all features to unit variance before fitting |
| Choosing λ by training error | Training loss is always minimized at λ=0, defeating the purpose of regularization | Select λ via k-fold or leave-one-out cross-validation |
| Expecting sparsity | Ridge shrinks continuously; it never sets a coefficient to exactly 0 | Use Lasso (L1) if feature selection is the goal |
| Data leakage in scaling | Fitting the scaler on the full dataset before splitting leaks test information | Fit mean/scale only on training folds, apply to validation/test |
| Comparing raw coefficients across λ | Coefficients shrink nonuniformly across correlated features, easy to misread | Compare predictive performance, not raw coefficient magnitude, across models |
Pioneers & history
Ridge regression's mathematical machinery predates its name: adding a diagonal term to stabilize an ill-conditioned linear system is a special case of Tikhonov regularization, developed in the Soviet school of numerical analysis and inverse problems for stabilizing solutions to ill-posed integral equations. Statisticians independently rediscovered the same fix for collinear regression design matrices and gave it the name that stuck in machine learning.
Origins · 1 minAndrey Nikolayevich Tikhonov and how this was discovered
Tikhonov developed a general theory for regularizing ill-posed problems — systems where a small change in the input causes a huge, unstable change in the solution. His regularization scheme, adding a penalty term to stabilize an otherwise singular or near-singular linear system, is mathematically identical to the ridge penalty used in regression: both replace an ill-conditioned system Aw = b with the well-conditioned (AᵀA + λI)w = Aᵀb. His work in the 1940s–60s on inverse and ill-posed problems gave the field the general template that statisticians later applied to the specific case of correlated regression features.
Where this matters
Ridge regression (and its L2 penalty in general) is embedded throughout modern machine learning far beyond textbook linear regression. In neural networks, the identical penalty term appears as weight decay, added to the training loss to prevent weights from growing unboundedly and to control overfitting, especially important in deep networks with millions of parameters. In genomics and chemometrics, ridge regression is standard when the number of measured features (genes, spectral bands) vastly exceeds the number of samples, exactly the p ≫ n regime where OLS is singular. Support vector machines and kernel ridge regression use the L2-penalized objective directly, and the dual formulation of ridge regression — expressing the solution through the Gram matrix XXᵀ rather than XᵀX — is the algebraic seed that grows into Kernels and the Kernel Trick, allowing ridge regression to be lifted into high-dimensional or infinite-dimensional feature spaces without ever computing the features explicitly. Recommender systems and collaborative filtering use L2 penalties on latent factor matrices to prevent overfitting to sparse user-item interactions. And in Bayesian terms, ridge regression is exactly the maximum a posteriori estimate under a Gaussian prior on the weights, connecting it directly to Bayesian linear regression and to the broader theme of regularization-as-prior that recurs throughout probabilistic machine learning.
Ask the tutor: How does the shrinkage factor dⱼ/(dⱼ+λ) change if I use a different penalty, like λ‖w‖₁, instead of λ‖w‖²?
Why does ridge regression help when features are highly correlated?
When two features are highly correlated, XᵀX becomes nearly singular, and OLS must divide by a near-zero eigenvalue to fit the data, producing huge, unstable coefficient estimates that can even have the wrong sign. Adding λI raises every eigenvalue by λ, so the smallest (most fragile) eigenvalues are proportionally boosted the most. This directly stabilizes the matrix inversion. The practical effect is that correlated features end up sharing the "credit" for prediction more evenly rather than one feature getting an enormous positive coefficient and its correlated partner an enormous negative one that cancels out on the training set but generalizes terribly.
How should I choose λ in practice?
Standard practice is to fit ridge regression across a logarithmically spaced grid of λ values (e.g., 0.001, 0.01, 0.1, 1, 10, 100) and evaluate each with k-fold cross-validation, selecting the λ with lowest average validation error. A useful shortcut is generalized cross-validation (GCV), an analytic approximation to leave-one-out error that avoids refitting the model n times per λ. Some practitioners use the "one-standard-error rule," picking the largest λ whose validation error is within one standard error of the minimum, favoring simpler, more heavily regularized models when performance is statistically indistinguishable.
Is ridge regression the same as weight decay in deep learning?
They are mathematically very close but not always identical in implementation. Weight decay in classic stochastic gradient descent multiplies weights by (1 − ηλ) at each update step, which is exactly gradient descent on the ridge-penalized loss ‖y−Xw‖² + λ‖w‖². However, in adaptive optimizers like Adam, naively adding the L2 penalty to the loss does not behave the same as true weight decay, because the adaptive learning rate rescales the penalty gradient inconsistently. This distinction motivated "decoupled weight decay" (AdamW), which applies the shrinkage directly to weights rather than through the loss gradient, restoring the intended ridge-like behavior.
Does ridge regression assume the noise is Gaussian?
Not strictly for the least-squares part — minimizing squared error is a reasonable choice under many noise assumptions — but the probabilistic interpretation of ridge regression does rely on Gaussian assumptions. Ridge regression is exactly the maximum a posteriori (MAP) estimate when the likelihood is Gaussian (y | X, w ~ Normal(Xw, σ²I)) and the prior on weights is also Gaussian, w ~ Normal(0, τ²I), with λ = σ²/τ². This connects ridge regression directly to Bayesian linear regression: the ridge penalty encodes a belief that large coefficients are a priori unlikely.
Can ridge regression be used for classification?
Yes, though logistic regression with an L2 penalty (sometimes still loosely called "ridge logistic regression") is more common for classification tasks than applying literal ridge regression to 0/1 labels. The penalty term λ‖w‖² is added to the logistic log-loss instead of squared error, and the optimization is no longer closed-form — it requires iterative methods like gradient descent or Newton's method (IRLS) because the logistic loss is not quadratic. The regularization logic is identical: it shrinks coefficients to reduce variance and prevent overfitting, especially with many or correlated features.
What is the "ridge trace" and is it still used?
The ridge trace, introduced by Hoerl and Kennard, is a plot of each coefficient's value against a range of λ values, similar to the shrinkage curve shown in the worked example above. Historically it was used to visually pick a λ where coefficients "stabilize" after initially swinging wildly at small λ due to collinearity. It remains a useful diagnostic and visualization tool today, though modern practice generally prefers a quantitative criterion — cross-validation error — over the more subjective visual stabilization criterion for actually selecting λ.
Why doesn't ridge regression perform feature selection like Lasso?
The geometric reason lies in the shape of the penalty's constraint region. Ridge's constraint ‖w‖² ≤ t is a smooth sphere (or ellipsoid), while Lasso's constraint ‖w‖₁ ≤ t is a polytope with sharp corners on the coordinate axes. The least-squares loss contours are more likely to first touch the constraint region exactly at a corner (where some coordinates are zero) for the polytope than at any single point on a smooth sphere. This geometric distinction is why L1 penalties tend to produce exactly-zero coefficients while L2 penalties shrink continuously without ever hitting exactly zero, a topic developed fully in Lasso Regression and L1 Sparsity.