Ridge Regression
What you'll learn
- Why Ordinary Least Squares (OLS) produces massive variance and erratic coefficients when predictors are multicollinear.
- How adding an squared magnitude penalty shrinks coefficients toward zero without discarding features.
- The step-by-step matrix derivation of the closed-form Ridge estimator .
- The mathematical proof of why adding guarantees strict positive definiteness and invertibility.
- The geometric tangency between the elliptical OLS contours and the circular constraint boundary.
- The Bias-Variance Trade-off and why accepting small bias dramatically reduces total prediction error.
- Why feature standardization (-score scaling) is mandatory prior to running Ridge Regression.
Explained in detail
1. The Problem: Why Do We Need Ridge Regression?
In standard Ordinary Least Squares (OLS), our only goal is to minimize training error:
When features are uncorrelated and the sample size is vastly larger than the number of predictors , OLS is optimal. However, fitting the observed training data with zero bias is not the true goal of machine learning. Our ultimate objective is generalization—making accurate predictions on brand new, unseen test data.
When predictors are strongly correlated with one another (multicollinearity), OLS breaks down disastrously.

What Is Multicollinearity?
Suppose we want to predict a person's blood pressure using two features:
- Weight in kilograms ().
- Weight in pounds ().
Because , these two predictors carry virtually identical information. In matrix terms, the columns of the design matrix are nearly linearly dependent.
When you attempt to solve the normal equations:
The matrix becomes ill-conditioned (its determinant is near zero, and its smallest eigenvalue approaches zero).
The variance of the OLS coefficient vector is given by:
When is nearly singular, the entries of its inverse explode to enormous magnitudes!

As shown in the simulation above, running OLS on slightly different random samples of the same population produces wild oscillations: one sample might estimate and , while the next yields and . The model overfits sample noise, resulting in poor out-of-sample predictive performance.
2. Ridge Intuition: Shrinkage and Regularization
How do we tame this extreme sensitivity? We introduce regularization: we restrict how large the coefficients are allowed to grow.
Instead of letting OLS assign massive canceling coefficients ( and ) to collinear features, Ridge Regression imposes a penalty on the total squared magnitude of the coefficient vector.
What Is Shrinkage?
Shrinkage pulls estimated coefficients toward zero. By restraining coefficient sizes:
- The model becomes far less sensitive to tiny fluctuations or measurement noise in the training sample.
- Coefficients become stable and interpretable.
- The model trades a slight increase in training error (bias) for a massive reduction in parameter sensitivity (variance).
What Ridge Is Not: Ridge Regression shrinks coefficients continuously toward zero, but it never sets coefficients exactly to zero. Ridge keeps all features in the model. If you require sparse feature selection (eliminating variables completely), you need Lasso () Regularization.
3. Mathematical Foundation: The Ridge Cost Function
Ridge Regression augments the classical OLS Residual Sum of Squares (RSS) with an penalty (proportional to the squared Euclidean norm of the coefficient vector):
In explicit summation notation across samples and features:
Deconstructing the Objective Function
- (Data Fit): Measures how poorly the model predicts the observed training targets.
- (Model Complexity): Measures the overall size of the coefficient vector. Large slopes receive a heavy quadratic penalty.
- (Tuning Hyperparameter): Controls the balance between fitting the data and keeping coefficients small.
Why Is It Called an Penalty?
The Euclidean length of a vector is its norm: . Ridge penalizes the square of this norm: . Squaring ensures the penalty is smooth, continuously differentiable, and convex, yielding an exact analytical closed-form solution.
4. Step-by-Step Derivation of the Ridge Estimator
Let us derive the exact matrix formula for step by step. (We assume here that features are standardized and the intercept is handled separately).
Step 1: Write the Matrix Objective
Step 2: Expand the Residual Product
Using the matrix transpose identity :
Distributing terms:
Because the scalar quantity equals its transpose :
Step 3: Combine Quadratic Terms
Using the identity matrix , we write . Factoring out :
Step 4: Differentiate with Respect to
Applying standard matrix differentiation rules:
Because is symmetric:
Combining gives the gradient:
Step 5: Set Gradient to Zero & Solve
At the global minimum:
Multiplying both sides by the inverse :
This is the celebrated Closed-Form Ridge Regression Estimator!
5. Why Does Adding Guarantee Invertibility?
Notice the profound difference between OLS and Ridge:
- OLS: requires to be non-singular (fails when or multicollinear).
- Ridge: is always invertible for any !
Proof of Strict Positive Definiteness
For any non-zero vector :
Even if (collinear features), the second term strictly exceeds zero whenever .
In terms of eigenvalues: if the eigenvalues of are , then the eigenvalues of are:
Every single eigenvalue is shifted strictly away from zero by , guaranteeing that the matrix is non-singular, well-conditioned, and invertible.
A Tiny Numerical Demonstration
Consider an extreme case with two identical, perfectly collinear predictors:
Computing :
OLS is completely paralyzed; it cannot invert .
Now apply Ridge with :
The system inverts effortlessly! By symmetry, Ridge divides the influence equally: .
6. The Regularization Parameter & Coefficient Paths
As we vary continuously from to large values, we trace the coefficient shrinkage paths:

- At : Coefficients start at their unconstrained OLS values (often wildly dispersed).
- As increases: All coefficients shrink toward zero at rates governed by the eigenvalues of the feature correlation matrix.
- As : All coefficients asymptotically approach zero, but never become strictly zero at any finite .
7. Geometric Intuition: The Circular Constraint
Ridge Regression can be equivalently formulated as a constrained optimization problem (Lagrangian duality):
where is a budget constraint inversely related to .

In 2D parameter space :
- The OLS Contours (Blue Ellipses): Centered at the unconstrained minimum . Each ellipse represents parameter combinations with equal RSS.
- The Ridge Constraint (Green Circle): The inequality defines a smooth circle (disk) centered at the origin.
- The Ridge Solution (Red Dot): The constrained optimum is the point where the expanding RSS ellipse first touches the circular boundary.
Why Ridge Doesn't Sparsify: Because the constraint boundary is a smooth circle with no sharp vertices on the coordinate axes, the elliptical contour touches the circle along its smooth arc rather than precisely on the axis. Thus, both and remain non-zero!
8. The Bias-Variance Trade-Off
Why would we deliberately add bias to our estimates? The answer lies in the Mean Squared Error (MSE) decomposition of an estimator:

- At (OLS): , but when predictors are correlated, is enormous. Total error is high.
- As increases: We introduce a small amount of bias (coefficients are shrunk toward zero). In exchange, parameter variance drops precipitously.
- At (Sweet Spot): The reduction in variance far outstrips the minor gain in bias, yielding the lowest total prediction error!
- As : Bias becomes dominant (underfitting), causing total MSE to rise again.
9. Feature Standardization: Why Must We Scale Predictors?
The Ridge penalty adds . Notice that the penalty treats all coefficients symmetrically!
Suppose feature is household income in dollars (\80,000x_23$).
- A one-unit change in bedrooms corresponds to a large slope (e.g., ).
- A one-unit change in dollar income corresponds to a tiny slope (e.g., ).
If features are unscaled, the penalty will dwarf ! Ridge will brutally penalize the bedroom coefficient simply because of the units used to measure it.

Standardization Formula (-Score)
Before applying Ridge Regression, every predictor must be scaled to mean and standard deviation :
Never Penalize the Intercept!
The intercept represents the baseline target value when all features are zero. Penalizing would unfairly force predictions toward zero simply because of the vertical origin of . In practice:
- We center the target: .
- Or we omit from the penalty matrix: .
10. Choosing Optimal via Cross-Validation
How do we pick the best value for ? Because is a hyperparameter, it cannot be learned by minimizing training error (which would always choose ).
Instead, we use -Fold Cross-Validation:

- Split training data into equal subsets (folds).
- For a grid of candidate values: train on folds and evaluate validation MSE on the remaining fold.
- Average validation errors across all iterations.
- Select the that achieves the minimum average cross-validation MSE.
Figure 3.4: Ridge Geometry & Smooth Shrinkage
Interactive Ridge Regularization. The Ridge solution is the tangency point where the elliptical OLS contours meet the smooth circular L₂ penalty boundary ||β||₂² ≤ s. As λ increases, the circle shrinks toward zero.
What to try
- Drag the Slider from to :
- In Geometric Contours View: Watch the green circular constraint disk shrink toward the origin. Notice how the red tangency point glides along the trajectory path from toward .
- In Coefficient Shrinkage Paths View: Observe how both and decay smoothly toward zero without ever abruptly dropping to zero.
- Inspect the Live Readouts:
- At : Variance is high (), .
- At : Variance drops by over , while increases only slightly, giving a superior overall model.
- Click the Presets: Switch between Unregularized OLS, Balanced Ridge, and Heavy Regularization.
Key ideas at a glance
Summary Reference Table
Check your understanding
🧩
Ready to test yourself?
15 questions · explanations shown after
Teach & Solidify
Teach This: Ridge Regression (L2 Regularization)
Core Intuition
Ridge prevents multicollinear overfitting by penalizing squared slopes: β̂_Ridge = (XᵀX + λI)⁻¹Xᵀy, trading a tiny pinch of bias for a massive drop in parameter variance.
Key Concepts to Explain
- 1Multicollinearity causes XᵀX to be nearly singular, making OLS coefficients wildly unstable.
- 2Ridge adds λ∑βⱼ² (L₂ penalty), shrinking coefficients smoothly toward zero.
- 3Adding λI shifts all eigenvalues of XᵀX by +λ, guaranteeing invertibility for any λ > 0.
- 4Geometrically, Ridge is the tangency between elliptical OLS contours and a circular constraint disk.
- 5Features must be standardized first, and the intercept β₀ is never penalized.
⚠️ What Most Students Get Confused About
Assuming Ridge performs automatic feature selection. Ridge shrinks coefficients close to zero, but retains every single predictor in the model.
Explain Ridge Regression in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
Author's comprehensive notes covering multicollinearity, closed-form derivations, positive definiteness proofs, and cross-validation workflows.
Full editable LaTeX document including simulation code listings, mathematical callout environments, and figure placement.
Josh Starmer visually illustrates why adding a small penalty λ stabilizes slopes and prevents overfitting on small samples.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Was this clear?