Unsupervised learning
PCA in Practice: Scaling, Whitening, and Reconstruction
Apply PCA safely through leakage control, explained variance, whitening, reconstruction, out-of-sample transformation, and component stability.
By the end you can
- Select a component count using reconstruction, downstream, stability, and rare-case evidence
- Explain whitening and its effect on component variance and downstream geometry
- Use fit and transform boundaries that prevent leakage
- Diagnose unstable loadings, outliers, and shifted future observations
Comparison
What whitening removes, and which estimators it rescues
Whitening changes the geometry a downstream model sees. It strips the retained components of their original variance scale. scikit-learn states the trade in one sentence, in the description of PCA's `whiten` parameter: “Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions.” The same page defines the operation exactly. Multiply the components by sqrt(n_samples), divide by the singular values, and every component has unit variance. The cost is arithmetic, not opinion.
Which estimators collect the gain has been measured. Coates and colleagues made whitening an explicit axis of variation on CIFAR-10 in 2011, across four unsupervised feature learners: sparse auto-encoders, sparse RBMs, K-means and Gaussian mixtures. Their “Effect of whitening” section is blunt about where it matters: “For the clustering algorithms, however, we see that whitening is a crucial pre-process since the clustering algorithms cannot handle the correlations in the data”. Their best configuration used whitening, a 1-pixel stride and a 6-pixel receptive field. It reached 79.6% on CIFAR-10 and 97.2% on NORB.
So the three columns below are not three tastes. Ordinary scores keep the fitted variance magnitudes, which is what reconstruction needs. Whitened scores equalize the retained components, which is what a distance-based or clustering estimator may need — at the price the library names. Keeping the prepared original features avoids component interpretation altogether. That is sometimes the right call when the signal is sparse or rare.
Ordinary PCA scores
Retain the variance magnitude associated with each component.
- Leading directions remain larger
- Useful for reconstruction
- Distance is dominated by high-variance components
- Preserves the fitted low-rank scale
Whitened scores
Rescale retained components to unit variance on the reference data.
- Equalizes component variance
- Can help some downstream estimators
- Amplifies low-variance retained directions
- Loses original variance scale
No reduction
Use the prepared original feature space.
- Preserves all measured coordinates
- Avoids component interpretation
- Can retain redundancy and noise
- May be preferable for sparse or rare signals
Visual
The PCA artifact used in a real pipeline
Shipping a PCA model takes more than a matrix of components. Five pieces of state travel together. Lose one and future transforms go silently wrong rather than loudly broken.
The preprocessing state is the imputer, the transformer, the centering means and any scaling parameters. The component matrix holds the retained feature-space directions, with a fixed sign convention for reporting. Sign is arbitrary, and flipping it between runs breaks every downstream comparison. The variance information is the singular values, the explained variances and the cumulative ratios from the fit data — descriptive of that dataset and of no other. The projection contract is the rule for transforming and inverse-transforming new observations. The monitoring profile is the score distributions, the reconstruction error, the missingness and the support diagnostics you need in order to notice drift.
- 01
Preprocessing state
Imputer, transformer, centering means, and optional scaling parameters.
- 02
Component matrix
Retained feature-space directions with a fixed sign convention for reporting.
- 03
Variance information
Singular values, explained variance, and cumulative ratios from the fit data.
- 04
Projection contract
Rules for transforming and inverse-transforming new observations.
- 05
Monitoring profile
Score distributions, reconstruction error, missingness, and support diagnostics.
The fitted centering and scaling state belongs to the PCA model.
The largest direction of variation turned out to be the sequencing flowcell
In 2014 a Mouse ENCODE study compared human and mouse tissues, and the samples grouped by species rather than by tissue: “the expression for many sets of genes was found to be more similar in different tissues within the same species than between species”. That was the headline of Lin and colleagues. Read as biology, it is a striking claim about how far mouse and human tissue programs have diverged.
A reanalysis of the same data followed in 2015. The assignment of samples to sequencing flowcells and lanes was nearly completely confounded with species. The dominant axis of variation was the instrument, not the organism. Gilad and Mizrahi-Man state the result in their abstract: “When we account for the batch effect, the corrected comparative gene expression data from human and mouse tend to cluster by tissue, not by species.”
Nothing in a variance ratio can tell you which of those two stories you are looking at. Explained variance is a property of the reference dataset and of how it was collected. It does not know which variation the downstream task values. It does not know which tail event must survive a truncation. And it does not know that the biggest direction in the matrix belongs to the machine that produced it.
The largest direction in the data can belong to the instrument rather than to the question.
Key idea
Do not fit PCA before the evaluation split
Fit components on the full dataset and the representation is defined using future or held-out covariance structure. Downstream validation then benefits from information outside the training boundary.
This is not a folk rule. A 2022 Nature Reviews Genetics review of machine learning in genomics gives a numbered section to “Pitfall 4: leaky preprocessing”, and Whalen and colleagues name this method specifically: “Any data transformation that looks at multiple examples together can be problematic. Specific methods include standardization and principal component analysis (PCA), plus various other scalings and unsupervised embedding approaches.”
The size and sign of the resulting error have been studied on their own. Moscovich and Rosset analysed three unsupervised preprocessing procedures — variance-based feature selection, grouping of rare categorical features, and feature rescaling — and demonstrated the cross-validation bias each one induces. The bias can be positive or negative. That is the part that makes it dangerous. You cannot assume a leaked estimate is merely optimistic and correct it by shading your expectations downward.
Place imputation, scaling and PCA inside the training pipeline or resampling fold. Transform validation and test observations only with the fitted training artifact.
A Nature Reviews Genetics review lists PCA by name among the transformations that leak.
Case
Leakage found across 17 fields, collectively affecting 294 papers
Fitting on the whole dataset before the split has a published record across the fields that have adopted machine learning. Kapoor and Narayanan surveyed it in 2023: “through a survey of literature in research communities that adopted ML methods, we find 22 papers across 17 fields where leakage has been found, collectively affecting 294 papers”.
Their taxonomy is blunt about preprocessing, and it carves out no exception for transformations that never see the labels: “using the entire dataset for any pre-processing steps, such as imputation or over/under sampling, results in leakage”. Twenty-two papers, seventeen fields, two hundred and ninety-four affected papers. The failure this lesson is warning about is the one that has already happened at scale.
Analogy
Compressing an orchestra recording into a few tracks
Several dominant audio tracks can stand in for a whole orchestra recording. Most energy may be preserved while a quiet instrument carrying an important cue disappears. That much the analogy earns.
Where it misleads is in the sources. Musical tracks have a physical origin: a cello is in the room. Principal components are orthogonal directions manufactured by the covariance geometry. Their separation guarantees nothing about a distinct real-world mechanism.
Population genetics holds the most famous demonstration of this. The gradients and waves in Cavalli-Sforza et al.'s classic PCA maps of European genetic variation had been read for thirty years as signatures of specific migration events. Then Novembre and Stephens looked again, and wrote in Nature Genetics in 2008: “Here, we find that gradients and waves observed in Cavalli-Sforza et al.'s maps resemble sinusoidal mathematical artifacts that arise generally when PCA is applied to spatial data, implying that the patterns do not necessarily reflect specific migration events.” The waves were the method's own sine functions.
The same conclusion arrived a year later from a second direction. McVean derived what PCA projections mean genealogically, and found that correlations between principal components and geography “can also be caused by other processes or even statistical artefacts”. Clines in principal components arise from recurrent bottlenecks, admixture and equilibrium models of spatial structure, as well as from expansion waves. He states the limitation in general form: “multiple processes can give the same projections”. Thirty years of migration narrative had been read off axes that a second mechanism could have produced identically.
Energy preservation and information value are different evaluation targets, and neither one is a mechanism.
Steps
Select and monitor a PCA representation
Use several candidate ranks and evaluate the relationships the pipeline must preserve. Tooling exists for exactly this boundary. The scikit-learn user guide, in the Safety bullet of “Pipelines and composite estimators”, says that “Pipelines help avoid leaking statistics from your test data into the trained model in cross-validation, by ensuring that the same samples are used to train the transformers and predictors”. The guarantee is mechanical — same samples, transformers and predictors alike. That is why the boundary is better enforced by a pipeline object than by discipline.
Five steps carry the work. First, fit within boundaries: learn all preprocessing and PCA parameters on the reference training period or fold. Second, compare ranks: review variance, reconstruction, neighbor preservation, runtime and downstream performance together, rather than one ratio alone. Third, test rare slices: measure retained signal for minority groups, anomalies and low-variance operational events, since a truncation discards those directions first. Fourth, evaluate whitening: compare ordinary and whitened scores for the specific downstream estimator. Coates and colleagues found the effect decisive for clustering methods and not uniform across the four learners they tested. Fifth, monitor future data: track score distributions, reconstruction error, missingness and feature drift.
1. Fit within boundaries
Learn all preprocessing and PCA parameters on the reference training period or fold.
2. Compare ranks
Review variance, reconstruction, neighbor preservation, runtime, and downstream performance.
3. Test rare slices
Measure retained signal for minority groups, anomalies, and low-variance operational events.
4. Evaluate whitening
Compare ordinary and whitened scores for the specific downstream estimator.
5. Monitor future data
Track score distributions, reconstruction error, missingness, and feature drift.
Example
Component-count evidence, including an estimator that chooses the rank
Several diagnostics should be reviewed together — and the rank does not have to be chosen by eye at all. In 2000 Minka treated PCA as density estimation and picked the dimensionality by Bayesian model selection, using Laplace's method. His abstract claims a great deal: “In simulations, it is convincingly better than cross-validation and other proposed algorithms, plus it runs much faster.” The method is not a curiosity in a proceedings volume. It ships. The scikit-learn API reference for PCA records that “If n_components == 'mle' and svd_solver == 'full', Minka's MLE is used to guess the dimension”, and cites Minka for it.
- Scree pattern: a gradual decay offers no natural elbow and argues against claiming one objectively correct rank — the exact situation Minka's estimator was written for, one argument away in `n_components='mle'` with `svd_solver='full'`.
- Reconstruction curve: aggregate error can fall quickly while remaining high on a slice that matters, so measure it per slice rather than only overall.
- Downstream retrieval: compare candidate ranks on the relation the pipeline must actually preserve, since that ordering and the cumulative-variance ordering need not agree.
- Loading stability: individual components can rotate across bootstrap samples while the combined subspace remains stable, so compare subspaces rather than demanding identical loading signs and order.
- Future support: new observations producing extreme scores and high reconstruction error signal distribution shift or an unsupported regime, not automatic anomaly truth.
A rank-2 signal, and a 90% energy rule that keeps 403 components
Fewer components improve compression and can reduce noise. More components preserve detail and instability. The correct balance depends on the downstream relation and the failure cost. Where the noise model is known, though, the balance can be computed rather than negotiated. Gavish and Donoho derived the AMSE-optimal hard threshold for singular values in 2014. For a square n-by-n matrix in white noise of known level σ, the cutoff is (4/√3)·√n·σ ≈ 2.309·√n·σ. When σ is unknown it becomes 2.858·y_med, where y_med is the median empirical singular value.
The threshold has a textbook demonstration. Brunton and Kutz describe it in Data-Driven Science and Engineering: “A recent theoretical breakthrough determines the optimal hard threshold τ for singular value truncation under the assumption that a matrix has a low-rank structure contaminated with Gaussian white noise.” Then they run it on a synthetic rank-2 matrix with n = 600 and σ = 1. The optimal cutoff, τ ≈ 56.6, keeps exactly the two true components. The 90% cumulative-energy criterion plotted in the same figure sits at r = 403. Two components of signal, four hundred and three components kept. That is what a ceremonial percentage does to a matrix whose true rank is small and whose noise is large.
Store the full fit state and the evidence used to choose rank and whitening. A cumulative variance percentage alone is not a deployment rationale.
Choose PCA by preserved behavior, not by a ceremonial variance cutoff — a 90% energy rule kept 403 components of a rank-2 signal.
Key takeaways
- Explained variance is a property of the collected dataset, not a measure of retained task information. In the Mouse ENCODE reanalysis the dominant axis was the sequencing flowcell, and the tissue signal appeared only once it was removed.
- Whitening equalizes retained component variance. In scikit-learn's own words it removes the relative variance scales of the components, in exchange for possible downstream gains; Coates and colleagues found the gain decisive for clustering algorithms.
- Imputation, scaling and PCA must be fitted inside evaluation boundaries. A Nature Reviews Genetics review names PCA under “Pitfall 4: leaky preprocessing”, and Moscovich and Rosset show the resulting cross-validation bias can run in either direction.
- Component stability and subspace stability are different questions: components can rotate across bootstrap samples while the retained subspace holds.
- Rare slices and low-variance signals need explicit retention tests, and component separation is no evidence of a distinct mechanism — Novembre and Stephens found the migration waves in the classic PCA maps to be artifacts PCA produces generally on spatial data.
- Rank can be chosen by an estimator rather than a habit: Minka's MLE ships as `n_components='mle'`, and the Gavish–Donoho threshold τ ≈ 56.6 kept the two true components of a rank-2 matrix where a 90% energy rule kept 403.