Sub topic 8
Choosing how many components to keep
This chapter assumes you can fit PCA with scikit-learn and read explained_variance_ratio_. It also assumes you know that principal components are ordered by decreasing variance, and that the data should be centered, and usually standardized, before PCA. The question here is how many components, k, to keep out of p features.
Why there is no single right answer
PCA gives you all p components, ordered by variance. Choosing k means deciding where to cut that list. Keep too few and you discard structure. Keep too many and you keep noise, which defeats the point of reducing dimensions.
The right k depends on what you want the components for:
- Compression or reconstruction: you want a bounded loss of information.
- Visualization:
kis fixed at 2 or 3 by the display. - Preprocessing for a model: you want the
kthat gives the best held-out score. - Denoising or exploration: you want the number of components that carry real signal.
Each goal suggests a different rule. The rules below run from simple heuristics to methods that test against data.
The link between variance and error
Suppose the data are centered and you keep the top k components. The total squared reconstruction error over all entries equals (n - 1) times the sum of the discarded eigenvalues. So the fraction of variance you drop is the fraction of squared error you incur. This is why a variance threshold is a sensible compression rule. It bounds reconstruction error directly.
Variance is not the same as usefulness, though. A low-variance direction can separate two classes perfectly, and a high-variance direction can be pure measurement noise. Keep this in mind for the heuristics below.
Rule 1: cumulative explained variance threshold
Compute the cumulative sum of explained_variance_ratio_ and take 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, y = 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, 0.99):
k = int(np.searchsorted(cum, target) + 1)
print(f"{target:.0%} of variance needs k = {k} of {X_std.shape[1]}")np.searchsorted returns the first index where the cumulative sum reaches the target. Adding 1 converts that index to a count.
The same rule is built into scikit-learn. A float between 0 and 1 for n_components means "keep the smallest number of components that reaches this fraction":
pca95 = PCA(n_components=0.95).fit(X_std)
print(pca95.n_components_)The threshold itself is a convention, not a theorem. Choose it by asking what error you can tolerate, not by habit.
Rule 2: the scree plot and the elbow
A scree plot shows eigenvalues (or explained variance ratios) against component number. Where the curve flattens, the remaining components add little. The point of the bend is the "elbow", and you keep the components before it.
The elbow is subjective. Many real datasets have a smooth decay with no clear bend, and different people will pick different points. A log scale on the y-axis sometimes makes the bend easier to see. Use the scree plot to look at the data, and don't treat it as a decision procedure.
Rule 3: the Kaiser criterion
When the features are standardized, each has variance 1. A component with eigenvalue below 1 then explains less variance than a single original feature. The Kaiser criterion keeps only components with eigenvalue greater than 1.
eig = pca.explained_variance_
print("Kaiser k =", int(np.sum(eig > 1)))This rule only makes sense on standardized data, where the average eigenvalue is exactly 1. It also tends to keep too many components when p is large and too few when p is small. Treat it as a quick sanity check.
Rule 4: parallel analysis
Parallel analysis asks whether a component explains more variance than you would expect from data with no correlation structure. You build a null dataset by shuffling each column independently, which keeps each feature's distribution but destroys the relationships between features. Then you fit PCA to many such shuffled copies and compare the real eigenvalues to the null ones. Keep components whose eigenvalue exceeds, say, the 95th percentile of the null.
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)
rng = np.random.default_rng(0)
def eigenvalues(Z):
return PCA().fit(Z).explained_variance_
observed = eigenvalues(X_std)
n_shuffles = 50
null = np.empty((n_shuffles, X_std.shape[1]))
for i in range(n_shuffles):
shuffled = np.column_stack([rng.permutation(col) for col in X_std.T])
null[i] = eigenvalues(shuffled)
threshold = np.percentile(null, 95, axis=0)
print("Parallel analysis k =", int(np.sum(observed > threshold)))This costs n_shuffles extra PCA fits, but it is more principled than the elbow. It answers a specific question: which components beat chance?
Rule 5: cross-validate against the downstream task
If PCA feeds a supervised model, the best k is the one that gives the best held-out performance. Treat n_components as a hyperparameter and put PCA inside a pipeline, so scaling and PCA are refit on each training fold.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
pipe = Pipeline([
("scale", StandardScaler()),
("pca", PCA()),
("clf", LogisticRegression(max_iter=2000)),
])
grid = GridSearchCV(
pipe,
param_grid={"pca__n_components": [5, 10, 20, 30, 40, 64]},
cv=5,
)
grid.fit(X, y)
print(grid.best_params_)
print(round(grid.best_score_, 3))
for k, score in zip(grid.cv_results_["param_pca__n_components"],
grid.cv_results_["mean_test_score"]):
print(k, round(score, 3))Look at the whole table, not only the winner. If 20 and 40 components score within noise of each other, prefer 20. A smaller model is cheaper and often more stable.
Choosing among the rules
The diagram shows one way to decide which rule to start with.
| Rule | Needs | Strength | Weakness |
|---|---|---|---|
| Variance threshold | Nothing else | Directly bounds reconstruction error | Threshold is arbitrary |
| Scree elbow | A plot | Shows the shape of the spectrum | Subjective, may have no elbow |
| Kaiser (eigenvalue > 1) | Standardized data | Instant | Over- or under-counts |
| Parallel analysis | Shuffled fits | Tests against chance | Extra compute, assumes noise is independent |
| Cross-validation | A supervised target | Optimizes what you care about | Only valid for that task and model |
Other scikit-learn options
PCA(n_components="mle") uses Minka's maximum likelihood estimate to pick k. It requires svd_solver="full" and at least as many samples as features. It assumes a probabilistic PCA model with Gaussian noise, so use it with that assumption in mind.
Common errors
- Confusing the integer and the float.
n_components=1keeps one component.n_components=1.0is a float, so scikit-learn reads it as a variance fraction (which for 1.0 asks for all the variance). Check the type you pass. - Applying a threshold to unscaled data. If one feature has a huge scale, it dominates the first component, and a few components reach 95%. Standardize first unless the original units are meaningful.
- Choosing
kon all the data before a split. Fitting the scaler and PCA on the full dataset leaks test information into the choice. Fit inside a pipeline or on the training set only. - Reading variance as importance. A component that explains 1% of the variance may still be the one that separates your classes. Check with the downstream task.
- Over-reading the elbow. If two reasonable readers pick different elbows, add another criterion instead of arguing.
- Forgetting the cap.
kcannot exceedmin(n_samples, n_features). With few samples, the spectrum has fewer meaningful components than features.
Exercises
Exercise
A standardized dataset has 10 features. The explained variance ratios of its components are 0.45, 0.25, 0.12, 0.08, 0.04, 0.03, 0.01, 0.01, 0.005, 0.005. What is the smallest k that keeps at least 90% of the variance, and how much reconstruction error (as a fraction of total variance) remains?
Show answer
The cumulative sums are 0.45, 0.70, 0.82, 0.90, so k = 4 reaches 90%. The remaining error is the discarded variance, 1 - 0.90 = 0.10, or 10% of the total variance.
Exercise
You fit StandardScaler and PCA(n_components=0.95) on the full dataset, then split into train and test sets and train a classifier on the PCA scores. Name the problem and give the fix.
Show answer
The scaler and PCA were fitted using test rows, so information about the test set leaked into the features and into the choice of k. Split first, then fit the scaler and PCA on the training data only, ideally inside a Pipeline passed to cross-validation, and apply the fitted transforms to the test set.
Exercise
Why does the Kaiser criterion (keep eigenvalues greater than 1) require standardized features?
Show answer
Standardizing gives every feature variance 1, so the eigenvalues of the correlation matrix average exactly 1. A component with an eigenvalue below 1 then explains less than a single original feature. On unscaled data the eigenvalues depend on the units, so the threshold of 1 has no meaning.