PCA in Practice: Scaling, Components and Pipelines
The previous lesson built PCA from its definition. Using it well on real data comes down to three decisions: whether to standardise the features first, how many components to keep, and where PCA sits in a modelling pipeline. This lesson makes each decision on real data sets and ends with a picture of 1797 handwritten digits in two dimensions.
Decision 1: scale first?
PCA maximises variance, and variance depends on units. If one feature is measured in the thousands and the others in fractions, the first component simply points along the big feature. Standardising (zero mean, unit variance per feature) makes PCA work on correlations instead of covariances, so each feature starts with equal weight. Standardise when features are in different units; keep the raw scale when all features share a unit and their spread matters (pixel intensities, measurements in the same unit).
Decision 2: how many components?
Common rules: keep enough components for a share of the variance (90 % or 95 %), look for an elbow in the explained-variance curve, or, best when PCA feeds a model, choose by the model's cross-validated score. The cumulative explained variance after components is
PCA(n_components=0.95) picks the smallest that reaches 95 %.
import numpy as np
from sklearn.datasets import load_wine, load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold, GridSearchCV
X, y = load_wine(return_X_y=True)
raw = PCA().fit(X)
std = PCA().fit(StandardScaler().fit_transform(X))
print("wine, raw features: PC1 explains", round(raw.explained_variance_ratio_[0], 3),
" largest loading:", load_wine().feature_names[np.abs(raw.components_[0]).argmax()])
print("wine, standardised: PC1 explains", round(std.explained_variance_ratio_[0], 3),
" components for 90 %:", int(np.searchsorted(np.cumsum(std.explained_variance_ratio_), 0.9) + 1), "of 13")
Xd, yd = load_digits(return_X_y=True) # 64 pixel features
cum = np.cumsum(PCA().fit(Xd).explained_variance_ratio_)
for share in [0.5, 0.8, 0.95]:
print(f"digits: {int(np.searchsorted(cum, share) + 1):2d} of 64 components keep {share:.0%} of the variance")
print("PCA(0.95) chooses", PCA(n_components=0.95).fit(Xd).n_components_, "components")
cv = StratifiedKFold(5, shuffle=True, random_state=0)
pipe = make_pipeline(StandardScaler(), PCA(), LogisticRegression(max_iter=2000))
search = GridSearchCV(pipe, {"pca__n_components": [5, 10, 20, 40, 64]}, cv=cv).fit(Xd, yd)
for k, s in zip([5, 10, 20, 40, 64], search.cv_results_["mean_test_score"]):
print(f"logistic regression on {k:2d} components: CV accuracy {s:.3f}")wine, raw features: PC1 explains 0.998 largest loading: proline
wine, standardised: PC1 explains 0.362 components for 90 %: 8 of 13
digits: 5 of 64 components keep 50% of the variance
digits: 13 of 64 components keep 80% of the variance
digits: 29 of 64 components keep 95% of the variance
PCA(0.95) chooses 29 components
logistic regression on 5 components: CV accuracy 0.811
logistic regression on 10 components: CV accuracy 0.884
logistic regression on 20 components: CV accuracy 0.942
logistic regression on 40 components: CV accuracy 0.963
logistic regression on 64 components: CV accuracy 0.969
On raw wine data, PC1 "explains" 99.8 % of the variance and is almost entirely proline, the one feature measured in the hundreds: a statement about units, not about wine. After standardising, PC1 explains 36.2 % and 8 components are needed for 90 %, a much more honest picture of 13 partly correlated measurements.
For digits, 29 of 64 components keep 95 % of the pixel variance. As input to logistic regression, accuracy keeps rising with : 20 components (0.942) lose about 3 points against all 64 (0.969). PCA is a trade: fewer, uncorrelated features (faster, sometimes more stable) against some lost information. Whether the trade is worth it is a question for cross-validation, and here the variance rule (29 components) and the accuracy curve tell similar stories. PCA sits inside the pipeline, so in every fold it is fitted on the training part only.
Decision 3: a picture of the data
Two components are rarely enough to model with, but they make a map. Coloured by digit (which PCA never saw), together with one image reconstructed from 2, 10 and 30 components:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
pca = PCA(n_components=2, random_state=0).fit(X)
Z = pca.transform(X)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
sc = axes[0].scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=6)
axes[0].set_title("1797 digits on the first two components")
axes[0].set_xlabel("PC1"); axes[0].set_ylabel("PC2")
fig.colorbar(sc, ax=axes[0], ticks=range(10))
# reconstruct one image from 2, 10 and 30 components
img = X[0]
for i, k in enumerate([2, 10, 30]):
p = PCA(n_components=k, random_state=0).fit(X)
rec = p.inverse_transform(p.transform(img[None]))[0]
axes[1].imshow(rec.reshape(8, 8), cmap="gray_r", extent=(i * 9, i * 9 + 8, 0, 8))
print(f"{k:2d} components: reconstruction error of image 0 = {np.mean((rec - img) ** 2):.2f}")
axes[1].imshow(img.reshape(8, 8), cmap="gray_r", extent=(27, 35, 0, 8))
axes[1].set_xlim(-1, 36); axes[1].set_ylim(-1, 9); axes[1].axis("off")
axes[1].set_title("k = 2, 10, 30 components, original")
fig.tight_layout() 2 components: reconstruction error of image 0 = 8.41
10 components: reconstruction error of image 0 = 2.23
30 components: reconstruction error of image 0 = 0.37
In the scatter plot some digits (0, 4, 6) form their own regions while others overlap: two linear directions keep only about 28.5 % of the pixel variance. The reconstructions of the first image (a zero) sharpen from a blur at 2 components to nearly the original at 30 (mean squared pixel error 8.41, 2.23, 0.37 on a 0 to 16 scale). For maps that separate classes better, nonlinear methods (t-SNE, UMAP) are common, with a caveat covered in Data Preparation: their distances and cluster sizes are not reliable.
Variants worth knowing
| Variant | Use |
|---|---|
PCA(whiten=True) |
scales components to unit variance; helps some models, loses relative scale |
IncrementalPCA |
fits in batches when the data does not fit in memory |
PCA(svd_solver="randomized") |
fast approximate top- components of large matrices |
TruncatedSVD |
the same without centring, for sparse matrices (text) |
KernelPCA |
nonlinear components via a kernel, as in kernel SVMs |
Pitfalls
- Fitting PCA on train and test together. It leaks; fit it in the pipeline.
- Interpreting a component by its largest loading only. Components mix all features; look at the full loading vector, and remember the sign is arbitrary.
- PCA before tree models. Trees split on single features; rotated features often make them worse, not better.
- Choosing by variance when the goal is prediction. Choose it by the model's validation score.
Practice
- Ten features, all in centimetres and of similar spread, measure the same object. Should you standardise before PCA?
Answer
Usually not. They share a unit and comparable spreads, so their covariance is meaningful, and standardising would give a feature that barely varies the same weight as one that varies a lot. Standardise when units or scales differ.
- Why does the grid search put
StandardScalerandPCAinside the pipeline instead of transformingXdonce?
Answer
Both are fitted transformations. Inside the pipeline they are refitted on the training folds only in every split, so the validation fold's statistics never shape the features, and the cross-validated scores stay honest.
Test yourself
Unscaled wine data gives PC1 99.8 % of the variance, almost all from proline. What is the best interpretation?
- Proline is the only important feature
- Proline's large units dominate the covariance; standardise first
- PCA failed
- The data has one dimension
When PCA feeds a classifier, how should you choose the number of components?
- Always 2
- By the classifier's cross-validated score
- As many as there are classes
- By the largest eigenvalue
Which model usually gains least from PCA-rotated features?
- Logistic regression
- kNN
- A decision tree or random forest
- A linear SVM