PCA in Depth
Variance, reconstruction, the SVD and probabilistic PCA.
PCA fits in one line, yet a century of theory went into knowing when its components mean anything. This lesson proves the theorem behind both of PCA's optimality properties, turns PCA into a probability model with a closed-form likelihood, uses random-matrix theory to tell signal components from noise, and extends PCA to curved structure, gross corruptions and sparse directions.
What you’ll learn
- Prove Ky Fan's maximum principle and derive from it PCA's optimality for variance and reconstruction, with the uniqueness condition .
- Derive the maximum-likelihood solution of probabilistic PCA, run its EM algorithm, and contrast it with factor analysis.
- State the BBP phase transition of the spiked covariance model, compute the limiting eigenvalue and eigenvector overlap, and use random-matrix thresholds to choose the number of components.
- Formulate kernel PCA (centering in feature space, the Gram eigenproblem, new points, pre-images), robust PCA by principal component pursuit, and sparse PCA, with their guarantees and limits.
Ky Fan’s theorem: one optimum, two meanings
Let be the sample covariance of centered data, with eigenvalues and orthonormal eigenvectors . The Descent lesson Dimensionality Reduction showed that for every with , the mean squared reconstruction error of projecting onto equals . Both of PCA's optimality properties therefore rest on a single statement about .
Let , the orthogonal projection onto . Expanding in its eigenbasis turns the objective into a weighted sum of eigenvalues, with weights :
A projection never lengthens a vector, and the weights add up to the trace of , which equals its rank :
So the objective can be no better than spending a total weight , at most 1 per eigenvalue, on the top . Formally, subtract and use . Both sums on the right are , because and in the first, and and in the second:
Equality holds at , where for and after. If , equality forces for all , hence for : contains and so equals their span. With a tie the maximizer is not unique: the part of the subspace that lies in the tied eigenspace can be any subspace of the right dimension.
With this settles both readings of PCA at once: the top- eigenvectors maximize the captured variance and minimize the mean squared reconstruction error, . Three consequences:
- Greedy is optimal. Hotelling's one-component-at-a-time construction (deflation) reaches the joint optimum, which most greedy procedures do not.
- Only the subspace is identified. with orthogonal changes nothing, and with a near-tie even the subspace is ill-determined: by the Davis–Kahan theorem (Linear Algebra for ML: Eigenvectors & the SVD), an estimated subspace can rotate by up to about the perturbation divided by the eigengap.
- No rank- matrix does better (Eckart–Young). For any of rank at most , let project onto a -dimensional subspace that contains the row space of . Every row of lies in that subspace, so row by row , and Ky Fan bounds the right side: . The truncated SVD attains it, so no linear encoder–decoder of width , orthonormal or not, beats PCA. Centering played no role: with the same lines prove the Frobenius-norm Eckart–Young theorem for any matrix . (The spectral-norm case is in Linear Algebra for ML: Eigenvectors & the SVD.)
Probabilistic PCA and factor analysis
Differentiate, using and . Stationary points satisfy
Write the thin SVD with , . Each column of is an eigenvector of with eigenvalue , so , and the stationarity condition makes every an eigenvector of :
Plug back in, with the set of chosen eigenvalues. On their eigenvectors agrees with ; on the other it equals . So and . Maximizing over gives the average of the discarded eigenvalues, and
Since , maximizing means minimizing times the log of the ratio between the arithmetic and geometric means of the discarded eigenvalues, which is zero only when they are all equal. Among choices that keep every (needed for real ), the optimum discards the smallest: the noise model wants the leftover spectrum as flat as possible.
A sample covariance in dimensions has eigenvalues . Fit probabilistic PCA with . What is ?
Show the answer
0.67
. The columns of (with ) have lengths and . The fitted covariance has eigenvalues , so its trace, 10, equals that of : the model keeps the total variance and flattens the tail.
What the likelihood buys:
- PCA is the zero-noise limit. As , : the posterior mean becomes the coordinates of the orthogonal projection onto the principal subspace.
- Denoising by shrinkage. At the optimum, the posterior-mean reconstruction is : weak components are shrunk most.
- Model choice. can be compared across with a complexity penalty; the covariance has free parameters.
- EM. The EM algorithm fits PPCA without forming , at about operations per iteration, and handles missing entries. As it becomes alternating least squares converging to the principal subspace (Roweis, 1998).
EM-PPCA(centered data rows x_1..x_n in R^d, latent dimension k)
initialize W (d x k) at random, sigma2 > 0
repeat until the log-likelihood stops increasing:
M = W^T W + sigma2 * I_k # k x k
E-step: m_i = M^{-1} W^T x_i # posterior means
G = n * sigma2 * M^{-1} + sum_i m_i m_i^T # sum of E[z_i z_i^T]
M-step: W_new = (sum_i x_i m_i^T) G^{-1}
sigma2 = (1/(n d)) * sum_i ( |x_i|^2 - 2 m_i^T W_new^T x_i )
+ (1/(n d)) * trace(G W_new^T W_new)
W = W_newEach iteration never decreases the likelihood (as for any EM algorithm; see Latent Variables & EM) and converges to the closed-form maximum from almost every start; the fitted is up to the rotation .
Factor analysis, which goes back to Spearman's 1904 "general intelligence" factor, gives every feature its own noise variance: with diagonal. The closed form is lost (EM fits it: Rubin & Thayer, 1982), but the model becomes scale-equivariant: rescaling feature rescales row of and , nothing else. Factor analysis explains correlations with shared factors and puts each feature's private variance in ; PCA spends components on whatever varies most.
| Aspect | PCA | Probabilistic PCA | Factor analysis |
|---|---|---|---|
| Noise model | none: a projection | isotropic, | diagonal, |
| Fit | eigenvectors of | closed form, or EM | EM; no closed form |
| Equivariant under | rotations | rotations | rescaling single features |
| Latent axes | unique if eigenvalues are distinct | up to a rotation | up to a rotation |
How many components are real? Spikes and the BBP transition
Classical asymptotics fix and let , so that and every sample eigenvalue converges to the truth. When is comparable to , the sample spectrum is distorted in a precise way. For pure noise, with , the eigenvalues of spread over the Marchenko–Pastur interval (Marchenko & Pastur, 1967) although every population eigenvalue is . The largest converges to the upper edge (Geman, 1980) with fluctuations of order that follow the Tracy–Widom law (Johnstone, 2001). Johnstone also proposed the model that makes "which components are real?" a precise question.
Write , with the sample covariance of white noise. has the same eigenvalues as , a rank-one perturbation of . For not an eigenvalue of , the matrix determinant lemma gives
So an eigenvalue of outside the noise spectrum must solve . Gaussian is rotation-invariant, so for a fixed unit the quadratic form converges to an integral against the Marchenko–Pastur law :
The transform solves a quadratic, and the outlier condition reads . The value satisfies both equations at once, which locates the outlier:
Right of the edge , decreases from to . The candidate lies in that range only if ; otherwise no eigenvalue separates from the noise and sticks to the edge. At the formula gives exactly . The eigenvector limit comes from the derivative of the same transform.
Data have dimensions (), and one spike doubles the variance along (). In the limit, what is the squared cosine between the top sample eigenvector and the truth?
Show the answer
0.6
The spike is above the threshold , so , an angle of about 39°. The eigenvalue is inflated: , although the true variance along is 2. A simulation with and (four runs) gives 2.49 and 0.61. With , below the threshold, it gives , just below the noise edge , and a squared overlap of a few hundredths at most: the spike is invisible.
What this means for choosing :
- The noise edge. A component whose eigenvalue sits inside the noise bulk is indistinguishable from noise, so , with estimated robustly, is a natural cutoff. Horn's (1965) parallel analysis is its empirical version: keep components whose eigenvalues beat those of random data of the same size (in a common variant, the data with each column independently permuted).
- Above the edge is not enough. Just past the transition the estimated direction is nearly orthogonal to the truth, and keeping it can add more error than it removes. For an matrix in white noise of known level , whose noise singular values reach about , the best hard threshold on singular values is , or times the median singular value when is unknown (Gavish & Donoho, 2014). Optimal shrinkage of each eigenvalue does better still (Donoho, Gavish & Johnstone, 2018).
- Likelihood. Minka (2000) approximates the Bayesian evidence of probabilistic PCA for each (scikit-learn's
PCA(n_components='mle')). - Cross-validation, done right. Held-out rows cannot choose : the fitted subspaces are nested, so their reconstruction error only falls as grows. Hold out individual entries instead (Wold, 1978; Bro, Kjeldahl, Smilde & Kiers, 2008).
Kernel PCA: components in a feature space
Map each input to in a feature space with kernel (The Kernel Trick). PCA in finds directions that are nonlinear in the input, but may be infinite-dimensional, so everything must be written through kernel values (Schölkopf, Smola & Müller, 1998). Even centering needs care: the centered features cannot be computed, but their inner products can. With , the centered Gram matrix is , that is (row, column and grand means of ).
Let be the feature-space covariance, with . Any eigenvector with eigenvalue is a combination of the data, because is:
Substitute and take inner products with every . The result involves only , and it is solved by the eigenvectors of (other solutions differ by null vectors of , which give the same ):
Normalize in , not in : . So if is a unit eigenvector of with eigenvalue , take
A new point is projected through kernel values against the training set, centered with the training means, exactly as linear PCA reuses the training mean:
With the linear kernel this is ordinary PCA computed from the Gram matrix, the cheaper route when . With a Gaussian (RBF) kernel the components are nonlinear in the input and depend strongly on the bandwidth. The price is an eigenproblem, time and memory, which Nyström and random-feature approximations reduce (Scaling Kernel Methods). Laplacian eigenmaps and LLE can be read as kernel PCA with kernels built from the data (Bengio et al., 2004).
The pre-image problem. The reconstruction lives in and is generally the image of no input. Denoising needs an approximate pre-image minimizing : a fixed-point iteration for Gaussian kernels that can stall in local minima (Mika et al., 1999), a closed-form estimate from distance constraints to nearby training points (Kwok & Tsang, 2004), or an inverse map learned by regression, as scikit-learn's KernelPCA(fit_inverse_transform=True) does with kernel ridge regression.
Robust and sparse PCA, and open problems
PCA's squared loss lets one wild entry wreck the fit. Robust PCA splits a data matrix as , low rank plus sparse corruptions, by principal component pursuit: minimize subject to . The nuclear norm is the convex stand-in for rank, as is for the number of nonzeros.
A constant fraction of entries may be corrupted by any amounts, and needs no tuning. Augmented-Lagrangian solvers alternate singular value thresholding (for ) with soft-thresholding (for ); in surveillance video is the static background and the moving foreground. Both assumptions matter: is sparse and low rank, and corruptions confined to one column form a rank-one matrix themselves.
Sparse PCA. In a single-spike model the top sample eigenvector is consistent only if (Johnstone & Lu, 2009), as the BBP formula suggests. If the true direction has only nonzero entries, maximize over unit vectors with at most nonzeros. That is NP-hard in general, so methods relax it: PCA on the highest-variance coordinates (Johnstone & Lu), lasso-type penalties on the loadings (Zou, Hastie & Tibshirani, 2006), or a semidefinite relaxation (d'Aspremont, El Ghaoui, Jordan & Lanckriet, 2007). A sparse spike is statistically detectable once its strength exceeds about ; the semidefinite test needs about , and Berthet & Rigollet (2013) showed that doing better in polynomial time would solve planted clique instances believed to be hard.
Key takeaways
- Ky Fan: , so the top- eigenvectors maximize captured variance and minimize reconstruction error at once; the subspace is unique exactly when .
- Probabilistic PCA has a closed-form maximum likelihood: is the average discarded eigenvalue and . PCA is its zero-noise limit, EM fits it in about operations per iteration, and factor analysis frees the noise to a diagonal , gaining scale-equivariance.
- With , a spike of strength separates from the noise only if ; then and . Choose against the noise edge, with parallel analysis, the Gavish–Donoho threshold, likelihoods or entry-wise cross-validation.
- Kernel PCA diagonalizes the centered Gram matrix , scales each eigenvector by , projects new points through training-centered kernel values, and needs approximate pre-images to map back to inputs.
- Principal component pursuit () recovers low rank plus sparse corruption exactly under incoherence and random support; sparse PCA restores consistency when , at an apparent statistical–computational price.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A covariance matrix has eigenvalues . Is the best 2-dimensional PCA subspace unique?
- Yes: it is
- No: every plane through the origin captures the same variance
- No: any plane spanned by and a unit vector of captures the maximum, 7
- Yes, once the features are standardized
Show the answer
C. No: any plane spanned by and a unit vector of captures the maximum, 7
Ky Fan's bound is , attained by any with and its other unit of weight in the tied eigenspace. Uniqueness needs , which fails, so "the second principal component" is not determined by the data.
In probabilistic PCA with a fixed of full column rank, what does the posterior mean become as ?
- , because the prior dominates
- , the coordinates of the orthogonal projection onto
- for every
- It is undefined, because becomes singular
Show the answer
B. , the coordinates of the orthogonal projection onto
with , which is invertible. The limit is the least-squares coordinates of in the columns of : PCA's projection, recovered as the noiseless limit of a probability model.
In the spiked model with , a single spike has strength . What do the top sample eigenvalue and eigenvector tell you as ?
- , the true variance along , and
- , and is partly aligned with
- is inflated above the edge, and tends to about 0.5
- , the noise edge, and becomes orthogonal to : PCA cannot see the spike
Show the answer
D. , the noise edge, and becomes orthogonal to : PCA cannot see the spike
The threshold is , so no eigenvalue separates from the Marchenko–Pastur bulk, and the top eigenvector carries asymptotically no information about . Only extra structure, such as sparsity of , can help.
You denoise images with kernel PCA and an RBF kernel: project each noisy image onto the top feature-space components. Why do you not simply get a clean image back?
- Because the kernel matrix was not centered
- Because the projection lies in the feature space and is generally the image of no input; an approximate pre-image must be computed
- Because kernel PCA can only be applied to the training images
- Because RBF kernel PCA keeps only components, too few for images
Show the answer
B. Because the projection lies in the feature space and is generally the image of no input; an approximate pre-image must be computed
The reconstruction is a point of , and the exact images form a curved low-dimensional surface in it that the reconstruction usually misses. Denoising ends with an optimization, or a learned inverse map, that finds an input whose image is closest.
Further reading
- M. E. Tipping & C. M. Bishop, "Probabilistic principal component analysis," Journal of the Royal Statistical Society B 61(3), 611–622 (1999).
- J. Baik, G. Ben Arous & S. Péché, "Phase transition of the largest eigenvalue for nonnull complex sample covariance matrices," Annals of Probability 33(5), 1643–1697 (2005).
- B. Schölkopf, A. Smola & K.-R. Müller, "Nonlinear component analysis as a kernel eigenvalue problem," Neural Computation 10(5), 1299–1319 (1998).
- E. J. Candès, X. Li, Y. Ma & J. Wright, "Robust principal component analysis?," Journal of the ACM 58(3), article 11 (2011).
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 12.