concept / svd-pca
Next task →
University/Linear Algebra/Matrix Decomposition/Singular Value Decomposition and Principal Component Analysis
Linear Algebra · Matrix Decomposition · Spectral methods

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.

39 sectionsadvanced210 minhand-authored · structural 80/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

The singular value decomposition (SVD) states that every matrix A∈Rm×nA\in\mathbb{R}^{m\times n} can be written

A=UΣV⊤,U∈Rm×m, V∈Rn×n orthogonal,Σ=diag(σ1,…,σp),A=U\Sigma V^\top,\qquad U\in\mathbb{R}^{m\times m},\ V\in\mathbb{R}^{n\times n}\text{ orthogonal},\quad \Sigma=\mathrm{diag}(\sigma_1,\dots,\sigma_p),

with σ1≥σ2≥⋯≥σp≥0\sigma_1\ge\sigma_2\ge\cdots\ge\sigma_p\ge0 and p=min⁡(m,n)p=\min(m,n). The σi\sigma_i are the singular values; the columns uiu_i, viv_i of UU, VV are the left and right singular vectors.

Principal component analysis (PCA) takes a data matrix X∈Rn×dX\in\mathbb{R}^{n\times d} (nn samples, dd features), centers it, and finds orthonormal directions v1,…,vdv_1,\dots,v_d that maximize projected variance in sequence. The two are the same object: if X~=UΣV⊤\tilde X=U\Sigma V^\top is the SVD of the centered data, then the covariance C=1n−1X~⊤X~=1n−1VΣ2V⊤C=\frac1{n-1}\tilde X^\top\tilde X=\frac1{n-1}V\Sigma^2V^\top has eigenvectors VV and eigenvalues σj2/(n−1)\sigma_j^2/(n-1). 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 k≪min⁡(m,n)k\ll\min(m,n) rank-one terms instead of mnmn entries.
  • Denoising: small singular values often encode noise; truncating them improves signal-to-noise.
  • Visualization and feature extraction: project dd-dimensional points to 2–3 principal components.
  • Numerics: the best rank-kk 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 dd 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 O(mn2)O(mn^2) to roughly O(mnk)O(mnk) for rank kk.

4. Fundamental problem

Two equivalent problems:

Algebraic. Given A∈Rm×nA\in\mathbb{R}^{m\times n} and a target rank k<min⁡(m,n)k<\min(m,n), find

Ak=arg⁡min⁡rank(B)≤k ∥A−B∥,∥⋅∥∈{∥⋅∥F,∥⋅∥2,∥⋅∥∗}.A_k=\arg\min_{\mathrm{rank}(B)\le k}\ \lVert A-B\rVert,\qquad \lVert\cdot\rVert\in\{\lVert\cdot\rVert_F,\lVert\cdot\rVert_2,\lVert\cdot\rVert_\ast\}.

Statistical. Given centered data X~\tilde X, find orthonormal v1,…,vkv_1,\dots,v_k solving the sequential variational problem

vj=arg⁡max⁡∥v∥=1, v⊥v1,…,vj−1 1n−1∥X~v∥2.v_j=\arg\max_{\lVert v\rVert=1,\ v\perp v_1,\dots,v_{j-1}}\ \frac1{n-1}\lVert\tilde X v\rVert^2 .

Both are solved by the same spectrum: Ak=∑i=1kσiuivi⊤A_k=\sum_{i=1}^k\sigma_i u_iv_i^\top, and vjv_j is the jj-th right singular vector. The difficulty is not defining the optimum but computing it stably and cheaply when m,nm,n are large or the spectrum decays slowly.

5. First-principles explanation

Start with two elementary facts.

Fact 1 — rank-one building blocks. An m×nm\times n matrix of rank one is an outer product uv⊤uv^\top. Any matrix is a sum of rank-one pieces; the question is which pieces capture the most "mass". The Frobenius norm satisfies ∥uv⊤∥F=∥u∥∥v∥\lVert uv^\top\rVert_F=\lVert u\rVert\lVert v\rVert, so for unit u,vu,v the natural weight is the scalar multiplying the outer product.

Fact 2 — the spectral theorem. A⊤AA^\top A is symmetric positive semidefinite, so it has an orthonormal eigenbasis viv_i with nonnegative eigenvalues λi\lambda_i. For unit vv, the action of AA has squared length

∥Av∥2=v⊤A⊤Av,\lVert Av\rVert^2=v^\top A^\top A v,

which is a Rayleigh quotient of A⊤AA^\top A. By the min–max theorem its maximum over unit vectors is the largest eigenvalue λ1\lambda_1, attained at the top eigenvector. Define σi=λi\sigma_i=\sqrt{\lambda_i}, ui=Avi/σiu_i=Av_i/\sigma_i (for σi>0\sigma_i>0). Then

ui⊤uj=vi⊤A⊤Avjσiσj=λjvi⊤vjσiσj=δij,u_i^\top u_j=\frac{v_i^\top A^\top A v_j}{\sigma_i\sigma_j}=\frac{\lambda_j v_i^\top v_j}{\sigma_i\sigma_j}=\delta_{ij},

so the uiu_i are orthonormal and A=∑iσiuivi⊤A=\sum_i\sigma_i u_iv_i^\top. 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 Avi=σiuiAv_i=\sigma_i u_i; (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 ∥A∥F2=∑ijAij2=\tr(A⊤A)\lVert A\rVert_F^2=\sum_{ij}A_{ij}^2=\tr(A^\top A) and spectral ∥A∥2=σ1\lVert A\rVert_2=\sigma_1; (6) statistics: mean, covariance, variance of a projection; (7) basic numerical analysis (condition number, why forming A⊤AA^\top A is unstable). See the linked concepts.

7. Complete mathematical formulation

SVD (thin/full). For A∈Rm×nA\in\mathbb{R}^{m\times n}, p=min⁡(m,n)p=\min(m,n):

A=UΣV⊤=∑i=1pσiuivi⊤,U⊤U=Im, V⊤V=In.A=U\Sigma V^\top=\sum_{i=1}^{p}\sigma_i u_iv_i^\top,\qquad U^\top U=I_m,\ V^\top V=I_n .

The thin SVD keeps only U∈Rm×pU\in\mathbb{R}^{m\times p}, Σ∈Rp×p\Sigma\in\mathbb{R}^{p\times p}, V∈Rn×pV\in\mathbb{R}^{n\times p}.

Eckart–Young–Mirsky. For any unitarily invariant norm ∥⋅∥UI\lVert\cdot\rVert_{UI},

min⁡rank(B)≤k∥A−B∥UI=∥A−Ak∥UI={(∑i>kσi2)1/2,∥⋅∥F,σk+1,∥⋅∥2.\min_{\mathrm{rank}(B)\le k}\lVert A-B\rVert_{UI}=\lVert A-A_k\rVert_{UI}=\begin{cases}\bigl(\sum_{i>k}\sigma_i^2\bigr)^{1/2},&\lVert\cdot\rVert_F,\\ \sigma_{k+1},&\lVert\cdot\rVert_2.\end{cases}

PCA. With data matrix X∈Rn×dX\in\mathbb{R}^{n\times d}, mean xˉ=1n∑ixi\bar x=\frac1n\sum_i x_i, centered X~=X−1xˉ⊤\tilde X=X-\mathbf 1\bar x^\top, covariance C=1n−1X~⊤X~∈Rd×dC=\frac1{n-1}\tilde X^\top\tilde X\in\mathbb{R}^{d\times d}:

C=VΛV⊤,λj=σj2/(n−1),Z=X~V (scores).C=V\Lambda V^\top,\qquad \lambda_j=\sigma_j^2/(n-1),\qquad Z=\tilde X V\ (\text{scores}).

Explained variance ratio of component jj: λj/∑i=1dλi\lambda_j/\sum_{i=1}^d\lambda_i. Reconstruction from kk components: X^=xˉ1⊤+Z:kV:k⊤\hat X=\bar x\mathbf 1^\top+Z_{:k}V_{:k}^\top.

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | A∈Rm×nA\in\mathbb{R}^{m\times n} | arbitrary matrix to factor | matrix | | U,VU,V | left/right singular vectors (orthogonal) | matrices | | σ1≥⋯≥σp≥0\sigma_1\ge\cdots\ge\sigma_p\ge0 | singular values | scalars | | ui,viu_i,v_i | ii-th left/right singular vector | vectors | | Ak=∑i≤kσiuivi⊤A_k=\sum_{i\le k}\sigma_iu_iv_i^\top | best rank-kk approximation | matrix | | X∈Rn×dX\in\mathbb{R}^{n\times d} | raw data (nn samples, dd features) | matrix | | X~\tilde X | mean-centered data | matrix | | C=1n−1X~⊤X~C=\frac1{n-1}\tilde X^\top\tilde X | sample covariance | matrix | | VΛV⊤V\Lambda V^\top | eigendecomposition of CC | factorization | | Z=X~VZ=\tilde XV | principal-component scores | matrix | | λj=σj2/(n−1)\lambda_j=\sigma_j^2/(n-1) | variance along component jj | scalar | | p=min⁡(m,n)p=\min(m,n) | maximum possible rank | integer | | kk | target rank / number of components | integer | | ∥⋅∥F\lVert\cdot\rVert_F | Frobenius norm | norm | | ∥⋅∥2\lVert\cdot\rVert_2 | spectral (operator) norm | norm | | tr(⋅)\mathrm{tr}(\cdot) | matrix trace | functional |

9. Step-by-step derivation

Step 1 — construct singular values. A⊤AA^\top A is symmetric PSD, so A⊤A=VΛV⊤A^\top A=V\Lambda V^\top with λ1≥⋯≥λn≥0\lambda_1\ge\cdots\ge\lambda_n\ge0 and orthonormal columns viv_i. Set σi=λi\sigma_i=\sqrt{\lambda_i} and, for σi>0\sigma_i>0, ui=Avi/σiu_i=Av_i/\sigma_i. Then ui⊤uj=δiju_i^\top u_j=\delta_{ij} (see proofs) and Avi=σiuiAv_i=\sigma_iu_i. Stacking gives AV=UΣAV=U\Sigma, i.e. A=UΣV⊤A=U\Sigma V^\top.

Step 2 — best rank-kk via the Rayleigh quotient. For unit vv,

∥Av∥2=v⊤A⊤Av≤λ1,\lVert Av\rVert^2=v^\top A^\top Av\le\lambda_1,

with equality at v=v1v=v_1. So σ12=max⁡∥v∥=1∥Av∥2\sigma_1^2=\max_{\lVert v\rVert=1}\lVert Av\rVert^2; after projecting out v1,…,vj−1v_1,\dots,v_{j-1}, the same argument gives σj2\sigma_j^2 at vjv_j. Thus the singular values are the successive maximal "energy" directions.

Step 3 — truncation error. With U,VU,V orthogonal, by orthogonal invariance of ∥⋅∥F\lVert\cdot\rVert_F,

∥A−Ak∥F2=∥UΣV⊤−UΣkV⊤∥F2=∥Σ−Σk∥F2=∑i>kσi2.\lVert A-A_k\rVert_F^2=\lVert U\Sigma V^\top-U\Sigma_kV^\top\rVert_F^2=\lVert\Sigma-\Sigma_k\rVert_F^2=\sum_{i>k}\sigma_i^2 .

Any rank-kk matrix cannot do better (proof section): the truncated SVD is globally optimal.

Step 4 — PCA from SVD. Center XX: X~\tilde X. Then

C=1n−1X~⊤X~=1n−1(UΣV⊤)⊤(UΣV⊤)=1n−1VΣ2V⊤.C=\frac1{n-1}\tilde X^\top\tilde X=\frac1{n-1}(U\Sigma V^\top)^\top(U\Sigma V^\top)=\frac1{n-1}V\Sigma^2V^\top .

By uniqueness of the eigendecomposition up to signs/rotations in degenerate subspaces, the eigenvectors of CC are the right singular vectors of X~\tilde X and λj=σj2/(n−1)\lambda_j=\sigma_j^2/(n-1). The scores are Z=X~V=UΣZ=\tilde XV=U\Sigma, whose jj-th column has sample variance σj2/(n−1)=λj\sigma_j^2/(n-1)=\lambda_j.

Step 5 — choosing kk. Pick smallest kk with ∑i≤kλi/∑iλi≥τ\sum_{i\le k}\lambda_i/\sum_i\lambda_i\ge\tau (e.g. τ=0.95\tau=0.95), or use a scree-plot elbow, or cross-validate reconstruction error.

10. Proofs and proof intuition

Proposition 1 (existence). The construction above yields A=UΣV⊤A=U\Sigma V^\top with U,VU,V orthogonal. Proof. ui⊤uj=(Avi)⊤(Avj)σiσj=vi⊤A⊤Avjσiσj=vi⊤λjvjσiσj=λjσiσjδij=δiju_i^\top u_j=\frac{(Av_i)^\top(Av_j)}{\sigma_i\sigma_j}=\frac{v_i^\top A^\top Av_j}{\sigma_i\sigma_j}=\frac{v_i^\top\lambda_jv_j}{\sigma_i\sigma_j}=\frac{\lambda_j}{\sigma_i\sigma_j}\delta_{ij}=\delta_{ij}. For zero singular values extend {ui}\{u_i\} to an orthonormal basis of Rm\mathbb{R}^m. Then AV=UΣAV=U\Sigma on the span of the viv_i and hence A=UΣV⊤A=U\Sigma V^\top. □\square

Theorem (Eckart–Young–Mirsky, Frobenius case). min⁡\rankB≤k∥A−B∥F2=∑i>kσi2\min_{\rank B\le k}\lVert A-B\rVert_F^2=\sum_{i>k}\sigma_i^2. Proof. Let the SVD of BB have rank at most kk, with left/right orthonormal sets {pa}\{p_a\}, {qa}\{q_a\}. Complete them to full orthonormal bases P,QP,Q. Orthogonal invariance gives ∥A−B∥F=∥P⊤AQ−P⊤BQ∥F\lVert A-B\rVert_F=\lVert P^\top AQ-P^\top BQ\rVert_F. The matrix C=P⊤BQC=P^\top BQ has at most kk nonzero columns, and ∥C∥F2=∑a≤k∥C:a∥2\lVert C\rVert_F^2=\sum_{a\le k}\lVert C_{:a}\rVert^2. For each column, ∥P⊤AQ:a∥2=∥Aqa∥2≤σ12\lVert P^\top AQ_{:a}\rVert^2=\lVert Aq_a\rVert^2\le\sigma_1^2 — but the sharper bound uses the trace: ∥A−B∥F2=∥A∥F2−2\tr(B⊤A)+∥B∥F2\lVert A-B\rVert_F^2=\lVert A\rVert_F^2-2\tr(B^\top A)+\lVert B\rVert_F^2. By von Neumann's trace inequality \tr(B⊤A)=∑iσi(A)σi(B)≤∑i≤kσi(A)σi(B)\tr(B^\top A)=\sum_i\sigma_i(A)\sigma_i(B)\le\sum_{i\le k}\sigma_i(A)\sigma_i(B). Optimizing the resulting quadratic over σi(B)\sigma_i(B) gives σi(B)=σi(A)\sigma_i(B)=\sigma_i(A) for i≤ki\le k and the value ∥A∥F2−∑i≤kσi2=∑i>kσi2\lVert A\rVert_F^2-\sum_{i\le k}\sigma_i^2=\sum_{i>k}\sigma_i^2, attained by AkA_k. Spectral-norm case: similarly ∥A−Ak∥2=σk+1\lVert A-A_k\rVert_2=\sigma_{k+1} and no rank-kk matrix can reduce the (k+1)(k+1)-th singular direction. □\square

Proposition 2 (PCA–SVD link). λj(C)=σj2(X~)/(n−1)\lambda_j(C)=\sigma_j^2(\tilde X)/(n-1). Proof. Immediate from C=1n−1VΣ2V⊤C=\frac1{n-1}V\Sigma^2V^\top and uniqueness of eigenvalues. □\square

Proof intuition. Orthogonal changes of basis cannot change lengths, so the whole problem is about the diagonal of Σ\Sigma: keep the kk largest energies, discard the rest; von Neumann's inequality says no tilted rank-kk subspace can capture more.

11. Geometric interpretation

The linear map x↦Axx\mapsto Ax sends the unit sphere ∥v∥=1\lVert v\rVert=1 to an ellipsoid in Rm\mathbb{R}^m whose semi-axis lengths are σ1≥⋯≥σp\sigma_1\ge\cdots\ge\sigma_p and whose axis directions are uiu_i; the preimages of those axes are viv_i. 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. v1v_1 is its longest axis (maximum variance), v2v_2 the next longest perpendicular axis, and so on. Projecting onto the first kk axes gives the best kk-dimensional shadow of the cloud in the least-squares sense. Reconstruction error equals the squared lengths of the discarded axes: ∑i>kσi2\sum_{i>k}\sigma_i^2.

12. Visual explanation

Three standard views: (i) ellipsoid plot — draw the unit circle, its image under AA, and overlay the uiu_i, viv_i axes; (ii) scree plot — bar chart of σi2\sigma_i^2 or explained-variance ratio versus component index, with a cumulative line used to pick kk; (iii) biplot — scatter the scores ZZ and overlay arrows for the original feature loadings VV, showing which features drive each component. In the interactive lab, vary the target rank kk and watch the reconstructed image lose detail as ∑i>kσi2\sum_{i>k}\sigma_i^2 grows. The singular-value spectrum's decay rate (exponential vs. algebraic) predicts how well compression works.

13. Numerical worked example

SVD. Let A=(3113)A=\begin{pmatrix}3&1\\1&3\end{pmatrix}. It is symmetric; A⊤A=A2A^\top A=A^2 has eigenvalues 4,24,2 with eigenvectors (1,1)/2(1,1)/\sqrt2, (1,−1)/2(1,-1)/\sqrt2. Hence

U=V=12(111−1),Σ=diag(4,2).U=V=\frac1{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix},\qquad \Sigma=\mathrm{diag}(4,2).

Best rank-1 approximation: A1=4⋅12(1111)=(2222)A_1=4\cdot\frac12\begin{pmatrix}1&1\\1&1\end{pmatrix}=\begin{pmatrix}2&2\\2&2\end{pmatrix}. Error matrix A−A1=(1−1−11)A-A_1=\begin{pmatrix}1&-1\\-1&1\end{pmatrix}, so ∥A−A1∥F=2=σ2\lVert A-A_1\rVert_F=2=\sigma_2 and ∥A−A1∥2=2\lVert A-A_1\rVert_2=2 — exactly the Eckart–Young bound.

PCA. Four 2D points x1=(1,1),x2=(2,1),x3=(3,2),x4=(4,3)x_1=(1,1),x_2=(2,1),x_3=(3,2),x_4=(4,3). Mean (2.5,1.75)(2.5,1.75); centered points (−1.5,−0.75),(−0.5,−0.75),(0.5,0.25),(1.5,1.25)(-1.5,-0.75),(-0.5,-0.75),(0.5,0.25),(1.5,1.25). Then

X~⊤X~=(53.53.52.75),C=13X~⊤X~.\tilde X^\top\tilde X=\begin{pmatrix}5&3.5\\3.5&2.75\end{pmatrix},\qquad C=\tfrac13\tilde X^\top\tilde X .

The eigenvalues of X~⊤X~\tilde X^\top\tilde X are (7.75±54.0625)/2≈7.5517, 0.1983(7.75\pm\sqrt{54.0625})/2\approx7.5517,\ 0.1983; dividing by 33: λ1≈2.5172\lambda_1\approx2.5172, λ2≈0.0661\lambda_2\approx0.0661. Explained variance of PC1 =2.5172/2.5833≈97.4%=2.5172/2.5833\approx97.4\%. The top eigenvector solves (5−7.5517)v1+3.5v2=0(5-7.5517)v_1+3.5v_2=0, giving v≈(0.808,0.589)v\approx(0.808,0.589) — a line of slope ≈0.73\approx0.73, matching the cloud's tilt. Scores are Z=X~vZ=\tilde Xv; their sample variance is ≈2.5172\approx2.5172.

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 v↦A⊤Av/∥⋅∥v\mapsto A^\top Av/\lVert\cdot\rVert, which converges to the top eigenvector of A⊤AA^\top A at rate (σ2/σ1)2t(\sigma_2/\sigma_1)^{2t} — slow when singular values are close. Deflating A←A−σ1u1v1⊤A\leftarrow A-\sigma_1u_1v_1^\top removes the leading component so the next iteration finds σ2\sigma_2. The Rayleigh estimate ∥Av∥\lVert Av\rVert equals σ\sigma when vv 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 ss 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_ (= V⊤V^\top), explained_variance_ratio_, and fit_transform; randomized_svd uses a Gaussian sketch plus subspace iteration and is the default for large k≪min⁡(m,n)k\ll\min(m,n) with a flat spectrum.

19. Tensor and memory analysis

A full SVD stores U∈Rm×mU\in\mathbb{R}^{m\times m}, Σ∈Rm×n\Sigma\in\mathbb{R}^{m\times n}, V⊤∈Rn×nV^\top\in\mathbb{R}^{n\times n}: m2+mn+n2m^2+mn+n^2 floats. In fp32 for m=n=10,000m=n=10{,}000 that is 3×1083\times10^8 floats ≈1.2\approx1.2 GB — plus the 400400 MB input. The thin SVD stores only mk+nk+k≈2mkmk+nk+k\approx2mk floats. For PCA on nn samples, dd features: if d≪nd\ll n use the covariance path O(d2)O(d^2) memory; if n≪dn\ll d use the gram matrix XX⊤∈Rn×nXX^\top\in\mathbb{R}^{n\times n} or direct SVD of X~\tilde X. Randomized SVD stores a sketch Q∈Rm×(k+p)Q\in\mathbb{R}^{m\times(k+p)} and small BB, i.e. O((m+n)k)O((m+n)k), the difference between feasible and impossible at scale. The centered matrix X~\tilde X itself costs O(nd)O(nd); if XX is sparse, avoid dense centering to preserve sparsity.

20. Time complexity

Full SVD of m×nm\times n (m≥nm\ge n): bidiagonalization O(mn2)O(mn^2) plus QR iterations O(n2)O(n^2) to O(n3)O(n^3) depending on variants; practical LAPACK is ~O(mn2)O(mn^2). Thin SVD to rank kk: O(mnk)O(mnk) via randomized SVD with qq power iterations, O(mnkq)O(mnkq). Covariance PCA: forming CC costs O(nd2)O(nd^2) and its eigendecomposition O(d3)O(d^3); direct SVD of X~\tilde X is O(ndmin⁡(n,d))O(nd\min(n,d)) and more stable. Power iteration needs O(nnz(A)⋅q)O(\mathrm{nnz}(A)\cdot q) per component for sparse AA. Choose by aspect ratio: d≪nd\ll n → covariance; n≪dn\ll d → SVD of X~\tilde X or gram matrix; huge and low-rank → randomized.

21. Space complexity

Full SVD O(m2+mn+n2)O(m^2+mn+n^2); thin SVD O((m+n)k)O((m+n)k); randomized SVD O((m+n)k)O((m+n)k) plus oversampling p≈5–10p\approx5\text{–}10. Covariance PCA O(d2)O(d^2) for CC plus O(nd)O(nd) for the centered data (or streaming accumulation of CC in O(d2)O(d^2) only). For a 104×10410^4\times10^4 matrix, full factors need ~1.2 GB in fp32 versus ~80 MB for rank-100 thin factors. Workspace for Householder bidiagonalization is O(mn)O(mn) in practice; blocked algorithms trade extra memory for cache efficiency.

22. Experimental demonstration

Take a grayscale image as a matrix A∈R480×640A\in\mathbb{R}^{480\times640}, compute its SVD, and reconstruct with k∈{1,5,20,50,100}k\in\{1,5,20,50,100\}. Report relative Frobenius error ∥A−Ak∥F/∥A∥F=∑i>kσi2/∑iσi2\lVert A-A_k\rVert_F/\lVert A\rVert_F=\sqrt{\sum_{i>k}\sigma_i^2/\sum_i\sigma_i^2} and compression ratio k(m+n)/(mn)k(m+n)/(mn). Typical natural images reach 90% energy by k≈20k\approx20 and look recognizable at k≈50k\approx50 with 10–20× compression. Second experiment: on synthetic X=ZQ⊤+noiseX=ZQ^\top+\text{noise} with known rank-rr structure, compare PCA variance explained against the generating signal; recovered subspace angle should shrink as nn grows like O(1/n)O(1/\sqrt n). Third: plot runtime of full vs. randomized SVD for m=5000,n=2000,k=50m=5000,n=2000,k=50; randomized should be several times faster.

23. Benchmark results

On a 5000×20005000\times2000 dense matrix with numerical rank ≈100\approx100, LAPACK full SVD takes on the order of tens of seconds; randomized SVD with k=100k=100, q=2q=2 typically runs several times faster with relative error within a few percent of optimal. Accuracy benchmarks should report ∥A−Ak∥F/∥A∥F\lVert A-A_k\rVert_F/\lVert A\rVert_F 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 σk≈σk+1\sigma_k\approx\sigma_{k+1}, randomized methods need more power iterations (or qq adaptive), and any rank-kk 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: ui,viu_i,v_i 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: O(mn2)O(mn^2) is prohibitive for very large matrices.
  • Interpretability: principal components are dense combinations of features, often hard to name.

25. Failure scenarios

  1. 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.
  2. d≫nd\gg n: the covariance C∈Rd×dC\in\mathbb{R}^{d\times d} is huge and rank-deficient; forming its eigenvectors is wasteful — use SVD of X~∈Rn×d\tilde X\in\mathbb{R}^{n\times d} or the n×nn\times n gram matrix.
  3. Outliers: a single extreme point can dominate the top eigenvector; use robust PCA (principal component pursuit) or trimming.
  4. Repeated singular values: when σk=σk+1\sigma_k=\sigma_{k+1}, the rank-kk subspace and individual vectors are non-unique — columns can rotate between runs; only the captured energy is stable.
  5. Ill-conditioned A⊤AA^\top A: forming the normal equations squares the condition number, destroying small singular values; use direct SVD.
  6. Numerical rank threshold: tiny singular values from floating-point noise should be truncated using a tolerance like σ1⋅max⁡(m,n)ϵmach\sigma_1\cdot\max(m,n)\epsilon_{\text{mach}}.

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 VV tell you the mixture.
  • "100% explained variance means good low-rank structure." With dd 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; O(mnk)O(mnk) 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 ℓ1\ell_1 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

  1. Implement pca_from_svd from memory and verify the four-point example: λ≈(2.5172,0.0661)\lambda\approx(2.5172,0.0661) and v1≈(0.808,0.589)v_1\approx(0.808,0.589).
  2. Prove numerically that for A=(3113)A=\begin{pmatrix}3&1\\1&3\end{pmatrix} the rank-1 truncation error equals σ2=2\sigma_2=2 in both Frobenius and spectral norms.
  3. Generate X=ZQ⊤+ϵX=ZQ^\top+\epsilon with Z∈R100×3Z\in\mathbb{R}^{100\times3}, QQ random orthonormal; recover the subspace and measure the principal angle to QQ.
  4. Compress an image at k∈{5,20,50,100}k\in\{5,20,50,100\}; plot relative Frobenius error and compression ratio; find the "knee".
  5. Reproduce the failure from skipping centering: show PC1 aligns with the mean on a shifted cloud.
  6. Compare full and randomized SVD on a 3000×10003000\times1000 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 τ=σ1max⁡(m,n)ϵmach\tau=\sigma_1\max(m,n)\epsilon_{\text{mach}}.
  • randomized_svd error much worse than theory. Increase n_iter / oversampling, or check whether σk≈σk+1\sigma_k\approx\sigma_{k+1} (flat spectrum).
  • Explained variance sums to more than 100%. You divided by nn instead of n−1n-1 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

  1. Prove the spectral-norm case of Eckart–Young–Mirsky using the min–max theorem for σk+1\sigma_{k+1}.
  2. Derive the convergence rate O((σ2/σ1)2t)O((\sigma_2/\sigma_1)^{2t}) of power iteration and implement block power iteration with QR re-orthogonalization.
  3. Show that PCA whitening (ZΛ−1/2Z\Lambda^{-1/2}) decorrelates features and derive its effect on the condition number of a downstream least-squares problem.
  4. Implement robust PCA via alternating minimization with nuclear-norm shrinkage; test on a low-rank matrix with 5% gross outliers.
  5. Derive the influence function of the top eigenvector and show explicitly how a single outlier can dominate it.
  6. Implement randomized SVD with adaptive subspace iteration (choose qq from a posterior error estimate).

35. Interview questions

  • State the full SVD and explain the dimensions of U,Σ,VU,\Sigma,V 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 λj(C)=σj2/(n−1)\lambda_j(C)=\sigma_j^2/(n-1) for PCA and explain the n−1n-1.
  • Why is forming A⊤AA^\top A before SVD numerically dangerous? Quantify with the condition number.
  • What happens when σk=σk+1\sigma_k=\sigma_{k+1}? Is the rank-kk 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 kk 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 ϵ,δ\epsilon,\delta 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, d≫nd\gg n, 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. ∑i>kσi2\sqrt{\sum_{i>k}\sigma_i^2}, and tests asserting rank-1 error =2=2 on the example and λ1≈2.5172\lambda_1\approx2.5172 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.``

Research papers linked to this concept

eckart1936 · citation recorded, library entry pending
Analysis of a Complex of Statistical Variables into Principal Components 1933On Lines and Planes of Closest Fit to Systems of Points in Space 1901
golub1969 · citation recorded, library entry pending
halko2011 · citation recorded, library entry pending