Course contents 06 / 16

06 / 16 · Linear Algebra

The singular value decomposition

Every matrix as a rotation, a stretch along the axes and another rotation: the SVD built from the Gram matrix, rank and the four subspaces, the best low-rank approximation, the pseudoinverse, and PCA.

On this page 7

Take the matrix

A=(22−21).A = \begin{pmatrix} 2 & 2 \\ -2 & 1 \end{pmatrix} .

Its trace is 3 and its determinant 6, so its characteristic polynomial λ2−3λ+6\lambda^2 - 3\lambda + 6 has the complex roots 1.5±1.936 i1.5 \pm 1.936\,i. There is no real eigenvector, and the eigendecomposition of the determinants note says nothing about the geometry of this map. Yet the geometry is simple. AA sends the unit circle to an ellipse, and an ellipse has two perpendicular axes.

Most matrices of machine learning are worse off still. The 1797×641797 \times 64 matrix of the small digit images bundled with scikit-learn, or a weight matrix that maps 768 features to 3,072, has no eigenvalues at all, because Av=λvAv = \lambda v needs AvAv and vv in the same space. What are the axes of the ellipse, which vectors land on them, and how do we answer that for any matrix? The previous note answered it for symmetric matrices, and that answer is the tool.

Building the SVD step by step#

We look for perpendicular input directions that AA keeps perpendicular. The symmetric matrix A⊤AA^\top A measures inner products after the map, (Ax)⊤(Ay)=x⊤A⊤Ay(Ax)^\top(Ay) = x^\top A^\top Ay, so its eigenvectors are the candidates. Normalizing their images gives a second set of perpendicular directions.

For A∈Rm×nA \in \mathbb R^{m \times n} of rank rr, the result will be

  A=UΣV⊤=σ1u1v1⊤+⋯+σrurvr⊤  \boxed{\;A = U\Sigma V^\top = \sigma_1u_1v_1^\top + \dots + \sigma_ru_rv_r^\top\;}

with orthogonal U∈Rm×mU \in \mathbb R^{m \times m} and V∈Rn×nV \in \mathbb R^{n \times n}, and Σ∈Rm×n\Sigma \in \mathbb R^{m \times n} zero except for the singular values σ1≥⋯≥σr>0\sigma_1 \ge \dots \ge \sigma_r > 0 on its diagonal. The columns viv_i of VV are the right singular vectors, the columns uiu_i of UU the left singular vectors. Five steps build it.

Step 1: the eigenvectors of A⊤AA^\top A. The n×nn \times n matrix A⊤AA^\top A is symmetric, and positive semidefinite since x⊤A⊤Ax=∥Ax∥2≥0x^\top A^\top Ax = \lVert Ax\rVert^2 \ge 0. By the spectral theorem it has orthonormal eigenvectors v1,…,vnv_1, \dots, v_n with eigenvalues λ1≥⋯≥λn≥0\lambda_1 \ge \dots \ge \lambda_n \ge 0. Exactly rr of them are positive. A⊤AA^\top A has the null space of AA: A⊤Ax=0A^\top Ax = 0 gives ∥Ax∥2=x⊤A⊤Ax=0\lVert Ax\rVert^2 = x^\top A^\top Ax = 0, and Ax=0Ax = 0 gives A⊤Ax=0A^\top Ax = 0. That null space has dimension n−rn - r by rank–nullity, and it is spanned by the viv_i with λi=0\lambda_i = 0, so n−rn - r eigenvalues are zero.

Step 2: the singular values. Set σi=λi\sigma_i = \sqrt{\lambda_i}. They are the lengths of the images, since ∥Avi∥2=vi⊤A⊤Avi=λi\lVert Av_i\rVert^2 = v_i^\top A^\top Av_i = \lambda_i.

Step 3: the left singular vectors. For i≤ri \le r set ui=Avi/σiu_i = Av_i/\sigma_i. These vectors are orthonormal:

ui⊤uj=vi⊤A⊤Avjσiσj=λj vi⊤vjσiσjA⊤Avj=λjvj={1,i=j,0,i≠j.σj2=λj\begin{aligned} u_i^\top u_j &= \frac{v_i^\top A^\top Av_j}{\sigma_i\sigma_j} \\ &= \frac{\lambda_j\,v_i^\top v_j}{\sigma_i\sigma_j} && A^\top Av_j = \lambda_jv_j \\ &= \begin{cases} 1, & i = j, \\ 0, & i \ne j. \end{cases} && \sigma_j^2 = \lambda_j \end{aligned}

Step 4: complete the bases. If r<mr < m, extend u1,…,uru_1, \dots, u_r to an orthonormal basis of Rm\mathbb R^m, for example by Gram–Schmidt. For i>ri > r, ∥Avi∥=σi=0\lVert Av_i\rVert = \sigma_i = 0, so Avi=0Av_i = 0.

Step 5: assemble. Now Avi=σiuiAv_i = \sigma_iu_i for every ii, with σi=0\sigma_i = 0 for i>ri > r. Column by column this is AV=UΣAV = U\Sigma, and multiplying on the right by V⊤=V−1V^\top = V^{-1} gives A=UΣV⊤A = U\Sigma V^\top. Written as columns times rows, the product is the sum of rank-one terms, and only the first rr survive.

The construction proves that the SVD exists; it is not how the SVD is computed. Forming A⊤AA^\top A squares the singular values, and with them the ratio σ1/σr\sigma_1/\sigma_r that measures sensitivity to rounding, so libraries work on AA directly (Golub and Kahan, 1965; Strang, 2018, lecture 6).

Example. For A=(22−21)A = \begin{pmatrix} 2 & 2 \\ -2 & 1 \end{pmatrix}:

  1. A⊤A=(8225)A^\top A = \begin{pmatrix} 8 & 2 \\ 2 & 5 \end{pmatrix}, with trace 13 and determinant 36, so its eigenvalues are 9 and 4. The null space of A⊤A−9IA^\top A - 9I gives v1=(2,1)/5v_1 = (2, 1)/\sqrt5, and v2=(−1,2)/5v_2 = (-1, 2)/\sqrt5 is perpendicular to it.
  2. σ1=3\sigma_1 = 3 and σ2=2\sigma_2 = 2.
  3. u1=Av1/3=(2,−1)/5u_1 = Av_1/3 = (2, -1)/\sqrt5 and u2=Av2/2=(1,2)/5u_2 = Av_2/2 = (1, 2)/\sqrt5. Their inner product is 2−2=02 - 2 = 0.
  4. Nothing to complete: r=m=n=2r = m = n = 2.
  5. The two layers add up to AA:
3u1v1⊤=35(42−2−1),2u2v2⊤=25(−12−24),3u1v1⊤+2u2v2⊤=15(1010−105)=A.\begin{aligned} 3u_1v_1^\top &= \tfrac35\begin{pmatrix} 4 & 2 \\ -2 & -1 \end{pmatrix}, \\ 2u_2v_2^\top &= \tfrac25\begin{pmatrix} -1 & 2 \\ -2 & 4 \end{pmatrix}, \\ 3u_1v_1^\top + 2u_2v_2^\top &= \tfrac15\begin{pmatrix} 10 & 10 \\ -10 & 5 \end{pmatrix} = A . \end{aligned}

Rotate, stretch, rotate#

Read from right to left, Ax=UΣV⊤xAx = U\Sigma V^\top x applies three maps. V⊤V^\top is orthogonal and takes viv_i to eie_i; here det⁡V=1\det V = 1, a rotation. Σ\Sigma stretches the ii-th axis by σi\sigma_i. UU is orthogonal and takes eie_i to uiu_i. A unit vector x=c1v1+c2v2x = c_1v_1 + c_2v_2, c12+c22=1c_1^2 + c_2^2 = 1, goes to z1u1+z2u2z_1u_1 + z_2u_2 with zi=σiciz_i = \sigma_ic_i, so (z1/σ1)2+(z2/σ2)2=1(z_1/\sigma_1)^2 + (z_2/\sigma_2)^2 = 1: the unit circle becomes an ellipse with half-axes σ1\sigma_1 along u1u_1 and σ2\sigma_2 along u2u_2:

Figure

The SVD: rotate, stretch, rotate

The SVD: rotate, stretch, rotateFour panels. The unit circle with the vectors v₁ = (2, 1)/√5 and v₂ = (−1, 2)/√5 and the point x = e₁. Step 1: Vᵀ rotates the plane by −26.6°, taking v₁ and v₂ to e₁ and e₂. Step 2: Σ stretches the axes by 3 and 2, and the circle becomes an ellipse with half-axes 3 and 2 along the coordinate axes. Step 3: U rotates by −26.6°, the half-axes become 3u₁ and 2u₂, and the point x arrives at Ax = (2, −2).v₁v₂xx on the unit circlee₁e₂Vᵀx3e₁2e₂ΣVᵀx3u₁2u₂AxUΣVᵀx = AxVᵀ: rotate by −26.6°1Σ: stretch by 3 and 22U: rotate by −26.6°3The SVD: rotate, stretch, rotateFour panels. The unit circle with the vectors v₁ = (2, 1)/√5 and v₂ = (−1, 2)/√5 and the point x = e₁. Step 1: Vᵀ rotates the plane by −26.6°, taking v₁ and v₂ to e₁ and e₂. Step 2: Σ stretches the axes by 3 and 2, and the circle becomes an ellipse with half-axes 3 and 2 along the coordinate axes. Step 3: U rotates by −26.6°, the half-axes become 3u₁ and 2u₂, and the point x arrives at Ax = (2, −2).v₁v₂xxe₁e₂Vᵀx3e₁2e₂ΣVᵀx3u₁2u₂AxAxVᵀ1Σ2U3
A = [[2, 2], [−2, 1]] = UΣVᵀ applied to the unit circle. Vᵀ rotates v₁ = (2, 1)/√5 and v₂ = (−1, 2)/√5 onto the axes, Σ = diag(3, 2) stretches them, and U rotates them onto u₁ = (2, −1)/√5 and u₂ = (1, 2)/√5; both rotations are by −26.6°. Follow the green point x = e₁ to Ax = (2, −2).

The count of numbers comes out right. A 2×22 \times 2 matrix has four entries; a rotation of the plane has one parameter, its angle, so the SVD spends 1+2+11 + 2 + 1 on two rotations and two stretches. For a rectangular AA the middle step also changes the dimension: Σ\Sigma keeps the first rr coordinates, scaled, and drops or pads the rest, so the unit sphere of Rn\mathbb R^n becomes a flattened ellipsoid in an rr-dimensional subspace of Rm\mathbb R^m.

What the singular values measure#

The largest stretch ∥Ax∥/∥x∥\lVert Ax\rVert/\lVert x\rVert is the square root of the largest Rayleigh quotient of A⊤AA^\top A, so the spectral norm is ∥A∥2=σ1\lVert A\rVert_2 = \sigma_1. The Frobenius norm, ∥A∥F=(∑ijaij2)1/2\lVert A\rVert_F = (\sum_{ij}a_{ij}^2)^{1/2}, squared is tr⁡(A⊤A)\operatorname{tr}(A^\top A), because the jj-th diagonal entry of A⊤AA^\top A is ∑iaij2\sum_i a_{ij}^2. The trace is the sum of the eigenvalues of A⊤AA^\top A:

∥A∥F2=σ12+⋯+σr2.\lVert A\rVert_F^2 = \sigma_1^2 + \dots + \sigma_r^2 .

For a square AA, ∣det⁡A∣=σ1⋯σn\lvert\det A\rvert = \sigma_1\cdots\sigma_n, because det⁡A=det⁡Udet⁡Σdet⁡V⊤\det A = \det U\det\Sigma\det V^\top and an orthogonal matrix has determinant ±1\pm 1. In the example, 3⋅2=6=det⁡A3 \cdot 2 = 6 = \det A, and the ellipse with half-axes 3 and 2 has area 6π6\pi, six times that of the disc. For a symmetric A=QΛQ⊤A = Q\Lambda Q^\top, write λi=si∣λi∣\lambda_i = s_i\lvert\lambda_i\rvert with signs si=±1s_i = \pm 1; then A=(QS)∣Λ∣Q⊤A = (QS)\lvert\Lambda\rvert Q^\top with S=diag⁡(si)S = \operatorname{diag}(s_i) is an SVD, so the singular values are the ∣λi∣\lvert\lambda_i\rvert. For a positive semidefinite one they are the eigenvalues themselves, with U=V=QU = V = Q.

The ratio σ1/σn\sigma_1/\sigma_n of a square invertible matrix, its condition number, says how much the map distorts shapes; the conditioning note shows that it also bounds how errors grow when solving Ax=bAx = b.

The singular values are unique: any SVD gives A⊤A=VΣ⊤ΣV⊤A^\top A = V\Sigma^\top\Sigma V^\top, so its σi2\sigma_i^2 are the eigenvalues of A⊤AA^\top A, which AA alone determines. When the nonzero singular values are distinct, each viv_i is a unit vector in a one-dimensional eigenspace of A⊤AA^\top A, hence fixed up to sign, and ui=Avi/σiu_i = Av_i/\sigma_i follows it. So (−ui,−vi)(-u_i, -v_i) works as well as (ui,vi)(u_i, v_i), which is why two libraries can return principal components with opposite signs. The left singular vectors are the eigenvectors of AA⊤=UΣΣ⊤U⊤AA^\top = U\Sigma\Sigma^\top U^\top; for a wide matrix it is cheaper to start from the smaller AA⊤AA^\top.

Rank and the four subspaces#

In the coordinates of the SVD a matrix is diagonal, and the four subspaces become spans of basis vectors:

subspacedimensionbasis from the SVD
column space col⁡(A)⊆Rm\operatorname{col}(A) \subseteq \mathbb R^mrru1,…,uru_1, \dots, u_r
left null space ker⁡A⊤⊆Rm\ker A^\top \subseteq \mathbb R^mm−rm - rur+1,…,umu_{r+1}, \dots, u_m
row space row⁡(A)⊆Rn\operatorname{row}(A) \subseteq \mathbb R^nrrv1,…,vrv_1, \dots, v_r
null space ker⁡A⊆Rn\ker A \subseteq \mathbb R^nn−rn - rvr+1,…,vnv_{r+1}, \dots, v_n

Write Ax=∑i≤rσi(vi⊤x) uiAx = \sum_{i \le r}\sigma_i(v_i^\top x)\,u_i. It is always a combination of u1,…,uru_1, \dots, u_r, and each uiu_i is reached by x=vi/σix = v_i/\sigma_i, so these span the column space. It is zero exactly when vi⊤x=0v_i^\top x = 0 for all i≤ri \le r, that is, when xx lies in the span of vr+1,…,vnv_{r+1}, \dots, v_n. The other two rows follow from A⊤=VΣ⊤U⊤A^\top = V\Sigma^\top U^\top. So the rank is the number of nonzero singular values, and the row space and null space are orthogonal complements in Rn\mathbb R^n, as are the column space and the left null space in Rm\mathbb R^m.

Example. For

B=(101011)B = \begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & 1 \end{pmatrix}

start from the smaller matrix BB⊤=(2112)BB^\top = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}, with eigenvalues 3 and 1 and eigenvectors u1=(1,1)/2u_1 = (1, 1)/\sqrt2 and u2=(1,−1)/2u_2 = (1, -1)/\sqrt2. So σ1=3\sigma_1 = \sqrt3, σ2=1\sigma_2 = 1, and the rank is 2. The right singular vectors are vi=B⊤ui/σiv_i = B^\top u_i/\sigma_i: v1=(1,1,2)/6v_1 = (1, 1, 2)/\sqrt6 and v2=(1,−1,0)/2v_2 = (1, -1, 0)/\sqrt2. The third, v3=(1,1,−1)/3v_3 = (1, 1, -1)/\sqrt3, completes the basis of R3\mathbb R^3, and indeed Bv3=0Bv_3 = 0. The null space is the line through (1,1,−1)(1, 1, -1), and the row space is the plane perpendicular to it, spanned by the two rows.

In floating point a singular value is almost never exactly zero. A matrix whose third column is the sum of the first two can come out with σ3=10−16\sigma_3 = 10^{-16} rather than 0. The numerical rank is the number of singular values above a tolerance; NumPy’s matrix_rank uses σ1max⁡(m,n) ε\sigma_1 \max(m, n)\,\varepsilon, with the machine epsilon ε≈2.2⋅10−16\varepsilon \approx 2.2 \cdot 10^{-16}. The SVD is the reliable way to compute a rank because, by the Eckart–Young theorem below, σk+1\sigma_{k+1} is the spectral-norm distance from AA to the nearest matrix of rank kk. Pivots carry no such guarantee. The 30×3030 \times 30 upper triangular matrix with ones on the diagonal and −1-1 above it is already triangular, so its pivots are its diagonal entries, all equal to 1; yet σ30=2.8⋅10−9\sigma_{30} = 2.8 \cdot 10^{-9}: a change of that size makes it singular.

The best low-rank approximation#

The sum A=∑iσiuivi⊤A = \sum_i\sigma_iu_iv_i^\top sorts a matrix into rank-one layers in order of importance. Keeping the first kk gives the truncation Ak=∑i≤kσiuivi⊤A_k = \sum_{i \le k}\sigma_iu_iv_i^\top. Is it the closest matrix of rank kk?

That is less obvious than it looks. Take A=diag⁡(4,3,2,1)A = \operatorname{diag}(4, 3, 2, 1) and k=2k = 2. The truncation keeps 4 and 3 and misses the 2 and the 1. A cleverer rank-two matrix puts a block of four 3.53.5s in the top-left corner and a block of four 1.51.5s in the bottom-right one, each block of rank one. On the diagonal it misses every entry by only 0.50.5, but the off-diagonal entries of the blocks cost more: its Frobenius error is 30=5.48\sqrt{30} = 5.48, against 5=2.24\sqrt{5} = 2.24 for the truncation (Strang, 2018, lecture 7).

The Eckart–Young theorem says that no matrix does better:

min⁡rank⁡B≤k∥A−B∥2=∥A−Ak∥2=σk+1,min⁡rank⁡B≤k∥A−B∥F2=∥A−Ak∥F2=σk+12+⋯+σr2.\begin{aligned} \min_{\operatorname{rank} B \le k}\lVert A - B\rVert_2 &= \lVert A - A_k\rVert_2 = \sigma_{k+1}, \\ \min_{\operatorname{rank} B \le k}\lVert A - B\rVert_F^2 &= \lVert A - A_k\rVert_F^2 \\ &= \sigma_{k+1}^2 + \dots + \sigma_r^2 . \end{aligned}

Halko, Martinsson and Tropp (2011, section 10.2) credit the Frobenius case to Eckart and Young (1936) and the spectral case to Mirsky (1960); both are proved below (Rakhuba, 2025, lecture 4).

The error of the truncation is the easy half. The difference A−Ak=∑i>kσiuivi⊤A - A_k = \sum_{i > k}\sigma_iu_iv_i^\top is itself an SVD, because its uiu_i and viv_i are still orthonormal, so its spectral norm is its largest singular value, σk+1\sigma_{k+1}. For the Frobenius norm:

∥A−Ak∥F2=tr⁡((A−Ak)⊤(A−Ak))=tr⁡(∑i>kσi2vivi⊤)ui⊤uj=δij=∑i>kσi2tr⁡(vivi⊤)=1.\begin{aligned} \lVert A - A_k\rVert_F^2 &= \operatorname{tr}\big((A - A_k)^\top(A - A_k)\big) \\ &= \operatorname{tr}\Big(\textstyle\sum_{i > k}\sigma_i^2v_iv_i^\top\Big) && u_i^\top u_j = \delta_{ij} \\ &= \textstyle\sum_{i > k}\sigma_i^2 && \operatorname{tr}(v_iv_i^\top) = 1 . \end{aligned}

Example. For A=(22−21)A = \begin{pmatrix} 2 & 2 \\ -2 & 1 \end{pmatrix}, the rank-one truncation is A1=3u1v1⊤A_1 = 3u_1v_1^\top, and the error is the other layer:

A1=(2.41.2−1.2−0.6),A−A1=(−0.40.8−0.81.6).\begin{aligned} A_1 &= \begin{pmatrix} 2.4 & 1.2 \\ -1.2 & -0.6 \end{pmatrix}, \\ A - A_1 &= \begin{pmatrix} -0.4 & 0.8 \\ -0.8 & 1.6 \end{pmatrix} . \end{aligned}

Its squared entries sum to 0.16+0.64+0.64+2.56=4=σ220.16 + 0.64 + 0.64 + 2.56 = 4 = \sigma_2^2, and its spectral norm is σ2=2\sigma_2 = 2. Relative to ∥A∥F=13\lVert A\rVert_F = \sqrt{13} the best rank-one approximation is off by 2/13=55%2/\sqrt{13} = 55\%: this matrix is far from rank one, because its two singular values are close.

Why no other matrix of rank k does better#

Optional depth: the proof of optimality for the spectral norm, and where the Frobenius case comes from. The rest of the note does not depend on it.

Let BB have rank at most kk. Its null space has dimension at least n−kn - k by rank–nullity, and the span of v1,…,vk+1v_1, \dots, v_{k+1} has dimension k+1k + 1. Two subspaces SS, TT of Rn\mathbb R^n with dim⁡S+dim⁡T>n\dim S + \dim T > n share a nonzero vector, since dim⁡(S∩T)=dim⁡S+dim⁡T−dim⁡(S+T)≥1\dim(S \cap T) = \dim S + \dim T - \dim(S + T) \ge 1 (Axler, 2024, 2.43). So there is a unit vector w=∑i≤k+1civiw = \sum_{i \le k+1}c_iv_i with Bw=0Bw = 0 and ∑ici2=1\sum_i c_i^2 = 1. Then

∥A−B∥22≥∥(A−B)w∥2∥w∥=1=∥Aw∥2Bw=0=∑i≤k+1σi2ci2Aw=∑iσiciui≥σk+12.\begin{aligned} \lVert A - B\rVert_2^2 &\ge \lVert(A - B)w\rVert^2 && \lVert w\rVert = 1 \\ &= \lVert Aw\rVert^2 && Bw = 0 \\ &= \textstyle\sum_{i \le k+1}\sigma_i^2c_i^2 && Aw = \textstyle\sum_i\sigma_ic_iu_i \\ &\ge \sigma_{k+1}^2 . \end{aligned}

The last step replaces each σi\sigma_i with i≤k+1i \le k + 1 by the smallest of them and uses ∑ici2=1\sum_i c_i^2 = 1. The truncation reaches this bound, so it is optimal.

The Frobenius case follows from the spectral one. Let Xi−1X_{i-1} and Yj−1Y_{j-1} be the truncations of two matrices XX and YY. Their sum has rank at most i+j−2i + j - 2, so by the spectral case and the triangle inequality

σi+j−1(X+Y)≤∥X+Y−Xi−1−Yj−1∥2≤∥X−Xi−1∥2+∥Y−Yj−1∥2=σi(X)+σj(Y).\begin{aligned} \sigma_{i+j-1}(X + Y) &\le \lVert X + Y - X_{i-1} - Y_{j-1}\rVert_2 \\ &\le \lVert X - X_{i-1}\rVert_2 + \lVert Y - Y_{j-1}\rVert_2 \\ &= \sigma_i(X) + \sigma_j(Y) . \end{aligned}

Take X=A−BX = A - B, Y=BY = B and j=k+1j = k + 1. Since rank⁡B≤k\operatorname{rank} B \le k, σk+1(B)=0\sigma_{k+1}(B) = 0, and the inequality reads σk+i(A)≤σi(A−B)\sigma_{k+i}(A) \le \sigma_i(A - B). Summing the squares over ii gives ∥A−B∥F2≥∑i>kσi2\lVert A - B\rVert_F^2 \ge \sum_{i > k}\sigma_i^2 (Horn and Johnson, 2013, sections 7.3 and 7.4).

Compressing a matrix#

A rank-kk approximation of an m×nm \times n matrix is stored as kk columns uiu_i, kk rows vi⊤v_i^\top and kk numbers σi\sigma_i: k(m+n+1)k(m + n + 1) numbers instead of mnmn. Whether that pays off depends on how fast the singular values fall. The test image below is a synthetic 64×6464 \times 64 grayscale matrix of 4,096 numbers: a constant background, a smooth bump sin⁡(πx)sin⁡(πy)\sin(\pi x)\sin(\pi y), a disc, an axis-aligned rectangle and a thin diagonal stripe. The Code section builds it from this formula.

Figure

A 64 × 64 image and its low-rank approximations

A 64 × 64 image and its low-rank approximationsFour grayscale squares. Rank 1: a blurred plaid made of a product of a column and a row, error 28.3%. Rank 5: the disc and the rectangle are visible, error 12.1%. Rank 20: almost the original except along the diagonal stripe, error 4.5%. Right: the original of rank 64, a constant background with a smooth bump, a bright disc, a rectangle and a thin diagonal stripe.rank k = 1error 28.3%129 numbers, 3%rank k = 5error 12.1%645 numbers, 16%rank k = 20error 4.5%2,580 numbers, 63%original, rank 64error 04,096 numbers, 100%A 64 × 64 image and its low-rank approximationsFour grayscale squares. Rank 1: a blurred plaid made of a product of a column and a row, error 28.3%. Rank 5: the disc and the rectangle are visible, error 12.1%. Rank 20: almost the original except along the diagonal stripe, error 4.5%. Right: the original of rank 64, a constant background with a smooth bump, a bright disc, a rectangle and a thin diagonal stripe.rank k = 1error 28.3%129 numbers, 3%rank k = 5error 12.1%645 numbers, 16%rank k = 20error 4.5%2,580 numbers, 63%original, rank 64error 04,096 numbers, 100%
A synthetic 64 × 64 image (right) and its best approximations of rank 1, 5 and 20, computed from the SVD when the page is built. Under each: the relative error ‖A − A_k‖_F / ‖A‖_F and the numbers stored, 129k against 4,096. The rectangle appears at rank 1, the diagonal stripe last.

The first singular value, σ1=38.3\sigma_1 = 38.3, carries the background and most of the bump: its square is 92% of ∥A∥F2=39.952\lVert A\rVert_F^2 = 39.95^2. The next ones fall quickly, 8.398.39, 3.943.94, 3.563.56, 2.442.44, and then slowly, down to 1.6⋅10−41.6 \cdot 10^{-4}:

Figure

The singular values of the image and the error of a rank-k approximation

The singular values of the image and the error of a rank-k approximationLeft: the 64 singular values on a log scale, from 38.3 down to 1.6·10⁻⁴; a fast drop after the first, then a slow tail. Right: the relative error of the rank-k approximation on a log scale: 28% at k = 1, 12% at k = 5, 4.5% at k = 20; a vertical dashed line at k ≈ 32, where storing the approximation costs as much as the whole matrix.10110⁻²10⁻⁴110⁻²10⁻⁴1326403264index irank kσᵢ (log scale)relative error (log scale)σ₁ = 38.3σ₆₄ = 1.6·10⁻⁴k(m + n + 1) = mnk = 1: 28%k = 5: 12%k = 20: 4.5%The singular values of the image and the error of a rank-k approximationLeft: the 64 singular values on a log scale, from 38.3 down to 1.6·10⁻⁴; a fast drop after the first, then a slow tail. Right: the relative error of the rank-k approximation on a log scale: 28% at k = 1, 12% at k = 5, 4.5% at k = 20; a vertical dashed line at k ≈ 32, where storing the approximation costs as much as the whole matrix.10110⁻²10⁻⁴110⁻²10⁻⁴1326403264index irank kσᵢ (log scale)relative error (log scale)σ₁ = 38.3σ₆₄ = 1.6·10⁻⁴k(m + n + 1) = mnk = 1: 28%k = 5: 12%k = 20: 4.5%
The same image. Left: its singular values σᵢ on a log scale, from 38.3 down to 1.6·10⁻⁴. Right: the relative error of the best rank-k approximation, the root of the share of Σσᵢ² that is discarded. The dashed line at k ≈ 32 marks where the factors cost as much storage as the matrix.
rank kkrelative error ∥A−Ak∥F/∥A∥F\lVert A - A_k\rVert_F/\lVert A\rVert_Fnumbers storedshare of 4,096
128.3%1293%
512.1%64516%
108.1%1,29031%
204.5%2,58063%

Each error equals the square root of the share of ∑iσi2\sum_i\sigma_i^2 that the discarded singular values carry, as the theorem says. Beyond k=31k = 31 the factors take more room than the matrix itself.

The components of the image behave differently. The rectangle and the bump are products of a function of the row and a function of the column, so each has rank one. The disc needs a handful of layers. The diagonal stripe needs nearly all of them, because a band along the diagonal is close to a multiple of the identity, whose singular values are all equal.

The SVD favours structure aligned with rows and columns, and image codecs use other transforms. It wins on matrices whose structure is genuinely low-rank: user–item ratings in recommender systems, word co-occurrence counts, and the updates of fine-tuned weights.

LoRA: a low-rank update#

LoRA fine-tunes a large model by restricting the update of each weight matrix to rank rr, ΔW=BA\Delta W = BA, which needs r(dout+din)r(d_{\text{out}} + d_{\text{in}}) trained numbers instead of doutdind_{\text{out}}d_{\text{in}}. By Eckart–Young, no rank-rr update comes closer, in the Frobenius norm, to the update that full fine-tuning would make than the root of the sum of its squared singular values beyond the rr-th; the PEFT note covers how LoRA is set up and trained.

The pseudoinverse and minimum-norm least squares#

The system Ax=bAx = b can fail in two ways. It may have no solution, when bb is not in the column space, and it may have infinitely many, when the null space is not {0}\{0\}. Least squares fixes the first failure by minimizing ∥Ax−b∥\lVert Ax - b\rVert, but its formula (A⊤A)−1A⊤b(A^\top A)^{-1}A^\top b needs independent columns, so it does not fix the second. The SVD fixes both.

Change coordinates to c=V⊤xc = V^\top x and d=U⊤bd = U^\top b. Orthogonal matrices keep lengths, so

∥Ax−b∥2=∥U⊤(UΣV⊤x−b)∥2=∥Σc−d∥2=∑i≤r(σici−di)2+∑i>rdi2,∥x∥2=∑i≤rci2+∑i>rci2.\begin{aligned} \lVert Ax - b\rVert^2 &= \lVert U^\top(U\Sigma V^\top x - b)\rVert^2 \\ &= \lVert\Sigma c - d\rVert^2 \\ &= \textstyle\sum_{i \le r}(\sigma_ic_i - d_i)^2 + \sum_{i > r}d_i^2 , \\ \lVert x\rVert^2 &= \textstyle\sum_{i \le r}c_i^2 + \sum_{i > r}c_i^2 . \end{aligned}

The problem has split into rr scalar equations σici=di\sigma_ic_i = d_i, which can be solved, residuals did_i for i>ri > r, which nothing can remove, and coordinates cic_i for i>ri > r, which do not affect the residual. The residual is smallest when ci=di/σic_i = d_i/\sigma_i for i≤ri \le r. Among all such choices the length is smallest when ci=0c_i = 0 for i>ri > r. Going back to x=Vcx = Vc:

x+=∑i≤rui⊤bσi vi=A+b,A+=VΣ+U⊤=∑i≤r1σi viui⊤,\begin{aligned} x^+ &= \textstyle\sum_{i \le r}\dfrac{u_i^\top b}{\sigma_i}\,v_i = A^+b, \\ A^+ &= V\Sigma^+U^\top = \textstyle\sum_{i \le r}\dfrac{1}{\sigma_i}\,v_iu_i^\top , \end{aligned}

where Σ+\Sigma^+ is the n×mn \times m matrix with 1/σi1/\sigma_i for the nonzero singular values and zeros elsewhere. A+A^+ is the pseudoinverse (Penrose, 1955), and x+x^+ is the least-squares solution of smallest length.

Special cases recover familiar formulas. If AA is square and invertible, Σ+=Σ−1\Sigma^+ = \Sigma^{-1} and A+=VΣ−1U⊤=A−1A^+ = V\Sigma^{-1}U^\top = A^{-1}. If the columns are independent (r=nr = n), Σ⊤Σ\Sigma^\top\Sigma is invertible, and

(A⊤A)−1A⊤=V(Σ⊤Σ)−1V⊤⋅VΣ⊤U⊤=V(Σ⊤Σ)−1Σ⊤U⊤=A+,\begin{aligned} (A^\top A)^{-1}A^\top &= V(\Sigma^\top\Sigma)^{-1}V^\top \cdot V\Sigma^\top U^\top \\ &= V(\Sigma^\top\Sigma)^{-1}\Sigma^\top U^\top = A^+ , \end{aligned}

because (Σ⊤Σ)−1Σ⊤(\Sigma^\top\Sigma)^{-1}\Sigma^\top has σi/σi2=1/σi\sigma_i/\sigma_i^2 = 1/\sigma_i on its diagonal: the normal equations. If the rows are independent (r=mr = m), the same computation with AA⊤AA^\top gives A+=A⊤(AA⊤)−1A^+ = A^\top(AA^\top)^{-1}, and x+x^+ solves the system exactly with the smallest length.

Example. For B=(101011)B = \begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & 1 \end{pmatrix} and b=(1,1)b = (1, 1), every x=(1−t,1−t,t)x = (1 - t, 1 - t, t) solves Bx=bBx = b. The rows are independent, so x+=B⊤(BB⊤)−1b=(13,13,23)x^+ = B^\top(BB^\top)^{-1}b = (\tfrac13, \tfrac13, \tfrac23), with ∥x+∥2=23\lVert x^+\rVert^2 = \tfrac23. The SVD gives the same: d=U⊤b=(2,0)d = U^\top b = (\sqrt2, 0), so c1=2/3c_1 = \sqrt{2/3} and x+=c1v1=(1,1,2)/3x^+ = c_1v_1 = (1, 1, 2)/3. Every other solution adds a multiple s(1,1,−1)s(1, 1, -1) of the null-space vector, which is orthogonal to x+x^+, so its squared length is 23+3s2\tfrac23 + 3s^2 by Pythagoras. The solution (0,0,1)(0, 0, 1), at s=−13s = -\tfrac13, has squared length 1.

Two training procedures land on x+x^+ without being asked. Ridge regression multiplies the component along viv_i by σi/(σi2+λ)\sigma_i/(\sigma_i^2 + \lambda) instead of 1/σi1/\sigma_i (which directions ridge shrinks). As λ→0\lambda \to 0 the factor tends to 1/σi1/\sigma_i for σi>0\sigma_i > 0 and stays 0 for σi=0\sigma_i = 0, so ridge tends to x+x^+; in the example, λ=10−3\lambda = 10^{-3} gives (0.3332,0.3332,0.6664)(0.3332, 0.3332, 0.6664).

Gradient descent on 12∥Ax−b∥2\tfrac12\lVert Ax - b\rVert^2 is the other. Its step x←x−ηA⊤(Ax−b)x \leftarrow x - \eta A^\top(Ax - b) in the coordinates c=V⊤xc = V^\top x and d=U⊤bd = U^\top b splits into

ci←(1−ησi2) ci+ησidii≤r,ci←cii>r.\begin{aligned} c_i &\leftarrow (1 - \eta\sigma_i^2)\,c_i + \eta\sigma_id_i && i \le r, \\ c_i &\leftarrow c_i && i > r . \end{aligned}

For 0<η<2/σ120 < \eta < 2/\sigma_1^2 every factor ∣1−ησi2∣\lvert 1 - \eta\sigma_i^2\rvert is below 1, so ci→di/σic_i \to d_i/\sigma_i for i≤ri \le r, while the null-space coordinates never move. Started at 0, descent converges to x+x^+, the minimum-norm solution. Started at (1,0,0)(1, 0, 0), it keeps that start’s component 13(1,1,−1)\tfrac13(1, 1, -1) along the null space and converges to (23,23,13)(\tfrac23, \tfrac23, \tfrac13) instead, with squared length 1; the Code section uses η=0.3<2/3\eta = 0.3 < 2/3. This is the simplest case of the implicit regularization of overparameterized models.

PCA is the SVD of the centred data#

For a data matrix X∈RN×dX \in \mathbb R^{N \times d} with centred columns, the SVD X=UΣV⊤X = U\Sigma V^\top gives all of principal component analysis. The sample covariance is 1NX⊤X=VΣ⊤ΣNV⊤\frac1N X^\top X = V\frac{\Sigma^\top\Sigma}{N}V^\top, so the principal directions are the right singular vectors and the variance along the jj-th is σj2/N\sigma_j^2/N. The coordinates of the data in the new basis are XV=UΣXV = U\Sigma, and the best reconstruction from kk components is the Eckart–Young truncation XkX_k. The dimensionality reduction note derives PCA from both variance and reconstruction error and works through these formulas on data.

One numerical point belongs here. Computing the SVD of XX is more accurate than computing the eigenvalues of X⊤XX^\top X, because forming X⊤XX^\top X squares the singular values. Rounding the entries of X⊤XX^\top X perturbs it by about εσ12\varepsilon\sigma_1^2 in norm, and by Weyl’s inequality its eigenvalues σj2\sigma_j^2 move by as much. A singular value below about ε σ1≈10−8σ1\sqrt{\varepsilon}\,\sigma_1 \approx 10^{-8}\sigma_1 is then lost: for XX with singular values 11, 10−410^{-4} and 10−1010^{-10}, the SVD returns 10−1010^{-10}, the route through X⊤XX^\top X rounding noise, 9⋅10−99 \cdot 10^{-9} in the Code section.

Where it breaks: small singular values#

The pseudoinverse divides by every nonzero singular value, however small. Take A=diag⁡(1,10−8)A = \operatorname{diag}(1, 10^{-8}) and the right-hand side b=(1,0)b = (1, 0), measured with an error of 10−610^{-6} in its second entry. The exact data give x+=(1,0)x^+ = (1, 0); the measured data give (1,100)(1, 100). A singular value of 10−810^{-8} multiplies the noise along its direction by 10810^8, while an exact zero would have ignored it. The map A↦A+A \mapsto A^+ is discontinuous at every matrix of rank r<min⁡(m,n)r < \min(m, n): the pseudoinverse of A+t ur+1vr+1⊤A + t\,u_{r+1}v_{r+1}^\top contains the term t−1vr+1ur+1⊤t^{-1}v_{r+1}u_{r+1}^\top, whose norm 1/t1/t grows without bound as t→0t \to 0.

Libraries therefore treat singular values below a threshold as zero: rcond in numpy.linalg.pinv and lstsq. With rcond =10−6= 10^{-6} the example returns (1,0)(1, 0) again. This is the truncated SVD applied to the inverse, and the threshold is a modelling choice: it decides which directions of the data count as signal. The conditioning note quantifies the trade-off, and ridge regression makes the same choice smoothly.

A full SVD of an m×nm \times n matrix with m≥nm \ge n costs on the order of mn2mn^2 operations, so large matrices get truncated or randomized methods that compute only the leading kk triplets (Halko, Martinsson and Tropp, 2011). Eckart–Young is about the spectral and Frobenius norms, which weigh all entries alike; an approximation robust to a few corrupted entries, or one with non-negative factors, needs other methods. And the SVD needs every entry: a ratings matrix with most entries unknown is factorized by optimizing over the known entries only, as in matrix factorization.

What you should remember#

  • Every A∈Rm×nA \in \mathbb R^{m \times n} factors as A=UΣV⊤=∑i≤rσiuivi⊤A = U\Sigma V^\top = \sum_{i \le r}\sigma_iu_iv_i^\top: rotate, stretch along the axes, rotate.
  • viv_i are the eigenvectors of A⊤AA^\top A, σi=λi(A⊤A)\sigma_i = \sqrt{\lambda_i(A^\top A)}, ui=Avi/σiu_i = Av_i/\sigma_i; compute it from AA, never from A⊤AA^\top A.
  • ∥A∥2=σ1\lVert A\rVert_2 = \sigma_1, ∥A∥F2=∑iσi2\lVert A\rVert_F^2 = \sum_i\sigma_i^2; the rank is the number of nonzero σi\sigma_i, and UU, VV hold bases of the four subspaces.
  • Eckart–Young: AkA_k is the best rank-kk approximation, with error σk+1\sigma_{k+1} in the spectral norm and ∑i>kσi2\sqrt{\sum_{i > k}\sigma_i^2} in the Frobenius norm.
  • A+=∑i≤rσi−1viui⊤A^+ = \sum_{i \le r}\sigma_i^{-1}v_iu_i^\top gives the least-squares solution of smallest norm, the limit of ridge and the point gradient descent reaches from zero.
  • Tiny singular values blow up A+A^+; a threshold decides what counts as zero.

Code#

The SVD built by the five steps against NumPy, the norms, the four subspaces, Eckart–Young on Strang’s diagonal example, on random matrices and on the image of the figures, the pseudoinverse against ridge and gradient descent, the effect of a tiny singular value, and the two numerical points about rank and X⊤XX^\top X. It runs in about a second; digits in the last places can differ across platforms and library versions.

import numpy as np

# 1. the SVD built from the eigenvectors of A^T A, step by step
A = np.array([[2.0, 2.0], [-2.0, 1.0]])
lam, V = np.linalg.eigh(A.T @ A)                     # step 1 (ascending order)
lam, V = lam[::-1], V[:, ::-1]                       # sort decreasing
sig = np.sqrt(lam)                                   # step 2
U = A @ V / sig                                      # step 3: u_i = A v_i / sigma_i
print(lam, sig, np.allclose(U.T @ U, np.eye(2)), np.allclose(U @ np.diag(sig) @ V.T, A))   # step 5
print(np.linalg.svd(A, compute_uv=False), np.linalg.eigvals(A).round(4))
# [9. 4.] [3. 2.] True True
# [3. 2.] [1.5+1.9365j 1.5-1.9365j]

# 2. the norms and the determinant from the singular values; the image of e1
print(round(np.linalg.norm(A, 2), 6), round(np.linalg.norm(A, 'fro') ** 2, 6), round(abs(np.linalg.det(A)), 6), round(sig.prod(), 6))
Ut, s, Vt = np.linalg.svd(A)
print(np.abs(Vt @ [1.0, 0.0]).round(3), A @ [1.0, 0.0])
# 3.0 13.0 6.0 6.0
# [0.894 0.447] [ 2. -2.]

# 3. rank and the four subspaces of B
B = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]])
UB, sB, VBt = np.linalg.svd(B)
r = int((sB > sB[0] * max(B.shape) * np.finfo(float).eps).sum())
null = VBt[r:].T                                     # basis of the null space
print(sB.round(4), r, (null[:, 0] / null[0, 0]).round(6), np.allclose(B @ null, 0))
C = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 9.0], [7.0, 8.0, 15.0]])   # third column = first + second
print([f'{v:.3g}' for v in np.linalg.svd(C, compute_uv=False)], np.linalg.matrix_rank(C))
# [1.7321 1.    ] 2 [ 1.  1. -1.] True
# ['21.8', '0.585', '8.89e-16'] 2   (the last singular value is zero up to rounding; its digits vary)

# 4. Eckart-Young: Strang's diagonal example, then the truncation error on a random matrix
D = np.diag([4.0, 3.0, 2.0, 1.0]); D2 = np.diag([4.0, 3.0, 0.0, 0.0])
Bd = np.zeros((4, 4)); Bd[:2, :2] = 3.5; Bd[2:, 2:] = 1.5     # two rank-one blocks: rank 2
print(np.linalg.matrix_rank(Bd), round(float(np.linalg.norm(D - D2)), 2), round(float(np.linalg.norm(D - Bd)), 2))
rng = np.random.default_rng(0)
M = rng.normal(size=(30, 20))
Um, sm, Vmt = np.linalg.svd(M, full_matrices=False)
k = 5
Mk = (Um[:, :k] * sm[:k]) @ Vmt[:k]
print(np.isclose(np.linalg.norm(M - Mk, 2), sm[k]), np.isclose(np.linalg.norm(M - Mk, 'fro'), np.sqrt((sm[k:] ** 2).sum())))
best_in_span = []
for _ in range(200):                                 # best approximation within a random k-dimensional column space
    Q, _ = np.linalg.qr(rng.normal(size=(30, k)))
    best_in_span.append(np.linalg.norm(M - Q @ (Q.T @ M), 'fro'))
print(round(float(np.linalg.norm(M - Mk, 'fro')), 4), round(min(best_in_span), 4))
# 2 2.24 5.48
# True True
# 16.5208 21.0277   (the truncation error, then the best of 200 random rank-5 column spaces)

# 5. the test image of the figures: singular values, relative errors and storage
n = 64
t = np.arange(n) / (n - 1)
x, y = np.meshgrid(t, t)                             # x along the columns, y along the rows
F = 0.2 + 0.5 * np.sin(np.pi * x) * np.sin(np.pi * y)
F += 0.6 * ((x - 0.35) ** 2 + (y - 0.6) ** 2 < 0.2 ** 2)
F += 0.4 * ((x >= 0.6) & (x <= 0.9) & (y >= 0.15) & (y <= 0.4))
F += 0.3 * (np.abs(x - y) < 0.05)
UF, sF, VFt = np.linalg.svd(F)
print(sF[:5].round(2), f'{sF[-1]:.1e}', round(float(np.linalg.norm(F)), 2), round(float(sF[0] ** 2 / (sF ** 2).sum()), 3))
for k in (1, 5, 10, 20):
    Fk = (UF[:, :k] * sF[:k]) @ VFt[:k]
    rel = np.linalg.norm(F - Fk) / np.linalg.norm(F)
    print(k, round(float(rel), 4), round(float(np.sqrt((sF[k:] ** 2).sum() / (sF ** 2).sum())), 4), k * (2 * n + 1), f'{k * (2 * n + 1) / n**2:.0%}')
# [38.32  8.39  3.94  3.56  2.44] 1.6e-04 39.95 0.92
# 1 0.2832 0.2832 129 3%
# 5 0.1213 0.1213 645 16%
# 10 0.081 0.081 1290 31%
# 20 0.0448 0.0448 2580 63%

# 6. the pseudoinverse: minimum-norm solution, the limit of ridge, and gradient descent from zero
b = np.array([1.0, 1.0])
xp = np.linalg.pinv(B) @ b
print(xp.round(6), round(float(xp @ xp), 6), np.linalg.lstsq(B, b, rcond=None)[0].round(6))
print(np.linalg.solve(B.T @ B + 1e-3 * np.eye(3), B.T @ b).round(4))
for start in (np.zeros(3), np.array([1.0, 0.0, 0.0])):
    w = start.copy()
    for _ in range(2000):
        w -= 0.3 * B.T @ (B @ w - b)
    print(start, w.round(6), round(float(w @ w), 6))
# [0.333333 0.333333 0.666667] 0.666667 [0.333333 0.333333 0.666667]
# [0.3332 0.3332 0.6664]
# [0. 0. 0.] [0.333333 0.333333 0.666667] 0.666667
# [1. 0. 0.] [0.666667 0.666667 0.333333] 1.0

# 7. a tiny singular value amplifies noise; a threshold removes it
As = np.diag([1.0, 1e-8]); bs = np.array([1.0, 0.0]) + np.array([0.0, 1e-6])
print(np.linalg.pinv(As) @ bs, np.linalg.pinv(As, rcond=1e-6) @ bs)
# [  1. 100.] [1. 0.]

# 8. pivots do not reveal near-singularity, singular values do; forming X^T X loses the small ones
T = np.eye(30) + np.triu(-np.ones((30, 30)), 1)        # ones on the diagonal, -1 above it
print(np.diag(T).min(), f'{np.linalg.svd(T, compute_uv=False)[-1]:.1e}')
Ux, _ = np.linalg.qr(rng.normal(size=(100, 3))); Vx, _ = np.linalg.qr(rng.normal(size=(3, 3)))
X = Ux @ np.diag([1.0, 1e-4, 1e-10]) @ Vx.T
print(f'{np.linalg.svd(X, compute_uv=False)[-1]:.1e}', f'{np.sqrt(abs(np.linalg.eigvalsh(X.T @ X)[0])):.0e}')
# 1.0 2.8e-09
# 1.0e-10 9e-09   (the second number is rounding noise and varies with the platform)

Next#

The linear algebra of the course is complete: vectors and maps, systems and their solutions, orthogonality and projections, eigenvalues, symmetric matrices and the SVD. Machine learning uses all of it inside optimization: a loss is minimized by following its derivatives, and those derivatives are themselves linear maps, a gradient vector or a Jacobian matrix. The next note starts the calculus section with the derivative as the best linear approximation of a function, and the Taylor series that turns a smooth loss near a point into the quadratic forms of the previous note.

References#