We return to the prostate data of Chapter 16: log(PSA) and 8 clinical measurements in 97 men, from Stamey et al. (1989). As before, we fit models on the 67 training men and test them on the other 30.
Ordinary least squares (OLS) with all 8 predictors gives a test mean squared error (MSE) of 0.521. In Chapter 16 we saw that the predictors are correlated, so the variance of the OLS coefficients is inflated. Stepwise selection tried to fix this by dropping predictors, but its choices were unstable.
Can we predict log(PSA) in new men better than OLS, without dropping any predictor?
17.2 Intuitive solution
OLS gives unbiased coefficients. When the predictors are correlated, these coefficients also have a large variance. The error of an estimate has two parts:
An estimate with a small bias and a much smaller variance can have a smaller total error than the unbiased one. One way to reduce variance is to pull every coefficient towards zero. A coefficient held near zero varies less from sample to sample.
We test this idea with the simulation of Chapter 16: two predictors with correlation 0.9, both true slopes equal to 1, and 30 people in each sample. For each of 1000 samples we calculate two estimates. The first is OLS. The second is a “shrunk” estimate, defined in the formal solution. It pulls the coefficients towards zero, and \(\lambda = 5\) sets the strength of the pull.
fit_both <-function(X, y, lambda) { X <-scale(X); y <- y -mean(y) XtX <-crossprod(X); Xty <-crossprod(X, y)c(solve(XtX, Xty), # OLSsolve(XtX + lambda *diag(ncol(X)), Xty)) # shrunk}S <-matrix(c(1, 0.9, 0.9, 1), 2)set.seed(38)est <-t(replicate(1000, { X <-mvrnorm(30, mu =c(0, 0), Sigma = S) y <- X %*%c(1, 1) +rnorm(30, sd =2)fit_both(X, y, lambda =5)}))colnames(est) <-c("ols_b1", "ols_b2", "shrunk_b1", "shrunk_b2")summary_tab <-rbind(mean =colMeans(est), sd =apply(est, 2, sd),mse =colMeans((est -1)^2))round(summary_tab, 3)
Figure 17.1: Estimated slopes from 1000 simulated samples with two predictors (r = 0.9). The cross marks the true values (1, 1). The shrunk estimates sit slightly closer to zero, but their cloud is much smaller.
Figure 17.1 and the table agree. The average of the OLS slopes for \(X_1\) is 0.98, close to the truth. The average of the shrunk slopes is 0.91, so they have a small bias towards zero. The standard deviation falls from 0.85 to 0.35. The mean squared error of the slope falls from 0.73 to 0.13.
17.3 Formal solution
17.3.1 The ridge objective
OLS chooses the coefficients that minimise the residual sum of squares (RSS). Ridge regression adds a penalty on the size of the coefficients:
The first term measures the fit. The second term, the L2 penalty, grows with the size of the coefficients. The tuning parameter \(\lambda \ge 0\) sets its weight.
When \(\lambda = 0\), the penalty has no effect and ridge gives the OLS estimate.
When \(\lambda \to \infty\), the penalty dominates and all slopes go to 0.
Between these limits, the slopes as a whole shrink towards zero. One slope can grow or change sign on the way, but ridge does not hold a slope at exactly zero.
Two practical rules follow from the form of the penalty.
Do not penalise the intercept. \(\beta_0\) is the mean of \(y\) when all predictors are 0. A pull towards 0 has no purpose for it. We centre \(y\) and the predictors, and then the intercept is \(\bar y\).
Standardise the predictors. The penalty adds \(\beta_j^2\) for every predictor. The size of \(\beta_j\) depends on the units of \(X_j\): age in years and age in days give slopes that differ by a factor of 365. If each predictor has standard deviation 1, the penalty treats all predictors equally.
17.3.2 The closed form
Write \(X\) for the \(n \times p\) matrix of standardised predictors and \(y\) for the centred outcome. The objective is \((y - X\beta)^\top (y - X\beta) + \lambda\, \beta^\top \beta\). Its derivative with respect to \(\beta\) is \(-2X^\top(y - X\beta) + 2\lambda\beta\). We set this to zero:
\[
(X^\top X + \lambda I)\,\beta = X^\top y
\quad\Longrightarrow\quad
\hat\beta^{\text{ridge}} = (X^\top X + \lambda I)^{-1} X^\top y.
\]
Compare this with OLS, \(\hat\beta = (X^\top X)^{-1} X^\top y\). When predictors are highly correlated, \(X^\top X\) is close to singular, and its inverse has large entries. This is the variance inflation of Chapter 16. Adding \(\lambda\) to each diagonal entry moves the matrix away from singularity, so the inverse is stable. Even when \(p > n\) and OLS has no unique solution, \(X^\top X + \lambda I\) has an inverse for every \(\lambda > 0\).
We calculate the formula directly on the training men:
The column for \(\lambda = 0\) equals the lm() fit on the standardised predictors. As \(\lambda\) grows, every coefficient moves towards zero. At \(\lambda = 10\,000\), the largest coefficient is 0.006.
Look at lcp. Its OLS coefficient is -0.29, the negative sign that we saw in Chapter 16. At \(\lambda = 100\) it is 0.08, with the same sign as the unadjusted slope. Ridge does more than scale every coefficient by the same factor. The penalty on \(\beta_j^2\) is smaller when correlated predictors share an effect than when one predictor takes all of it.
17.3.3 History
Andrey Tikhonov, a Soviet mathematician, published the same idea in 1963. His paper was about “incorrectly formulated” problems (Soviet Mathematics Doklady, volume 4, pages 1035 to 1038). In those problems a small error in the data gives a large error in the solution. His fix added a penalty on the size of the solution, and mathematicians call it Tikhonov regularisation. In statistics, Hoerl and Kennard (1970) proposed ridge regression for regression with correlated predictors. They proved that some \(\lambda > 0\) always gives a smaller mean squared error than OLS.
17.3.4 Ridge in R: glmnet
The glmnet package (Friedman, Hastie and Tibshirani, 2010) fits ridge, lasso and elastic net. For ridge, set alpha = 0. glmnet() standardises the predictors by default and does not penalise the intercept. It reports coefficients on the original scale of the predictors. Its objective divides the RSS by \(2n\), so its \(\lambda\) is on a different scale from the \(\lambda\) in our formula, with the same role.
glmnet() fits the model for a sequence of 100 values of \(\lambda\). For ridge on these data, the default sequence stops before the best \(\lambda\), so we give our own sequence from 0.001 to 1000. Figure 17.2 shows how each coefficient changes with \(\lambda\).
Figure 17.2: Ridge coefficient paths for the prostate training data, on the standardised scale (coefficient × standard deviation of the predictor). At small λ (left) the coefficients are close to OLS. At large λ (right) they all approach zero together.
17.3.5 The choice of λ: bias against variance
A small \(\lambda\) gives low bias and high variance. A large \(\lambda\) gives high bias and low variance. The best \(\lambda\) lies between the two. We return to the simulation and calculate the bias and variance of the slope estimates for many values of \(\lambda\).
lambdas <-seq(0, 40, by =1)set.seed(42)sims <-replicate(1000, { Xs <-scale(mvrnorm(30, mu =c(0, 0), Sigma = S)) y <- Xs %*%c(1, 1) +rnorm(30, sd =2); y <- y -mean(y)sapply(lambdas, \(l) solve(crossprod(Xs) + l *diag(2), crossprod(Xs, y))[1])})bv <-tibble(lambda = lambdas,bias2 = (rowMeans(sims) -1)^2,variance =apply(sims, 1, var),mse = bias2 + variance)bv[which.min(bv$mse), ]
Figure 17.3: Bias², variance and mean squared error of the ridge slope for X1 in the simulation, as λ grows. The MSE is smallest where a further fall in variance no longer offsets the rise in bias.
In Figure 17.3 the variance falls quickly and the squared bias rises slowly. The MSE is smallest at \(\lambda = 12\), where it is 0.085. At \(\lambda = 0\) (OLS) it is 0.745.
In real data we do not know the true coefficients, so we cannot draw this figure. We estimate the prediction error for each \(\lambda\) by K-fold cross-validation instead:
Split the training data at random into \(K\) parts (folds). cv.glmnet() uses \(K = 10\).
For each fold, fit the model on the other \(K - 1\) folds and predict the held-out fold.
Average the squared prediction errors over all folds. Do this for every \(\lambda\).
Choose the \(\lambda\) with the smallest average error (lambda.min). A more cautious choice is the largest \(\lambda\) whose error is within one standard error of the minimum (lambda.1se).
Figure 17.4: Ten-fold cross-validation error for ridge on the prostate training data. Bars show ±1 standard error. The dashed lines mark lambda.min (left) and lambda.1se (right).
Figure 17.4 has the same shape as Figure 17.3. At the left, the model is close to OLS. At the right, all coefficients are close to zero and the model predicts the mean for every man. The error is smallest between these extremes.
With lambda.min, ridge gives a test MSE of 0.505, against 0.521 for OLS. With the more cautious lambda.1se, the test MSE is 0.512. The coefficient table shows that ridge keeps all 8 predictors. Most coefficients move a little towards zero. The lcp coefficient moves from -0.21 to -0.16, and the small gleason coefficient moves from -0.03 to -0.004.
The improvement here is small. The prostate data have 67 training men and 8 predictors, and the VIFs are moderate, so OLS already does well. The test set has 30 men, and a different random seed can give different folds and a different \(\lambda\). Ridge gives larger gains when \(p\) is close to \(n\) or when the predictors are more strongly correlated, as in the simulation.
17.4 Ridge keeps every predictor
Ridge never sets a coefficient exactly to zero. With 8 predictors this does not matter. With 20,000 genes, a model that keeps all 20,000 is hard to interpret and expensive to measure in new patients. Chapter 18 changes the penalty from \(\beta_j^2\) to \(|\beta_j|\), and this small change makes some coefficients exactly zero.
17.5 Summary
Ridge regression minimises \(\text{RSS} + \lambda \sum_j \beta_j^2\). The solution is \((X^\top X + \lambda I)^{-1} X^\top y\), which exists even when predictors are highly correlated or \(p > n\).
Shrinkage of the coefficients adds a little bias and removes much more variance, so the mean squared error can fall below that of OLS.
Ridge regression needs standardised predictors and an unpenalised intercept. glmnet() does both by default.
The penalty \(\lambda\) comes from K-fold cross-validation with cv.glmnet(x, y, alpha = 0). The folds are random, so the result depends on the seed, and lambda.min must not lie at the end of the grid.