Principal component analysis (PCA)
Compress correlated features into a few directions that keep most of the variance.
Lesson 18 of 6614 minIntermediate
You will learn to
- Explain components as directions of maximum variance
- Read explained variance
- Decide when PCA helps a model
Before this lesson
Intuition
Suppose you record the height of people in centimetres and also in inches. Two columns, but really one piece of information: if you know one, you know the other. A model fed both is not helped by the second column, and a linear model may even become unstable because the columns move together.
Real data is rarely so extreme, but correlated columns are everywhere: the area of a house and its number of rooms, the price of a share at the open and at the close. The cloud of rows looks like a thin tilted ellipse rather than a round ball. Most of the spread lies along one long direction, and only a little lies across it.
Principal component analysis (PCA) finds those directions. The first principal component is the direction along which the rows are most spread out. The second is the most spread-out direction at a right angle to the first, and so on. Each component is a weighted mix of the original columns. If you keep only the first few, you describe each row with fewer numbers while losing as little of the spread as possible.
PCA is unsupervised: it never looks at the target. It answers the question "how can I describe these inputs with fewer numbers?", not "which numbers predict the target?".
Picture it
Replace every point by its shadow on the PC1 line and you have one number per row instead of two. The shadows are spread out almost as much as the original points were, so little is lost. If the cloud were round, no direction would be special and the compression would lose a lot.
The math
Centre every column (subtract its mean). Let be the covariance matrix of the columns: the variances on the diagonal and the covariances between columns off it. The principal components are the eigenvectors of , and the variance along each one is its eigenvalue:
Here is a direction of length 1 (the loadings, one weight per original column), is the variance of the data along it and is the number of columns. The score of a row on component is the dot product of the centred row with .
The explained variance ratio of component is
The sum of all eigenvalues equals the total variance of the columns (the trace of ), so the ratios add up to 1. When you keep the first components, the sum of their ratios is the share of the total variance you keep.
Two consequences matter in practice. First, variance depends on units, so a column measured in thousands dominates one measured in fractions; scale the columns first. Second, components are linear mixes, so PCA cannot straighten a curved cloud, and a component no longer has a plain meaning such as "age".
Worked example
Five rows with two columns, made up for illustration:
| Row | Feature 1 | Feature 2 |
|---|---|---|
| 1 | 2 | 1.8 |
| 2 | 4 | 3.9 |
| 3 | 6 | 6.5 |
| 4 | 8 | 7.6 |
| 5 | 10 | 10.4 |
The means are 6 and 6.04. The covariance matrix of the centred columns (dividing by 4) is
The two columns have variances 10 and 11.05, and the covariance 10.45 shows they move together (their correlation is 0.994). The eigenvalues, computed numerically, are and . Check: they add up to 21.05, the total variance 10 + 11.053.
- Explained variance ratio of PC1: 20.99 / 21.053 = 99.7%.
- Explained variance ratio of PC2: 0.3%.
- The first direction is : almost an equal-weight average of the two columns, as expected for two columns that rise together.
The scores of the five rows on PC1 are -5.83, -2.93, 0.33, 2.51 and 5.92. One number per row now stands in for two, and 99.7% of the variance is kept. Dropping PC2 discards the tiny wobble of each row around the line.
Now imagine the same data with Feature 2 measured in thousandths (all values times 1,000). Its variance becomes about 11 million, PC1 points almost exactly along Feature 2, and the explained ratio for PC1 is near 100% for the wrong reason: the scale, not the structure. This is why a scaling step comes first.
How mlflow does it
The Across several columns section of the Columns part has Combine columns (PCA), which you add with Use. It works on numeric columns and has one parameter, n_components (default 2), the number of components to keep. The step does not scale the columns for you, so scale the columns first. After the step the original columns are replaced by the component columns, which no longer carry the original names. See the preprocessing reference.
Choose how many components with cross-validation: train with a few values of n_components and compare the scores, rather than relying only on a threshold such as "95% of the variance".
Common mistakes
- Running PCA on unscaled columns. The column with the largest units wins. Standardise first.
- Treating explained variance as predictive value. The target never enters PCA. A low-variance direction can be the one that separates the classes. Judge the result by the cross-validated score.
- Fitting PCA on all the data before splitting. The components then contain information from the validation rows. Fit PCA inside each training fold, which a pipeline does for you.
- Expecting PCA to help tree models. Trees split on one column at a time and cope well with correlated columns. PCA helps most with linear models, distance-based models and when you need to reduce the number of columns.
- Trying to explain a model in terms of components. A component is a mix of all columns. If you need clear explanations, prefer feature selection.
Try it in mlflow
Add a PCA step
- Open Pipelines and pick a pipeline with several numeric columns.
- Scale first (press Choose... on each numeric column and pick Standardise, under Scale numbers), because PCA follows the units of the columns.
- Add PCA from the Dimensionality group and set n_components, for example to 5.
- Train from Review & run (Train N models) and compare the run with a pipeline that has no PCA step.