Survey of Mathematics

3.4 The singular value decomposition and PCA

Every matrix, of any shape, is a rotation, then a stretch along the axes, then another rotation. The stretch factors (singular values) measure how much each direction matters, which gives the best low-rank approximation of a matrix and the principal components of a data set.

Beyond the courseStrang, Introduction to Linear Algebra, 7.1 to 7.3Trefethen and Bau, Numerical Linear Algebra, Lectures 4 and 5CS 532 (Matrix Methods in Machine Learning)MATH 375 Piazza @128

The spectral theorem (3.1) is wonderful but only covers symmetric matrices. Most matrices in practice are not symmetric, and many are not even square: a data table with 10,000 rows and 50 columns, an image of 1080 by 1920 pixels, a neural-network layer mapping 768 numbers to 3072. The singular value decomposition says every one of them, without exception, is a rotation followed by a stretch along perpendicular axes followed by another rotation. The stretch factors tell you which directions matter, and throwing away the small ones is the best possible compression.

Before you start

Chapters 3.1 (spectral theorem), 3.2 (positive semidefinite) and 3.3 (orthogonal matrices).

Quick checkFor any matrix AA, what kind of matrix is ATAA^{\mathsf T}A?
Quick checkAn orthogonal matrix QQ does what to the length of a vector?

The picture

Press Next three times. Move 1 (VTV^{\mathsf T}) turns the circle so that two special perpendicular directions v1,v2v_1, v_2 line up with the axes; a circle stays a circle. Move 2 (Σ\Sigma) stretches along the axes by σ1\sigma_1 and σ2\sigma_2, making an ellipse. Move 3 (UU) turns the ellipse into its final position. The result is exactly what AA does to the circle. Try “Rank one”: σ2=0\sigma_2 = 0 and the ellipse collapses to a segment.

Where this came from· Discovered twice, computed a century later

Eugenio Beltrami (1873) and Camille Jordan (1874) independently found the decomposition while studying bilinear forms, which are the expressions xTAyx^{\mathsf T}Ay with two different vectors. Erhard Schmidt proved the matching approximation result for integral operators in 1907. Carl Eckart and Gale Young proved it for matrices in 1936, in the journal Psychometrika, where such approximations were wanted for test-score data. Principal component analysis has a separate history: Karl Pearson (1901) fitted lines and planes to data, and Harold Hotelling (1933) named it. A practical way to compute the SVD came only in the 1960s, from Gene Golub and William Kahan. Their idea of reducing the matrix to a simpler bidiagonal form first is still the first stage of the routines behind NumPy’s svd.

Definitions and the theorem

Definition B

Singular value

The singular values of a real m×nm \times n matrix AA are σi=λi\sigma_i = \sqrt{\lambda_i}, where λ1≥λ2≥⋯≥λn≥0\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_n \ge 0 are the eigenvalues of the symmetric positive semidefinite matrix ATAA^{\mathsf T}A. (Positive semidefinite was shown in 3.2: xTATAx=∥Ax∥2≥0x^{\mathsf T}A^{\mathsf T}Ax = \lVert Ax \rVert^2 \ge 0, so no λi\lambda_i is negative and the square roots exist. If m<nm < n then rank⁡A≤m\operatorname{rank} A \le m, so at most mm of the σi\sigma_i are non-zero.)

In one lineThe singular values of A are the square roots of the eigenvalues of AᵀA, listed from largest to smallest: the stretch factors of A.

Why it existsThey measure how much A stretches each of a set of perpendicular directions, which is what 'the size of A in each direction' should mean.

Definition B

Singular value decomposition

A singular value decomposition of AA is a factorisation A=UΣVTA = U\Sigma V^{\mathsf T} where UU is an m×mm \times m orthogonal matrix, VV is an n×nn \times n orthogonal matrix, and Σ\Sigma is m×nm \times n with the singular values σ1≥σ2≥⋯≥0\sigma_1 \ge \sigma_2 \ge \dots \ge 0 on its diagonal and zeros elsewhere. The columns viv_i of VV are the right singular vectors and the columns uiu_i of UU the left singular vectors, with

Avi=σiui.Av_i = \sigma_i u_i.

In one lineA = UΣVᵀ with U (m×m) and V (n×n) orthogonal and Σ (m×n) diagonal with σ₁ ≥ σ₂ ≥ … ≥ 0.

Why it existsIt describes any matrix as rotate, stretch along axes, rotate, and exposes its rank, its four subspaces and its best approximations.

Theorem B Strang 7.2; Trefethen–Bau Thm 4.1

Every matrix has an SVD

Every real m×nm \times n matrix AA has a singular value decomposition.

In one lineEvery real m×n matrix has a singular value decomposition A = UΣVᵀ.

Why it is trueDiagonalize the symmetric AᵀA to get V; then the vectors Avᵢ are automatically perpendicular, and dividing by their lengths gives U.

Why· The picture behind the proof

Look for perpendicular inputs whose outputs are also perpendicular. Those inputs are the eigenvectors of ATAA^{\mathsf T}A: their images under AA come out perpendicular “for free”, because (Avi)⋅(Avj)=vi⋅(ATAvj)(Av_i)\cdot(Av_j) = v_i \cdot (A^{\mathsf T}Av_j), and ATAA^{\mathsf T}A only rescales vjv_j. The lengths of the images are the singular values, and the image directions are the uiu_i.

ProofStrang 7.2
The idea: Apply the spectral theorem to AᵀA: orthonormal eigenvectors v_i, eigenvalues λ_i = σ_i² ≥ 0. For σ_i > 0 set u_i = Av_i/σ_i; these are orthonormal. Extend to an orthonormal basis of ℝ^m. Then AV = UΣ.
Let v1,…,vnv_1, \dots, v_n be orthonormal eigenvectors of ATAA^{\mathsf T}A with eigenvalues λ1≥⋯≥λn≥0\lambda_1 \ge \dots \ge \lambda_n \ge 0. Set σi=λi\sigma_i = \sqrt{\lambda_i}.
ATAA^{\mathsf T}A is symmetric, so the spectral theorem (3.1) gives an orthonormal eigenbasis; its eigenvalues are ≥0\ge 0 because it is positive semidefinite (3.2).
(Avi)⋅(Avj)=vi⋅(ATAvj)=λj vi⋅vj(Av_i)\cdot(Av_j) = v_i \cdot (A^{\mathsf T}Av_j) = \lambda_j\, v_i \cdot v_j, which is σj2\sigma_j^2 if i=ji = j and 0 otherwise.
Move AA across the dot product with the transpose, then use the eigenvector equation and orthonormality.
Let rr be the number of σi>0\sigma_i > 0. For i≤ri \le r set ui=Aviσiu_i = \frac{Av_i}{\sigma_i}. By the previous line these are orthonormal.
So the images are perpendicular, and ∥Avi∥=σi\lVert Av_i \rVert = \sigma_i.
Extend u1,…,uru_1, \dots, u_r to an orthonormal basis u1,…,umu_1, \dots, u_m of Rm\mathbb R^m.
Any orthonormal set in Rm\mathbb R^m extends to an orthonormal basis (extend to a basis, 2.2, then Gram–Schmidt, 2.9).
So Avi=σiuiAv_i = \sigma_i u_i for every i≤ri \le r and Avi=OAv_i = O for i>ri > r, which in matrix form is AV=UΣAV = U\Sigma.
For i≤ri \le r, Avi=σiuiAv_i = \sigma_i u_i by definition. For i>ri > r, ∥Avi∥=σi=0\lVert Av_i \rVert = \sigma_i = 0, so Avi=OAv_i = O. (If m<nm < n, there is no uiu_i for i>mi > m, but then σi=0\sigma_i = 0 and the column of Σ\Sigma is zero anyway.)
A=UΣVTA = U\Sigma V^{\mathsf T}. ■\blacksquare
VV is orthogonal, so V−1=VTV^{-1} = V^{\mathsf T}.
Worked example
Compute an SVD of A=[3045]A = \begin{bmatrix}3&0\\4&5\end{bmatrix}.

Solution. The method is: form ATAA^{\mathsf T}A, diagonalize it, then get each uiu_i by applying AA. The step-through below shows each stage.

Answer. A=UΣVTA = U\Sigma V^{\mathsf T} with σ1=35\sigma_1 = 3\sqrt5, σ2=5\sigma_2 = \sqrt5, U=110[1−331]U = \frac1{\sqrt{10}}\begin{bmatrix}1&-3\\3&1\end{bmatrix} and VT=12[11−11]V^{\mathsf T} = \frac1{\sqrt2}\begin{bmatrix}1&1\\-1&1\end{bmatrix}.

Your answerFor A=[3045]A = \begin{bmatrix}3&0\\4&5\end{bmatrix}, what is σ2\sigma_2 squared? (It is an eigenvalue of ATA=[25202025]A^{\mathsf T}A = \begin{bmatrix}25&20\\20&25\end{bmatrix}.)
Worked example
Find the singular values and the rank of [1224]\begin{bmatrix}1&2\\2&4\end{bmatrix}, and of the symmetric matrix [200−3]\begin{bmatrix}2&0\\0&-3\end{bmatrix}.

Solution.

  1. First matrix: form ATAA^{\mathsf T}A. ATA=[1+42+82+84+16]=[5101020]A^{\mathsf T}A = \begin{bmatrix}1+4 & 2+8\\ 2+8 & 4+16\end{bmatrix} = \begin{bmatrix}5&10\\10&20\end{bmatrix}. Entry (i,j)(i,j) is column ii dotted with column jj.
  2. Its eigenvalues. Trace 2525, determinant 100−100=0100 - 100 = 0, so λ=25,0\lambda = 25, 0. For a 2×22 \times 2 matrix the eigenvalues have sum equal to the trace and product equal to the determinant.
  3. Singular values and rank. σ=5,0\sigma = 5, 0, so the rank is 1. Rank is the number of non-zero singular values. The second column is twice the first, so rank 1 agrees.
  4. Second matrix. ATA=diag⁡(4,9)A^{\mathsf T}A = \operatorname{diag}(4, 9), so the singular values are 33 and 22 (largest first). Singular values are square roots, never negative. The eigenvalues of AA are 22 and −3-3, so ∣λi∣|\lambda_i| is what we see here.
  5. Where did the minus sign go? The right singular vector for σ1=3\sigma_1 = 3 is v1=e2v_1 = e_2, and for σ2=2\sigma_2 = 2 it is v2=e1v_2 = e_1. Then u1=Av1/3=(0,−3)/3=(0,−1)u_1 = Av_1/3 = (0, -3)/3 = (0, -1) and u2=Av2/2=(1,0)u_2 = Av_2/2 = (1, 0). Apply AA and divide by the singular value, as in the proof. The minus sign lands in u1u_1.
  6. Check the product. U=[01−10]U = \begin{bmatrix}0&1\\-1&0\end{bmatrix}, Σ=diag⁡(3,2)\Sigma = \operatorname{diag}(3, 2), VT=[0110]V^{\mathsf T} = \begin{bmatrix}0&1\\1&0\end{bmatrix} give UΣVT=[02−30][0110]=[200−3]U\Sigma V^{\mathsf T} = \begin{bmatrix}0&2\\-3&0\end{bmatrix}\begin{bmatrix}0&1\\1&0\end{bmatrix} = \begin{bmatrix}2&0\\0&-3\end{bmatrix}. Multiplying back is the check that the factorization is right.

Answer. First matrix: σ=5,0\sigma = 5, 0, rank 1. Second matrix: σ=3,2\sigma = 3, 2. For a symmetric matrix, σi=∣λi∣\sigma_i = |\lambda_i|, and the signs of negative eigenvalues move into UU.

Your answerThe singular values of [200−3]\begin{bmatrix}2&0\\0&-3\end{bmatrix}: what is σ1\sigma_1, the largest?
Quick checkHow is rank read off the SVD?
Worked example
Prove: the largest stretch of AA, namely max⁡∥x∥=1∥Ax∥\max_{\lVert x \rVert = 1}\lVert Ax \rVert, equals σ1\sigma_1. Test it on [3045]\begin{bmatrix}3&0\\4&5\end{bmatrix}.

Solution.

  1. Square the length. ∥Ax∥2=(Ax)T(Ax)=xT(ATA)x\lVert Ax \rVert^2 = (Ax)^{\mathsf T}(Ax) = x^{\mathsf T}(A^{\mathsf T}A)x. This turns the question into a quadratic form of the symmetric matrix ATAA^{\mathsf T}A (3.2).
  2. Use the eigenbasis. Write x=∑civix = \sum c_iv_i with ∑ci2=1\sum c_i^2 = 1. Then xTATAx=∑λici2x^{\mathsf T}A^{\mathsf T}Ax = \sum \lambda_ic_i^2. The viv_i are orthonormal eigenvectors of ATAA^{\mathsf T}A, so the cross terms vanish (3.1).
  3. Bound it. ∑λici2≤λ1∑ci2=λ1\sum\lambda_ic_i^2 \le \lambda_1\sum c_i^2 = \lambda_1, with equality at x=v1x = v_1. λ1\lambda_1 is the largest eigenvalue.
  4. Take square roots. max⁡∥Ax∥=λ1=σ1\max\lVert Ax \rVert = \sqrt{\lambda_1} = \sigma_1. Square root is increasing.
  5. Test. For A=[3045]A = \begin{bmatrix}3&0\\4&5\end{bmatrix}, x=v1=12(1,1)x = v_1 = \frac1{\sqrt2}(1, 1) gives Ax=12(3,9)Ax = \frac1{\sqrt2}(3, 9) of length 45=35≈6.71\sqrt{45} = 3\sqrt5 \approx 6.71. The longest output from a unit input.

Answer. max⁡∥x∥=1∥Ax∥=σ1\max_{\lVert x \rVert = 1}\lVert Ax \rVert = \sigma_1, attained at v1v_1. ■\blacksquare This number is called the operator norm of AA (3.5).

Worked example
Prove: for a square matrix AA, ∣det⁡A∣=σ1σ2⋯σn|\det A| = \sigma_1\sigma_2\cdots\sigma_n. Test on [3045]\begin{bmatrix}3&0\\4&5\end{bmatrix}.

Solution.

  1. Take determinants of the SVD. det⁡A=det⁡U⋅det⁡Σ⋅det⁡VT\det A = \det U\cdot\det\Sigma\cdot\det V^{\mathsf T}. Product rule for determinants (2.7).
  2. Evaluate each factor. det⁡U=±1\det U = \pm1 and det⁡VT=±1\det V^{\mathsf T} = \pm1, and det⁡Σ=σ1⋯σn\det\Sigma = \sigma_1\cdots\sigma_n since Σ\Sigma is diagonal. Orthogonal matrices have determinant ±1\pm1 (3.3), and a diagonal determinant is the product of the diagonal.
  3. Absolute value. ∣det⁡A∣=σ1⋯σn|\det A| = \sigma_1\cdots\sigma_n. The signs disappear, and the σi\sigma_i are non-negative.
  4. Test. det⁡[3045]=15\det\begin{bmatrix}3&0\\4&5\end{bmatrix} = 15 and σ1σ2=35⋅5=15\sigma_1\sigma_2 = 3\sqrt5\cdot\sqrt5 = 15. Matches the step-through above.

Answer. ∣det⁡A∣=∏σi|\det A| = \prod\sigma_i. ■\blacksquare Rotations keep area, so all the area change comes from the stretches.

Quick checkWhy is a singular value of a matrix never negative, even when AA has a negative eigenvalue?

The SVD as a sum: low-rank approximation

Multiplying out UΣVTU\Sigma V^{\mathsf T} column by row gives

A=σ1u1v1T+σ2u2v2T+⋯+σrurvrT.A = \sigma_1 u_1 v_1^{\mathsf T} + \sigma_2 u_2 v_2^{\mathsf T} + \dots + \sigma_r u_r v_r^{\mathsf T}.

Each uiviTu_i v_i^{\mathsf T} is a rank-1 matrix (every row a multiple of viTv_i^{\mathsf T}). The SVD writes AA as a sum of rank-1 pieces, in decreasing order of importance σi\sigma_i.

Definition B

Low-rank approximation

For k<rk < r, the rank-kk truncation of AA is Ak=∑i=1kσiuiviTA_k = \sum_{i=1}^k \sigma_i u_i v_i^{\mathsf T}.

In one lineKeep the first k terms of the SVD sum: A_k = σ₁u₁v₁ᵀ + … + σ_k u_k v_kᵀ, a rank-k matrix close to A.

Why it existsIt compresses A to k(m + n + 1) numbers while keeping as much of A as any rank-k matrix can.

Theorem B Eckart and Young 1936; Trefethen–Bau Thm 5.8

Eckart–Young theorem

For every matrix BB of rank at most kk, ∥A−B∥≥σk+1=∥A−Ak∥\lVert A - B \rVert \ge \sigma_{k+1} = \lVert A - A_k \rVert, where ∥M∥=max⁡∥x∥=1∥Mx∥\lVert M \rVert = \max_{\lVert x \rVert = 1}\lVert Mx \rVert is the largest stretch of MM (the operator norm, 3.5). In the Frobenius norm (square root of the sum of squared entries) the same AkA_k is best, with error σk+12+⋯+σr2\sqrt{\sigma_{k+1}^2 + \dots + \sigma_r^2}. (We prove the operator-norm version below. The Frobenius version has a longer proof, in Trefethen–Bau.)

In one lineThe truncated SVD A_k is the best rank-k approximation of A; its error is the first discarded singular value σ_{k+1} (in the operator norm).

Why it is trueAny rank-k matrix kills some direction in the span of v₁, …, v_{k+1}, and A stretches every vector of that span by at least σ_{k+1}.

ProofTrefethen–Bau 5.8
The idea: (Operator norm.) B has rank ≤ k, so its null space has dimension ≥ n − k and must meet the (k + 1)-dimensional span of v₁, …, v_{k+1}. Pick a unit vector w there: Bw = O, and ‖Aw‖ ≥ σ_{k+1}.
dim⁡N(B)≥n−k\dim N(B) \ge n - k.
Rank–nullity (2.3).
N(B)N(B) and W=span⁡(v1,…,vk+1)W = \operatorname{span}(v_1, \dots, v_{k+1}) have dimensions adding to at least n+1n + 1, so there is a unit vector w∈N(B)∩Ww \in N(B) \cap W.
Two subspaces of Rn\mathbb R^n with dimensions adding to more than nn share a non-zero vector (the dim⁡(U+W)\dim(U + W) formula, 2.2).
∥Aw∥2=∑i≤k+1ci2σi2≥σk+12\lVert Aw \rVert^2 = \sum_{i \le k+1} c_i^2\sigma_i^2 \ge \sigma_{k+1}^2.
Write w=∑i≤k+1civiw = \sum_{i \le k+1} c_i v_i with ∑ci2=1\sum c_i^2 = 1; then Aw=∑ciσiuiAw = \sum c_i\sigma_i u_i and the uiu_i are orthonormal.
∥A−B∥≥∥(A−B)w∥=∥Aw∥≥σk+1\lVert A - B \rVert \ge \lVert (A - B)w \rVert = \lVert Aw \rVert \ge \sigma_{k+1}.
Bw=OBw = O, so (A−B)w=Aw(A - B)w = Aw.
And ∥A−Ak∥=σk+1\lVert A - A_k \rVert = \sigma_{k+1}, so AkA_k achieves the bound. ■\blacksquare
A−Ak=∑i>kσiuiviTA - A_k = \sum_{i > k}\sigma_i u_i v_i^{\mathsf T} is itself an SVD with largest singular value σk+1\sigma_{k+1}, and the largest stretch of a matrix is its largest singular value (the worked example above).
Proof workshopRebuild the Eckart–Young argument (operator norm)

Tap the lines in the order a proof would write them. Each line can only use what is already above it.

    Worked example Strang 7.2 style
    Find the SVD of the wide matrix A=[32223−2]A = \begin{bmatrix}3&2&2\\2&3&-2\end{bmatrix} using AATAA^{\mathsf T}, then give its best rank-1 approximation and the error.

    Solution.

    1. Choose the small product. AA is 2×32 \times 3, so AATAA^{\mathsf T} is 2×22 \times 2 while ATAA^{\mathsf T}A is 3×33 \times 3. We work with AAT=[178817]AA^{\mathsf T} = \begin{bmatrix}17&8\\8&17\end{bmatrix}. Its non-zero eigenvalues are the same σi2\sigma_i^2 as those of ATAA^{\mathsf T}A: if ATAv=λvA^{\mathsf T}Av = \lambda v with λ≠0\lambda \ne 0, then Av≠OAv \ne O and AAT(Av)=A(ATAv)=λ(Av)AA^{\mathsf T}(Av) = A(A^{\mathsf T}Av) = \lambda(Av). And it is smaller.
    2. Eigenvalues. 17±8=25,917 \pm 8 = 25, 9, so σ1=5\sigma_1 = 5, σ2=3\sigma_2 = 3. Same pattern a±ba \pm b as before.
    3. Left singular vectors. Eigenvectors of AATAA^{\mathsf T}: u1=12(1,1)u_1 = \frac1{\sqrt2}(1, 1) for 25 and u2=12(1,−1)u_2 = \frac1{\sqrt2}(1, -1) for 9. The uiu_i are the orthonormal eigenvectors of AATAA^{\mathsf T}.
    4. Right singular vectors. vi=ATui/σiv_i = A^{\mathsf T}u_i/\sigma_i: v1=12(1,1,0)v_1 = \frac1{\sqrt2}(1, 1, 0) and v2=132(1,−1,4)v_2 = \frac1{3\sqrt2}(1, -1, 4). From Avi=σiuiAv_i = \sigma_iu_i we get ATui=σiviA^{\mathsf T}u_i = \sigma_iv_i. Check: ∥(1,−1,4)∥=18=32\lVert(1, -1, 4)\rVert = \sqrt{18} = 3\sqrt2, so v2v_2 is a unit vector.
    5. Best rank-1 approximation. A1=σ1u1v1T=5⋅1212[11][110]=52[110110]A_1 = \sigma_1u_1v_1^{\mathsf T} = 5\cdot\frac1{\sqrt2}\frac1{\sqrt2}\begin{bmatrix}1\\1\end{bmatrix}\begin{bmatrix}1&1&0\end{bmatrix} = \frac52\begin{bmatrix}1&1&0\\1&1&0\end{bmatrix}. Keep the term with the largest singular value.
    6. Error. ∥A−A1∥=σ2=3\lVert A - A_1 \rVert = \sigma_2 = 3 in the operator norm. Eckart–Young: the error is the first discarded singular value. Check: A−A1=[0.5−0.52−0.50.5−2]A - A_1 = \begin{bmatrix}0.5&-0.5&2\\-0.5&0.5&-2\end{bmatrix} equals σ2u2v2T\sigma_2u_2v_2^{\mathsf T}.

    Answer. σ=5,3\sigma = 5, 3. A1=52[110110]A_1 = \frac52\begin{bmatrix}1&1&0\\1&1&0\end{bmatrix}, with error 33. There is no third uu, because a 2×32 \times 3 matrix has at most 2 non-zero singular values. The third right singular vector v3=13(2,−2,−1)v_3 = \frac13(2, -2, -1) spans the null space of AA.

    Your answerFor A=[32223−2]A = \begin{bmatrix}3&2&2\\2&3&-2\end{bmatrix}, the best rank-1 approximation has operator-norm error equal to σ2\sigma_2. What is it?
    Worked example
    Compress a 1000 by 1000 greyscale image to rank 50. How much storage is saved, and what decides the quality?

    Solution.

    1. Count the full image. 1000×1000=1061000 \times 1000 = 10^6 numbers. One brightness value per pixel.
    2. Count the rank-50 version. Each term σiuiviT\sigma_i u_i v_i^{\mathsf T} needs uiu_i (1000 numbers), viv_i (1000) and σi\sigma_i (1): 2001 numbers. For 50 terms: 100,050100{,}050. Store the factors, not the product.
    3. Ratio. 100,050/106≈10%100{,}050 / 10^6 \approx 10\% of the storage. About a tenfold saving.
    4. Quality. By Eckart–Young no rank-50 image is closer, and the error is governed by σ51,σ52,…\sigma_{51}, \sigma_{52}, \dots. Many photos have quickly decaying singular values (smooth regions are nearly low rank), so rank 50 can look close to the original, though fine texture is lost first. The theorem gives the best possible; the data decides how good “best” is.

    Answer. About 10% of the numbers, with the smallest possible error for that budget. (JPEG uses a fixed cosine basis instead, 2.2, because it is cheaper to compute; the SVD adapts its basis to each image.)

    Python labTruncate the SVD of a small synthetic image
    import numpy as np
    
    x = np.linspace(0, 1, 40)
    rng = np.random.default_rng(0)
    # a smooth 40 by 40 "image": two rank-1 patterns plus a little noise
    img = 5 * np.outer(np.sin(np.pi * x), np.cos(3 * x)) + 3 * np.outer(x, x**2)
    img = img + 0.05 * rng.standard_normal((40, 40))
    
    U, s, Vt = np.linalg.svd(img)
    print("first singular values:", np.round(s[:5], 3))
    for k in (1, 2, 3, 5):
        Ak = (U[:, :k] * s[:k]) @ Vt[:k]
        err = np.linalg.norm(img - Ak, 2)
        print(f"k={k}: error = {err:.4f}   next sigma = {s[k]:.4f}   numbers stored = {k*(40+40+1)} of 1600")

    Try this. Run it and compare each error with the 'next sigma' printed beside it: they match, as Eckart–Young says. The picture is built from two rank-1 patterns plus noise, so the error collapses at k=2k = 2 and then barely moves. Change the noise level 0.05 to 0.5 and watch the singular values from the third onward grow: that tail is the noise, and truncation throws it away.

    Your answerHow many numbers store a rank-kk approximation of an m×nm \times n matrix? Give the answer for m=768m = 768, n=768n = 768, k=8k = 8 (a LoRA-style update).

    Principal component analysis

    Definition B

    Principal component analysis

    Let XX be an N×dN \times d data matrix (one row per sample, one column per feature) with each column’s mean subtracted (centered). The principal components are the right singular vectors v1,v2,…v_1, v_2, \dots of XX. The variance of the data along viv_i is σi2N−1\frac{\sigma_i^2}{N - 1}, and v1v_1 is the direction of greatest variance.

    In one lineCenter the data, take the SVD of the data matrix; the right singular vectors are the directions of greatest variance, in decreasing order.

    Why it existsIt finds the few directions that carry most of the variation in high-dimensional data, so the data can be seen, compressed or denoised.

    Why· Why the singular vectors are the directions of greatest variance

    The variance of the data along a unit vector ww is 1N−1∑j(xj⋅w)2=1N−1∥Xw∥2=1N−1wT(XTX)w\frac{1}{N - 1}\sum_j (x_j \cdot w)^2 = \frac{1}{N - 1}\lVert Xw \rVert^2 = \frac{1}{N - 1}w^{\mathsf T}(X^{\mathsf T}X)w. That is a quadratic form in ww with the symmetric matrix XTXX^{\mathsf T}X (the covariance matrix up to the factor 1N−1\frac1{N-1}). By the Rayleigh-quotient problem of 3.1, its maximum over unit ww is the largest eigenvalue of XTXX^{\mathsf T}X, which is σ12\sigma_1^2, at w=v1w = v_1. The next direction, perpendicular to v1v_1, is v2v_2, and so on.

    Worked example
    Find the first principal component of the four points (2,1),(−2,−1),(1,2),(−1,−2)(2, 1), (-2, -1), (1, 2), (-1, -2).

    Solution.

    1. Center. The mean is (0,0)(0, 0) already. PCA measures spread around the mean, so the mean must be subtracted first.
    2. Form XTXX^{\mathsf T}X. XTX=[4+4+1+12+2+2+281+1+4+4]=[108810]X^{\mathsf T}X = \begin{bmatrix}4+4+1+1 & 2+2+2+2\\ 8 & 1+1+4+4\end{bmatrix} = \begin{bmatrix}10&8\\8&10\end{bmatrix}. Entry (i,j)(i, j) is the sum over points of (coordinate ii) times (coordinate jj).
    3. Eigenvectors. Eigenvalues 1818 and 22, with eigenvectors (1,1)(1, 1) and (1,−1)(1, -1). Same pattern as 3.1’s [2112]\begin{bmatrix}2&1\\1&2\end{bmatrix}.
    4. Read off. v1=12(1,1)v_1 = \frac1{\sqrt2}(1, 1) carries variance 183=6\frac{18}{3} = 6; v2v_2 carries 23\frac23. Variance along viv_i is σi2/(N−1)\sigma_i^2/(N - 1) with N=4N = 4.

    Answer. The points spread mostly along the diagonal y=xy = x: 90% of the total variance (1818+2\frac{18}{18 + 2}) lies along v1v_1. Projecting onto v1v_1 alone keeps 90% of the information in one number per point.

    Your answerIn the four-point example the eigenvalues of XTXX^{\mathsf T}X are 18 and 2. What fraction of the total variance lies along the first principal component? Give a decimal.
    Quick checkThe shear [1101]\begin{bmatrix}1&1\\0&1\end{bmatrix} has eigenvalues 1,11, 1. What are its singular values?
    Quick checkWhy must you center the data before PCA?
    Proof workshopGive the reason for each line: why the images Avᵢ are perpendicular

    Each line of the proof is shown in order. Choose the reason that justifies it, then press Check.

    1. (Avi)⋅(Avj)=vi⋅(ATAvj)(Av_i)\cdot(Av_j) = v_i \cdot (A^{\mathsf T}Av_j)
    2. =vi⋅(λjvj)= v_i \cdot (\lambda_j v_j)
    3. =λj (vi⋅vj)= \lambda_j\,(v_i \cdot v_j)
    4. =0= 0 when i≠ji \ne j

    Where it is used

    Used inside maths· Inside maths: the four subspaces, the pseudoinverse, conditioning

    The SVD hands you orthonormal bases of all four fundamental subspaces (2.6): u1..uru_1..u_r for the column space, vr+1..vnv_{r+1}..v_n for the null space, and so on. It gives the least squares solution even when columns are dependent (the pseudoinverse A+=VΣ+UTA^+ = V\Sigma^+U^{\mathsf T}). And σ1/σr\sigma_1/\sigma_r is the condition number of 3.5, which says how badly a system amplifies errors.

    Used in the real world· Data and AI: recommendations, genes, and language models

    In the Netflix Prize (2006 to 2009), the leading teams modelled the huge users-by-films ratings matrix as approximately low rank, a few “taste” directions explaining most ratings, and fitted SVD-like factorisations. In population genetics, the first two principal components of genetic data from Europeans reproduce a recognisable map of Europe (Novembre and colleagues, Nature, 2008). In language models, the LoRA paper (Hu and colleagues, 2021) hypothesised that the change in a weight matrix during fine-tuning has low rank, so it trains two thin factors BB and AA with ΔW=BA\Delta W = BA instead of the full matrix, and found that small ranks perform competitively.

    Traps

    Watch out· Singular values are not eigenvalues

    For non-symmetric AA, the singular values are the square roots of the eigenvalues of ATAA^{\mathsf T}A, not the eigenvalues of AA. The shear [1101]\begin{bmatrix}1&1\\0&1\end{bmatrix} has eigenvalues 1,11, 1 but singular values about 1.6181.618 and 0.6180.618.

    Watch out· Computing the SVD by forming AᵀA is fine by hand, risky in floating point

    Forming ATAA^{\mathsf T}A squares the condition number (3.5), so small singular values get lost to rounding. Library routines (Golub–Kahan) work on AA directly. Use np.linalg.svd(A), never np.linalg.eig(A.T @ A), for real data.

    Problems

    check

    Find the singular values of [1100]\begin{bmatrix}1&1\\0&0\end{bmatrix} and its rank.

    Solution

    ATA=[1111]A^{\mathsf T}A = \begin{bmatrix}1&1\\1&1\end{bmatrix} with eigenvalues 2,02, 0, so σ=2,0\sigma = \sqrt2, 0. Rank 1.

    check

    For a symmetric positive definite matrix, how are its SVD and its spectral decomposition related?

    Solution

    They coincide: A=QΛQTA = Q\Lambda Q^{\mathsf T} is already an SVD with U=V=QU = V = Q and Σ=Λ\Sigma = \Lambda (all λi>0\lambda_i > 0). For symmetric matrices with negative eigenvalues, σi=∣λi∣\sigma_i = |\lambda_i| and the signs move into UU.

    useStrang 7.2 style

    Compute an SVD of [1100]\begin{bmatrix}1&1\\0&0\end{bmatrix}.

    Solution

    v1=12(1,1)v_1 = \frac1{\sqrt2}(1, 1), v2=12(1,−1)v_2 = \frac1{\sqrt2}(1, -1); σ1=2\sigma_1 = \sqrt2, σ2=0\sigma_2 = 0. u1=Av1/σ1=(1,0)u_1 = Av_1/\sigma_1 = (1, 0); extend with u2=(0,1)u_2 = (0, 1). A=[1001][2000]12[111−1]A = \begin{bmatrix}1&0\\0&1\end{bmatrix}\begin{bmatrix}\sqrt2&0\\0&0\end{bmatrix}\frac1{\sqrt2}\begin{bmatrix}1&1\\1&-1\end{bmatrix}.

    use

    Give the best rank-1 approximation of the [3045]\begin{bmatrix}3&0\\4&5\end{bmatrix} from the step-through, and its error in the operator norm.

    Solution

    A1=σ1u1v1T=35⋅110(1,3)T12(1,1)=32[1133]A_1 = \sigma_1 u_1 v_1^{\mathsf T} = 3\sqrt5 \cdot \frac1{\sqrt{10}}(1, 3)^{\mathsf T}\frac1{\sqrt2}(1, 1) = \frac{3}{2}\begin{bmatrix}1&1\\3&3\end{bmatrix}. Error σ2=5≈2.24\sigma_2 = \sqrt5 \approx 2.24.

    prove

    Prove that σ1=max⁡∥x∥=1∥Ax∥\sigma_1 = \max_{\lVert x \rVert = 1}\lVert Ax \rVert.

    Solution

    ∥Ax∥2=xTATAx\lVert Ax \rVert^2 = x^{\mathsf T}A^{\mathsf T}Ax, a quadratic form whose maximum over unit xx is the largest eigenvalue of ATAA^{\mathsf T}A, which is σ12\sigma_1^2 (the Rayleigh problem of 3.1). Take square roots.

    prove

    Prove that ∣det⁡A∣=σ1σ2⋯σn|\det A| = \sigma_1\sigma_2\cdots\sigma_n for a square AA.

    Solution

    det⁡A=det⁡Udet⁡Σdet⁡VT=(±1) σ1⋯σn (±1)\det A = \det U \det\Sigma \det V^{\mathsf T} = (\pm1)\,\sigma_1\cdots\sigma_n\,(\pm1), since orthogonal matrices have determinant ±1\pm1 (3.3). Taking absolute values gives the claim. Geometrically: rotations keep area, so all the area change comes from the stretches.

    stretch

    Show that the eigenvalues of AATAA^{\mathsf T} (an m×mm \times m matrix) are the same non-zero numbers σi2\sigma_i^2, with eigenvectors uiu_i. Why might you compute the SVD of a wide data matrix this way?

    Solution

    AATui=AATAviσi=A(ATAvi)σi=Aσi2viσi=σi2uiAA^{\mathsf T}u_i = AA^{\mathsf T}\frac{Av_i}{\sigma_i} = \frac{A(A^{\mathsf T}Av_i)}{\sigma_i} = \frac{A\sigma_i^2 v_i}{\sigma_i} = \sigma_i^2 u_i. For a matrix with few rows and many columns (say 100 by 1,000,000), AATAA^{\mathsf T} is 100×100100 \times 100 while ATAA^{\mathsf T}A is enormous, so work with the small one and recover vi=ATui/σiv_i = A^{\mathsf T}u_i/\sigma_i.

    Summary

    • SVD: every matrix is A=UΣVTA = U\Sigma V^{\mathsf T}: rotate, stretch along axes by σ1≥σ2≥⋯≥0\sigma_1 \ge \sigma_2 \ge \dots \ge 0, rotate.
    • Build it from the spectral theorem on ATAA^{\mathsf T}A: viv_i its eigenvectors, σi=λi\sigma_i = \sqrt{\lambda_i}, ui=Avi/σiu_i = Av_i/\sigma_i.
    • Rank = number of non-zero singular values; σ1\sigma_1 = the largest stretch.
    • A=∑σiuiviTA = \sum \sigma_i u_i v_i^{\mathsf T}; keeping kk terms gives the best rank-kk approximation, with error σk+1\sigma_{k+1} (Eckart–Young).
    • PCA: center the data; the right singular vectors are the directions of greatest variance, with variance σi2/(N−1)\sigma_i^2/(N-1).
    • Applications: compression, recommendations, genetics, low-rank fine-tuning of AI models.

    Watch and read

    The same ideas explained by someone else. Use these when an explanation here does not land.

    Where this sits

    Comes from
    3.1 Symmetric matrices and the spectral theorem
    3.2 Quadratic forms and principal axes
    3.3 Orthogonal matrices, rotations and reflections
    Leads to
    3.5 Matrix norms, conditioning, and why numerics fail
    Same idea elsewhere
    MATH 375: Spagnolie on Piazza (@128): the SVD is 'a critically important topic that we didn't quite get to'. This is that topic.
    CS 532: The SVD is the central tool of CS 532 (Matrix Methods in ML): least squares, PCA, low-rank models and recommender systems all reduce to it.
    AI: LoRA fine-tuning trains a low-rank change to each weight matrix, and embedding compression and the analysis of trained weights use the fact that the SVD gives the best low-rank approximation.