Sub topic 15
Reducing Dimensions with PCA
This chapter assumes you know how to scale numeric features, build a scikit-learn Pipeline, and read a cross-validation score. Principal component analysis (PCA) replaces many correlated columns with fewer new columns that keep most of the variation in the data.
What PCA does
PCA finds new axes, called principal components. Each component is a weighted sum of the original features. The first component points in the direction of greatest variance. Each later component is perpendicular to the earlier ones and captures the most remaining variance. You keep the first k components and drop the rest.
The share of total variance each component keeps is its explained variance ratio. The ratios sum to 1 when all components are kept.
Why scaling comes first
PCA chases variance. A column measured in dollars has a far larger variance than one measured in years, so unscaled data lets the large-unit column dominate the first component. Apply StandardScaler before PCA. PCA also centers the data by subtracting each column's mean.
A worked example
The code below uses the 64-pixel digits dataset. It fits PCA on the training split only, then shows how many components are needed to keep 95% of the variance.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
pca_model = Pipeline([
("scale", StandardScaler()),
("pca", PCA(n_components=0.95)),
("clf", LogisticRegression(max_iter=2000)),
])
pca_model.fit(X_train, y_train)
pca = pca_model.named_steps["pca"]
print("components kept:", pca.n_components_)
print("variance kept:", pca.explained_variance_ratio_.sum().round(3))
print("test accuracy:", pca_model.score(X_test, y_test).round(3))
baseline = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=2000)),
])
print("PCA cv:", cross_val_score(pca_model, X_train, y_train, cv=5).mean().round(3))
print("no PCA cv:", cross_val_score(baseline, X_train, y_train, cv=5).mean().round(3))Passing a float between 0 and 1 as n_components tells PCA to keep just enough components to reach that share of variance. Passing an integer keeps exactly that many. Because PCA sits inside the pipeline, cross-validation refits it on each training fold, so the validation folds never influence the components. This follows the leakage rule from earlier chapters.
Choosing the number of components
Treat k as a hyperparameter. Three common approaches:
- Set a variance target such as 0.90 or 0.95.
- Plot cumulative explained variance and look for the point where the curve flattens.
- Tune
pca__n_componentswith a grid search and pick the value with the best cross-validation score.
Trade-offs and common errors
- Lost interpretability. A component such as "0.4 × age − 0.3 × income + ..." has no plain meaning. Use PCA when prediction matters more than explanation.
- Variance is not relevance. PCA ignores the target. A low-variance direction can be the one that separates your classes, and PCA may discard it.
- Linear only. PCA captures linear structure. Curved structure needs other methods.
- Categorical columns. One-hot columns are poor input for PCA. Apply it to numeric columns, for example inside the numeric branch of a
ColumnTransformer. - Fitting on all data. Running PCA on the full dataset before splitting leaks information from the validation rows.
Exercise
A teammate runs PCA on a table with columns for salary in dollars and age in years, without scaling. The first component is almost identical to salary. Why did this happen, and what is the fix?
Show answer
PCA maximizes variance, and salary in dollars has a far larger variance than age in years, so it dominates the first component. Put StandardScaler before PCA in the pipeline so every column has unit variance.
Exercise
Why should PCA be placed inside the Pipeline passed to crossvalscore, rather than applied to the full dataset first?
Show answer
Inside the pipeline, PCA is refit on each training fold only. Fitting it on the full dataset lets validation rows shape the components, which leaks information and inflates the score.