Sub topic 13
Limitations and common pitfalls
This chapter assumes you can run PCA with NumPy or scikit-learn, and that you know what the covariance matrix, explained variance and a projection are. It covers where PCA gives misleading results and how to avoid those results.
PCA is a linear, unsupervised method. It finds orthogonal directions that capture the most variance, and it is only as good as that goal fits your problem. Most failures come from one of four mismatches:
- The scale of the features.
- The shape of the data.
- The meaning of "variance".
- The workflow around the fit.
Pitfall 1: Features on different scales
PCA maximizes variance, and variance depends on units. A feature measured in grams has a larger variance than the same feature in kilograms. Without standardization, the feature with the largest numeric range dominates the first component, whether or not it carries useful structure.
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_wine(return_X_y=True)
raw = PCA(n_components=2).fit(X)
std = PCA(n_components=2).fit(StandardScaler().fit_transform(X))
print("raw: ", raw.explained_variance_ratio_)
print("standardized:", std.explained_variance_ratio_)On the wine data, the proline feature has values in the hundreds while most others are below 10. Without scaling, PC1 explains over 99% of the variance and is essentially the proline column. After standardization, the variance spreads across several components.
Standardizing is not always correct. If all features share a physical unit and the differences in spread are meaningful, such as pixel intensities, centering alone may be better. Standardizing also inflates noisy, low-variance features to unit variance. Decide on purpose, and do not rely on a default.
Pitfall 2: Fitting on the wrong data
The mean, the scaling factors and the components are all learned parameters. Learn them from the training data only, then apply them to validation and test data. Fitting on the full dataset before splitting lets test-set information shape the transformation.
For plain PCA the leak is usually mild, because no labels are involved. It still makes your estimates optimistic, and it becomes severe once you add supervised steps such as feature selection. A pipeline makes the correct behavior automatic, because each cross-validation fold refits every step on its own training portion.
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
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
pipe = make_pipeline(
StandardScaler(),
PCA(n_components=0.95),
LogisticRegression(max_iter=1000),
)
scores = cross_val_score(pipe, X, y, cv=5)
print(scores.mean())Pitfall 3: Outliers
Variance is a sum of squared deviations, so a single extreme point can rotate a component. The next example adds one outlier to a two-dimensional cloud that is mostly spread along the x-axis.
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2)) @ np.array([[3.0, 0.0],
[0.0, 1.0]])
X_out = np.vstack([X, [0.0, 50.0]])
v1 = PCA(n_components=1).fit(X).components_[0]
v2 = PCA(n_components=1).fit(X_out).components_[0]
cos = abs(v1 @ v2)
print("angle between PC1 directions (degrees):",
np.degrees(np.arccos(np.clip(cos, 0.0, 1.0))))Without the outlier, PC1 points along the x-axis. With one added point out of 101, PC1 swings toward the y-axis. The printed angle is large, close to a right angle.
Typical defenses:
- Inspect the data and the scores for extreme points before trusting a fit.
- Winsorize or clip heavy-tailed features, or apply a log or similar transform.
- Use a robust method such as robust PCA, which splits the data into a low-rank part and a sparse part of outliers.
Pitfall 4: Nonlinear structure
PCA only finds linear subspaces. Data that lies on a curved surface, such as a spiral, a ring, or concentric shapes, cannot be unfolded by rotating axes and dropping some of them.
import numpy as np
from sklearn.datasets import make_circles
from sklearn.decomposition import KernelPCA, PCA
X, y = make_circles(n_samples=400, factor=0.3, noise=0.03, random_state=0)
z_lin = PCA(n_components=1).fit_transform(X)[:, 0]
z_rbf = KernelPCA(n_components=1, kernel="rbf", gamma=10).fit_transform(X)[:, 0]
print("PCA |corr(PC1, label)|:", abs(np.corrcoef(z_lin, y)[0, 1]))
print("KPCA |corr(PC1, label)|:", abs(np.corrcoef(z_rbf, y)[0, 1]))The two circles are not linearly separable, and the cloud is nearly round. Its two eigenvalues are close, so the first principal axis is almost arbitrary and carries almost no label information. The RBF kernel version typically places the circles at different positions along its first component, so its correlation is much higher. The last chapter section lists further nonlinear options.
A related sign is a scree plot with no clear elbow and slowly decaying eigenvalues. That shape means the data has no strong low-dimensional linear structure, and PCA may not compress it usefully.
Pitfall 5: High variance is not the same as relevance
PCA never sees your target. A direction with large variance may be irrelevant to the prediction task, such as a lighting change in photos of faces. A direction with small variance may be exactly what separates the classes. Discarding low-variance components can therefore throw away the signal.
If prediction is the goal, treat the number of components as a hyperparameter and tune it by cross-validation inside a pipeline. Do not choose it only from a variance threshold. If you have labels and want directions that separate classes, consider linear discriminant analysis or partial least squares.
Pitfall 6: Over-reading the components
Several properties of the output are easy to misinterpret.
- Signs are arbitrary. If
vis a principal axis, so is-v. Different library versions, solvers or random seeds can flip signs. Do not compare signs across runs, and do not read meaning into "positive" and "negative" ends without checking against the data. - Components mix features. A loading vector is a weighted combination of all features. Calling PC1 "size" or "quality" is a hypothesis, and it should be backed by looking at which loadings are large.
- Near-equal eigenvalues make axes unstable. When two eigenvalues are almost equal, any rotation within that plane is almost as good. Small changes in the data can rotate the two components a lot, so interpret them as a pair.
- Uncorrelated is not independent. Scores on different components have zero covariance, but they can still depend on each other in nonlinear ways. Independence needs a different method such as ICA.
- Dependence on the sample. With few samples relative to features, the estimated components are noisy. The number of components is also capped at
min(n_samples, n_features), and with centered data the effective rank is at mostn_samples - 1.
Pitfall 7: Data types PCA does not suit
- Categorical or binary features. One-hot columns have variances set by category frequency, and their covariances are not Gaussian-like. PCA runs without error, but the result is hard to justify. Consider multiple correspondence analysis or an embedding.
- Missing values. Standard PCA requires a complete matrix. Imputing before PCA works, but the components then reflect the imputation. Imputation must also happen inside the cross-validation pipeline.
- Sparse matrices. Centering turns a sparse matrix into a dense one, which can exhaust memory. For sparse text features, use
TruncatedSVD, which skips centering. Remember that its first component is then often close to the mean direction. - Counts and heavy-tailed data. Raw counts with a skewed distribution are dominated by a few large values. Transform them first.
Quick diagnostic checklist
Summary of failure modes
| Pitfall | Symptom | Remedy |
|---|---|---|
| Unscaled features | PC1 is one large-range column | Standardize inside a pipeline |
| Leakage | Optimistic test scores | Fit only on training folds |
| Outliers | Components point at single samples | Clip, transform or use robust PCA |
| Nonlinear structure | Flat scree plot, overlapping classes | Kernel PCA or manifold methods |
| Variance is not relevance | Accuracy falls after reduction | Tune components by cross-validation, or use a supervised method |
| Sign and rotation | Loadings change between runs | Compare directions up to sign, interpret near-ties together |
| Sparse or categorical data | Memory errors or odd components | `TruncatedSVD`, MCA or embeddings |
Exercise
You standardize all features on the full dataset, run PCA, and then split into train and test sets to evaluate a classifier. Which parts of the evaluation are compromised, and how do you fix it?
Show answer
The scaler's means and standard deviations, and the PCA components, were computed using test rows, so the test data influenced the transformation and the score is optimistic. Split first, then fit the scaler and PCA on the training set only, and apply transform to the test set. A make_pipeline passed to cross_val_score does this for every fold.
Exercise
A dataset has two classes whose means differ only along a direction with 1% of the total variance. You keep the components that explain 95% of the variance and train a classifier, but accuracy is near chance. Why, and what would you try next?
Show answer
The discriminative direction has low variance, so PCA drops it, and PCA never uses the labels to decide what to keep. Treat the number of components as a hyperparameter and tune it by cross-validation, keep more components, or use a supervised method such as linear discriminant analysis or partial least squares.
Exercise
Why can PCA on a large sparse document-term matrix run out of memory, and what is the usual alternative?
Show answer
PCA centers the data, and subtracting the column means makes every entry nonzero, so the sparse matrix becomes dense. TruncatedSVD computes the SVD without centering, so the matrix stays sparse.