Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

🔎 PCA, PCR & PLS

In the last session, we dealt with many or correlated predictors by selecting a subset of them or by shrinking their coefficients. Today we take a third route: we first combine the predictors into a few new variables and then use these for the regression.

Principal Component Analysis

Principal Component Analysis (PCA) is an unsupervised method for dimensionality reduction. It describes a dataset with fewer variables while losing as little information as possible. There is no target: PCA only looks at the variables themselves.

PCA finds new axes for the data, the principal components (PCs). PC1 points in the direction in which the data vary most. PC2 is perpendicular to PC1 and captures the largest remaining variance, and so on. With pp variables, there are at most pp components. Mathematically, the components are the eigenvectors of the covariance matrix of the data.

Each component is a weighted sum of the original variables:

Z1=ϕ11X1+ϕ21X2+⋯+ϕp1XpZ_1 = \phi_{11} X_1 + \phi_{21} X_2 + \dots + \phi_{p1} X_p

X1,…,XpX_1, \dots, X_p are the (centered) variables. The weights ϕ11,…,ϕp1\phi_{11}, \dots, \phi_{p1} are the loadings: they tell us how much each variable contributes to PC1, and together they form its direction (the red arrow in the plot below). If we plug in the values of one observation, we get its score on PC1, i.e. its position along this axis. Keeping only the first few components, we can describe each observation with a few scores instead of all pp values. In scikit-learn, pca.components_ holds the loadings and pca.transform() returns the scores.

Explained variance ratio: [0.931 0.069]
<Figure size 640x480 with 1 Axes>

The two features are strongly correlated, so most of the variation lies along a single diagonal direction (PC1, 93% of the variance). PC2 only captures the remaining 7%. If we kept only PC1, we would describe each observation with one number instead of two and still keep most of the information.

PCA on the Iris dataset

Next, we apply PCA to the Iris dataset (4 features), which you already know from the resampling session. A pairplot shows how the features relate to each other and to the species:

<Figure size 1120x1000 with 20 Axes>

Petal length and petal width separate the three species most clearly. They are also strongly correlated with each other and with sepal length, so the four features contain a lot of redundant information. Let’s fit a PCA with three components:

     sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
PC1               0.36             -0.08               0.86              0.36
PC2               0.66              0.73              -0.17             -0.08
PC3              -0.58              0.60               0.08              0.55

Explained variance ratio: [0.925 0.053 0.017]

How many components?

To decide how many components to keep, we can plot the explained variance of each component (a scree plot) and the cumulative explained variance:

<Figure size 1000x350 with 2 Axes>

A common rule of thumb is to look for the “elbow” in the scree plot, or to keep enough components to reach a certain amount of explained variance (e.g. 80% or 95%). For Iris, one or two components are enough. These rules are only heuristics. When the components are used for a prediction task, as in PCR below, we choose their number with cross-validation instead.

Projecting the data

Finally, we can project the data onto the components with .transform(). This centers the data (subtracts each feature’s mean) and then computes the scores for each component. The result X_pca has the shape (n_samples, 3):

<Figure size 1200x400 with 3 Axes>

The 3D panel is hard to read on a flat page, so here is the same projection as a figure you can rotate and zoom with the mouse. If you rotate it, you will see that almost all of the separation between the species lies along PC1:

Source
Loading...

Note that PCA never saw the species labels. It found a direction that separates them anyway, because here the direction of largest variance happens to be the one that differs between species. As we will see next, this is not guaranteed.

Principal Component Regression

Ridge and Lasso deal with correlated or many predictors by shrinking the regression coefficients. Principal Component Regression (PCR) takes a different approach and changes the predictors themselves:

  1. Run a PCA on the predictors XX and keep the first MM components.

  2. Fit a linear regression of yy on the new variables Z1,…,ZMZ_1, \dots, Z_M instead of the original predictors X1,…,XpX_1, \dots, X_p:

y=θ0+θ1Z1+⋯+θMZM+ϵy = \theta_0 + \theta_1 Z_1 + \dots + \theta_M Z_M + \epsilon

We write θ\theta instead of β\beta for the coefficients, because they belong to the components, not to the original predictors.

The components are uncorrelated with each other, so the problem of correlated predictors disappears, and with M<pM < p we have fewer coefficients to estimate. The number of components MM controls the bias-variance trade-off, just like λ in Ridge and Lasso. With M=pM = p, PCR is identical to ordinary linear regression. With fewer components, the model has less variance but more bias. We choose MM with cross-validation.

PCR works well when the directions of high variance in XX are also the ones that predict yy. But since PCA ignores yy, there is no guarantee for this. To see what can go wrong, let’s have another look at the simulated data from above:

Source
<Figure size 640x480 with 1 Axes>

For this example, we construct the target so that it depends on the low-variance direction, PC2:

<Figure size 1000x300 with 2 Axes>

We now fit a PCR with a single component. A pipeline lets us chain the scaling, the PCA, and the regression into one model:

<Figure size 640x480 with 1 Axes>
PCR R²: -0.026

PCA keeps the direction of highest variance (PC1), but PC2 contains the predictive signal. With one component, PCR therefore does not predict anything: the R² is around 0. If we add the second component, PCR captures the predictive direction and performs much better:

PCR (2 components) R²: 0.673

Of course, with two components out of two features we are back at ordinary linear regression and have not reduced anything. The example is extreme on purpose, but the same thing happens in real data: a component that explains little variance in XX can still be important for predicting yy. You will see an example of this in the exercise.

Partial Least Squares Regression

Partial Least Squares (PLS) regression also builds new components from the predictors, but unlike PCA, it uses the target yy to do so. PLS is therefore a supervised method.

The first PLS component is a weighted sum of the predictors, just like a principal component. The difference lies in how the weights are chosen. PCA picks the direction with the largest variance in XX. PLS picks the direction with the largest covariance with yy: each (standardized) predictor gets a weight proportional to its covariance with yy. The next components are found in the same way on what is left of XX and yy after removing the previous components. Because of this, PLS can find a predictive direction even if it only explains a small part of the variance in XX.

Fitting the model is straightforward. PLSRegression standardizes the predictors by default (scale=True), so we do not need a scaler:

<Figure size 640x480 with 1 Axes>
PLS R²: 0.658

Even with a single component, PLS finds the predictive direction, because it uses the target to build its components. It reaches almost the same R² as PCR with both components.

This does not mean that PLS is always better. Since it uses yy, PLS can adapt more closely to the training data, which means more variance. In practice, PCR and PLS often perform similarly, and in both cases we choose the number of components with cross-validation.

Summary

PCAPCRPLS
TypeUnsupervisedSupervised (regression)Supervised (regression)
ComponentsDirections of maximal variance in XXPrincipal components of XXDirections of maximal covariance with yy
Uses yy to build components?NoNoYes
Tuning parameterNumber of componentsNumber of componentsNumber of components
Loading...
Loading...
Loading...
Loading...

Now it’s your turn: head to the exercise section for Exercise 3, in which you will apply PCA, PCR, and PLS to a medical dataset.