When covariates contain nearly the same information, ordinary least squares can fit the response well while its individual coefficient estimates change sharply from one sample to another. Ridge regression accepts some bias to reduce that instability. This lecture develops that idea from a correlated-covariate example and connects it to the bias-variance trade-off from Week 2.
Learning goals
By the end of this lecture, you should be able to:
explain why nearly redundant covariates make ordinary least squares unstable;
formulate ridge regression with slopes for standardized covariates and an unpenalized intercept;
derive its normal equation and closed-form solution;
interpret shrinkage for orthogonal covariates and for general principal directions;
explain in plain language how shrinkage trades squared bias for lower variance; and
connect ridge shrinkage to the effective-degrees-of-freedom idea from Week 2.
From instability to ridge regression
We begin with the instability caused by nearly redundant covariates, then ask how a penalty can stabilize their fitted coefficients.
Instability with correlated covariates
Ordinary least squares chooses the coefficient vector that fits the observed responses most closely. That sounds like an unqualified advantage. Why would we ever move away from its answer?
Imagine that two covariates record almost the same information. For example, two laboratory instruments may measure nearly the same biological quantity. The data can tell us that their combined contribution matters, but may contain very little information about how that contribution should be divided between the two coefficients. One sample may assign most of the effect to the first covariate; another sample may assign it to the second. Both fitted response vectors can be similar even while the individual coefficients move dramatically.
This is not mainly a story about an optimizer making a mistake. It is an information problem. The least-squares loss has a long, nearly flat valley: moving along the valley changes the coefficients substantially but changes the fitted values very little. Small changes in the response can therefore move the OLS solution a long distance.
Guiding question. Can we accept a small amount of bias in order to make coefficients and predictions much less sensitive to response noise?
Ridge regression answers yes. It shrinks the overall size of the slope vector. Its penalty adds curvature to weak directions, gives a unique solution when least squares is rank deficient, and reduces estimation variance. The cost is shrinkage bias.
Start with centered data
For now, suppose the covariate matrix already has column means zero and unit variances, and the response vector is already centered.1 Here is the number of observations and is the number of covariates. The code calls the centered response y_centered.
The fitted intercept is zero on this centered scale, so we can concentrate on the slopes. The covariates can still be strongly correlated: putting them on a common scale does not remove the instability we want to study.
Let contain the slopes for these standardized covariates. For a fixed penalty , ridge regression minimizes
The first term measures fit to the observed response. The second term penalizes large slopes. Its solution is
We state the solution here so that we can use it in the simulation. We derive it after the simulation makes the stability problem visible.
At , this reduces to OLS when has full column rank. A positive penalizes the size of the slope vector while leaving the intercept unpenalized. The rest of the lecture explains why this deliberate change can improve prediction.
A controlled experiment: stability under correlation
We hold one standardized covariate matrix fixed and repeatedly generate new response noise. The design has rows and covariates. To make the first two raw covariates nearly redundant, begin with independent standard normal variables and construct
where , , and are independent. The remaining four raw covariates are independent standard normal variables. The setup code centers and scales these columns to produce the matrix assumed above. The first two columns remain nearly redundant. We set
Thus, the true mean depends on the sum of the first two covariates but not on their difference.
Each repetition uses the same covariates and the same true mean. Only the random response noise changes. Each repetition also includes a second, independent response at those same covariate values so that we can ask how well a fitted model predicts a response it did not see.
This is fixed-design prediction. The independent response changes the noise while keeping the covariate rows fixed, so it isolates the effect of response noise. It does not evaluate prediction at newly sampled covariate values.
Predict before calculation.
Will the two OLS slopes be stable when the response noise changes?
Will their sum be more stable than either slope separately?
If ridge makes the slopes less variable, must it also improve prediction?
In one repetition, the observed response and an independent test response are
where
The two error vectors are independent and have normal distributions. We repeat this experiment independently 1,000 times while keeping and fixed.
Each generated response can have a nonzero sample mean . The code subtracts that mean to obtain for fitting the slopes, then adds it back for prediction. This fits slopes and one unpenalized intercept, for mean coefficients in total.
We highlight OLS, , and two positive penalties. Within one repetition, every penalty is fitted to the same realized training response and evaluated on the same realized independent test response. Only after all penalties have been compared do we draw a new response pair for the next repetition.
The following R chunk generates and saves the fixed covariates and their true mean response. R and Python then run separate seeded simulations, drawing fresh errors inside each repetition. Their Monte Carlo results need not match numerically, but both should track the same theoretical expectations.
Show the reproducible code
set.seed(43203)n <-80p <-6repetitions <-1000sigma <-1# Make the first two raw covariates nearly redundant.L <-rnorm(n)U1 <-rnorm(n)U2 <-rnorm(n)X_raw <-cbind(x1 = L +0.025* U1,x2 = L +0.025* U2,x3 =rnorm(n),x4 =rnorm(n),x5 =rnorm(n),x6 =rnorm(n))feature_names <-colnames(X_raw)# Center each covariate so its average squared value is one.x_bar <-colMeans(X_raw)X <-sweep(X_raw, 2, x_bar, "-")s <-sqrt(colMeans(X^2))X <-sweep(X, 2, s, "/")beta <-c(1.5, 1.5, 1, 0.75, 0.5, 0)mu <-drop(X %*% beta)# Save the genuine raw covariates. Each language then performs the stated# centering and standardization before fitting.ridge_data <-data.frame(row_id =seq_len(n), X_raw, mu = mu, check.names =FALSE)dir.create("data/week-03", recursive =TRUE, showWarnings =FALSE)write.csv( ridge_data, "data/week-03/fixed-x.csv", row.names =FALSE)singular_values <-svd(X, nu =0, nv =0)$dround(c("Cor(x1, x2)"=cor(X[, 1], X[, 2]),`Largest singular value`=max(singular_values),`Smallest singular value`=min(singular_values),`Condition number`= (max(singular_values) /min(singular_values))^2), 3)
Cor(x1, x2) Largest singular value Smallest singular value
0.999 13.077 0.214
Condition number
3748.488
In this realized design, . The largest and smallest singular values of are approximately and , so the unpenalized quadratic loss has condition number about . For this quadratic loss, the condition number is the largest curvature eigenvalue divided by the smallest. A large ratio means that some coefficient directions are much flatter than others. The correlation, singular values, and loss geometry all express the same point: the two columns are nearly copies, the difference direction is barely visible, and the least-squares loss is extremely elongated.
Each table reports one realized training/test response pair. Its test MSE ordering can be noisy and may differ between R and Python. The repeated loop estimates average behavior: it draws new errors when a repetition begins, then uses that same realized response pair for every penalty before moving to the next repetition.
Stable and unstable coefficient directions
The first two covariates are almost copies. The sum of their coefficients, , controls the well-observed combined effect. The difference of their coefficients, , controls how that effect is divided between the two covariates. The simulation below compares these two directions directly.
# Re-express the first two coefficients in stable and unstable directions.beta_sum <- beta_hat[, 1, selected_grid_positions] + beta_hat[, 2, selected_grid_positions]beta_difference <- beta_hat[, 1, selected_grid_positions] - beta_hat[, 2, selected_grid_positions]method_labels <-c("OLS", expression(lambda ==0.02), expression(lambda ==0.2))old_par <-par(no.readonly =TRUE)par(mfrow =c(1, 2), mar =c(4.5, 4.3, 1.4, 0.8))boxplot( beta_sum,names = method_labels,ylab =expression(hat(beta)[1] +hat(beta)[2]),col =c("#D9E8F5", "#A8CBE5", "#6FA8D1"),border ="#2F6FB3")abline(h =3, lty =2, lwd =2, col ="#C84A16")boxplot( beta_difference,names = method_labels,ylab =expression(hat(beta)[1] -hat(beta)[2]),col =c("#F5DFD5", "#EFB89F", "#E28A66"),border ="#C84A16")abline(h =0, lty =2, lwd =2, col ="#13294B")
Estimates of the combined and difference directions across 1,000 responses at the same fixed design. Dashed lines mark the true values.
Show the reproducible code
par(old_par)
Coefficient estimates across 1,000 responses at the same fixed design. The star is the true coefficient pair and the dashed line preserves their true sum.
Show the reproducible code
# Re-express the first two coefficients in stable and unstable directions.beta_sum = beta_hat[:, 0, selected_grid_positions] + beta_hat[:, 1, selected_grid_positions]beta_difference = beta_hat[:, 0, selected_grid_positions] - beta_hat[:, 1, selected_grid_positions]method_labels = ["OLS", r"$\lambda=0.02$", r"$\lambda=0.2$"]fig, axes = plt.subplots(1, 2, figsize=(9, 4))sum_box = axes[0].boxplot( [beta_sum[:, l] for l inrange(3)], tick_labels=method_labels, patch_artist=True,)for patch, color inzip(sum_box["boxes"], ["#D9E8F5", "#A8CBE5", "#6FA8D1"]): patch.set_facecolor(color) patch.set_edgecolor("#2F6FB3")axes[0].axhline(3, linestyle="--", linewidth=2, color="#C84A16")axes[0].set_ylabel(r"$\widehat\beta_1+\widehat\beta_2$")difference_box = axes[1].boxplot( [beta_difference[:, l] for l inrange(3)], tick_labels=method_labels, patch_artist=True,)for patch, color inzip( difference_box["boxes"], ["#F5DFD5", "#EFB89F", "#E28A66"]): patch.set_facecolor(color) patch.set_edgecolor("#C84A16")axes[1].axhline(0, linestyle="--", linewidth=2, color="#13294B")axes[1].set_ylabel(r"$\widehat\beta_1-\widehat\beta_2$")for axis in axes: axis.spines[["top", "right"]].set_visible(False)fig.tight_layout()plt.show()
Estimates of the combined and difference directions across 1,000 responses at the same fixed design. Dashed lines mark the true values.
Coefficient estimates across 1,000 responses at the same fixed design. The star is the true coefficient pair and the dashed line preserves their true sum.
OLS estimates the combined direction quite precisely, but it estimates the difference direction very poorly. The elongated coefficient cloud makes the flat direction visible: moving one coefficient upward and the other downward changes the individual slopes much more than it changes the fitted response.
Ridge sharply reduces variation in the weak difference direction. The stronger penalty also moves the estimated sum below its true value of 3. The figures therefore show the central trade-off directly: less sampling variation in exchange for systematic shrinkage.
Ridge does not reveal which of two redundant covariates is βreallyβ responsible. It prefers a smaller, more balanced coefficient vector among fits that predict similarly. That is useful for stability, but it is not causal identification.
Understand ridge shrinkage mathematically
Derive the ridge solution
The objective introduced earlier is quadratic in . Differentiate it once and set the gradient to zero:
The second line is the ridge normal equation. Relative to OLS, ridge adds to the slope Gram matrix, increasing each eigenvalue by . Therefore,
For every , the added diagonal term makes the matrix invertible and the solution unique. At , the formula also requires to have full column rank.
The inverse is useful notation, but numerical code should solve the displayed linear system rather than explicitly construct an inverse. The simulation already used a linear-system solve for every penalty. The following calculation takes the fitted coefficient vector at from its final repetition and verifies that it satisfies the normal equation.
Maximum absolute normal-equation residual: 2.842e-14
The near-zero residual is a numerical check of the normal equation. The table also illustrates a substantive point: the estimates need not be individually close to their true coefficients for every realized response. Ridge improves stability and can improve average prediction; it does not guarantee exact recovery from one noisy sample.
What happens at the two ends of the path?
If has full column rank, then
If the design is rank deficient, OLS has multiple coefficient solutions. In that case, the ridge path approaches the Moore-Penrose minimum-norm least-squares solution as .
At the other end,
The fitted centered response approaches zero as the slopes vanish. Adding the response mean back gives the constant on the original response scale.
Orthogonal design: shrink every slope by the same fraction
The easiest case makes shrinkage completely transparent. Suppose the standardized covariates are orthogonal, so
Substituting this identity into the ridge solution gives
Every OLS slope is multiplied by the same number between zero and one. For example, retains of every OLS coefficient; retains one half.
In this orthogonal setting, ridge does not create exact zeros. For finite , the multiplier is positive. A nonzero OLS slope becomes smaller but remains nonzero.
General designs: shrink principal directions
Real covariates are not usually orthogonal. The singular value decomposition provides the right coordinate system. Let the rank- thin SVD be
where , , , and
The values are singular values. Their squares are the positive eigenvalues of . The columns of are coefficient-space directions, and tells us how visible each direction is in the observed design.
Substitute the SVD into the ridge solution:
If , coefficient directions in the null space of do not change the fitted response. Ridge sets those components to zero because any nonzero null-space component would increase the penalty without improving fit. This is how the penalty selects one unique coefficient vector when the design is rank deficient.
For , the coefficient along divides by . If is tiny, even a small noise component is magnified by . This is the algebraic source of unstable OLS coefficients.
Within each observed direction, ridge multiplies the corresponding minimum-norm OLS coefficient by
When is large relative to , is near one and ridge largely preserves that direction. A small singular value marks a weakly identified direction, so the same penalty shrinks it much more strongly.
This factor gives the direction-wise bias-variance trade-off. Under ,
and
When , the variance is , which is large when the design contains little information in direction . A positive penalty reduces this variance, but it also moves the expected coefficient toward zero.
Ridge shrinkage factors along the six singular-vector directions of the fixed design. Directions are ordered from strongest to weakest.
Ridge shrinkage factors along the six singular-vector directions of the fixed design. Directions are ordered from strongest to weakest.
The weakest direction in this design is approximately the difference between the first two covariates. The true signal mainly uses their stable sum. Ridge therefore removes a large amount of noise amplification in a direction that contributes little to the true fitted mean. This alignment is why a modest penalty can help substantially here.
The fitted centered response has an especially simple form:
Ridge keeps every observed singular direction but attenuates it continuously. Unlike lasso, ordinary ridge does not usually set individual slopes exactly to zero.
Connect stability to prediction
Return to the original measurement units
We have seen how ridge stabilizes slopes in a centered, standardized problem. For data recorded in their original units, how do we obtain that setting and translate the fitted model back?
Let contain the raw covariates. For each nonconstant covariate , calculate its training-sample mean and scale:
The centered, standardized covariate matrix has entries
Thus every column of has mean zero and average squared value one. We center the response without dividing by its standard deviation:
These are the transformations used in the simulation code. The numerical size of a raw slope depends on its measurement unit. Converting a covariate from meters to millimeters divides its slope by 1,000 even though the scientific relationship is unchanged. Standardization prevents this arbitrary unit choice from determining how strongly a covariate is penalized.
Leave the intercept unpenalized
Centering separates the baseline level from the slopes. Ridge fits without penalty and applies shrinkage only to the slopes. If every response increases by 100, every fitted value should also increase by 100. The penalty should not resist that translation.
For a raw covariate vector , the fitted value is
where is the fitted slope on the standardized scale at the chosen penalty. Expanding this expression gives slopes and an intercept in the original units:
Divide each fitted slope by its covariateβs scale, then adjust the intercept for the covariate means. The predictions are unchanged:
ImportantPreprocessing is part of the fitted model
The denominator in is a convention. Using changes the numerical meaning of . During cross-validation, all means and scales must be learned inside each training fold. The tuning lecture implements that procedure.
Does greater stability improve prediction?
Smaller slope variance is encouraging, but it is not the final goal. A very large penalty would make the slope estimates almost perfectly stable by making them almost zero; that could badly underfit the true mean. For each repetition, we record the observed training MSE and the observed MSE on its independent test response. We then average those values over the 1,000 repetitions and compare them with their theoretical expectations.
For a fixed , define the ridge smoother matrix, including the unpenalized intercept, as
Then . All expectations in this section condition on the fixed matrix . You do not need to derive the following formulas. Focus on identifying the squared-bias, estimation-variance, and independent-response noise terms and on using them to interpret the risk curves. The training and test risks are
The first term in the test expression is the mean squared bias of the fitted mean vector, the second is estimation variance, and the final is the noise in the independent test response. The formulas explain what the simulation should approach after many repetitions. One realized training or test MSE can still differ from its expectation.
Risk over the practically relevant part of the penalty path, from OLS through lambda = 0.2. Left: mean observed training and independent-test MSE, together with their theoretical expectations. Right: mean squared bias and estimation variance of the fitted mean.
Risk over the practically relevant part of the penalty path, from OLS through lambda = 0.2. Left: mean observed training and independent-test MSE, together with their theoretical expectations. Right: mean squared bias and estimation variance of the fitted mean.
Mean training error rises as the penalty strengthens because ridge places more weight on keeping slopes small relative to minimizing training RSS. That rise is not evidence that the method is failing. It is the visible cost of restricting how closely the model follows an observed response.
Mean independent-test error initially falls. In that region, the variance reduction is worth more than the added squared bias. Eventually the penalty becomes too strong, genuine mean structure is erased, and squared bias dominates. The useful lies between the unstable OLS endpoint and the nearly constant-model endpoint.
For this design, expected test MSE falls from at to at . At the same time, the quadratic loss condition number falls from about to . Increasing the penalty to improves the condition number further, to about , but expected test MSE rises to because squared bias has become too large. Numerical stability and predictive accuracy are related, but they are not the same target.
Bias and variance in plain language. Across repeated response samples, bias is the systematic shift in the average fitted mean caused by shrinkage. Variance is how much the fitted mean changes from one response sample to another. Ridge helps when the decrease in variance is larger than the increase in squared bias. One observed test MSE is noisy; the curve summarizes average behavior over repetitions.
ImportantA U-shape is a result, not a law
The simulation was designed so the true signal has little contribution in its weakest direction, making ridge especially helpful. If important signal lay mostly in a weak singular direction, shrinkage bias would grow sooner. If the design were already well conditioned and were large, OLS variance might be small enough that ridge offers little improvement.
Connecting back to Week 2
Week 2 used a matrix that maps the response vector to fitted values. Ridge has the same linear-smoother structure. The matrix defined in the prediction-risk section includes the fitted response mean in its first term and the shrunken slope contribution in its second. For a fixed , the fitted vector is
For , is not a projection matrix. Ridge still estimates all slopes, but each principal direction responds by only the fraction . This leads to a fractional measure of complexity rather than a count of nonzero coefficients.
Effective degrees of freedom
Week 2 connected model complexity to how strongly fitted values respond to the observed responses. For a linear smoother, that effective complexity is the trace of its smoother matrix. Ridge therefore has
The leading one is the unpenalized intercept. At and full column rank, the total is . As grows, every decreases and the total approaches one. Ridge can therefore have all slopes nonzero while using less than effective degrees of freedom.
Week 2 showed that training error is optimistic because the same responses are used to fit and evaluate a model. Under the fixed- noise model used above, and for a fixed , ridge has the expected gap
This equation compares expectations over repeated observed and independent test responses. A single observed test MSE can be above or below its own expectation. As grows, ridge responds less to training noise, so its effective degrees of freedom and its average optimism both decrease.
WarningA software column named Df may mean something else
Some regularization packages use Df to count nonzero slopes. That count usually remains for ridge. It is not the fractional effective degrees of freedom .
Limitations
Ridge is powerful, but its scope is specific.
It does not repair a wrong mean structure. If the response depends nonlinearly on the covariates and the required features are absent, shrinking a linear fit does not create them.
It does not automatically select variables. Ridge coefficients are usually small but nonzero. If a sparse variable list is required, a different penalty or a separate decision rule is needed.
It does not identify individual causal effects. It stabilizes a preferred combination, often by sharing weight among correlated covariates. That is different from establishing which variable is causal.
It depends on preprocessing and the penalty convention. A numerical value called βlambdaβ is not directly comparable across software until the loss normalization and standardization rules are aligned.
It does not choose its own tuning parameter. Training RSS prefers . Selecting requires an estimate of future prediction performance, such as cross-validation or generalized cross-validation.
The next lecture addresses the computational side: gradient descent, package conventions, cross-validation without preprocessing leakage, the minimum-error and one-standard-error rules, and one final test-set evaluation.
Review
Check your understanding
Two covariates are almost identical. Why can their OLS slopes vary greatly even when the fitted response changes little?
Why do we center the response and leave the intercept outside the ridge penalty?
Why does ridge shrink a singular-vector direction with a small more strongly?
Can ridge produce lower prediction MSE even though its coefficient estimator is biased? Explain what must compensate for the squared bias.
Key ideas
Near redundancy creates a flat loss direction and high OLS coefficient variance.
Ridge adds a quadratic penalty, stabilizing the same directions that are statistically weak.
Standardization gives the penalty a comparable meaning across covariates; the intercept remains unpenalized.
Ridge shrinks singular direction by .
Positive trades added squared bias for lower variance. The penalty must be tuned against a prediction target, not training RSS.
Hoerl and Kennard (1970) introduced ridge estimation for nonorthogonal regression problems and emphasized that a biased estimator can achieve smaller mean squared error.
James, Witten, Hastie, Tibshirani, and Taylor, An Introduction to Statistical Learning, Chapter 6, give an accessible treatment of shrinkage methods. Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning, Chapter 3, provide a more advanced account of linear shrinkage and principal-component directions.