Sub topic 15
Reducing dimensions with PCA
This chapter assumes you know how to build a scikit-learn Pipeline, why scaling matters, and what variance and covariance mean. It covers principal component analysis (PCA), the most common way to reduce the number of numeric columns in a feature matrix.
What PCA does
PCA replaces your original columns with a smaller set of new columns called principal components. Each component is a weighted sum of the original features. The components have three properties:
- The first component points in the direction along which the data varies most.
- Each later component captures the most remaining variance while staying at a right angle (uncorrelated) to the earlier ones.
- Together, all components describe the same data as the original columns. Keeping only the first few gives a compressed approximation.
Internally, scikit-learn centers each column (subtracts its mean) and computes a singular value decomposition (SVD) of the centered matrix. The right singular vectors are the component directions, and the squared singular values divided by n_samples - 1 are the variances along them. Projecting the data onto the first k directions gives the reduced matrix.
PCA is unsupervised. It never looks at the target y. It only asks which directions carry the most variance in X.
When PCA helps
PCA is useful in these situations:
- Many correlated numeric columns. Sensor channels, pixel intensities, and survey items often move together. A few components can hold most of their information.
- Multicollinearity in linear models. Components are uncorrelated, so coefficient estimates become more stable.
- Distance-based models. k-nearest neighbors and clustering suffer when many redundant or noisy dimensions dilute distances.
- Visualization. Projecting to two or three components lets you plot high-dimensional data.
- Speed and memory. Fewer columns make training and prediction cheaper.
PCA is often not worth it for tree ensembles such as random forests and gradient boosting. Trees split on one feature at a time, and rotated components can blur the axis-aligned structure they exploit well. For sparse high-dimensional data, such as TF-IDF text matrices, plain PCA cannot take sparse input because centering would make the matrix dense. Use TruncatedSVD instead.
Scale first
PCA maximizes variance, and variance depends on units. A column measured in dollars (variance in the millions) will dominate a column measured in years (variance in the hundreds). Without scaling, the first component mostly points along the largest-unit column. Standardize numeric features with StandardScaler before PCA unless all columns already share a meaningful common unit.
Look at explained variance
After fitting, explained_variance_ratio_ gives the fraction of total variance each component holds. The cumulative sum tells you how many components you need.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA())
pipe.fit(X)
pca = pipe.named_steps["pca"]
cumulative = np.cumsum(pca.explained_variance_ratio_)
print("original columns:", X.shape[1])
print("components for 95% variance:", int(np.argmax(cumulative >= 0.95)) + 1)
print("first three ratios:", pca.explained_variance_ratio_[:3].round(3))On this 30-column dataset, roughly 10 components are enough to retain 95% of the variance. Plotting the cumulative curve (a "scree" or elbow plot) is a common way to pick a cut-off by eye.
Choosing the number of components
There are three common ways to set n_components:
| Setting | Meaning | Use when |
|---|---|---|
| An integer, such as `n_components=10` | Keep exactly that many components | You need a fixed output size, or a 2D plot |
| A float in (0, 1), such as `n_components=0.95` | Keep the fewest components whose cumulative variance reaches that fraction | You want to preserve a variance budget |
| `n_components="mle"` | Estimate the dimension with Minka's maximum likelihood method | You want an automatic guess (requires `n_samples >= n_features`) |
Treat the number of components as a hyperparameter. Variance explained is only a proxy for usefulness. The directions that matter for predicting y can have small variance, and a high-variance direction can be pure noise. The reliable way to choose is to tune n_components by cross-validation against your real metric.
PCA inside a pipeline
PCA learns its means and directions from data, so it can leak information like any other fitted transformer. If you fit PCA on the full dataset and then cross-validate, the validation folds have already influenced the components. Put PCA in the pipeline so each training fold fits its own.
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
baseline = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
with_pca = Pipeline([
("scale", StandardScaler()),
("pca", PCA(n_components=0.95)),
("clf", LogisticRegression(max_iter=1000)),
])
for name, model in [("baseline", baseline), ("pca 95%", with_pca)]:
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(f"{name}: {scores.mean():.4f} +/- {scores.std():.4f}")
search = GridSearchCV(
with_pca,
param_grid={"pca__n_components": [2, 5, 10, 15, 20]},
cv=5,
scoring="roc_auc",
)
search.fit(X, y)
print("best n_components:", search.best_params_["pca__n_components"])The double underscore in pca__n_components addresses a parameter of the step named pca. The comparison between baseline and with_pca is the honest test of whether PCA helps. On many datasets the two scores are close, and PCA mainly buys speed. It only improves the score when the dropped directions were mostly noise.
Mixed data and `ColumnTransformer`
Apply PCA only to numeric columns. One-hot encoded columns are binary indicators, and rotating them into dense components destroys their meaning and interpretability. In a ColumnTransformer, put scaling and PCA in the numeric branch and leave the categorical branch alone. If you want PCA on a block of related numeric columns only, such as all sensor channels, give that block its own branch.
Interpreting components
Each fitted component is a row of pca.components_, with one weight (loading) per original feature. Large absolute loadings show which original columns drive that component. This helps you name a component, for example "overall size" when many size-related columns load with the same sign.
Interpretation has limits:
- The sign of a component is arbitrary. Refitting may flip it, so do not rely on the sign alone.
- Components mix many features, so the model is harder to explain than one using the original columns.
- If stakeholders need statements such as "income increased the risk", prefer feature selection over PCA.
Gotchas and failure modes
- Fitting before splitting. This leaks information from validation or test rows into the components. Keep PCA inside the pipeline.
- Skipping scaling. The largest-unit column takes over the first component.
- Outliers. PCA is based on variance, so extreme values can pull the leading components toward themselves. Consider clipping or a robust transform first.
- Nonlinear structure. PCA finds only linear directions. Data on a curved surface may need many components. Methods such as kernel PCA or UMAP handle this, with extra cost and tuning.
- Dropping predictive low-variance signal. A rare but strongly predictive feature may live in a low-variance direction and be thrown away. Check against cross-validation.
- Large data. For big matrices,
svd_solver="randomized"orIncrementalPCAreduces compute and memory. - Serving. At prediction time, new rows must go through the same fitted scaler and PCA. Saving the whole pipeline object handles this.
Summary
PCA rotates standardized numeric features into uncorrelated components ordered by variance, and you keep the first few. Scale first, fit it only on training data inside a pipeline, and choose n_components by cross-validation instead of by variance explained alone. Use it on correlated numeric blocks, not on one-hot columns, and not when you need interpretable features.
Exercise
You standardize your data, fit PCA on all rows, keep 95% of the variance, and then run 5-fold cross-validation on the reduced matrix. A colleague says the score is optimistic. Why, and how do you fix it?
Show answer
PCA was fitted on all rows, so the validation folds influenced the means and component directions used to transform the training folds. This is leakage. Fix it by putting the StandardScaler and PCA steps in a Pipeline together with the model and passing that pipeline to crossvalscore, so both are refitted on each training fold only.
Exercise
A dataset has columns "salary" (values around 50,000) and "years_experience" (values around 5). You run PCA without scaling. What will the first component look like, and what do you change?
Show answer
The first component will point almost entirely along "salary", because its variance is far larger, so it mostly reproduces that one column. Add a StandardScaler before PCA so both columns have unit variance and contribute according to their correlation, not their units.