Sub topic 8
Choosing how many components to keep
This chapter assumes you can fit a PCA with scikit-learn, and that you know what explained variance and reconstruction mean. Here you decide how many components, called k, to keep.
The trade-off
Each extra component adds a little more variance and a little more complexity. Keeping too few discards real structure. Keeping too many keeps noise and defeats the purpose of reducing dimensions. No rule is correct for every dataset, so you pick a rule that fits your goal.
Rule 1: a variance threshold
Compute the cumulative explained variance and keep the smallest k that reaches a target such as 90% or 95%.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_digits(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
pca = PCA().fit(X_std)
cum = np.cumsum(pca.explained_variance_ratio_)
for target in (0.80, 0.90, 0.95):
k = int(np.searchsorted(cum, target)) + 1
print(f"{target:.0%} of variance needs {k} components")np.searchsorted returns the first index where the cumulative sum reaches the target. Indexes start at 0, so add 1 to get a count.
scikit-learn offers a shortcut. PCA(n_components=0.95) picks k for you. The fitted object stores the result in n_components_.
Rule 2: the elbow in the scree plot
Plot the eigenvalues, or the explained variance ratios, in decreasing order. Often the curve drops steeply and then flattens. The bend is called the elbow. Components after it each add little, so you keep those before it.
The elbow is a judgment call. Many real datasets have a smooth curve with no clear bend, and two people can read different elbows from the same plot.
Rule 3: reconstruction error
Project the data to k components, map it back, and measure the mean squared error. The error falls as k grows. Choose the smallest k whose error you can accept.
from sklearn.decomposition import PCA
for k in (5, 10, 20, 40):
p = PCA(n_components=k).fit(X_std)
X_back = p.inverse_transform(p.transform(X_std))
mse = ((X_std - X_back) ** 2).mean()
print(k, round(float(mse), 4))The mean squared error equals the variance you discarded, divided by the number of features. So this rule and the variance threshold measure the same thing in different units.
Rule 4: judge by the downstream task
If the components feed a classifier or a regression, the best k is the one that gives the best validation score. Put PCA inside a pipeline, so each cross-validation fold fits its own PCA. Then search over n_components with GridSearchCV. This rule is the most reliable when you have a clear metric, but it costs more compute.
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA(), LogisticRegression(max_iter=2000))
grid = GridSearchCV(pipe, {"pca__n_components": [5, 10, 20, 40]}, cv=5)
grid.fit(X, y)
print(grid.best_params_, round(grid.best_score_, 3))Common errors
- Choosing k on the full dataset, then evaluating a model on a test split. Fit PCA on training data only.
- Skipping standardization. Features with large scales dominate the variance, so the cumulative curve misleads you.
- Treating 95% as a law. For noisy data, 95% may keep mostly noise. For some tasks, 70% is enough.
Exercise
On a standardized dataset, 12 components reach 90% of the variance and 25 reach 95%. You are feeding the components to a classifier. How do you decide between them?
Show answer
Treat 12 and 25 as candidates, not answers. Put PCA in a pipeline and cross-validate both values of n_components (and others in between). Pick the smallest k whose validation score is close to the best, since a smaller k is cheaper and less prone to overfitting.