Singular Value Decomposition and Principal Component Analysis
The singular value decomposition factors any matrix into orthogonal directions and nonnegative scales, giving the optimal low-rank approximation; PCA is that same spectral structure applied to a centered data matrix, recovering the directions of maximum variance.
1. Concept overview
The singular value decomposition (SVD) states that every matrix can be written
with and . The are the singular values; the columns , of , are the left and right singular vectors.
Principal component analysis (PCA) takes a data matrix ( samples, features), centers it, and finds orthonormal directions that maximize projected variance in sequence. The two are the same object: if is the SVD of the centered data, then the covariance has eigenvectors and eigenvalues . SVD is the general factorization; PCA is SVD plus centering plus a statistical interpretation.
2. Why this concept exists
Raw data matrices are large and noisy, but often approximately low-rank: a few latent factors generate most of the variation. Examples: pixel images of the same object under lighting changes, user–item rating tables, gene-expression profiles, term–document matrices.
Goals that SVD/PCA serve:
- Compression: store rank-one terms instead of entries.
- Denoising: small singular values often encode noise; truncating them improves signal-to-noise.
- Visualization and feature extraction: project -dimensional points to 2–3 principal components.
- Numerics: the best rank- approximation exists in closed form, unlike for most low-rank constraints; it also conditions linear systems and reveals rank deficiency.
Predecessors were inadequate. Selecting a subset of columns (CUR-like pivot selection) discards information and is not optimal. Hand-chosen projections ignore the data. Solving the eigenproblem of a gram matrix directly squares the condition number and is unstable when is large. SVD is numerically stable (via Householder bidiagonalization), dimension-agnostic, and comes with an optimality theorem — the Eckart–Young–Mirsky result — that no heuristic shares.
3. Historical background
The spectral thread runs through Sylvester (1850s) and Beltrami (1873), who studied singular values of square matrices; Jordan (1874) independently obtained the decomposition for real matrices. Schmidt (1907) proved the optimal low-rank approximation property for integral operators, which is the infinite-dimensional ancestor of Eckart–Young. In statistics, Pearson (1901) fitted lines and planes by minimizing orthogonal distances — essentially the first principal component; Hotelling (1933) formalized PCA as a transformation maximizing successive variances.
Eckart and Young (1936) stated the approximation theorem for matrices; Mirsky (1960) extended it to all unitarily invariant norms, giving the modern Eckart–Young–Mirsky theorem. Golub and Reinsch (1969/1970) published the numerically stable bidiagonalization-plus-QR algorithm that became LAPACK's dgesvd, making SVD routine in practice. With massive matrices, randomized methods (Halko, Martinsson, Tropp 2011; Liberty et al. 2007) replaced full factorizations by sketching, reducing cost from to roughly for rank .
4. Fundamental problem
Two equivalent problems:
Algebraic. Given and a target rank , find
Statistical. Given centered data , find orthonormal solving the sequential variational problem
Both are solved by the same spectrum: , and is the -th right singular vector. The difficulty is not defining the optimum but computing it stably and cheaply when are large or the spectrum decays slowly.
5. First-principles explanation
Start with two elementary facts.
Fact 1 — rank-one building blocks. An matrix of rank one is an outer product . Any matrix is a sum of rank-one pieces; the question is which pieces capture the most "mass". The Frobenius norm satisfies , so for unit the natural weight is the scalar multiplying the outer product.
Fact 2 — the spectral theorem. is symmetric positive semidefinite, so it has an orthonormal eigenbasis with nonnegative eigenvalues . For unit , the action of has squared length
which is a Rayleigh quotient of . By the min–max theorem its maximum over unit vectors is the largest eigenvalue , attained at the top eigenvector. Define , (for ). Then
so the are orthonormal and . Everything — existence, orthogonality, optimality — flows from the spectral theorem plus Cauchy–Schwarz/min–max.
6. Prerequisite concepts
Required background: (1) matrix multiplication and outer products, including the identity ; (2) orthogonal matrices and preservation of norms/angles; (3) the spectral theorem for symmetric matrices and positive semidefiniteness; (4) Rayleigh quotients and the Courant–Fischer min–max theorem; (5) matrix norms — Frobenius and spectral ; (6) statistics: mean, covariance, variance of a projection; (7) basic numerical analysis (condition number, why forming is unstable). See the linked concepts.
7. Complete mathematical formulation
SVD (thin/full). For , :
The thin SVD keeps only , , .
Eckart–Young–Mirsky. For any unitarily invariant norm ,
PCA. With data matrix , mean , centered , covariance :
Explained variance ratio of component : . Reconstruction from components: .
8. Notation dictionary
| Symbol | Meaning | Type | |---|---|---| | | arbitrary matrix to factor | matrix | | | left/right singular vectors (orthogonal) | matrices | | | singular values | scalars | | | -th left/right singular vector | vectors | | | best rank- approximation | matrix | | | raw data ( samples, features) | matrix | | | mean-centered data | matrix | | | sample covariance | matrix | | | eigendecomposition of | factorization | | | principal-component scores | matrix | | | variance along component | scalar | | | maximum possible rank | integer | | | target rank / number of components | integer | | | Frobenius norm | norm | | | spectral (operator) norm | norm | | | matrix trace | functional |
9. Step-by-step derivation
Step 1 — construct singular values. is symmetric PSD, so with and orthonormal columns . Set and, for , . Then (see proofs) and . Stacking gives , i.e. .
Step 2 — best rank- via the Rayleigh quotient. For unit ,
with equality at . So ; after projecting out , the same argument gives at . Thus the singular values are the successive maximal "energy" directions.
Step 3 — truncation error. With orthogonal, by orthogonal invariance of ,
Any rank- matrix cannot do better (proof section): the truncated SVD is globally optimal.
Step 4 — PCA from SVD. Center : . Then
By uniqueness of the eigendecomposition up to signs/rotations in degenerate subspaces, the eigenvectors of are the right singular vectors of and . The scores are , whose -th column has sample variance .
Step 5 — choosing . Pick smallest with (e.g. ), or use a scree-plot elbow, or cross-validate reconstruction error.
10. Proofs and proof intuition
Proposition 1 (existence). The construction above yields with orthogonal. Proof. . For zero singular values extend to an orthonormal basis of . Then on the span of the and hence .
Theorem (Eckart–Young–Mirsky, Frobenius case). . Proof. Let the SVD of have rank at most , with left/right orthonormal sets , . Complete them to full orthonormal bases . Orthogonal invariance gives . The matrix has at most nonzero columns, and . For each column, — but the sharper bound uses the trace: . By von Neumann's trace inequality . Optimizing the resulting quadratic over gives for and the value , attained by . Spectral-norm case: similarly and no rank- matrix can reduce the -th singular direction.
Proposition 2 (PCA–SVD link). . Proof. Immediate from and uniqueness of eigenvalues.
Proof intuition. Orthogonal changes of basis cannot change lengths, so the whole problem is about the diagonal of : keep the largest energies, discard the rest; von Neumann's inequality says no tilted rank- subspace can capture more.
11. Geometric interpretation
The linear map sends the unit sphere to an ellipsoid in whose semi-axis lengths are and whose axis directions are ; the preimages of those axes are . So SVD is "the most honest coordinate system" for a linear map: it aligns input and output axes so the action is pure stretching with no rotation between the two bases.
For PCA, the centered data cloud is an ellipsoid in feature space. is its longest axis (maximum variance), the next longest perpendicular axis, and so on. Projecting onto the first axes gives the best -dimensional shadow of the cloud in the least-squares sense. Reconstruction error equals the squared lengths of the discarded axes: .
12. Visual explanation
Three standard views: (i) ellipsoid plot — draw the unit circle, its image under , and overlay the , axes; (ii) scree plot — bar chart of or explained-variance ratio versus component index, with a cumulative line used to pick ; (iii) biplot — scatter the scores and overlay arrows for the original feature loadings , showing which features drive each component. In the interactive lab, vary the target rank and watch the reconstructed image lose detail as grows. The singular-value spectrum's decay rate (exponential vs. algebraic) predicts how well compression works.
13. Numerical worked example
SVD. Let . It is symmetric; has eigenvalues with eigenvectors , . Hence
Best rank-1 approximation: . Error matrix , so and — exactly the Eckart–Young bound.
PCA. Four 2D points . Mean ; centered points . Then
The eigenvalues of are ; dividing by : , . Explained variance of PC1 . The top eigenvector solves , giving — a line of slope , matching the cloud's tilt. Scores are ; their sample variance is .
14. Real-world analogy
Imagine shining a light on a three-dimensional object and studying its two-dimensional shadow. Many different 3D shapes cast similar shadows; PCA picks the shadow angle that preserves the most "spread" of the data. An ellipsoid of points (think a tilted cigar) has a long axis and a thin axis: you can describe every point nearly as well by its coordinate along the long axis alone. SVD is the same idea for a linear transformation — it finds the input direction that gets stretched most and the output direction where the stretch lands, like identifying a machine's dominant lever arm and the direction it pushes.
15. Algorithm pseudocode
algorithm PowerIterationSVD(A, k, n_iter):
# finds leading singular triplets; randomized variant sketches A first
for i = 1 .. k:
v <- random unit vector in R^n, orthogonalized against V
repeat n_iter times:
u <- A v / ||A v|| # apply A
v <- A^T u / ||A^T u|| # apply A^T
sigma <- ||A v|| # Rayleigh estimate
store (u, sigma, v); deflate A <- A - sigma u v^T
return U, Sigma, V
algorithm PCA(X, k):
mu <- mean of rows of X
Xc <- X - 1 mu^T # centering is mandatory
U, Sigma, V <- SVD(Xc, thin) # or eigendecompose Xc^T Xc / (n-1)
lambda <- Sigma^2 / (n-1)
Z <- Xc V[:, 1..k] # scores
return mu, V[:, 1..k], lambda[1..k], Z
16. Implementation from scratch
import numpy as np
def pca_from_svd(X, k):
"""PCA via the (thin) SVD of the centered data. Pure NumPy."""
X = np.asarray(X, dtype=float)
mu = X.mean(axis=0)
Xc = X - mu # never skip centering
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
var = s**2 / (X.shape[0] - 1)
order = np.argsort(-var)[:k]
return mu, Vt[order].T, var[order], Xc @ Vt[order].T, s[order]
def top_singular_vectors(A, k, n_iter=100, seed=0):
"""Randomized power iteration with deflation, no LAPACK SVD call."""
rng = np.random.default_rng(seed)
A = np.asarray(A, dtype=float).copy()
Us, ss, Vs = [], [], []
for _ in range(k):
v = rng.standard_normal(A.shape[1]); v /= np.linalg.norm(v)
for _ in range(n_iter):
u = A @ v; u /= np.linalg.norm(u) + 1e-300
v = A.T @ u; v /= np.linalg.norm(v) + 1e-300
sigma = np.linalg.norm(A @ v)
Us.append(u); ss.append(sigma); Vs.append(v)
A -= sigma * np.outer(u, v) # deflate
return np.array(Us).T, np.array(ss), np.array(Vs).T
X = np.array([[1,1],[2,1],[3,2],[4,3]], float)
mu, V, var, Z, s = pca_from_svd(X, 1)
print(var, var[0]/var.sum(), V.ravel()) # ~2.517, ~0.974, ~[0.808,0.589]
A = np.array([[3.,1.],[1.,3.]])
U, sv, Vt = top_singular_vectors(A, 2)
print(np.round(sv, 6)) # [4, 2]
17. Professional library implementation
import numpy as np
from sklearn.decomposition import PCA
from sklearn.utils.extmath import randomized_svd
# scikit-learn: centering handled internally, stable LAPACKdriver ARPACK/randomized
pca = PCA(n_components=2, svd_solver="full")
Z = pca.fit_transform(X) # scores
print(pca.explained_variance_, pca.explained_variance_ratio_, pca.components_)
# NumPy full SVD (Golub–Reinsch via LAPACK)
U, s, Vt = np.linalg.svd(A, full_matrices=True)
# Large matrices: randomized SVD, O(m n k) instead of O(m n^2)
Uk, sk, Vkt = randomized_svd(A, n_components=k, n_iter=5, random_state=0)
In PyTorch use torch.linalg.svd(A, full_matrices=False) (or torch.svd_lowrank for large tensors). Always check svd_solver: "full" is exact, "randomized" is fast, "arpack" targets a few components but can fail to converge.
18. Code walkthrough
Scratch SVD. Power iteration alternates , which converges to the top eigenvector of at rate — slow when singular values are close. Deflating removes the leading component so the next iteration finds . The Rayleigh estimate equals when is exactly a right singular vector; monitor its convergence.
PCA function. mu = X.mean(axis=0) then Xc = X - mu implements centering; forgetting it makes PC1 point toward the mean instead of the variance. np.linalg.svd(Xc, full_matrices=False) returns in descending order. var = s**2/(n-1) is the sample variance along each component (Bessel correction), matching sklearn's explained_variance_. Scores Xc @ Vt[:k].T are the coordinates in the new basis.
Library version. scikit-learn centers internally and exposes components_ (= ), explained_variance_ratio_, and fit_transform; randomized_svd uses a Gaussian sketch plus subspace iteration and is the default for large with a flat spectrum.
19. Tensor and memory analysis
A full SVD stores , , : floats. In fp32 for that is floats GB — plus the MB input. The thin SVD stores only floats. For PCA on samples, features: if use the covariance path memory; if use the gram matrix or direct SVD of . Randomized SVD stores a sketch and small , i.e. , the difference between feasible and impossible at scale. The centered matrix itself costs ; if is sparse, avoid dense centering to preserve sparsity.
20. Time complexity
Full SVD of (): bidiagonalization plus QR iterations to depending on variants; practical LAPACK is ~. Thin SVD to rank : via randomized SVD with power iterations, . Covariance PCA: forming costs and its eigendecomposition ; direct SVD of is and more stable. Power iteration needs per component for sparse . Choose by aspect ratio: → covariance; → SVD of or gram matrix; huge and low-rank → randomized.
21. Space complexity
Full SVD ; thin SVD ; randomized SVD plus oversampling . Covariance PCA for plus for the centered data (or streaming accumulation of in only). For a matrix, full factors need ~1.2 GB in fp32 versus ~80 MB for rank-100 thin factors. Workspace for Householder bidiagonalization is in practice; blocked algorithms trade extra memory for cache efficiency.
22. Experimental demonstration
Take a grayscale image as a matrix , compute its SVD, and reconstruct with . Report relative Frobenius error and compression ratio . Typical natural images reach 90% energy by and look recognizable at with 10–20× compression. Second experiment: on synthetic with known rank- structure, compare PCA variance explained against the generating signal; recovered subspace angle should shrink as grows like . Third: plot runtime of full vs. randomized SVD for ; randomized should be several times faster.
23. Benchmark results
On a dense matrix with numerical rank , LAPACK full SVD takes on the order of tens of seconds; randomized SVD with , typically runs several times faster with relative error within a few percent of optimal. Accuracy benchmarks should report or subspace angle, not just wall-clock. For PCA, scikit-learn's full solver matches NumPy exactly; ARPACK is faster for a single component but can fail on flat spectra. Caveat: when , randomized methods need more power iterations (or adaptive), and any rank- subspace is unstable — no method can produce a reliable basis.
24. Limitations
- Linearity: PCA finds linear directions; nonlinear structure (manifolds) needs kernel PCA, ICA, or autoencoders.
- Variance ≠ importance: high-variance directions may be noise or nuisance; low-variance directions can be task-critical.
- Sign/rotation ambiguity: are determined only up to simultaneous sign flips; degenerate singular values allow arbitrary rotations inside the eigenspace.
- No labeled supervision: PCA ignores target labels; LDA or supervised metric learning may be better.
- Scaling sensitivity: changing feature units changes the covariance; standardize when appropriate.
- Full SVD cost: is prohibitive for very large matrices.
- Interpretability: principal components are dense combinations of features, often hard to name.
25. Failure scenarios
- Forgot to center: with nonzero mean, PC1 aligns with the offset from origin and "explains" variance that is just location; you must subtract the mean before SVD or eigen-decomposition.
- : the covariance is huge and rank-deficient; forming its eigenvectors is wasteful — use SVD of or the gram matrix.
- Outliers: a single extreme point can dominate the top eigenvector; use robust PCA (principal component pursuit) or trimming.
- Repeated singular values: when , the rank- subspace and individual vectors are non-unique — columns can rotate between runs; only the captured energy is stable.
- Ill-conditioned : forming the normal equations squares the condition number, destroying small singular values; use direct SVD.
- Numerical rank threshold: tiny singular values from floating-point noise should be truncated using a tolerance like .
26. Common misconceptions
- "PCA and SVD are different algorithms." PCA is SVD of centered data with a covariance interpretation; the factorization is the same.
- "The first principal component is the most informative for prediction." It maximizes variance, not label separation; supervised tasks may need other directions.
- "Components are original features." They are linear combinations; loadings tell you the mixture.
- "100% explained variance means good low-rank structure." With components you trivially explain 100%; what matters is the spectrum's decay.
- "Singular vectors are unique." Signs are arbitrary and degenerate subspaces allow rotations.
- "Truncating SVD always denoises." If signal and noise have similar singular-value magnitudes, truncation removes signal too.
27. Alternative approaches
- Randomized SVD: Gaussian sketch + subspace iteration; for large low-rank matrices.
- Truncated SVD / Lanczos / ARPACK: Krylov methods targeting a few extreme singular triplets.
- CUR / Nyström: select actual columns/rows for interpretability and sparsity.
- NMF: nonnegative factors for parts-based representations.
- Kernel PCA: nonlinear features via the kernel trick.
- ICA / FA: independent or generative latent factors with different assumptions.
- Robust PCA: sparse outliers plus low-rank decomposition via nuclear-norm minimization.
- Autoencoders: nonlinear generalization learned by gradient descent.
- t-SNE / UMAP: visualization-focused nonlinear embeddings (not linear reconstructions).
29. Research applications
- Recommender systems: low-rank collaborative filtering; the Netflix Prize popularized SVD-style latent factors.
- NLP / IR: latent semantic analysis (LSA) via term–document SVD; embeddings and compression.
- Computer vision: eigenfaces, image compression, structure-from-motion (factorization method).
- Genomics: population structure via PCA; correcting for stratification in GWAS.
- Scientific computing: model reduction (POD), proper orthogonal decomposition for PDEs.
- Deep learning: analyzing weight matrices, spectral initialization, compression via low-rank factorization.
- Differential privacy: private PCA via noise addition to covariance or output perturbation.
30. Important research papers
- Pearson K. (1901), On Lines and Planes of Closest Fit to Systems of Points in Space, Philosophical Magazine 2(11):559–572 — original PCA.
- Hotelling H. (1933), Analysis of a complex of statistical variables into principal components, Journal of Educational Psychology — formal PCA.
- Eckart C., Young G. (1936), The approximation of one matrix by another of lower rank, Psychometrika 1:211–218 — optimal low-rank theorem.
- Mirsky L. (1960), Symmetric gauge functions and unitarily invariant norms, Quarterly Journal of Mathematics — EYM generalization.
- Golub G. H., Reinsch C. (1970), Singular value decomposition and least squares solutions, Numerische Mathematik 14:403–420 — stable algorithm.
- Halko N., Martinsson P.-G., Tropp J. A. (2011), Finding structure with randomness: probabilistic algorithms for constructing approximate matrix decompositions, SIAM Review 53(2):217–288.
31. Further reading
- Golub & Van Loan, Matrix Computations (4th ed., 2013), chapters 2, 5, 8 — the numerical reference.
- Trefethen & Bau, Numerical Linear Algebra (1997), lectures 4–6, 31 — SVD and low-rank.
- Jolliffe, Principal Component Analysis (2nd ed., 2002) — statistics and caveats.
- Stewart, Decompositional Methods in Applied Linear Algebra (1998).
- Halko et al. (2011), SIAM Review — randomized algorithms (free PDF).
- scikit-learn user guide, "Decomposing signals in components (matrix factorization problems)".
32. Practical exercises
- Implement
pca_from_svdfrom memory and verify the four-point example: and . - Prove numerically that for the rank-1 truncation error equals in both Frobenius and spectral norms.
- Generate with , random orthonormal; recover the subspace and measure the principal angle to .
- Compress an image at ; plot relative Frobenius error and compression ratio; find the "knee".
- Reproduce the failure from skipping centering: show PC1 aligns with the mean on a shifted cloud.
- Compare full and randomized SVD on a matrix: runtime and subspace angle.
33. Debugging challenges
- PCA component points at the cloud's mean. You forgot to subtract the row means before the SVD.
- Singular vectors flip sign between runs. Expected: signs are arbitrary; fix a convention (e.g. largest absolute loading positive) if needed for reproducibility.
- Tiny singular values not near zero in a rank-deficient matrix. Numerical noise; truncate with a tolerance .
randomized_svderror much worse than theory. Increasen_iter/ oversampling, or check whether (flat spectrum).- Explained variance sums to more than 100%. You divided by instead of inconsistently, or mixed up components from a different fit.
- SVD of a sparse matrix runs out of memory. Dense factorization; switch to truncated/randomized sparse methods.
34. Advanced exercises
- Prove the spectral-norm case of Eckart–Young–Mirsky using the min–max theorem for .
- Derive the convergence rate of power iteration and implement block power iteration with QR re-orthogonalization.
- Show that PCA whitening () decorrelates features and derive its effect on the condition number of a downstream least-squares problem.
- Implement robust PCA via alternating minimization with nuclear-norm shrinkage; test on a low-rank matrix with 5% gross outliers.
- Derive the influence function of the top eigenvector and show explicitly how a single outlier can dominate it.
- Implement randomized SVD with adaptive subspace iteration (choose from a posterior error estimate).
35. Interview questions
- State the full SVD and explain the dimensions of in both full and thin forms.
- Prove that the Eckart–Young truncation is optimal in Frobenius norm; why does it also work for any unitarily invariant norm?
- Derive the identity for PCA and explain the .
- Why is forming before SVD numerically dangerous? Quantify with the condition number.
- What happens when ? Is the rank- approximation unique?
- When would you use randomized SVD, and how does its error depend on the spectral gap?
- PCA vs. LDA vs. ICA: state the objective each optimizes.
36. Research questions
- How can one choose with statistical guarantees when the spectrum decays slowly and noise is heteroscedastic?
- What are optimal sketching distributions for randomized SVD on structured (e.g. Toeplitz or graph) matrices?
- Can principal components be made stable under small perturbations by adding sparsity or smoothness constraints?
- How does private PCA trade off against the spectral gap in high dimensions?
- What is the right generalization of Eckart–Young for tensors (Tucker/CP rank), and which norms admit optimality?
37. Mastery assessment
To pass: (1) state and prove the SVD existence and Eckart–Young optimality without notes; (2) derive the PCA–SVD identity and explain centering; (3) implement both a scratch power-iteration SVD and a library PCA, reproducing the numerical example; (4) explain the failure modes (no centering, , outliers, repeated singular values) with examples; (5) answer the interview questions. Complete the linked assessment; a read is not mastery.`
38. Implementation submission
Push a repository with svd_pca.py (scratch power-iteration SVD and PCA from SVD), experiments.ipynb (the 2×2 example, the four-point PCA, image compression at five ranks, full vs. randomized timing), a README.md with the derivations and observed error vs. , and tests asserting rank-1 error on the example and on the four points. Submit the repository URL and the exact reproduction command.`
39. Completion criteria
All of: every section read; existence and Eckart–Young proofs reproduced on paper; scratch implementation passing tests; compression experiment with recorded errors and compression ratios; one failure case reproduced and explained; a one-page answer to a research question citing at least one paper. Only then mark the concept mastered.``