Skip to main content

17  Ridge regression

17.1 The problem

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.

prostate <- read.table("https://hastie.su.domains/ElemStatLearn/datasets/prostate.data",
                       header = TRUE)
train <- prostate |> filter(train) |> select(-train)
test  <- prostate |> filter(!train) |> select(-train)
x_train <- as.matrix(select(train, -lpsa)); y_train <- train$lpsa
x_test  <- as.matrix(select(test, -lpsa));  y_test  <- test$lpsa

ols <- lm(lpsa ~ ., data = train)
mse_ols <- mean((y_test - predict(ols, test))^2)
mse_ols
[1] 0.521274

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:

\[ \text{mean squared error} = \text{bias}^2 + \text{variance}. \]

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),                              # OLS
    solve(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)
     ols_b1 ols_b2 shrunk_b1 shrunk_b2
mean  0.982  1.006     0.907     0.916
sd    0.854  0.877     0.346     0.360
mse   0.730  0.768     0.129     0.136
Show code
as_tibble(est) |>
  pivot_longer(everything(), names_to = c("method", ".value"), names_sep = "_") |>
  mutate(method = recode(method, ols = "OLS", shrunk = "shrunk (lambda = 5)")) |>
  ggplot(aes(b1, b2)) +
  geom_point(aes(colour = method), alpha = 0.3, size = 0.8, show.legend = FALSE) +
  annotate("point", x = 1, y = 1, shape = 3, size = 4, stroke = 1.2, colour = "black") +
  scale_colour_manual(values = c("steelblue", "firebrick")) +
  facet_wrap(~method) + coord_equal() +
  labs(x = expression(hat(beta)[1]), y = expression(hat(beta)[2]))
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:

\[ \hat\beta^{\text{ridge}} = \arg\min_{\beta} \left\{ \sum_{i=1}^{n} \Big(y_i - \beta_0 - \sum_{j=1}^{p} \beta_j x_{ij}\Big)^2 + \lambda \sum_{j=1}^{p} \beta_j^2 \right\}. \]

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.

  1. 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\).
  2. 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:

X <- scale(x_train); yc <- y_train - mean(y_train)
ridge_beta <- function(lambda) solve(crossprod(X) + lambda * diag(ncol(X)), crossprod(X, yc))
b <- cbind(lm_standardised = coef(lm(yc ~ X))[-1],
           lambda_0 = ridge_beta(0), lambda_10 = ridge_beta(10),
           lambda_100 = ridge_beta(100), lambda_10000 = ridge_beta(1e4))
colnames(b) <- c("lm", "lambda=0", "lambda=10", "lambda=100", "lambda=10000")
rownames(b) <- colnames(x_train)
round(b, 3)
            lm lambda=0 lambda=10 lambda=100 lambda=10000
lcavol   0.716    0.716     0.541      0.240        0.006
lweight  0.293    0.293     0.277      0.165        0.004
age     -0.143   -0.143    -0.086      0.017        0.002
lbph     0.212    0.212     0.192      0.102        0.002
svi      0.310    0.310     0.267      0.156        0.004
lcp     -0.289   -0.289    -0.088      0.084        0.004
gleason -0.021   -0.021     0.027      0.055        0.003
pgg45    0.277    0.277     0.172      0.095        0.003

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\).

lambda_grid <- exp(seq(log(1000), log(0.001), length.out = 100))
ridge_path <- glmnet(x_train, y_train, alpha = 0, lambda = lambda_grid)
Show code
sds <- apply(x_train, 2, sd)
path_df <- as.matrix(ridge_path$beta) |>
  sweep(1, sds, `*`) |>
  as_tibble(rownames = "predictor") |>
  pivot_longer(-predictor, names_to = "step", values_to = "beta") |>
  mutate(log_lambda = log(ridge_path$lambda)[as.integer(str_remove(step, "s")) + 1])
ends <- path_df |> filter(log_lambda == min(log_lambda)) |> arrange(beta)
gap <- 0.04 * diff(range(path_df$beta))          # spread labels that overlap
for (i in seq_len(nrow(ends))[-1]) ends$beta[i] <- max(ends$beta[i], ends$beta[i - 1] + gap)
ggplot(path_df, aes(log_lambda, beta, group = predictor)) +
  geom_hline(yintercept = 0, colour = "grey60") +
  geom_line(colour = "steelblue") +
  geom_text(data = ends, aes(label = predictor), hjust = 1.1, size = 3, colour = "grey30") +
  scale_x_continuous(expand = expansion(mult = c(0.15, 0.02))) +
  labs(x = expression(log(lambda)), y = "standardised coefficient")
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), ]
# A tibble: 1 × 4
  lambda  bias2 variance    mse
   <dbl>  <dbl>    <dbl>  <dbl>
1     12 0.0340   0.0508 0.0848
Show code
bv |>
  pivot_longer(-lambda, names_to = "part") |>
  mutate(part = factor(part, c("mse", "variance", "bias2"),
                       c("MSE", "variance", "bias²"))) |>
  ggplot(aes(lambda, value, colour = part)) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = bv$lambda[which.min(bv$mse)], linetype = "dashed", colour = "grey50") +
  scale_colour_manual(values = c("black", "steelblue", "firebrick")) +
  labs(x = expression(lambda), y = NULL, colour = NULL)
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:

  1. Split the training data at random into \(K\) parts (folds). cv.glmnet() uses \(K = 10\).
  2. For each fold, fit the model on the other \(K - 1\) folds and predict the held-out fold.
  3. Average the squared prediction errors over all folds. Do this for every \(\lambda\).
  4. 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).

The folds are random, so we set the seed.

set.seed(2026)
cv_ridge <- cv.glmnet(x_train, y_train, alpha = 0, lambda = lambda_grid)
c(lambda_min = cv_ridge$lambda.min, lambda_1se = cv_ridge$lambda.1se)
lambda_min lambda_1se 
0.03764936 0.81113083 
Show code
tibble(log_lambda = log(cv_ridge$lambda), cvm = cv_ridge$cvm,
       lo = cv_ridge$cvlo, hi = cv_ridge$cvup) |>
  ggplot(aes(log_lambda, cvm)) +
  geom_errorbar(aes(ymin = lo, ymax = hi), colour = "grey70", width = 0) +
  geom_point(colour = "firebrick", size = 1.2) +
  geom_vline(xintercept = log(c(cv_ridge$lambda.min, cv_ridge$lambda.1se)),
             linetype = "dashed", colour = "grey50") +
  labs(x = expression(log(lambda)), y = "CV mean squared error")
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.

17.3.6 Results on the test men

pred_min <- predict(cv_ridge, newx = x_test, s = "lambda.min")
pred_1se <- predict(cv_ridge, newx = x_test, s = "lambda.1se")
mse_ridge <- c(ols = mse_ols,
               ridge_min = mean((y_test - pred_min)^2),
               ridge_1se = mean((y_test - pred_1se)^2))
round(mse_ridge, 3)
      ols ridge_min ridge_1se 
    0.521     0.505     0.512 
round(cbind(ols = coef(ols), ridge = as.vector(coef(cv_ridge, s = "lambda.min"))), 3)
               ols  ridge
(Intercept)  0.429  0.249
lcavol       0.577  0.535
lweight      0.614  0.610
age         -0.019 -0.017
lbph         0.145  0.142
svi          0.737  0.709
lcp         -0.206 -0.161
gleason     -0.030 -0.004
pgg45        0.009  0.008

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.