Skip to main content

19  Principal components regression

19.1 The problem

A routine blood panel gives dozens of numbers, but many of them measure the same few things. C-reactive protein, white cell count and ferritin rise with inflammation. Creatinine, urea and cystatin C rise when the kidneys fail. Bilirubin and the liver enzymes rise together when the liver fails. Together, 40 lab values can carry the information of 3 hidden factors.

We use simulated data with this structure. Each of 50 patients has 3 hidden factors (for example inflammation, kidney function and liver function). Each of 40 biomarkers reflects one factor plus its own measurement noise. The outcome depends on the 3 factors only. We also simulate 500 new patients to measure prediction error.

simulate_panel <- function(n) {
  factors <- matrix(rnorm(n * 3), n, 3)
  which_factor <- rep(1:3, length.out = 40)
  X <- sapply(1:40, \(j) 0.8 * factors[, which_factor[j]] + 0.6 * rnorm(n))
  colnames(X) <- sprintf("marker%02d", 1:40)
  y <- drop(factors %*% c(1.5, -1, 0.8) + rnorm(n))
  data.frame(y = y, X)
}
set.seed(9)
panel <- simulate_panel(50)
panel_new <- simulate_panel(500)
dim(panel)
[1] 50 41

How can we predict the outcome from 40 correlated biomarkers in 50 patients?

OLS with 40 predictors and 50 patients is possible, but it estimates 41 coefficients from 50 observations.

ols <- lm(y ~ ., data = panel)
mse_ols <- mean((panel_new$y - predict(ols, panel_new))^2)
mse_ols
[1] 7.470585

The test MSE of OLS is 7.47. The noise in the outcome has variance 1, so the test MSE of a perfect model is close to 1. OLS fits the noise in the 50 patients, and its predictions for new patients are poor.

19.2 Intuitive solution

If 40 biomarkers carry the information of 3 factors, we can summarise the 40 numbers by 3 new numbers and regress the outcome on those. Principal component analysis (PCA) finds such a summary without knowing the factors.

Start with only two biomarkers that measure the same factor. In Figure 19.1 each point is one patient. We want one number per patient instead of two. We draw a line through the centre of the cloud and project each point onto it. The position along the line is the new number. The projection loses the distance from the point to the line, which is the reconstruction error.

set.seed(57)
two <- scale(mvrnorm(100, mu = c(0, 0), Sigma = matrix(c(1, 0.8, 0.8, 1), 2)))
angles <- seq(0, 180, by = 1)
by_angle <- map_dfr(angles, \(a) {
  u <- c(cos(a * pi / 180), sin(a * pi / 180))   # direction of the line
  score <- two %*% u                             # position along the line
  tibble(angle = a, variance = as.numeric(var(score)), recon_error = mean(rowSums((two - score %*% t(u))^2)))
})
by_angle |> slice_max(variance, n = 1)
# A tibble: 1 × 3
  angle variance recon_error
  <dbl>    <dbl>       <dbl>
1    45     1.82       0.175
by_angle |> slice_min(recon_error, n = 1)
# A tibble: 1 × 3
  angle variance recon_error
  <dbl>    <dbl>       <dbl>
1    45     1.82       0.175
Show code
best <- by_angle$angle[which.max(by_angle$variance)]
u <- c(cos(best * pi / 180), sin(best * pi / 180))
proj <- (two %*% u) %*% t(u)
pts <- tibble(x = two[, 1], y = two[, 2], px = proj[, 1], py = proj[, 2])
p1 <- ggplot(pts, aes(x, y)) +
  geom_segment(aes(xend = px, yend = py), colour = "grey70") +
  geom_abline(slope = u[2] / u[1], intercept = 0, colour = "firebrick", linewidth = 1) +
  geom_point(colour = "steelblue", size = 1.2) +
  coord_equal() + labs(x = "biomarker 1", y = "biomarker 2")
p2 <- by_angle |>
  pivot_longer(-angle) |>
  mutate(name = recode(name, variance = "variance of projections",
                       recon_error = "reconstruction error")) |>
  ggplot(aes(angle, value, colour = name)) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = best, linetype = "dashed", colour = "grey50") +
  scale_colour_manual(values = c("firebrick", "steelblue")) +
  labs(x = "angle of the line (degrees)", y = NULL, colour = NULL) +
  theme(legend.position = "bottom")
p1 + p2
Figure 19.1: Two correlated biomarkers (standardised) for 100 simulated patients (left). The red line is the first principal component. The grey segments are the reconstruction errors when we replace each point by its projection. The right panel shows, for lines at every angle, the variance of the projected points (blue) and the mean squared reconstruction error (red). The best line maximises one and minimises the other.

The variance of the projected points is largest at 45 degrees. The reconstruction error is smallest at the same angle, 45 degrees.

The two angles agree because of Pythagoras. For each point, the squared distance from the centre is the sum of the squared projection and the squared reconstruction error. The total of the squared distances does not depend on the line. So a line that keeps more variance loses less in reconstruction. The best line is the first principal component. At this angle, the projections keep 91% of the total variance of the two standardised biomarkers.

19.3 Formal solution

19.3.1 Principal components

Let \(X_1, \dots, X_p\) be the standardised predictors. A principal component is a weighted sum

\[ Z_m = \phi_{1m} X_1 + \phi_{2m} X_2 + \dots + \phi_{pm} X_p, \qquad \sum_{j=1}^{p} \phi_{jm}^2 = 1 . \]

The weights \(\phi_{jm}\) are the loadings. The values of \(Z_m\) for each patient are the scores. The first component \(Z_1\) has the largest variance of all such sums. The second, \(Z_2\), has the largest variance among sums that are uncorrelated with \(Z_1\), and so on. There are \(p\) components in total, and together they keep all the variance of the predictors. The loadings are the eigenvectors of the correlation matrix of the predictors, and the variances of the components are its eigenvalues.

Karl Pearson described the line of best fit to a cloud of points in Pearson (1901). Harold Hotelling gave the method its name and its modern form in Hotelling (1933).

In R, prcomp() calculates the components. Use scale. = TRUE so that each biomarker has standard deviation 1. Without it, a biomarker with large units dominates the first components.

pca <- prcomp(select(panel, -y), scale. = TRUE)
var_explained <- pca$sdev^2 / sum(pca$sdev^2)
round(cumsum(var_explained)[1:6], 3)
[1] 0.265 0.504 0.688 0.716 0.740 0.763
Show code
tibble(component = 1:40, share = var_explained) |>
  ggplot(aes(component, share)) +
  geom_col(fill = "steelblue") +
  scale_y_continuous(labels = scales::percent) +
  labs(x = "principal component", y = "share of variance")
Figure 19.2: Share of the total variance of the 40 biomarkers kept by each principal component (the scree plot). The first three components stand out. The rest are noise of similar size.

The first three components keep 69% of the variance of the 40 biomarkers. Each later component keeps less than 3%. Figure 19.2 shows a clear “elbow” after component 3, which matches the 3 hidden factors.

19.3.2 Principal components regression

Principal components regression (PCR) has two steps:

  1. Calculate the first \(M\) principal components \(Z_1, \dots, Z_M\) of the predictors.
  2. Fit an OLS regression of \(y\) on \(Z_1, \dots, Z_M\).

The model has \(M\) slopes instead of \(p\). If a few components hold most of the information in the predictors, PCR estimates a few coefficients with low variance. Maurice Kendall and Harold Hotelling suggested regression on principal components in 1957 (Jolliffe, 1982). Massy (1965) gave the first full treatment, for exploratory research with many correlated predictors.

The fitted model is still a linear model in the original predictors. Substitute the definition of each \(Z_m\):

\[ \hat y = \hat\theta_0 + \sum_{m=1}^{M} \hat\theta_m Z_m = \hat\theta_0 + \sum_{j=1}^{p} \Big( \sum_{m=1}^{M} \hat\theta_m \phi_{jm} \Big) X_j . \]

PCR gives one coefficient for every predictor, but these coefficients are constrained to come from \(M\) directions. When \(M = p\), there is no constraint, and PCR gives exactly the OLS fit.

19.3.3 The choice of M by cross-validation

The pls package fits PCR with pcr(). With validation = "CV", it calculates the 10-fold cross-validated error for every \(M\) from 0 to \(p\). The folds are random, so we set the seed.

set.seed(109)
pcr_fit <- pcr(y ~ ., data = panel, scale = TRUE, validation = "CV")
cv_rmsep <- RMSEP(pcr_fit, estimate = "CV")$val[1, 1, ]
best_m <- which.min(cv_rmsep) - 1          # the first entry is M = 0
c(best_M = unname(best_m), one_sigma_M = selectNcomp(pcr_fit, method = "onesigma"))
     best_M one_sigma_M 
          3           3 

RMSEP() returns the root mean squared error of prediction. The cross-validated error is smallest at \(M = 3\). The one-standard-error rule, which chooses the smallest \(M\) whose error is within one standard error of the minimum, gives the same answer. In this sample, cross-validation recovers the 3 hidden factors from the data alone.

One sample can give a lucky result. We repeat the full experiment on 50 new simulated panels, each with its own 50 training patients and 500 test patients.

set.seed(2026)
reps <- map_dfr(1:50, \(r) {
  train <- simulate_panel(50); test <- simulate_panel(500)
  fit <- pcr(y ~ ., data = train, scale = TRUE, validation = "CV")
  m <- unname(which.min(RMSEP(fit, estimate = "CV")$val[1, 1, ]) - 1)
  tibble(M = m,
         pcr = mean((test$y - predict(fit, test, ncomp = max(m, 1)))^2),
         ols = mean((test$y - predict(lm(y ~ ., data = train), test))^2))
})
table(reps$M)

 2  3  4  5  6  7  8  9 10 12 15 16 17 18 26 
 3 15  4  2  6  7  1  3  1  2  2  1  1  1  1 
round(colMeans(reps[, c("pcr", "ols")]), 2)
 pcr  ols 
1.35 7.12 

Cross-validation picks exactly 3 components in 15 of the 50 panels, and between 2 and 5 in 24. The choice varies from sample to sample. The gain in prediction is stable, with an average test MSE of 1.35 for PCR and 7.12 for OLS.

We now check this choice with the 500 new patients. For each \(M\) from 1 to 40, we predict the new patients and calculate the test MSE.

test_mse <- sapply(1:40, \(m) mean((panel_new$y - predict(pcr_fit, panel_new, ncomp = m))^2))
round(c(M1 = test_mse[1], M3 = test_mse[3], M10 = test_mse[10], M30 = test_mse[30], M40 = test_mse[40],
        ols = mse_ols), 2)
  M1   M3  M10  M30  M40  ols 
2.08 1.22 1.24 1.98 7.47 7.47 
Show code
tibble(M = 1:40, `test (500 new patients)` = test_mse, `cross-validation` = cv_rmsep[-1]^2) |>
  pivot_longer(-M) |>
  ggplot(aes(M, value, colour = name)) +
  geom_line(linewidth = 1) + geom_point(size = 1) +
  geom_vline(xintercept = best_m, linetype = "dashed", colour = "grey50") +
  scale_colour_manual(values = c("firebrick", "steelblue")) +
  labs(x = "number of components M", y = "mean squared error", colour = NULL) +
  theme(legend.position = "bottom")
Figure 19.3: Mean squared error against the number of components M: 10-fold cross-validation in the 50 training patients (red) and the test error in 500 new patients (blue). Both are lowest near M = 3. At M = 40 PCR equals OLS, and the test error climbs back to the OLS value.

With \(M = 3\), the test MSE is 1.22. That is close to the noise variance of 1, the best that any model can do. With \(M = 1\), the model misses two of the factors and the test MSE is 2.08. As \(M\) grows past 3, the extra components add mostly noise. The test error stays almost flat at first (1.24 at \(M = 10\)), and then rises as the last components enter (1.98 at \(M = 30\)). At \(M = 40\) the test MSE is 7.47, the same as OLS (7.47), as the algebra above requires.

19.3.4 Components that ignore the outcome

PCA chooses the components from the predictors alone, without \(y\). PCR works well when the directions of largest variance in the predictors are also the directions that predict the outcome. In the biomarker panel this is true by design, because the factors cause both the variance of the biomarkers and the outcome.

In real data it can be false. A direction with small variance can be the one that predicts the outcome, and PCR then discards it with the noise.

The prostate data of Chapter 16 show this. We fit PCR to the 67 training men.

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)

set.seed(13)
pcr_prostate <- pcr(lpsa ~ ., data = train, scale = TRUE, validation = "CV")
cv_prostate <- RMSEP(pcr_prostate, estimate = "CV")$val[1, 1, ]
round(cv_prostate, 3)
(Intercept)     1 comps     2 comps     3 comps     4 comps     5 comps 
      1.217       0.918       0.887       0.809       0.801       0.818 
    6 comps     7 comps     8 comps 
      0.838       0.802       0.758 
best_prostate <- which.min(cv_prostate) - 1
best_prostate
8 comps 
      8 
mse_pcr <- sapply(1:8, \(m) mean((test$lpsa - predict(pcr_prostate, test, ncomp = m))^2))
mse_ols_prostate <- mean((test$lpsa - predict(lm(lpsa ~ ., data = train), test))^2)
round(c(pcr_chosen = mse_pcr[best_prostate], ols = mse_ols_prostate), 3)
pcr_chosen        ols 
     0.521      0.521 
round(cor(pcr_prostate$scores[, 1:8], train$lpsa)[, 1], 2)
Comp 1 Comp 2 Comp 3 Comp 4 Comp 5 Comp 6 Comp 7 Comp 8 
  0.67  -0.24   0.30   0.12   0.04  -0.10   0.21  -0.18 
round(explvar(pcr_prostate), 1)   # % of predictor variance per component
Comp 1 Comp 2 Comp 3 Comp 4 Comp 5 Comp 6 Comp 7 Comp 8 
  42.8   20.4   13.0    7.7    5.7    4.7    3.5    2.2 

Cross-validation keeps all 8 components, so PCR is the same model as OLS, with a test MSE of 0.521. The last line of the output gives the reason. The correlation between the outcome and each component’s scores does not fall steadily with the component number. Component 1 has a correlation of 0.67 with log(PSA). Component 7 keeps only 3.5% of the predictor variance, but it still has a correlation of 0.21. A PCR model with fewer components loses this information about the outcome.

The penalised methods of Chapter 17 and Chapter 18 use \(y\) when they shrink. On the same split they gave a slightly smaller test MSE than OLS. Ridge is related to PCR. Ridge shrinks the coefficient of each principal component direction, and it shrinks the directions with small variance most. PCR keeps the first \(M\) directions in full and drops the rest.

19.4 Partial least squares

Partial least squares (PLS) also builds \(M\) weighted sums of the predictors, and it chooses the weights with the outcome in view. The first PLS direction gives each predictor a weight in proportion to its covariance with \(y\). Later directions do the same for the part of \(y\) and \(X\) that the earlier directions leave unexplained.

Herman Wold developed the PLS idea for econometrics in the 1960s and 1970s. In 1983 his son Svante Wold, with Harald Martens and Herman Wold, turned it into PLS regression for chemistry. In chemistry, spectra have hundreds of correlated wavelengths (Wold et al., 2001).

The pls package fits it with plsr(), with the same arguments as pcr().

set.seed(13)
pls_prostate <- plsr(lpsa ~ ., data = train, scale = TRUE, validation = "CV")
cv_pls <- RMSEP(pls_prostate, estimate = "CV")$val[1, 1, ]
best_pls <- unname(which.min(cv_pls) - 1)
mse_pls <- mean((test$lpsa - predict(pls_prostate, test, ncomp = best_pls))^2)
c(components = best_pls, test_mse = round(mse_pls, 3))
components   test_mse 
     6.000      0.521 

On the prostate data, cross-validation chooses 6 PLS components, with a test MSE of 0.521. PCR needed all 8 components to reach 0.521. PLS uses \(y\), so it reaches a similar test MSE with fewer directions. On these data, neither method predicts better than OLS.

19.5 Summary

  • PCA replaces \(p\) correlated predictors by uncorrelated components \(Z_m = \sum_j \phi_{jm} X_j\). The first component is the direction of largest variance, which is also the direction of smallest reconstruction error.
  • PCR regresses \(y\) on the first \(M\) components. The number \(M\) comes from cross-validation with pcr(y ~ ., data, scale = TRUE, validation = "CV"). With \(M = p\), PCR is OLS.
  • PCR works when a few high-variance directions in the predictors also drive the outcome, as with biomarkers that reflect a few hidden factors.
  • The components of PCR ignore \(y\). If the outcome depends on a low-variance direction, PCR gives no gain, as in the prostate data.