21.5 Singular Value Decomposition and Low-Rank Approximation

In Section 21.3, we saw how the eigendecomposition describes a square matrix in terms of the directions it merely stretches, turning powers of a matrix into simple powers of numbers. Most matrices in deep learning, however, are not like that. A weight matrix maps inputs of one width to outputs of another, and a data matrix has one row per example and one column per feature. Neither is applied repeatedly to its own output, and neither needs to be square. Even when a matrix is square, eigenvalues can still let us down. The shear T=(1101)\mathbf{T}=\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right) is defective, having only a single eigenvector direction where the plane needs two, and in Section 21.4 we met a matrix whose sixth power stretches a vector ten-fold even though both of its eigenvalues are smaller than 1. We need a factorization that exists for every matrix, measures stretching directly, and tells us how few numbers are needed to approximate a large matrix well.

A concrete photograph makes that last requirement easy to appreciate. A grayscale picture of a cat, 400×500400\times500 pixels, is simply a matrix of 200,000 numbers. Like any matrix, it can be written as a sum of rank-one pieces, each formed by the outer product of a single column and a single row. Remarkably, just twenty well-chosen pieces (18,020 numbers, or 9% of the original data) reproduce the photograph with a relative error of only 8% (Figure 21.5.5). Which twenty pieces achieve this, and could any other twenty do better? That same question arises across deep learning: it tells us how many parameters a fine-tuning adapter for a large model needs, and which directions in a dataset are actually worth keeping.

The key idea is to stop asking a single basis to serve for both the inputs and the outputs. If we allow one orthonormal basis for the input space and a separate orthonormal basis for the output space, then every matrix reduces to a list of independent non-negative stretches σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\cdots\ge0. From that single list we can read off a matrix's rank, its best low-rank approximation, principal component analysis, least-squares solutions, and how sensitive a linear system is to measurement error. Recall that Section 1.3 introduced two ways to measure the size of a matrix: the Frobenius norm ∥A∥F\|\mathbf{A}\|_F (the square root of the sum of squared entries) and the spectral norm ∥A∥2\|\mathbf{A}\|_2 (the largest factor by which A\mathbf{A} can stretch a unit vector). In this section, both become simple functions of the singular values σi\sigma_i.

Two main results anchor what follows: the existence of the singular value decomposition for any matrix, and the Eckart--Young theorem, which guarantees that truncating the decomposition gives the best approximation of every rank. From there, the pseudoinverse and the condition number follow in just a few lines. The final subsection connects these tools to modern deep learning and can be skipped on a first reading. All numerical experiments below use NumPy; throughout, T\mathbf{T} denotes the shear matrix and A\mathbf{A} denotes a general matrix unless stated otherwise.

21.5.1 The Singular Value Decomposition#

21.5.1.1 The Factorization and Its Geometry#

In Section 1.3, we saw that the symmetric matrix (2112)\left(\begin{smallmatrix}2&1\\1&2\end{smallmatrix}\right) maps the unit circle to an ellipse whose semi-axes lie along its eigenvectors (1,1)(1,1) and (−1,1)(-1,1), with half-lengths 3 and 1. Remarkably, a non-symmetric matrix also maps the unit circle to an ellipse (or flattens it to a line segment if the matrix is singular), as we will prove shortly. The difference is that the orthogonal input directions landing on the axes of this ellipse are no longer the axes themselves. Instead, there are two orthonormal frames, one for the input space and one for the output space, and the singular value decomposition names both.

Theorem (singular value decomposition). Every real m×nm\times n matrix A\mathbf{A} can be written as

A=U Σ V⊤,(21.5.1)\mathbf{A} = \mathbf{U}\,\boldsymbol{\Sigma}\,\mathbf{V}^\top, \tag{21.5.1}

where U∈Rm×m\mathbf{U}\in\mathbb{R}^{m\times m} and V∈Rn×n\mathbf{V}\in\mathbb{R}^{n\times n} are orthogonal (U⊤U=I\mathbf{U}^\top\mathbf{U}=\mathbf{I}, V⊤V=I\mathbf{V}^\top\mathbf{V}=\mathbf{I}) and Σ∈Rm×n\boldsymbol{\Sigma}\in\mathbb{R}^{m\times n} is zero except for the non-negative entries σ1≥σ2≥⋯≥σmin⁡(m,n)≥0\sigma_1\ge\sigma_2\ge\cdots\ge\sigma_{\min(m,n)}\ge0 on its main diagonal. The columns vi\mathbf{v}_i of V\mathbf{V} are the right singular vectors, the columns ui\mathbf{u}_i of U\mathbf{U} are the left singular vectors, and the diagonal entries σi\sigma_i are the singular values.

In geometric terms, every matrix, regardless of its shape, is simply an orthogonal transformation, followed by a diagonal stretch, followed by a second orthogonal transformation. Writing AV=UΣ\mathbf{A}\mathbf{V}=\mathbf{U}\boldsymbol{\Sigma} and reading off column ii makes the action explicit one direction at a time:

Avi=σi ui,i≤min⁡(m,n).(21.5.2)\mathbf{A}\mathbf{v}_i = \sigma_i\,\mathbf{u}_i, \qquad i\le\min(m,n). \tag{21.5.2}

Each input direction vi\mathbf{v}_i is sent to the corresponding output direction ui\mathbf{u}_i, stretched by σi\sigma_i; when n>mn>m, the extra input directions vm+1,…,vn\mathbf{v}_{m+1},\ldots,\mathbf{v}_n are collapsed to zero. Reading (21.5.1) from right to left, applying A\mathbf{A} to a vector x\mathbf{x} unfolds in three stages:

  1. V⊤\mathbf{V}^\top rotates the input so that each right singular vector vi\mathbf{v}_i aligns with the coordinate axis ei\mathbf{e}_i;
  2. Σ\boldsymbol{\Sigma} stretches axis ii by σi\sigma_i and, when m≠nm\ne n, either appends zero coordinates or drops excess ones to match the output dimension;
  3. U\mathbf{U} rotates the stretched axes so that axis ii points along ui\mathbf{u}_i.

Here "rotation" is convenient shorthand for an orthogonal map, which may also include a reflection.

Figure 21.5.1 illustrates these three stages for the shear T\mathbf{T}. Its singular values are σ1=1.618\sigma_1=1.618 and σ2=0.618\sigma_2=0.618; the first right singular vector v1\mathbf{v}_1 points at 58.3∘58.3^\circ above the xx-axis, while its image direction u1\mathbf{u}_1 points at 31.7∘31.7^\circ. Because the input and output frames differ, U≠V\mathbf{U}\ne\mathbf{V}. We will derive these exact numbers in Section 21.5.1.2.

Figure 21.5.1:

The shear T=(1101)=UΣV⊤\mathbf{T}=\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right)=\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top acting on the unit circle, read left to right: V⊤\mathbf{V}^\top rotates by −58.3∘-58.3^\circ, Σ\boldsymbol{\Sigma} stretches by φ=1.618\varphi=1.618 along xx and by 1/φ=0.6181/\varphi=0.618 along yy, and U\mathbf{U} rotates by 31.7∘31.7^\circ. The input frame {vi}\{\mathbf{v}_i\} and the output frame {ui}\{\mathbf{u}_i\} differ.

In nn dimensions, the same three stages deform the unit sphere into an ellipsoid whose semi-axes are the vectors σiui\sigma_i\mathbf{u}_i. If only r<nr\lt n of the input directions have positive singular values, the remaining n−rn-r directions collapse to zero, and the image is a flat rr-dimensional ellipsoid lying inside the span of u1,…,ur\mathbf{u}_1,\ldots,\mathbf{u}_r.

Compact and thin forms. Let rr be the number of positive singular values (in Section 21.5.1.5 we will verify that rr is precisely the rank of A\mathbf{A}). Every row and column of Σ\boldsymbol{\Sigma} beyond the first rr is zero, so the singular vectors paired with them contribute nothing to the product. Dropping those zero entries yields the compact SVD, A=UrΣrVr⊤\mathbf{A}=\mathbf{U}_r\boldsymbol{\Sigma}_r\mathbf{V}_r^\top, where Ur∈Rm×r\mathbf{U}_r\in\mathbb{R}^{m\times r} and Vr∈Rn×r\mathbf{V}_r\in\mathbb{R}^{n\times r} hold the first rr singular vectors and Σr=diag⁡(σ1,…,σr)\boldsymbol{\Sigma}_r=\operatorname{diag}(\sigma_1,\ldots,\sigma_r). Between the full and compact forms sits the thin SVD, the default reduced form that numerical libraries return on request, which keeps min⁡(m,n)\min(m,n) columns in U\mathbf{U} and V\mathbf{V} and still records any zero singular values when r<min⁡(m,n)r\lt \min(m,n). For a 3×23\times2 matrix of rank 2, the full factors have shapes 3×33\times3, 3×23\times2, and 2×22\times2, whereas the thin factors have shapes 3×23\times2, 2×22\times2, and 2×22\times2 (matching the compact SVD here because the matrix has full column rank). The full and thin forms differ whenever the matrix is not square, and the thin and compact forms whenever it is rank-deficient. Figure 21.5.2 draws a 6×46\times4 matrix of rank 3, for which all three differ.

Figure 21.5.2:

Shapes of the SVD factors of an m×nm\times n matrix of rank rr, drawn to scale for m=6m=6, n=4n=4, and r=3r=3: (a) full, (b) thin, (c) compact, and (d) the dyadic sum of rr rank-one terms. Filled squares on the diagonal of Σ\boldsymbol{\Sigma} are positive singular values, and the dashed square is a zero singular value. The dashed parts of U\mathbf{U} and V⊤\mathbf{V}^\top multiply only zeros of Σ\boldsymbol{\Sigma}, so each smaller form drops some of them without changing the product.

The dyadic sum. Multiplying out the compact SVD column by row expresses A\mathbf{A} as a weighted sum of rank-one matrices, often called dyads:

A=∑i=1rσi uivi⊤.(21.5.3)\mathbf{A} = \sum_{i=1}^{r} \sigma_i\,\mathbf{u}_i\mathbf{v}_i^\top. \tag{21.5.3}

Each term uivi⊤\mathbf{u}_i\mathbf{v}_i^\top is the outer product of an output direction and an input direction, scaled by its singular value, and the terms are already sorted from heaviest to lightest. For the shear, T=φ u1v1⊤+φ−1 u2v2⊤\mathbf{T}=\varphi\,\mathbf{u}_1\mathbf{v}_1^\top+\varphi^{-1}\,\mathbf{u}_2\mathbf{v}_2^\top, splitting the matrix into one piece of weight 1.6181.618 and a second of weight 0.6180.618. Keeping only the heaviest pieces is the idea behind low-rank approximation in Section 21.5.2.1.

21.5.1.2 Existence#

Where do the σi\sigma_i, vi\mathbf{v}_i, and ui\mathbf{u}_i come from, and why should the output directions come out orthonormal? The spectral theorem of Section 21.3.2.1 guarantees that every symmetric matrix has an orthonormal basis of eigenvectors with real eigenvalues. We can apply it to the Gram matrix A⊤A\mathbf{A}^\top\mathbf{A}, the n×nn\times n matrix of dot products between the columns of A\mathbf{A}. This matrix is symmetric, and it is positive semidefinite (Section 21.3.2.2) because x⊤A⊤Ax=∥Ax∥2≥0\mathbf{x}^\top\mathbf{A}^\top\mathbf{A}\mathbf{x}=\|\mathbf{A}\mathbf{x}\|^2\ge0 for every vector x\mathbf{x}.

Proof of (21.5.1) (existence). By the spectral theorem, A⊤A\mathbf{A}^\top\mathbf{A} has an orthonormal basis of eigenvectors v1,…,vn\mathbf{v}_1,\ldots,\mathbf{v}_n with eigenvalues λ1≥⋯≥λn\lambda_1\ge\cdots\ge\lambda_n. Every eigenvalue is non-negative because λi=vi⊤A⊤Avi=∥Avi∥2\lambda_i=\mathbf{v}_i^\top\mathbf{A}^\top\mathbf{A}\mathbf{v}_i=\|\mathbf{A}\mathbf{v}_i\|^2. Define

σi=λi,r=#{i:σi>0}.\sigma_i = \sqrt{\lambda_i}, \qquad r = \#\{i : \sigma_i > 0\} .

Thus the singular values are the square roots of the eigenvalues of the Gram matrix, and rr counts the positive ones. For each i≤ri\le r, set ui=Avi/σi\mathbf{u}_i = \mathbf{A}\mathbf{v}_i/\sigma_i. The crucial check is that these pushed-through vectors are automatically orthonormal, which follows from vj\mathbf{v}_j being an eigenvector of A⊤A\mathbf{A}^\top\mathbf{A} and the vi\mathbf{v}_i being orthonormal:

ui⊤uj=1σiσj vi⊤A⊤A vj=λjσiσj vi⊤vj=λjσiσj δij=δij.\mathbf{u}_i^\top\mathbf{u}_j = \frac{1}{\sigma_i\sigma_j}\,\mathbf{v}_i^\top\mathbf{A}^\top\mathbf{A}\,\mathbf{v}_j = \frac{\lambda_j}{\sigma_i\sigma_j}\,\mathbf{v}_i^\top\mathbf{v}_j = \frac{\lambda_j}{\sigma_i\sigma_j}\,\delta_{ij} = \delta_{ij} .

Orthonormality of the input frame therefore passes directly through A⊤A\mathbf{A}^\top\mathbf{A} to the output frame. Next we check the dimensions. Since the rr orthonormal vectors u1,…,ur\mathbf{u}_1,\ldots,\mathbf{u}_r lie in Rm\mathbb{R}^m, we have r≤mr\le m, and since there are nn eigenvalues in total, r≤nr\le n; hence r≤min⁡(m,n)r\le\min(m,n), and λi=0\lambda_i=0 for every i>ri>r. Complete u1,…,ur\mathbf{u}_1,\ldots,\mathbf{u}_r to an orthonormal basis u1,…,um\mathbf{u}_1,\ldots,\mathbf{u}_m of Rm\mathbb{R}^m (for example, by applying Gram--Schmidt to any completion). For r<i≤nr\lt i\le n, ∥Avi∥2=λi=0\|\mathbf{A}\mathbf{v}_i\|^2=\lambda_i=0, so Avi=0\mathbf{A}\mathbf{v}_i=\mathbf{0}. Comparing AV\mathbf{A}\mathbf{V} with UΣ\mathbf{U}\boldsymbol{\Sigma} column by column, column ii of UΣ\mathbf{U}\boldsymbol{\Sigma} is σiui\sigma_i\mathbf{u}_i for i≤min⁡(m,n)i\le\min(m,n) (which vanishes when i>ri>r) and 0\mathbf{0} for i>mi>m (where Σ\boldsymbol{\Sigma} has no diagonal entry). In every case, column ii of AV\mathbf{A}\mathbf{V} matches column ii of UΣ\mathbf{U}\boldsymbol{\Sigma}. Hence AV=UΣ\mathbf{A}\mathbf{V}=\mathbf{U}\boldsymbol{\Sigma}, and right-multiplying by V⊤=V−1\mathbf{V}^\top=\mathbf{V}^{-1} yields A=UΣV⊤\mathbf{A}=\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top. ■\blacksquare

This proof is also a recipe: diagonalize the symmetric matrix A⊤A\mathbf{A}^\top\mathbf{A}, take square roots to get the singular values, and map the eigenvectors through A\mathbf{A} to obtain the left singular vectors.

Let us work through the shear by hand to see every step in action. For T=(1101)\mathbf{T}=\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right), the Gram matrix is T⊤T=(1112)\mathbf{T}^\top\mathbf{T}=\left(\begin{smallmatrix}1&1\\1&2\end{smallmatrix}\right). It has trace 3 and determinant 1, so its characteristic polynomial is λ2−3λ+1\lambda^2-3\lambda+1, giving eigenvalues (3±5)/2(3\pm\sqrt5)/2. Introducing the golden ratio φ=(1+5)/2\varphi=(1+\sqrt5)/2, which satisfies φ2=φ+1\varphi^2=\varphi+1, these eigenvalues simplify neatly to φ2\varphi^2 and φ−2\varphi^{-2}. The singular values are therefore σ1=φ≈1.618\sigma_1=\varphi\approx1.618 and σ2=1/φ≈0.618\sigma_2=1/\varphi\approx0.618, and their product is 1=∣det⁡T∣1=|\det\mathbf{T}|.

Now we find the singular vectors. For the first right singular vector (x,y)(x,y), the first row of (T⊤T−φ2I)(x,y)=0(\mathbf{T}^\top\mathbf{T}-\varphi^2\mathbf{I})(x,y)=\mathbf{0} reads (1−φ2)x+y=0(1-\varphi^2)x+y=0; using φ2−1=φ\varphi^2-1=\varphi gives y=φxy=\varphi x, so v1∝(1,φ)\mathbf{v}_1\propto(1,\varphi). Applying T\mathbf{T} yields T(1,φ)=(1+φ,φ)=φ (φ,1)\mathbf{T}(1,\varphi)=(1+\varphi,\varphi)=\varphi\,(\varphi,1), so u1∝(φ,1)\mathbf{u}_1\propto(\varphi,1). Both vectors have length 1+φ2=φ+2\sqrt{1+\varphi^2}=\sqrt{\varphi+2}, giving v1≈(0.526,0.851)\mathbf{v}_1\approx(0.526,0.851) at angle arctan⁡φ=58.3∘\arctan\varphi=58.3^\circ and u1≈(0.851,0.526)\mathbf{u}_1\approx(0.851,0.526) at 31.7∘31.7^\circ. The second pair follows by orthogonality, v2=(−φ,1)/φ+2\mathbf{v}_2=(-\varphi,1)/\sqrt{\varphi+2} and u2=(−1,φ)/φ+2\mathbf{u}_2=(-1,\varphi)/\sqrt{\varphi+2}, and indeed Tv2=(1−φ,1)/φ+2=φ−1u2\mathbf{T}\mathbf{v}_2=(1-\varphi,1)/\sqrt{\varphi+2}=\varphi^{-1}\mathbf{u}_2 since (1−φ)φ=−1(1-\varphi)\varphi=-1. Both V\mathbf{V} and U\mathbf{U} are rotations Rθ=(cos⁡θ−sin⁡θsin⁡θcos⁡θ)\mathbf{R}_\theta=\left(\begin{smallmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{smallmatrix}\right), so the shear factors as

T=[1101]=R31.7∘[φ001/φ]R58.3∘⊤.(21.5.4)\mathbf{T} = \begin{bmatrix} 1 & 1\\ 0 & 1\end{bmatrix} = \mathbf{R}_{31.7^\circ} \begin{bmatrix} \varphi & 0\\ 0 & 1/\varphi\end{bmatrix} \mathbf{R}_{58.3^\circ}^\top . \tag{21.5.4}

Geometrically, the shear rotates the plane by −58.3∘-58.3^\circ, stretches it by 1.6181.618 along the xx-axis and 0.6180.618 along the yy-axis, and rotates it back by only 31.7∘31.7^\circ. The two angles sum to 90∘90^\circ because u1\mathbf{u}_1 is simply v1\mathbf{v}_1 with its coordinates swapped, reflecting the symmetry T⊤=JTJ\mathbf{T}^\top=\mathbf{J}\mathbf{T}\mathbf{J} for the swap matrix J=(0110)\mathbf{J}=\left(\begin{smallmatrix}0&1\\1&0\end{smallmatrix}\right).

Does NumPy's np.linalg.svd agree with our hand calculation? Because singular vectors are only determined up to sign (Section 21.5.1.3), the cell below stores the shear as A and first fixes signs so that u1\mathbf{u}_1 lies in the first quadrant and U\mathbf{U} is a proper rotation.

A = np.array([[1., 1.], [0., 1.]])
U, s, Vt = np.linalg.svd(A)
if U[0, 0] < 0:                         # joint sign choice: u_1 in the first quadrant
    U[:, 0], Vt[0] = -U[:, 0], -Vt[0]
if np.linalg.det(U) < 0:                # joint sign choice: U a rotation (then so is V)
    U[:, 1], Vt[1] = -U[:, 1], -Vt[1]
phi = (1 + np.sqrt(5)) / 2
print('singular values', s.round(4), '  phi, 1/phi', np.array([phi, 1 / phi]).round(4))
print('U =', U.round(3).tolist(), '  Vt =', Vt.round(3).tolist())
print('angles of u_1, v_1 (degrees):', np.degrees(np.arctan2(U[1, 0], U[0, 0])).round(1),
      np.degrees(np.arctan2(Vt[0, 1], Vt[0, 0])).round(1))
print('A v_1 = sigma_1 u_1:', np.allclose(A @ Vt[0], s[0] * U[:, 0]),
      '  sigma_1 sigma_2 =', s.prod().round(6))
singular values [1.618 0.618]   phi, 1/phi [1.618 0.618]
U = [[0.851, -0.526], [0.526, 0.851]]   Vt = [[0.526, 0.851], [-0.851, 0.526]]
angles of u_1, v_1 (degrees): 31.7 58.3
A v_1 = sigma_1 u_1: True   sigma_1 sigma_2 = 1.0

It matches: the library returns φ\varphi and 1/φ1/\varphi together with the two rotations of (21.5.4).

The same construction works unchanged for a rectangular matrix. Consider the 3×23\times2 matrix with rows (3,1)(3,1), (1,3)(1,3), and (0,2)(0,2). Its Gram matrix is (106614)\left(\begin{smallmatrix}10&6\\6&14\end{smallmatrix}\right), with eigenvalues 12±4012\pm\sqrt{40}. The next cell carries out the proof's three steps directly (eigenvectors of A⊤A\mathbf{A}^\top\mathbf{A}, square roots, and ui=Avi/σi\mathbf{u}_i=\mathbf{A}\mathbf{v}_i/\sigma_i) and compares the result against np.linalg.svd.

A = np.array([[3., 1.], [1., 3.], [0., 2.]])
lam, V = np.linalg.eigh(A.T @ A)
lam, V = lam[::-1], V[:, ::-1]                     # descending order
sigma = np.sqrt(lam)
U = A @ V / sigma                                   # u_i = A v_i / sigma_i
U_lib, s_lib, Vt_lib = np.linalg.svd(A, full_matrices=False)
print('sigma from eigh:', sigma.round(5), '  from svd:', s_lib.round(5))
print('U orthonormal:', np.allclose(U.T @ U, np.eye(2)), '  same U, V up to sign:',
      np.allclose(abs(U), abs(U_lib)), np.allclose(abs(V), abs(Vt_lib.T)))
print('rebuild error:', np.linalg.norm((U * sigma) @ V.T - A).round(12))
sigma from eigh: [4.28072 2.38232]   from svd: [4.28072 2.38232]
U orthonormal: True   same U, V up to sign: True True
rebuild error: 0.0

Both routes yield σ1=12+40≈4.281\sigma_1=\sqrt{12+\sqrt{40}}\approx4.281 and σ2=12−40≈2.382\sigma_2=\sqrt{12-\sqrt{40}}\approx2.382. As the proof promised, the pushed-through vectors ui\mathbf{u}_i come out orthonormal, and both U\mathbf{U} and V\mathbf{V} agree with the library's output up to sign.

21.5.1.3 Uniqueness and the Largest Stretch#

Is the SVD of a matrix unique? The singular values are always unique, because they are the square roots of the eigenvalues of A⊤A\mathbf{A}^\top\mathbf{A}, which A\mathbf{A} determines completely. The singular vectors, by contrast, have three kinds of freedom:

  • For a simple (unrepeated) σi>0\sigma_i>0, the only choice is a joint sign flip (ui,vi)→(−ui,−vi)(\mathbf{u}_i,\mathbf{v}_i)\to(-\mathbf{u}_i,-\mathbf{v}_i). Both vectors must flip together, because flipping only one side would violate Avi=σiui\mathbf{A}\mathbf{v}_i=\sigma_i\mathbf{u}_i.
  • For a repeated singular value σ>0\sigma>0 with index set I\mathcal{I}, the columns VI\mathbf{V}_{\mathcal I} may be rotated by any orthogonal matrix Q\mathbf{Q} of matching size, becoming VIQ\mathbf{V}_{\mathcal I}\mathbf{Q}, provided UI\mathbf{U}_{\mathcal I} is rotated by the same Q\mathbf{Q} to preserve UI=AVI/σ\mathbf{U}_{\mathcal I}=\mathbf{A}\mathbf{V}_{\mathcal I}/\sigma.
  • For σ=0\sigma=0, the null-space vectors vr+1,…,vn\mathbf{v}_{r+1},\ldots,\mathbf{v}_n and left-null-space vectors ur+1,…,um\mathbf{u}_{r+1},\ldots,\mathbf{u}_m can be rotated completely independently, since they do not appear in the dyadic sum (21.5.3).

This freedom explains why two numerical libraries, or even the same library on two different machines, may return opposite signs for the singular vectors, and why our code cells fix a sign convention before printing vectors.

Beyond factoring A\mathbf{A}, the top singular value has a direct geometric meaning: it is the largest factor by which A\mathbf{A} can stretch any unit vector,

σ1=max⁡∥x∥=1∥Ax∥=∥A∥2.(21.5.5)\sigma_1 = \max_{\|\mathbf{x}\|=1}\|\mathbf{A}\mathbf{x}\| = \|\mathbf{A}\|_2 . \tag{21.5.5}

This follows immediately from the Rayleigh proposition of Section 21.3.2.3, which states that over unit vectors x\mathbf{x}, the quadratic form x⊤Sx\mathbf{x}^\top\mathbf{S}\mathbf{x} of a symmetric matrix S\mathbf{S} is maximized by its top eigenvector with value equal to its top eigenvalue. Taking S=A⊤A\mathbf{S}=\mathbf{A}^\top\mathbf{A}, we see that ∥Ax∥2=x⊤A⊤Ax\|\mathbf{A}\mathbf{x}\|^2=\mathbf{x}^\top\mathbf{A}^\top\mathbf{A}\mathbf{x} is maximized at x=v1\mathbf{x}=\mathbf{v}_1 with value λ1=σ12\lambda_1=\sigma_1^2. Thus σ1\sigma_1 is precisely the spectral norm ∥A∥2\|\mathbf{A}\|_2 from Section 1.3: for the shear, no unit vector is stretched by more than φ=1.618\varphi=1.618, and v1\mathbf{v}_1 achieves that stretch. The remaining singular values solve the same maximization problem once the earlier right singular vectors are ruled out, a procedure called deflation: σk=max⁡{∥Ax∥:∥x∥=1, x⊥v1,…,vk−1}\sigma_k=\max\{\|\mathbf{A}\mathbf{x}\| : \|\mathbf{x}\|=1,\ \mathbf{x}\perp\mathbf{v}_1,\ldots,\mathbf{v}_{k-1}\}. In fact, Exercise 1a reverses this logic and constructs the entire SVD from the maximum stretch alone, without invoking the spectral theorem.

21.5.1.4 Singular Values and Eigenvalues#

How do singular values relate to eigenvalues? Substituting (21.5.1) into the two Gram matrices and using U⊤U=I\mathbf{U}^\top\mathbf{U}=\mathbf{I} and V⊤V=I\mathbf{V}^\top\mathbf{V}=\mathbf{I} gives

A⊤A=V Σ⊤Σ V⊤,AA⊤=U ΣΣ⊤ U⊤.(21.5.6)\mathbf{A}^\top\mathbf{A} = \mathbf{V}\,\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}\,\mathbf{V}^\top, \qquad \mathbf{A}\mathbf{A}^\top = \mathbf{U}\,\boldsymbol{\Sigma}\boldsymbol{\Sigma}^\top\,\mathbf{U}^\top . \tag{21.5.6}

Both expressions are symmetric eigendecompositions: the right singular vectors are the eigenvectors of A⊤A\mathbf{A}^\top\mathbf{A}, the left singular vectors are the eigenvectors of AA⊤\mathbf{A}\mathbf{A}^\top, and the squares σi2\sigma_i^2 are the nonzero eigenvalues that the two Gram matrices share. When A\mathbf{A} is symmetric positive semidefinite, its SVD and eigendecomposition coincide, with U=V\mathbf{U}=\mathbf{V}.

For any other matrix, however, the two decompositions differ, and it is a common mistake to assume that singular values equal eigenvalue magnitudes. Consider the chapter's running matrix A=(12−13)\mathbf{A}=\left(\begin{smallmatrix}1&2\\-1&3\end{smallmatrix}\right), whose eigenvalues are 2±i2\pm i, both of modulus 5≈2.236\sqrt5\approx2.236 (Section 21.3). Its Gram matrix A⊤A=(2−1−113)\mathbf{A}^\top\mathbf{A}=\left(\begin{smallmatrix}2&-1\\-1&13\end{smallmatrix}\right) has trace 15 and determinant 25, yielding σ1,22=(15±55)/2\sigma_{1,2}^2=(15\pm5\sqrt5)/2 and therefore σ1,2=(5±5)/2≈3.618, 1.382\sigma_{1,2}=(5\pm\sqrt5)/2\approx3.618,\,1.382, far from 2.2362.236. Still, one clean identity links the two lists for every square matrix:

∣det⁡A∣=∏iσi=∏i∣λi∣.|\det\mathbf{A}| = \prod_i \sigma_i = \prod_i |\lambda_i| .

The first equality holds because orthogonal matrices have determinant ±1\pm1, and the second because the determinant is the product of all eigenvalues. For a 2×22\times2 matrix with a conjugate pair of eigenvalues of common modulus ∣λ∣|\lambda|, this forces ∣λ∣=σ1σ2|\lambda|=\sqrt{\sigma_1\sigma_2}; here indeed 3.618⋅1.382=5\sqrt{3.618\cdot1.382}=\sqrt5. The identity also recovers the volume interpretation of the determinant from Section 21.2: rotations preserve area, so the diagonal stretch Σ\boldsymbol{\Sigma} accounts for the entire change of area, and our running matrix maps the unit square to a parallelogram of area 3.618⋅1.382=53.618\cdot1.382=5.

Computing the SVD in practice. Although our existence proof constructs the SVD from A⊤A\mathbf{A}^\top\mathbf{A}, numerical libraries never form that product. Forming A⊤A\mathbf{A}^\top\mathbf{A} squares the condition number (Section 21.5.3.2), which can wipe out small singular values in floating-point arithmetic. Instead, libraries apply orthogonal transformations directly to A\mathbf{A} to reduce it to bidiagonal form (Golub--Kahan bidiagonalization) and then diagonalize that bidiagonal matrix (Golub and Van Loan, 1996).

21.5.1.5 The Four Fundamental Subspaces#

Which inputs does A\mathbf{A} collapse to zero, and which outputs can it reach? In Section 21.2, we named these sets the null space and the column space, and defined the rank as the number of linearly independent columns. Because U\mathbf{U} and V\mathbf{V} are invertible, multiplying by them leaves all dimensions unchanged, so rank⁡A=rank⁡Σ\operatorname{rank}\mathbf{A}=\operatorname{rank}\boldsymbol{\Sigma}, which is simply the count of nonzero diagonal entries:

rank⁡A=#{i:σi>0}=r.(21.5.7)\operatorname{rank}\mathbf{A} = \#\{i : \sigma_i > 0\} = r . \tag{21.5.7}

In other words, the rank counts the directions that survive without collapsing. Paired with a rounding tolerance (below), counting singular values is the most numerically reliable way to determine rank. It costs more than Gaussian elimination, but it is far more stable: a perturbation E\mathbf{E}, such as floating-point rounding error, shifts no singular value by more than ∥E∥2\|\mathbf{E}\|_2 (Weyl's inequality in Section 21.5.2.1). A clear gap between large and tiny singular values can therefore be trusted.

Even better, splitting the singular vectors at the index rr gives explicit orthonormal bases for all four fundamental subspaces of A\mathbf{A} directly from the dyadic sum (21.5.3):

  • The column space (range) of A\mathbf{A} is span⁡{u1,…,ur}\operatorname{span}\{\mathbf{u}_1,\ldots,\mathbf{u}_r\}, because every output Ax=∑i≤rσi(vi⊤x)ui\mathbf{A}\mathbf{x}=\sum_{i\le r}\sigma_i(\mathbf{v}_i^\top\mathbf{x})\mathbf{u}_i is a linear combination of these vectors, and each one is attained via ui=A(vi/σi)\mathbf{u}_i=\mathbf{A}(\mathbf{v}_i/\sigma_i).
  • The null space of A\mathbf{A} is span⁡{vr+1,…,vn}\operatorname{span}\{\mathbf{v}_{r+1},\ldots,\mathbf{v}_n\}, because by the same formula Ax=0\mathbf{A}\mathbf{x}=\mathbf{0} holds if and only if vi⊤x=0\mathbf{v}_i^\top\mathbf{x}=0 for every i≤ri\le r (the ui\mathbf{u}_i are independent and the σi\sigma_i are positive), meaning x\mathbf{x} is orthogonal to v1,…,vr\mathbf{v}_1,\ldots,\mathbf{v}_r.
  • The row space (column space of A⊤\mathbf{A}^\top) is span⁡{v1,…,vr}\operatorname{span}\{\mathbf{v}_1,\ldots,\mathbf{v}_r\} and the left null space (null space of A⊤\mathbf{A}^\top) is span⁡{ur+1,…,um}\operatorname{span}\{\mathbf{u}_{r+1},\ldots,\mathbf{u}_m\}, by applying the same two arguments to A⊤=VΣ⊤U⊤\mathbf{A}^\top=\mathbf{V}\boldsymbol{\Sigma}^\top\mathbf{U}^\top, which simply swaps the roles of the ui\mathbf{u}_i and vi\mathbf{v}_i.

This gives a remarkably clean picture of any linear map. The input space splits into two orthogonal pieces: the rr-dimensional row space and the (n−r)(n-r)-dimensional null space. Likewise, the output space splits into the rr-dimensional column space and the (m−r)(m-r)-dimensional left null space. On the row space, A\mathbf{A} maps each vi\mathbf{v}_i to σiui\sigma_i\mathbf{u}_i, a one-to-one bijection onto the column space; everything in the null space is sent to zero.

To see this in the simplest nontrivial case, consider the singular matrix B=(2142)\mathbf{B}=\left(\begin{smallmatrix}2&1\\4&2\end{smallmatrix}\right) from Section 21.2. Its Gram matrix (2010105)\left(\begin{smallmatrix}20&10\\10&5\end{smallmatrix}\right) has eigenvalues 25 and 0, so σ1=5\sigma_1=5, σ2=0\sigma_2=0, and r=1r=1. The four subspaces are the lines spanned by

v1=15(2,1),v2=15(−1,2),u1=15(1,2),u2=15(−2,1),B=5 u1v1⊤.\mathbf{v}_1=\tfrac{1}{\sqrt5}(2,1),\quad \mathbf{v}_2=\tfrac{1}{\sqrt5}(-1,2),\quad \mathbf{u}_1=\tfrac{1}{\sqrt5}(1,2),\quad \mathbf{u}_2=\tfrac{1}{\sqrt5}(-2,1), \qquad \mathbf{B} = 5\,\mathbf{u}_1\mathbf{v}_1^\top .

Here the column space is the line y=2xy=2x along u1\mathbf{u}_1, and the left null space is the perpendicular line along u2\mathbf{u}_2. In the input plane, the null space is the line along (1,−2)(1,-2), perpendicular to the row (2,1)(2,1) that spans the row space. Figure 21.5.3 illustrates the general geometry; as we will see in Section 21.5.3.1, the pseudoinverse simply runs the bijection from the row space to the column space in reverse.

Figure 21.5.3:

The four fundamental subspaces. A\mathbf{A} maps the row space span⁡{v1,…,vr}\operatorname{span}\{\mathbf{v}_1,\dots,\mathbf{v}_r\} one-to-one onto the column space span⁡{u1,…,ur}\operatorname{span}\{\mathbf{u}_1,\dots,\mathbf{u}_r\} by vi↦σiui\mathbf{v}_i\mapsto\sigma_i\mathbf{u}_i, and maps the null space to zero. The pseudoinverse A+\mathbf{A}^{+} (dashed) runs the map backwards, σiui↦vi\sigma_i\mathbf{u}_i\mapsto\mathbf{v}_i, and sends the left null space to zero.

Numerical rank. In floating-point arithmetic, a matrix that is mathematically rank-deficient cannot be relied on to have singular values that are literally zero; rounding error typically leaves tiny values of order ϵmachσ1\epsilon_{\text{mach}}\sigma_1 instead. In practice, rank is therefore decided with a threshold. NumPy's np.linalg.matrix_rank counts singular values above σ1max⁡(m,n) ϵmach\sigma_1\max(m,n)\,\epsilon_{\text{mach}}, a tolerance that scales naturally with both the largest singular value and the matrix dimensions. Let us see what the "zero" singular values of a 4×44\times4 matrix of rank 2 actually look like.

A = np.random.standard_normal((4, 2)) @ np.random.standard_normal((2, 4))   # rank <= 2
s = np.linalg.svd(A, compute_uv=False)
tol = s[0] * max(A.shape) * np.finfo(float).eps
print('singular values:', np.array2string(s, formatter={'float_kind': '{:.1e}'.format}))
print(f'tolerance {tol:.1e};  exact zeros: {(s == 0).sum()};  '
      f'numerical rank: {np.linalg.matrix_rank(A)}')
singular values: [4.4e+00 2.2e+00 4.7e-17 0.0e+00]
tolerance 3.9e-15;  exact zeros: 1;  numerical rank: 2

Two singular values are of order one, while the remaining two are pure rounding noise: 10−1510^{-15} or smaller, well below the tolerance. Rounding may happen to leave one of them at exactly zero, but it rarely does so for both. Counting exact zeros would therefore misreport the rank, whereas the threshold recovers the true rank of 2.

21.5.2 Low-Rank Approximation#

21.5.2.1 Best Low-Rank Approximation#

We can now return to the cat photograph from the start of the section: which twenty rank-one pieces should we keep? The dyadic sum (21.5.3) already orders the pieces of A\mathbf{A} from heaviest to lightest, so the natural candidate is to keep the first kk terms. This gives the truncated SVD,

Ak=∑i=1kσi uivi⊤.(21.5.8)\mathbf{A}_k = \sum_{i=1}^{k}\sigma_i\,\mathbf{u}_i\mathbf{v}_i^\top . \tag{21.5.8}

The matrix Ak\mathbf{A}_k has rank at most kk, and storing it requires only kk singular values, kk columns of length mm, and kk columns of length nn, for a total of k(m+n+1)k(m+n+1) numbers instead of mnmn. For our 400×500400\times500 photograph with k=20k=20, that is 18,020 numbers out of 200,000. Two questions immediately arise: how large is the approximation error, and could some cleverer rank-kk matrix do even better?

Matrix norms as singular values. To measure approximation error, we need a matrix norm. The Frobenius norm from Section 1.3, ∥A∥F2=∑ijaij2\|\mathbf{A}\|_F^2=\sum_{ij}a_{ij}^2, sums the squared lengths of the columns of A\mathbf{A}, which are the diagonal entries of A⊤A\mathbf{A}^\top\mathbf{A}; thus ∥A∥F2=tr⁡(A⊤A)\|\mathbf{A}\|_F^2=\operatorname{tr}(\mathbf{A}^\top\mathbf{A}). Substituting the SVD and using the cyclic property of the trace (Section 21.2) to move V\mathbf{V} across, we find

∥A∥F2=tr⁡(VΣ⊤ΣV⊤)=tr⁡(Σ⊤Σ V⊤V)=∑iσi2.(21.5.9)\|\mathbf{A}\|_F^2 = \operatorname{tr}(\mathbf{V}\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}\mathbf{V}^\top) = \operatorname{tr}(\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}\,\mathbf{V}^\top\mathbf{V}) = \sum_i \sigma_i^2 . \tag{21.5.9}

The Frobenius norm is therefore the square root of the sum of squared singular values, which immediately tells us that multiplying on either side by an orthogonal matrix never changes it. For the shear, 1+1+0+1=3=φ2+φ−21+1+0+1=3=\varphi^2+\varphi^{-2}. Meanwhile, the spectral norm is simply the largest singular value, ∥A∥2=σ1\|\mathbf{A}\|_2=\sigma_1, by (21.5.5).

With both norms expressed in terms of singular values, we can state the central approximation theorem of linear algebra.

Theorem (Eckart--Young--Mirsky). Let σi=0\sigma_i=0 for i>ri>r. For every k≥0k\ge0, the smallest spectral-norm error attainable by a matrix of rank at most kk is

min⁡rank⁡B≤k∥A−B∥2=σk+1,(21.5.10)\min_{\operatorname{rank}\mathbf{B}\le k}\|\mathbf{A}-\mathbf{B}\|_2 = \sigma_{k+1}, \tag{21.5.10}

and the smallest squared Frobenius error is min⁡rank⁡B≤k∥A−B∥F2=∑i>kσi2\min_{\operatorname{rank}\mathbf{B}\le k}\|\mathbf{A}-\mathbf{B}\|_F^2=\sum_{i>k}\sigma_i^2. Both minima are attained at the truncated SVD B=Ak\mathbf{B}=\mathbf{A}_k.

In short, no rank-kk matrix can beat the truncated SVD in either norm: the best rank-kk approximation misses by the first singular value it omits (in the spectral norm), or by the combined energy of all omitted singular values (in the Frobenius norm). Eckart and Young proved the Frobenius case (Eckart and Young, 1936), and Mirsky later extended it to every norm that is invariant under orthogonal multiplication on both sides (Mirsky, 1960). We prove the spectral-norm bound first; the Frobenius bound then follows cleanly from one extra ingredient, Weyl's inequality, which drops right out of the same argument.

Before writing the general proof, picture n=3n=3 and k=1k=1. Any matrix B\mathbf{B} of rank one collapses an entire plane of inputs to zero, while the top two right singular vectors of A\mathbf{A} span another plane. In R3\mathbb{R}^3, two planes through the origin must intersect in at least a line. Along that line, B\mathbf{B} outputs zero while A\mathbf{A} stretches every vector by at least σ2\sigma_2, so A−B\mathbf{A}-\mathbf{B} must stretch some unit vector by at least σ2\sigma_2 (Figure 21.5.4). The proof below simply carries this dimension count into nn dimensions.

Figure 21.5.4:

The dimension count behind Eckart--Young for n=3n=3, k=1k=1: the plane ker⁡B\ker\mathbf{B} and the plane spanned by the top two right singular vectors must meet in a line. On that line B\mathbf{B} vanishes while A\mathbf{A} still stretches by at least σ2\sigma_2.

Proof (spectral norm). First, the truncation achieves σk+1\sigma_{k+1}. The residual A−Ak=∑i>kσiuivi⊤\mathbf{A}-\mathbf{A}_k=\sum_{i>k}\sigma_i\mathbf{u}_i\mathbf{v}_i^\top is already in compact SVD form with largest singular value σk+1\sigma_{k+1}, so ∥A−Ak∥2=σk+1\|\mathbf{A}-\mathbf{A}_k\|_2=\sigma_{k+1} by (21.5.5). Likewise, (21.5.9) gives ∥A−Ak∥F2=∑i>kσi2\|\mathbf{A}-\mathbf{A}_k\|_F^2=\sum_{i>k}\sigma_i^2.

Second, no matrix of rank at most kk can do better. If k≥rk\ge r the error is zero and there is nothing to prove, so assume k<rk\lt r and let rank⁡B≤k\operatorname{rank}\mathbf{B}\le k. By rank--nullity (Section 21.2), the null space K=ker⁡B\mathcal{K}=\ker\mathbf{B} has dimension at least n−kn-k. Meanwhile, the span V=span⁡{v1,…,vk+1}\mathcal{V}=\operatorname{span}\{\mathbf{v}_1,\ldots,\mathbf{v}_{k+1}\} of the top k+1k+1 right singular vectors has dimension k+1k+1. Because these two dimensions add to more than nn, the subspaces must share a nonzero vector:

dim⁡(K∩V)=dim⁡K+dim⁡V−dim⁡(K+V)≥(n−k)+(k+1)−n=1,\dim(\mathcal{K}\cap\mathcal{V}) = \dim\mathcal{K}+\dim\mathcal{V}-\dim(\mathcal{K}+\mathcal{V}) \ge (n-k) + (k+1) - n = 1 ,

where the equality is the dimension formula for two subspaces and the inequality uses dim⁡(K+V)≤n\dim(\mathcal{K}+\mathcal{V})\le n. (To verify the dimension formula, extend a basis of K∩V\mathcal{K}\cap\mathcal{V} separately to a basis of K\mathcal{K} and a basis of V\mathcal{V}; the combined vectors are linearly independent, span K+V\mathcal{K}+\mathcal{V}, and number dim⁡K+dim⁡V−dim⁡(K∩V)\dim\mathcal{K}+\dim\mathcal{V}-\dim(\mathcal{K}\cap\mathcal{V}).) Pick a unit vector x∈K∩V\mathbf{x}\in\mathcal{K}\cap\mathcal{V} and expand it as x=∑i≤k+1civi\mathbf{x}=\sum_{i\le k+1}c_i\mathbf{v}_i with ∑ici2=1\sum_i c_i^2=1. Then Bx=0\mathbf{B}\mathbf{x}=\mathbf{0}, and using Avi=σiui\mathbf{A}\mathbf{v}_i=\sigma_i\mathbf{u}_i together with the orthonormality of the ui\mathbf{u}_i,

∥Ax∥2=∥∑i≤k+1ciσiui∥2=∑i≤k+1ci2σi2≥σk+12∑i≤k+1ci2=σk+12.\|\mathbf{A}\mathbf{x}\|^2 = \Bigl\|\sum_{i\le k+1}c_i\sigma_i\mathbf{u}_i\Bigr\|^2 = \sum_{i\le k+1} c_i^2\sigma_i^2 \ge \sigma_{k+1}^2 \sum_{i\le k+1} c_i^2 = \sigma_{k+1}^2 .

Hence ∥A−B∥2≥∥(A−B)x∥=∥Ax∥≥σk+1\|\mathbf{A}-\mathbf{B}\|_2\ge\|(\mathbf{A}-\mathbf{B})\mathbf{x}\|=\|\mathbf{A}\mathbf{x}\|\ge\sigma_{k+1}. ■\blacksquare

The geometry is worth repeating in one sentence: any rank-kk competitor B\mathbf{B} must annihilate at least one direction inside the span of the top k+1k+1 right singular vectors, and A\mathbf{A} stretches every direction in that span by at least σk+1\sigma_{k+1}. For the shear T\mathbf{T} with k=1k=1, the truncation T1=φ u1v1⊤=15(φφ21φ)≈(0.7241.1710.4470.724)\mathbf{T}_1=\varphi\,\mathbf{u}_1\mathbf{v}_1^\top=\tfrac{1}{\sqrt5}\left(\begin{smallmatrix}\varphi&\varphi^2\\1&\varphi\end{smallmatrix}\right)\approx\left(\begin{smallmatrix}0.724&1.171\\0.447&0.724\end{smallmatrix}\right) misses by 1/φ=0.6181/\varphi=0.618 in both norms (the residual has rank one, so its spectral and Frobenius norms coincide), and no rank-one matrix can get closer.

To complete the theorem for the Frobenius norm, we first harvest a general perturbation inequality from the spectral-norm bound we just proved.

Lemma (Weyl's inequality for singular values). For any two matrices X,Y\mathbf{X},\mathbf{Y} of the same shape and indices i,j≥1i,j\ge1 with i+j−1≤min⁡(m,n)i+j-1\le\min(m,n),

σi+j−1(X+Y)≤σi(X)+σj(Y).(21.5.11)\sigma_{i+j-1}(\mathbf{X}+\mathbf{Y})\le\sigma_i(\mathbf{X})+\sigma_j(\mathbf{Y}) . \tag{21.5.11}

Proof. Let Xi−1\mathbf{X}_{i-1} and Yj−1\mathbf{Y}_{j-1} be the truncated SVDs (21.5.8) (with X0=0\mathbf{X}_0=\mathbf{0}). Their sum Xi−1+Yj−1\mathbf{X}_{i-1}+\mathbf{Y}_{j-1} has rank at most i+j−2i+j-2, so applying the spectral-norm lower bound to X+Y\mathbf{X}+\mathbf{Y} with k=i+j−2k=i+j-2 gives σi+j−1(X+Y)≤∥X+Y−Xi−1−Yj−1∥2\sigma_{i+j-1}(\mathbf{X}+\mathbf{Y})\le\|\mathbf{X}+\mathbf{Y}-\mathbf{X}_{i-1}-\mathbf{Y}_{j-1}\|_2. By the triangle inequality and the achievability half of Eckart--Young, the right-hand side is at most ∥X−Xi−1∥2+∥Y−Yj−1∥2=σi(X)+σj(Y)\|\mathbf{X}-\mathbf{X}_{i-1}\|_2+\|\mathbf{Y}-\mathbf{Y}_{j-1}\|_2=\sigma_i(\mathbf{X})+\sigma_j(\mathbf{Y}). ■\blacksquare

In words, adding Y\mathbf{Y} to X\mathbf{X} can lift the (i+j−1)(i+j-1)-th singular value above the ii-th singular value of X\mathbf{X} by at most σj(Y)\sigma_j(\mathbf{Y}). Setting j=1j=1 and applying the inequality in both directions shows that perturbing a matrix by Y\mathbf{Y} moves no singular value by more than ∥Y∥2\|\mathbf{Y}\|_2 (Horn and Johnson, 2012); Exercise 2 works out the details.

Proof (Frobenius norm). Apply Weyl's lemma with X=A−B\mathbf{X}=\mathbf{A}-\mathbf{B}, Y=B\mathbf{Y}=\mathbf{B}, and j=k+1j=k+1. Because rank⁡B≤k\operatorname{rank}\mathbf{B}\le k, we have σk+1(B)=0\sigma_{k+1}(\mathbf{B})=0, which yields σk+i(A)≤σi(A−B)\sigma_{k+i}(\mathbf{A})\le\sigma_i(\mathbf{A}-\mathbf{B}) for every i≥1i\ge1. Squaring and summing over ii, then applying (21.5.9),

∥A−B∥F2=∑i≥1σi(A−B)2≥∑i≥1σk+i(A)2=∑j>kσj(A)2,\|\mathbf{A}-\mathbf{B}\|_F^2=\sum_{i\ge1}\sigma_i(\mathbf{A}-\mathbf{B})^2 \ge\sum_{i\ge1}\sigma_{k+i}(\mathbf{A})^2=\sum_{j>k}\sigma_j(\mathbf{A})^2 ,

which the truncation Ak\mathbf{A}_k attains. ■\blacksquare

Uniqueness of the minimizer. One subtle difference separates the two norms. In the spectral norm, the best rank-kk approximation is never unique when k≥1k\ge1 and σk+1>0\sigma_{k+1}>0: for A=diag⁡(3,2,1)\mathbf{A}=\operatorname{diag}(3,2,1) and k=1k=1, every matrix B=diag⁡(3+t,0,0)\mathbf{B}=\operatorname{diag}(3+t,0,0) with ∣t∣≤1|t|\le1 gives ∥A−B∥2=max⁡(∣t∣,2,1)=2=σ2\|\mathbf{A}-\mathbf{B}\|_2=\max(|t|,2,1)=2=\sigma_2. In the Frobenius norm, by contrast, Ak\mathbf{A}_k is the unique minimizer whenever σk>σk+1\sigma_k>\sigma_{k+1} or σk+1=0\sigma_{k+1}=0 (in which case Ak=A\mathbf{A}_k=\mathbf{A}) (Golub and Van Loan, 1996). This uniqueness is one reason principal component analysis, which we meet next, is formulated in the Frobenius norm.

Let us now test the theorem on our 400×500400\times500 cat photograph. Eckart--Young fixes the spectral error of every truncation at σk+1\sigma_{k+1}, but it does not tell us how quickly the singular values of a real image decay, nor how much worse a natural rank-kk competitor performs. The cell below loads img/cat1.jpg, converts it to grayscale using standard luminance weights for red, green, and blue, and builds the truncations with np.einsum (which multiplies its inputs and sums over every index omitted after the arrow; since row ii of Vt is vi⊤\mathbf{v}_i^\top, 'i,mi,in->mn' computes the dyadic sum).

img = d2l.plt.imread('../img/cat1.jpg') @ np.array([0.299, 0.587, 0.114])  # 400 x 500
U, s, Vt = np.linalg.svd(img, full_matrices=False)
m, n = img.shape
fro = np.linalg.norm(img)
energy = np.cumsum(s**2) / (s**2).sum()                        # energy kept at each rank
slope = np.polyfit(np.log(np.arange(1, 101)), np.log(s[:100]), 1)[0]
print(f'{m} x {n} = {m * n} numbers;  slope of log sigma_i on log i: {slope:.2f}')
print(f'energy kept at rank 1: {energy[0]:.3f}, at rank 4: {energy[3]:.3f}')
for k in [1, 5, 20, 50]:
    A_k = np.einsum('i,mi,in->mn', s[:k], U[:, :k], Vt[:k])    # first k dyads
    print(f'k={k:2d}: ||A-A_k||_2={np.linalg.norm(img - A_k, 2):6.0f}  '
          f'sigma_{k + 1}={s[k]:6.0f}  rel. err {np.linalg.norm(img - A_k) / fro:.3f}  '
          f'stores {k * (m + n + 1) / (m * n):.1%}')
cols = np.argsort(-np.linalg.norm(img, axis=0))[:20]           # 20 largest columns
C = img[:, cols]
proj = C @ np.linalg.pinv(C) @ img
print(f'projection onto the 20 largest columns: rel. err {np.linalg.norm(img - proj) / fro:.3f}')
400 x 500 = 200000 numbers;  slope of log sigma_i on log i: -1.11
energy kept at rank 1: 0.886, at rank 4: 0.955
k= 1: ||A-A_k||_2=  9234  sigma_2=  9234  rel. err 0.337  stores 0.5%
k= 5: ||A-A_k||_2=  4048  sigma_6=  4048  rel. err 0.191  stores 2.3%
k=20: ||A-A_k||_2=   874  sigma_21=   874  rel. err 0.080  stores 9.0%
k=50: ||A-A_k||_2=   342  sigma_51=   342  rel. err 0.045  stores 22.5%
projection onto the 20 largest columns: rel. err 0.310

The spectral error matches σk+1\sigma_{k+1} at every rank, as guaranteed, and rank 20 stores just 9% of the numbers at an 8% relative error. In Figure 21.5.5, the cat appears as a bright blur at rank 1, a recognizable silhouette with four paws at rank 5, and unmistakably a cat lying on its back by rank 20. The left panel reveals why so few pieces suffice: over the first hundred indices, the singular values decay roughly as a power law, σi∝i−1.1\sigma_i\propto i^{-1.1}.

Figure 21.5.5:

Eckart--Young on a 400×500400\times500 photograph. Left: the singular values fall roughly as a power law (log--log axes; the shaded band marks the twenty kept in the rank-20 panel). Right: the truncations Ak\mathbf{A}_k with their relative Frobenius error and the fraction k(m+n+1)/mnk(m+n+1)/mn of the original numbers they store.

The energy ratio. The Frobenius error formula gives a practical rule for choosing kk. The fraction of total squared "energy" ∑iσi2\sum_i\sigma_i^2 retained by the rank-kk truncation is

∑i≤kσi2∑iσi2=1−∥A−Ak∥F2∥A∥F2,(21.5.12)\frac{\sum_{i\le k}\sigma_i^2}{\sum_{i}\sigma_i^2} = 1 - \frac{\|\mathbf{A}-\mathbf{A}_k\|_F^2}{\|\mathbf{A}\|_F^2} , \tag{21.5.12}

meaning the relative Frobenius error is the square root of one minus the energy ratio. Retaining 95% of the energy thus corresponds to a relative error of 0.05≈22%\sqrt{0.05}\approx22\%, while retaining 99% brings the error down to 10%. One must read this ratio with care, however. On the photograph, σ12\sigma_1^2 alone accounts for 89% of the energy because a constant image has rank one (all rows identical) and the photograph's average brightness is large, so the first dyad mostly captures that mean. Rank 4 already retains 95% of the energy (at 21% relative error), whereas once we subtract the mean pixel value, reaching 95% requires rank 8 instead of 4 (as we verify in Section 21.5.4.3). Always check whether σ1\sigma_1 is dominated by a nonzero mean, or subtract the mean first, just as principal component analysis does.

To see how much Eckart--Young saves over a naive rank-20 scheme, the last lines of the cell select the 20 actual columns of the photograph with the largest norms and project every column onto their span (the idea behind CUR decompositions, which approximate a matrix using subsets of its own rows and columns). Its relative error is 0.31, nearly four times worse than the 0.08 of the truncated SVD.

Truncation as denoising. Compression is not the only reason to truncate an SVD; denoising is another. Suppose an observed m×nm\times n matrix (m≤nm\le n) consists of a low-rank signal plus random noise, A=B+N\mathbf{A}=\mathbf{B}+\mathbf{N}, where the entries of N\mathbf{N} are independent with mean zero and standard deviation σnoise\sigma_{\text{noise}}. By the Marchenko--Pastur law of Section 21.3.2.4 applied to NN⊤/n\mathbf{N}\mathbf{N}^\top/n, the singular values of a large noise matrix concentrate inside the interval [(n−m)σnoise,(n+m)σnoise][(\sqrt n-\sqrt m)\sigma_{\text{noise}},(\sqrt n+\sqrt m)\sigma_{\text{noise}}]. Signal components whose singular values rise well above the upper edge stand out cleanly from the noise bulk, while weaker ones disappear into it. For square matrices with a known noise level, Gavish and Donoho proved that the asymptotically optimal hard threshold is 43n σnoise≈2.309n σnoise\tfrac{4}{\sqrt3}\sqrt n\,\sigma_{\text{noise}}\approx2.309\sqrt n\,\sigma_{\text{noise}}, sitting slightly above the noise edge 2n σnoise2\sqrt n\,\sigma_{\text{noise}} (Gavish and Donoho, 2014). Exercise 8 derives the constant 4/34/\sqrt3.

21.5.2.2 Principal Component Analysis#

Suppose we are given a dataset whose examples are the rows of X∈Rn×d\mathbf{X}\in\mathbb{R}^{n\times d}, with nn data points and dd features. Often most of the variation in the data lies along just a few directions. Two natural questions arise: which unit direction captures the largest variance of the data, and which kk-dimensional affine subspace approximates the points with the smallest squared error? Surprisingly, both questions have the exact same answer, and it is simply the truncated SVD of the centered data.

Centering. First fix any kk-dimensional subspace with orthogonal projector P\mathbf{P}, and ask which offset c\mathbf{c} minimizes the total squared reconstruction error ∑i∥(I−P)(xi−c)∥2\sum_i\|(\mathbf{I}-\mathbf{P})(\mathbf{x}_i-\mathbf{c})\|^2. This objective is a convex quadratic in c\mathbf{c}, and its gradient −2(I−P)∑i(xi−c)-2(\mathbf{I}-\mathbf{P})\sum_i(\mathbf{x}_i-\mathbf{c}) vanishes at the sample mean c=xˉ\mathbf{c}=\bar{\mathbf{x}}, regardless of P\mathbf{P}. The best affine subspace therefore always passes through the mean, so we begin by centering the data: X~=X−1xˉ⊤\tilde{\mathbf{X}}=\mathbf{X}-\mathbf{1}\bar{\mathbf{x}}^\top. Its empirical covariance is the symmetric positive semidefinite matrix C=1nX~⊤X~\mathbf{C}=\tfrac1n\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}}. (Using the unbiased factor 1n−1\tfrac1{n-1} rescales every eigenvalue identically and changes neither the principal directions nor the fraction of variance they explain.)

Proposition (PCA via Rayleigh). Over all unit vectors w\mathbf{w}, the projected variance 1n∥X~w∥2=w⊤Cw\tfrac1n\|\tilde{\mathbf{X}}\mathbf{w}\|^2=\mathbf{w}^\top\mathbf{C}\mathbf{w} is maximized by the top eigenvector of C\mathbf{C}, which is the top right singular vector v1\mathbf{v}_1 of X~\tilde{\mathbf{X}}, with maximal variance σ12/n\sigma_1^2/n.

Proof. Projecting a centered point onto w\mathbf{w} yields the scalar coordinate x~⊤w\tilde{\mathbf{x}}^\top\mathbf{w}, whose empirical variance is 1n∑i(x~i⊤w)2=1n∥X~w∥2=w⊤Cw\tfrac1n\sum_i(\tilde{\mathbf{x}}_i^\top\mathbf{w})^2=\tfrac1n\|\tilde{\mathbf{X}}\mathbf{w}\|^2=\mathbf{w}^\top\mathbf{C}\mathbf{w}. By the Rayleigh proposition of Section 21.3.2.3, this quadratic form is maximized by the top eigenvector of C\mathbf{C}, with value λ1(C)\lambda_1(\mathbf{C}). By (21.5.6), C=1nVΣ⊤ΣV⊤\mathbf{C}=\tfrac1n\mathbf{V}\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}\mathbf{V}^\top, so the eigenvectors of C\mathbf{C} are the right singular vectors vi\mathbf{v}_i of X~\tilde{\mathbf{X}} and its eigenvalues are σi2/n\sigma_i^2/n. ■\blacksquare

Among unit vectors orthogonal to v1\mathbf{v}_1, the variance is maximized by v2\mathbf{v}_2, and continuing inductively gives the top kk principal directions v1,…,vk\mathbf{v}_1,\ldots,\mathbf{v}_k, with component ii explaining variance σi2/n\sigma_i^2/n. Now check the reconstruction error. Projecting every centered point onto span⁡{v1,…,vk}\operatorname{span}\{\mathbf{v}_1,\ldots,\mathbf{v}_k\} corresponds to right-multiplying X~\tilde{\mathbf{X}} by VkVk⊤\mathbf{V}_k\mathbf{V}_k^\top. Since V⊤Vk\mathbf{V}^\top\mathbf{V}_k selects the first kk columns of the identity,

X~VkVk⊤=UΣV⊤VkVk⊤=UkΣkVk⊤=X~k.\tilde{\mathbf{X}}\mathbf{V}_k\mathbf{V}_k^\top = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\mathbf{V}_k\mathbf{V}_k^\top = \mathbf{U}_k\boldsymbol{\Sigma}_k\mathbf{V}_k^\top = \tilde{\mathbf{X}}_k .

Projecting onto the top kk principal directions is therefore identical to taking the rank-kk truncated SVD of the centered data. By Eckart--Young in the Frobenius norm, no other projection, and indeed no other rank-kk matrix at all, can reconstruct the centered points with smaller squared error. The discarded variance ∑i>kσi2/n\sum_{i>k}\sigma_i^2/n equals the mean squared reconstruction error, and the explained-variance ratio is simply the energy ratio (21.5.12) of X~\tilde{\mathbf{X}}.

Figure 21.5.6 shows a cloud of 300 points with standard deviations 3 and 0.8 along axes rotated by π/5=36∘\pi/5=36^\circ, together with its two principal axes. In the population, the first direction holds 9/9.64≈93.4%9/9.64\approx93.4\% of the variance and aligns with the long axis. The cell below checks how accurately a finite sample of 300 points recovers these values.

Figure 21.5.6:

A cloud of 300 points centered at (1,0.6)(1,0.6) with standard deviations 3 and 0.8 along axes rotated by 36∘36^\circ, and its principal axes drawn from the mean, each two standard deviations 2σi/n2\sigma_i/\sqrt{n} long. The first axis points along the direction of largest variance.

theta = np.pi / 5
rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
X = np.random.standard_normal((300, 2)) * np.array([3.0, 0.8]) @ rot.T   # the cloud
Xc = X - X.mean(0)
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
X1 = np.outer(U[:, 0] * s[0], Vt[0])                                    # rank-1 reconstruction
print('explained-variance ratio:', (s**2 / (s**2).sum()).round(3), ' (population 0.934, 0.066)')
print('angle of v_1 to the long axis:',
      np.degrees(np.arccos(abs(Vt[0] @ rot[:, 0]))).round(1), 'degrees')
print('mean squared rank-1 error:', (((Xc - X1)**2).sum() / 300).round(4),
      '  sigma_2^2 / n:', (s[1]**2 / 300).round(4))
explained-variance ratio: [0.923 0.077]  (population 0.934, 0.066)
angle of v_1 to the long axis: 0.6 degrees
mean squared rank-1 error: 0.7111   sigma_2^2 / n: 0.7111

Across random draws, the first principal direction explains roughly 91% to 95% of the variance and lands within a few degrees of the true long axis. If we forget to center the data, however, the first singular vector swings toward the mean of the cloud as soon as the mean's offset exceeds the spread of the points; it then describes where the cloud sits rather than how it varies. Exercise 3 quantifies this effect.

21.5.3 Solving Linear Systems with the SVD#

21.5.3.1 The Pseudoinverse and Least Squares#

A linear system Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} with more equations than unknowns generally has no exact solution, while one with fewer equations than unknowns has infinitely many. In both situations, we look for the least-squares solution introduced in Section 21.1 (writing the target as b\mathbf{b} instead of y\mathbf{y}),

min⁡x∥Ax−b∥2,\min_{\mathbf{x}} \|\mathbf{A}\mathbf{x}-\mathbf{b}\|^2 ,

and whenever multiple x\mathbf{x} achieve the same minimum residual, we choose the one with the smallest norm.

Consider the simplest underdetermined example first: a single equation in two unknowns, x1+x2=2x_1+x_2=2. Its solutions form an entire line, and the residual is zero everywhere on it. Which point on the line should we pick? Here A=(1    1)\mathbf{A}=(1\;\;1), which has one nonzero singular value σ1=2\sigma_1=\sqrt2, right singular vector v1=(1,1)/2\mathbf{v}_1=(1,1)/\sqrt2, and u1=1u_1=1. The equation fixes the coordinate of x\mathbf{x} along v1\mathbf{v}_1 to 2\sqrt2, while the coordinate along the null-space direction v2=(1,−1)/2\mathbf{v}_2=(1,-1)/\sqrt2 does not affect the residual at all. Setting that free coordinate to zero yields (1,1)(1,1), the foot of the perpendicular from the origin to the line, with norm 2\sqrt2; every other solution (1+t,1−t)(1+t,1-t) has strictly larger squared norm 2+2t22+2t^2 (Figure 21.5.7).

Figure 21.5.7:

Least squares with one equation and two unknowns. Every point of the line solves x1+x2=2x_1+x_2=2; the pseudoinverse returns the one closest to the origin, the foot of the perpendicular.

The general rule simply inverts every nonzero singular value and transposes the orthogonal factors. The Moore--Penrose pseudoinverse of A\mathbf{A} is

A+=VΣ+U⊤,Σii+={1/σiσi>0,0σi=0,(21.5.13)\mathbf{A}^{+} = \mathbf{V}\boldsymbol{\Sigma}^{+}\mathbf{U}^\top, \qquad \boldsymbol{\Sigma}^{+}_{ii} = \begin{cases} 1/\sigma_i & \sigma_i>0,\\ 0 & \sigma_i=0,\end{cases} \tag{21.5.13}

where Σ+\boldsymbol{\Sigma}^{+} has shape n×mn\times m, the transpose shape of Σ\boldsymbol{\Sigma}. Geometrically, A+\mathbf{A}^{+} reverses every stretch that can be reversed and sends the left null space to zero. For the shear, T+=T−1=(1−101)\mathbf{T}^{+}=\mathbf{T}^{-1}=\left(\begin{smallmatrix}1&-1\\0&1\end{smallmatrix}\right); for A=(1    1)\mathbf{A}=(1\;\;1), A+=v1σ1−1u1=(12,12)⊤\mathbf{A}^{+}=\mathbf{v}_1\sigma_1^{-1}u_1=(\tfrac12,\tfrac12)^\top, so A+⋅2=(1,1)\mathbf{A}^{+}\cdot2=(1,1).

Proposition (minimum-norm least squares). Among all minimizers of ∥Ax−b∥\|\mathbf{A}\mathbf{x}-\mathbf{b}\|, the unique one of smallest norm is x^=A+b\hat{\mathbf{x}}=\mathbf{A}^{+}\mathbf{b}.

Proof. Change variables to the singular bases by setting y=V⊤x\mathbf{y}=\mathbf{V}^\top\mathbf{x} and c=U⊤b\mathbf{c}=\mathbf{U}^\top\mathbf{b}. Because U\mathbf{U} is orthogonal, it preserves Euclidean norms, so

∥Ax−b∥2=∥U⊤(Ax−b)∥2=∥Σy−c∥2=∑i≤r(σiyi−ci)2+∑i>rci2.\|\mathbf{A}\mathbf{x}-\mathbf{b}\|^2 = \|\mathbf{U}^\top(\mathbf{A}\mathbf{x}-\mathbf{b})\|^2 = \|\boldsymbol{\Sigma}\mathbf{y}-\mathbf{c}\|^2 = \sum_{i\le r}(\sigma_i y_i - c_i)^2 + \sum_{i> r} c_i^2 .

Rotating into the singular bases decouples the system into independent scalar equations. The first sum is minimized term by term by setting yi=ci/σiy_i=c_i/\sigma_i for i≤ri\le r. The second sum is a fixed constant, the component of b\mathbf{b} outside the column space, which no choice of x\mathbf{x} can reduce. Meanwhile, the coordinates yiy_i for i>ri>r do not enter the residual at all, and since ∥x∥=∥y∥\|\mathbf{x}\|=\|\mathbf{y}\|, setting them to zero gives the unique minimizer of smallest norm. That choice is y=Σ+c\mathbf{y}=\boldsymbol{\Sigma}^{+}\mathbf{c}, which translates back to x^=VΣ+U⊤b=A+b\hat{\mathbf{x}}=\mathbf{V}\boldsymbol{\Sigma}^{+}\mathbf{U}^\top\mathbf{b}=\mathbf{A}^{+}\mathbf{b}. ■\blacksquare

In the singular bases, minimizing the residual and minimizing the norm govern completely disjoint coordinates (i≤ri\le r versus i>ri>r), so both goals are achieved simultaneously. When A\mathbf{A} is square and invertible, every σi\sigma_i is positive and A+=VΣ−1U⊤=A−1\mathbf{A}^{+}=\mathbf{V}\boldsymbol{\Sigma}^{-1}\mathbf{U}^\top=\mathbf{A}^{-1}. Yet the same formula also exposes the main danger of least squares: dividing by a tiny σi\sigma_i multiplies any noise in b\mathbf{b} along ui\mathbf{u}_i by 1/σi1/\sigma_i.

Two standard remedies tame these unstable directions. Ridge regression minimizes ∥Ax−b∥2+λ∥x∥2\|\mathbf{A}\mathbf{x}-\mathbf{b}\|^2+\lambda\|\mathbf{x}\|^2 for λ>0\lambda>0, giving xλ=(A⊤A+λI)−1A⊤b\mathbf{x}_\lambda=(\mathbf{A}^\top\mathbf{A}+\lambda\mathbf{I})^{-1}\mathbf{A}^\top\mathbf{b}. The truncated pseudoinverse xk\mathbf{x}_k instead keeps only the first kk singular terms of A+b\mathbf{A}^{+}\mathbf{b}. Substituting the SVD and noting that A⊤A+λI=V(Σ⊤Σ+λI)V⊤\mathbf{A}^\top\mathbf{A}+\lambda\mathbf{I}=\mathbf{V}(\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}+\lambda\mathbf{I})\mathbf{V}^\top, both solutions take a transparent filter form:

xλ=∑i≤rσi2σi2+λ ui⊤bσi vi,xk=∑i≤kui⊤bσi vi.(21.5.14)\mathbf{x}_\lambda = \sum_{i\le r}\frac{\sigma_i^2}{\sigma_i^2+\lambda}\, \frac{\mathbf{u}_i^\top\mathbf{b}}{\sigma_i}\,\mathbf{v}_i, \qquad \mathbf{x}_k = \sum_{i\le k}\frac{\mathbf{u}_i^\top\mathbf{b}}{\sigma_i}\,\mathbf{v}_i . \tag{21.5.14}

Both start from the unregularized pseudoinverse terms ui⊤b/σi\mathbf{u}_i^\top\mathbf{b}/\sigma_i. Ridge regression scales component ii by the smooth filter factor σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2+\lambda), which stays near 1 when σi2≫λ\sigma_i^2\gg\lambda and shrinks toward 0 when σi2≪λ\sigma_i^2\ll\lambda; truncation applies a sharp step function of 1 or 0. For λ=1\lambda=1, singular values 33, 11, and 0.30.3 receive filter factors 0.90.9, 0.50.5, and 0.0830.083. For a linear model trained with squared loss, weight decay (Section 2.7) is precisely ridge regression, and these filter factors show exactly which directions it damps.

The normal equations. The classical textbook route to least squares solves the normal equations A⊤Ax=A⊤b\mathbf{A}^\top\mathbf{A}\mathbf{x}=\mathbf{A}^\top\mathbf{b}. For any A\mathbf{A}, its solutions are the least-squares minimizers (since A⊤(Ax−b)=0\mathbf{A}^\top(\mathbf{A}\mathbf{x}-\mathbf{b})=\mathbf{0} states that the residual is orthogonal to the column space), and the solution is unique whenever A\mathbf{A} has full column rank. Numerically, however, forming A⊤A\mathbf{A}^\top\mathbf{A} is a bad idea because it squares the condition number (Section 21.5.3.2). Modern libraries therefore solve least-squares problems via the SVD or a QR factorization instead.

Let us test the pseudoinverse on one overdetermined and one underdetermined system. The first fits a line b≈x1+x2tb\approx x_1+x_2 t to the four observations b=(6,5,7,10)\mathbf{b}=(6,5,7,10) at t=1,2,3,4t=1,2,3,4; the second is our single equation x1+x2=2x_1+x_2=2.

A = np.array([[1., 1.], [1., 2.], [1., 3.], [1., 4.]])     # 4 equations, 2 unknowns
b = np.array([6., 5., 7., 10.])
x_pinv = np.linalg.pinv(A) @ b
x_lstsq = np.linalg.lstsq(A, b, rcond=None)[0]
print('overdetermined: pinv', x_pinv.round(4), ' lstsq', x_lstsq.round(4),
      ' residual', np.linalg.norm(A @ x_pinv - b).round(4))
A1 = np.array([[1., 1.]])                                  # 1 equation: x1 + x2 = 2
x1 = np.linalg.pinv(A1) @ np.array([2.])
print('underdetermined: pinv gives', x1.round(4), ' norm', np.linalg.norm(x1).round(4))
overdetermined: pinv [3.5 1.4]  lstsq [3.5 1.4]  residual 2.0494
underdetermined: pinv gives [1. 1.]  norm 1.4142

The pseudoinverse and np.linalg.lstsq agree on the fitted line 3.5+1.4t3.5+1.4t, with residual 4.2≈2.049\sqrt{4.2}\approx2.049, and for the single equation the pseudoinverse returns the foot of the perpendicular, (1,1)(1,1).

21.5.3.2 The Condition Number#

In practice, the entries of a linear system come from noisy measurements or finite-precision rounding. Before trusting a computed solution, we need to know how much a tiny change in the data can alter the answer. A simple 2×22\times2 system reveals how dramatic the amplification can be. Consider Kx=b\mathbf{K}\mathbf{x}=\mathbf{b} with K=(1111.0001)\mathbf{K}=\left(\begin{smallmatrix}1&1\\1&1.0001\end{smallmatrix}\right) and b=(2,2.0001)\mathbf{b}=(2,2.0001). Its exact solution is x=(1,1)\mathbf{x}=(1,1). Now nudge b2b_2 by just 10−410^{-4}, to 2.00022.0002: the solution jumps all the way to (0,2)(0,2). A perturbation of roughly three parts in 10510^5 in the data has completely changed the answer. The singular values of K\mathbf{K}, roughly 2.000052.00005 and 5×10−55\times10^{-5}, tell us why.

The condition number of a matrix A\mathbf{A} of rank rr is the ratio of its largest to its smallest nonzero singular value,

κ(A)=σ1σr.(21.5.15)\kappa(\mathbf{A}) = \frac{\sigma_1}{\sigma_r} . \tag{21.5.15}

Geometrically, κ(A)\kappa(\mathbf{A}) measures how unevenly A\mathbf{A} stretches different directions: for K\mathbf{K} it is about 4×1044\times10^4, whereas for the shear it is only φ2≈2.618\varphi^2\approx2.618. When A\mathbf{A} is symmetric positive definite, its singular values coincide with its eigenvalues, so κ=λmax⁡/λmin⁡\kappa=\lambda_{\max}/\lambda_{\min}, recovering the condition number for quadratic bowls in Section 21.3.2.3. The next proposition shows that κ(A)\kappa(\mathbf{A}) is the exact worst-case amplification factor for relative errors in a linear solve.

Proposition (error amplification). Let A\mathbf{A} be square and invertible, Ax=b\mathbf{A}\mathbf{x}=\mathbf{b} with b≠0\mathbf{b}\ne\mathbf{0}, and let a perturbation δb\delta\mathbf{b} shift the solution to x+δx\mathbf{x}+\delta\mathbf{x}. Then

∥δx∥∥x∥≤κ(A) ∥δb∥∥b∥,(21.5.16)\frac{\|\delta\mathbf{x}\|}{\|\mathbf{x}\|} \le \kappa(\mathbf{A})\,\frac{\|\delta\mathbf{b}\|}{\|\mathbf{b}\|}, \tag{21.5.16}

and for every A\mathbf{A} there exist b\mathbf{b} and δb\delta\mathbf{b} that attain equality.

Proof. From A δx=δb\mathbf{A}\,\delta\mathbf{x}=\delta\mathbf{b} we have δx=A−1δb\delta\mathbf{x}=\mathbf{A}^{-1}\delta\mathbf{b}. The largest singular value of A−1=VΣ−1U⊤\mathbf{A}^{-1}=\mathbf{V}\boldsymbol{\Sigma}^{-1}\mathbf{U}^\top is 1/σn1/\sigma_n, so (21.5.5) gives ∥δx∥≤σn−1∥δb∥\|\delta\mathbf{x}\|\le\sigma_n^{-1}\|\delta\mathbf{b}\|. Likewise, b=Ax\mathbf{b}=\mathbf{A}\mathbf{x} gives ∥b∥≤σ1∥x∥\|\mathbf{b}\|\le\sigma_1\|\mathbf{x}\|. Combining the two inequalities yields

∥δx∥∥x∥≤σ1σn ∥δb∥∥b∥=κ(A) ∥δb∥∥b∥.\frac{\|\delta\mathbf{x}\|}{\|\mathbf{x}\|} \le \frac{\sigma_1}{\sigma_n}\,\frac{\|\delta\mathbf{b}\|}{\|\mathbf{b}\|} = \kappa(\mathbf{A})\,\frac{\|\delta\mathbf{b}\|}{\|\mathbf{b}\|} .

Equality holds in both bounds simultaneously when b=u1\mathbf{b}=\mathbf{u}_1 (making x=σ1−1v1\mathbf{x}=\sigma_1^{-1}\mathbf{v}_1 as short as possible for a unit right-hand side) and δb=εun\delta\mathbf{b}=\varepsilon\mathbf{u}_n (making δx=εσn−1vn\delta\mathbf{x}=\varepsilon\sigma_n^{-1}\mathbf{v}_n as large as possible for a perturbation of size ε\varepsilon). ■\blacksquare

The relative error in the data is therefore amplified by at most κ\kappa. With κ=104\kappa=10^4, a relative error of 10−810^{-8} in b\mathbf{b} can grow into 10−410^{-4} in x\mathbf{x}, costing four digits of accuracy. In our 2×22\times2 example, the relative change in b\mathbf{b} is 10−4/∥b∥≈3.5×10−510^{-4}/\|\mathbf{b}\|\approx3.5\times10^{-5}, so the bound allows a relative change of 1.411.41 in x\mathbf{x}, and the realized change is 1.01.0. The perturbation (0,10−4)(0,10^{-4}) places 1/21/\sqrt2 of its length along the most amplified direction u2≈(1,−1)/2\mathbf{u}_2\approx(1,-1)/\sqrt2, while b\mathbf{b} points almost directly along u1\mathbf{u}_1.

At the ideal extreme, an orthogonal matrix has all singular values equal to 1, so κ=1\kappa=1: rotations and reflections never amplify error. That is why computing with the orthogonal factors U\mathbf{U} and V\mathbf{V} is numerically safe, and why an orthogonally initialized weight matrix preserves the norm of every input vector. At the opposite extreme, forming the Gram matrix squares the condition number,

κ(A⊤A)=κ(A)2,\kappa(\mathbf{A}^\top\mathbf{A})=\kappa(\mathbf{A})^2 ,

because (21.5.6) is the SVD of A⊤A\mathbf{A}^\top\mathbf{A}, with singular values σi2\sigma_i^2 (for any matrix A\mathbf{A} of any rank). For the shear, κ\kappa jumps from φ2≈2.62\varphi^2\approx2.62 to φ4≈6.85\varphi^4\approx6.85. The cell below verifies our 2×22\times2 example and compares κ(A)\kappa(\mathbf{A}) with κ(A⊤A)\kappa(\mathbf{A}^\top\mathbf{A}) for the line-fitting matrix above.

K = np.array([[1., 1.], [1., 1.0001]])
b = np.array([2., 2.0001])
x = np.linalg.solve(K, b)
x2 = np.linalg.solve(K, b + np.array([0., 1e-4]))
print('x =', x.round(4), '  after changing b_2 by 1e-4:', x2.round(4) + 0.)
kappa = np.linalg.cond(K)
print(f'kappa(K) = {kappa:.0f};  bound {kappa * 1e-4 / np.linalg.norm(b):.2f};  '
      f'realized {np.linalg.norm(x2 - x) / np.linalg.norm(x):.2f}')
A = np.array([[1., 1.], [1., 2.], [1., 3.], [1., 4.]])
print(f'kappa(A) = {np.linalg.cond(A):.3f};  kappa(A^T A) = {np.linalg.cond(A.T @ A):.2f};  '
      f'kappa(A)^2 = {np.linalg.cond(A)**2:.2f}')
x = [1. 1.]   after changing b_2 by 1e-4: [0. 2.]
kappa(K) = 40002;  bound 1.41;  realized 1.00
kappa(A) = 7.469;  kappa(A^T A) = 55.78;  kappa(A)^2 = 55.78

The output confirms our hand calculation: the solution jumps from (1,1)(1,1) to (0,2)(0,2), with κ(K)≈40,002\kappa(\mathbf{K})\approx40{,}002. Even for the modest 4×24\times2 line-fitting matrix, κ=7.47\kappa=7.47, so forming the normal equations would already inflate the condition number to κ2=55.8\kappa^2=55.8.

Conditioning and the shape of a bowl. A large condition number also shows up directly in optimization as elongated level sets. For a full-column-rank least-squares objective 12∥Ax−b∥2\tfrac12\|\mathbf{A}\mathbf{x}-\mathbf{b}\|^2, the Hessian is H=A⊤A\mathbf{H}=\mathbf{A}^\top\mathbf{A}, whose level sets are ellipsoids with semi-axes proportional to 1/σi1/\sigma_i along the vi\mathbf{v}_i. The contours therefore have axis ratio κ(A)\kappa(\mathbf{A}), while the Hessian itself has condition number κ(A)2\kappa(\mathbf{A})^2. On such a narrow valley, gradient descent zig-zags across the steep walls and makes slow progress along the floor (Figure 21.5.8), at a convergence rate governed by κ(H)\kappa(\mathbf{H}) that we derive in Section 23.1.

Figure 21.5.8:

Gradient descent on a well-conditioned quadratic bowl (κ(H)=1.3\kappa(\mathbf{H})=1.3, near-circular contours, an almost straight path) versus an ill-conditioned one (κ(H)=18\kappa(\mathbf{H})=18, a zig-zag trajectory across the narrow valley). The panel titles give the condition number κ(H)\kappa(\mathbf{H}) of the Hessian; the contours are elongated by its square root, a factor of about 4.24.2 in the second panel.

21.5.4 The SVD in Deep Learning#

Three recurring questions in modern large-model training come down directly to the singular values of a weight matrix: how many parameters a fine-tuning adapter needs, how to construct an update that treats every direction of weight space equally, and how much a single layer can stretch its input.

21.5.4.1 Low-Rank Updates#

Updating every parameter of a large pretrained model during fine-tuning is costly in both memory and compute. LoRA (Hu et al., 2021) avoids this by freezing each pretrained weight matrix W∈Rm×n\mathbf{W}\in\mathbb{R}^{m\times n} and learning only a rank-kk correction ΔW=BA\Delta\mathbf{W}=\mathbf{B}\mathbf{A}, where B∈Rm×k\mathbf{B}\in\mathbb{R}^{m\times k} and A∈Rk×n\mathbf{A}\in\mathbb{R}^{k\times n} (here A\mathbf{A} follows the paper's notation for the k×nk\times n down-projection, not the generic matrix of earlier subsections). The adapter uses k(m+n)k(m+n) trainable parameters instead of mnmn. For a 4096×40964096\times4096 layer with k=8k=8, that drops the parameter count from 16,777,21616{,}777{,}216 to 8⋅8192=65,5368\cdot8192=65{,}536, or just 0.39%. As Figure 21.5.9 illustrates, the frozen weight and the low-rank bypass act in parallel on the same input and add their outputs.

Figure 21.5.9:

The LoRA architecture for one layer. The pretrained W\mathbf{W} (all mn=16.8mn = 16.8M parameters for m=n=4096m=n=4096) stays frozen; a parallel bypass first compresses the input to k=8k=8 dimensions with A\mathbf{A} and then expands back with B\mathbf{B}, so only k(m+n)≈65.5k(m+n) \approx 65.5K parameters (about 0.39%0.39\%) are trained. The two branches add: h=Wx+BAx\mathbf{h} = \mathbf{W}\mathbf{x} + \mathbf{B}\mathbf{A}\mathbf{x}. After training, BA\mathbf{B}\mathbf{A} can be merged into W\mathbf{W}, so deployment costs nothing extra.

What does Eckart--Young tell us here, and what does it not tell us? If full fine-tuning would produce an update with singular values σ1≥σ2≥⋯\sigma_1\ge\sigma_2\ge\cdots, then Eckart--Young guarantees that no rank-kk adapter can approximate that specific update closer than σk+1\sigma_{k+1} in the spectral norm or (∑i>kσi2)1/2(\sum_{i>k}\sigma_i^2)^{1/2} in the Frobenius norm. It does not dictate which adapter gradient descent actually learns. LoRA succeeds whenever some low-rank update achieves low loss—even if it is not the closest rank-kk approximation to the full fine-tuning update. That such low-rank solutions exist for many downstream tasks is the empirical discovery behind LoRA. Exercise 2 bounds how much a rank-kk adapter can perturb the singular values of W\mathbf{W}.

21.5.4.2 Orthogonalized Updates#

The Muon optimizer (Jordan et al., 2024) updates a weight matrix not along its raw momentum matrix M\mathbf{M}, but along the polar factor of M\mathbf{M}, the matrix that keeps the singular vectors of M\mathbf{M} while setting every nonzero singular value to 1. Section 9.6 motivates and develops the full optimizer; here we supply the two linear-algebraic tools it relies on: what the polar factor is, and how to compute it using only matrix multiplications.

The polar decomposition. For a square matrix A\mathbf{A}, inserting V⊤V=I\mathbf{V}^\top\mathbf{V}=\mathbf{I} into the SVD splits it into an orthogonal factor times a symmetric stretch:

A=UΣV⊤=(UV⊤) (VΣV⊤)=Q P.(21.5.17)\mathbf{A} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top = (\mathbf{U}\mathbf{V}^\top)\,(\mathbf{V}\boldsymbol{\Sigma}\mathbf{V}^\top) = \mathbf{Q}\,\mathbf{P}. \tag{21.5.17}

Here Q=UV⊤\mathbf{Q}=\mathbf{U}\mathbf{V}^\top is orthogonal (as a product of orthogonal matrices) and P=VΣV⊤\mathbf{P}=\mathbf{V}\boldsymbol{\Sigma}\mathbf{V}^\top is symmetric positive semidefinite with eigenvalues σi\sigma_i. Every square matrix thus decomposes into a symmetric stretch followed by an orthogonal map, the matrix analogue of writing a complex number in polar form as z=eiθ∣z∣z=e^{i\theta}|z|. Note that Q\mathbf{Q} need not be a pure rotation: when A\mathbf{A} is invertible, det⁡Q=sign⁡det⁡A\det\mathbf{Q}=\operatorname{sign}\det\mathbf{A}, so Q\mathbf{Q} includes a reflection whenever det⁡A<0\det\mathbf{A}\lt 0. For the shear T\mathbf{T}, (21.5.4) yields Q=R31.7∘R58.3∘⊤=R−26.6∘=15(21−12)\mathbf{Q}=\mathbf{R}_{31.7^\circ}\mathbf{R}_{58.3^\circ}^\top=\mathbf{R}_{-26.6^\circ}=\tfrac{1}{\sqrt5}\left(\begin{smallmatrix}2&1\\-1&2\end{smallmatrix}\right) (since tan⁡26.6∘=12\tan26.6^\circ=\tfrac12) and P=15(2113)\mathbf{P}=\tfrac{1}{\sqrt5}\left(\begin{smallmatrix}2&1\\1&3\end{smallmatrix}\right). Checking the product confirms QP=15(5505)=T\mathbf{Q}\mathbf{P}=\tfrac15\left(\begin{smallmatrix}5&5\\0&5\end{smallmatrix}\right)=\mathbf{T} and P2=(1112)=T⊤T\mathbf{P}^2=\left(\begin{smallmatrix}1&1\\1&2\end{smallmatrix}\right)=\mathbf{T}^\top\mathbf{T}.

For a rectangular matrix M\mathbf{M} with thin SVD M=UΣV⊤\mathbf{M}=\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top, the polar factor is still UV⊤\mathbf{U}\mathbf{V}^\top: it shares the singular vectors of M\mathbf{M} and has all singular values equal to 1, so its columns (when m≥nm\ge n) or its rows (when m≤nm\le n) are orthonormal. When M\mathbf{M} is rank-deficient (r<min⁡(m,n)r\lt \min(m,n)), the polar factor is not unique, and the natural canonical choice is UrVr⊤\mathbf{U}_r\mathbf{V}_r^\top from the compact SVD. Exercise 6 shows that for a square matrix, UV⊤\mathbf{U}\mathbf{V}^\top is also the closest orthogonal matrix to A\mathbf{A} in the Frobenius norm.

Odd polynomials of a matrix. Computing a full SVD of every weight matrix at every training step would be prohibitively slow. Fortunately, we can transform the singular values without touching the singular vectors using nothing more than matrix multiplications.

Proposition (odd polynomials act on singular values). Let X=UΣV⊤\mathbf{X}=\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top be a thin SVD and let p(σ)=∑jcjσ2j+1p(\sigma)=\sum_j c_j\sigma^{2j+1} be an odd polynomial. Then

p(X):=∑jcj X(X⊤X)j=U p(Σ) V⊤.(21.5.18)p(\mathbf{X}) := \sum_j c_j\,\mathbf{X}(\mathbf{X}^\top\mathbf{X})^j = \mathbf{U}\,p(\boldsymbol{\Sigma})\,\mathbf{V}^\top . \tag{21.5.18}

Proof. Since X⊤X=VΣ2V⊤\mathbf{X}^\top\mathbf{X}=\mathbf{V}\boldsymbol{\Sigma}^2\mathbf{V}^\top, taking powers gives (X⊤X)j=VΣ2jV⊤(\mathbf{X}^\top\mathbf{X})^j=\mathbf{V}\boldsymbol{\Sigma}^{2j}\mathbf{V}^\top, and left-multiplying by X=UΣV⊤\mathbf{X}=\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top gives X(X⊤X)j=UΣ2j+1V⊤\mathbf{X}(\mathbf{X}^\top\mathbf{X})^j=\mathbf{U}\boldsymbol{\Sigma}^{2j+1}\mathbf{V}^\top. Summing over jj completes the proof. ■\blacksquare

Any odd matrix polynomial therefore leaves U\mathbf{U} and V\mathbf{V} untouched while applying the scalar function pp independently to each singular value. To reach the polar factor UV⊤\mathbf{U}\mathbf{V}^\top, we simply need an odd polynomial pp whose repeated application drives every positive singular value to 1.

Newton--Schulz. The classic Newton--Schulz iteration X←12(3X−XX⊤X)\mathbf{X}\leftarrow\tfrac12(3\mathbf{X}-\mathbf{X}\mathbf{X}^\top\mathbf{X}) applies the cubic polynomial p(σ)=12(3σ−σ3)p(\sigma)=\tfrac12(3\sigma-\sigma^3) to every singular value. Its fixed points are 00 and ±1\pm1. On (0,1](0,1], pp pushes every value upward without ever overshooting 1, since p(σ)−σ=12σ(1−σ2)≥0p(\sigma)-\sigma=\tfrac12\sigma(1-\sigma^2)\ge0 and pp reaches its maximum p(1)=1p(1)=1. In fact, pp maps the entire interval (0,3)(0,\sqrt3) into (0,1](0,1], so every starting value in this immediate basin of 1 converges to 1, whereas larger starting values can behave erratically (Exercise 5). Scaling the initial matrix as X0=M/∥M∥F\mathbf{X}_0=\mathbf{M}/\|\mathbf{M}\|_F guarantees that every singular value starts inside (0,1](0,1], because ∥M∥F≥σ1(M)\|\mathbf{M}\|_F\ge\sigma_1(\mathbf{M}). Any zero singular value stays zero (since p(0)=0p(0)=0), so a rank-deficient M\mathbf{M} converges cleanly to UrVr⊤\mathbf{U}_r\mathbf{V}_r^\top.

How many iterations does this take? Near 0, p(σ)≈32σp(\sigma)\approx\tfrac32\sigma, so a small singular value ss grows by a factor of 3/23/2 per step and needs roughly log⁡3/2(1/s)\log_{3/2}(1/s) steps to reach order one. Near 1, expanding gives p(1−e)=1−32e2+12e3p(1-e)=1-\tfrac32e^2+\tfrac12e^3: the error roughly squares at every step, shrinking from order one to 10−610^{-6} in about four additional steps. Gluing the two phases together predicts roughly log⁡3/2(1/smin⁡)+4\log_{3/2}(1/s_{\min})+4 steps, governed by the smallest normalized singular value smin⁡=σmin⁡(M)/∥M∥Fs_{\min}=\sigma_{\min}(\mathbf{M})/\|\mathbf{M}\|_F. Let us test this rough estimate on a random 6×46\times4 matrix standing in for the momentum.

M = np.random.standard_normal((6, 4))                # a stand-in momentum matrix
X = M / np.linalg.norm(M)                            # Frobenius normalization: sigma in (0, 1]
s_min = np.linalg.svd(X, compute_uv=False)[-1]
for k in range(1, 41):
    X = 1.5 * X - 0.5 * X @ X.T @ X                  # p(sigma) = (3 sigma - sigma^3) / 2
    if np.abs(np.linalg.svd(X, compute_uv=False) - 1).max() < 1e-6:
        break
U, s, Vt = np.linalg.svd(M, full_matrices=False)
print(f'smallest scaled sigma {s_min:.3f};  predicted steps '
      f'{np.log(1 / s_min) / np.log(1.5) + 4:.1f}')
print(f'steps until max|sigma_i - 1| < 1e-6: {k};  distance to U V^T: '
      f'{np.linalg.norm(X - U @ Vt):.1e}')
smallest scaled sigma 0.146;  predicted steps 8.7
steps until max|sigma_i - 1| < 1e-6: 9;  distance to U V^T: 7.3e-11

The actual step count matches the prediction to within a single iteration, and the iterate lands within 10−510^{-5} of the exact polar factor from a full SVD. Because smin⁡s_{\min} varies across random draws, so does the step count; a nearly rank-deficient M\mathbf{M} takes longer. In practice, Muon replaces the cubic with a tuned quintic polynomial that trades exact convergence to 1 for speed (Section 9.6.2).

21.5.4.3 Measuring and Controlling the Spectrum#

Our third question asks how much a linear layer can stretch its input, and the largest singular value answers it directly. More broadly, the full singular spectrum tells us whether a matrix is truly close to low rank. Modern training recipes therefore bound, inspect, and approximate singular values without ever paying for a full SVD.

Spectral normalization. By (21.5.5), a linear layer x↦Wx\mathbf{x}\mapsto\mathbf{W}\mathbf{x} satisfies ∥Wx−Wx′∥≤σ1∥x−x′∥\|\mathbf{W}\mathbf{x}-\mathbf{W}\mathbf{x}'\|\le\sigma_1\|\mathbf{x}-\mathbf{x}'\|, with equality whenever x−x′\mathbf{x}-\mathbf{x}' aligns with v1\mathbf{v}_1. The smallest constant bounding how much a map can amplify input differences is its Lipschitz constant, so here the Lipschitz constant is simply σ1=∥W∥2\sigma_1=\|\mathbf{W}\|_2. Dividing W\mathbf{W} by σ1\sigma_1 caps the layer's stretch at 1, a technique that stabilizes the training of GAN discriminators (Miyato et al., 2018). Rather than computing a full SVD, σ1\sigma_1 is estimated via power iteration on W⊤W\mathbf{W}^\top\mathbf{W} (Section 21.4.1.2). In practice, one alternates u←Wv\mathbf{u}\leftarrow\mathbf{W}\mathbf{v} and v←W⊤u\mathbf{v}\leftarrow\mathbf{W}^\top\mathbf{u}, normalizing at each half-step; together they perform one multiplication by W⊤W\mathbf{W}^\top\mathbf{W}, with ∥Wv∥\|\mathbf{W}\mathbf{v}\| as the estimate of σ1\sigma_1. Each round pulls v\mathbf{v} closer to v1\mathbf{v}_1, shrinking the error by roughly (σ2/σ1)2(\sigma_2/\sigma_1)^2. Miyato et al. (2018) found empirically that a single round per training step suffices when warm-started from the previous step's vector. (For a convolutional layer, reshaping the kernel into a 2D matrix gives an approximation to the convolution's spectral norm, though not its exact value.)

Measuring the spectrum. Our earlier 0.39% LoRA figure assumed that rank 8 suffices. Whether a matrix is truly close to low rank depends entirely on how fast its singular values decay, so one should measure before truncating. The cell below compares two 400×500400\times500 matrices: a random Gaussian matrix with no structure at all, and our cat photograph with its mean pixel value subtracted.

G = np.random.standard_normal(img.shape)                       # no structure
for name, W in [('Gaussian', G), ('photograph', img - img.mean())]:
    s = np.linalg.svd(W, compute_uv=False)
    r95 = int(np.searchsorted(np.cumsum(s**2) / (s**2).sum(), 0.95)) + 1
    print(f'{name:10s}: sigma from {s[0]:.3g} to {s[-1]:.2g};  95% energy at rank {r95:3d};  '
          f'adapter {r95 * (m + n) / (m * n):.1%} of W')
Gaussian  : sigma from 42.2 to 2.5;  95% energy at rank 269;  adapter 121.0% of W
photograph: sigma from 2.65e+04 to 2.4;  95% energy at rank   8;  adapter 3.6% of W

The contrast is stark. The singular values of the Gaussian matrix spread across the Marchenko--Pastur interval [n−m,n+m]≈[2.4,42.4][\sqrt n-\sqrt m,\sqrt n+\sqrt m]\approx[2.4,42.4] from Section 21.5.2.1, with no drop-off: capturing 95% of its energy takes rank roughly 270 out of 400, so a low-rank adapter would actually use more parameters than the original matrix. The centered photograph, by contrast, reaches 95% of its energy at rank 8, corresponding to an adapter with under 4% of the parameters. Neither matrix is a trained neural-network weight, so this pair only illustrates the two extremes; for LoRA, the matrix that matters is the task-specific update, whose spectrum must be measured rather than assumed.

Randomized SVD. When a matrix is too large to factor directly, randomized SVD (Halko et al., 2011) computes an accurate rank-kk approximation using only a handful of matrix--vector products with A\mathbf{A}. Its core ingredient is a range finder: multiply A\mathbf{A} by a random Gaussian matrix Ω\boldsymbol{\Omega} with slightly more than kk columns, orthonormalize the columns of AΩ\mathbf{A}\boldsymbol{\Omega} into Q\mathbf{Q}, and compute the SVD of the much smaller matrix Q⊤A\mathbf{Q}^\top\mathbf{A}. Whenever the singular values decay, the top singular directions dominate every random linear combination of the columns of A\mathbf{A}, so Q\mathbf{Q} captures them with high probability. Exercise 7 implements this algorithm along with a power-iteration refinement for slowly decaying spectra, and Section 21.6 places it in the broader context of randomized sketching.

Finally, keep three limits of the SVD in mind. First, a full SVD costs O(mnmin⁡(m,n))O(mn\min(m,n)) operations (roughly 40963≈7×10104096^3\approx7\times10^{10} for a single 4096×40964096\times4096 weight matrix), which is why practical algorithms like Newton--Schulz and randomized range finders rely solely on matrix products. Second, low rank is a property of the data, never a free guarantee, as the Gaussian matrix just demonstrated. Third, the SVD captures only linear structure: points lying on a circle in the plane form a rank-2 data matrix even though the circle is inherently one-dimensional. Understanding curved functions and nonlinear structure requires derivatives, which is where we turn in the next chapter.

21.5.5 Summary#

Every real matrix A\mathbf{A}, regardless of its shape, admits an orthonormal input basis {vi}\{\mathbf{v}_i\} and an orthonormal output basis {ui}\{\mathbf{u}_i\} between which it acts as a simple list of non-negative stretches, Avi=σiui\mathbf{A}\mathbf{v}_i=\sigma_i\mathbf{u}_i with σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\cdots\ge0. The factorization follows from applying the spectral theorem to the Gram matrix A⊤A\mathbf{A}^\top\mathbf{A}, with σi=λi(A⊤A)\sigma_i=\sqrt{\lambda_i(\mathbf{A}^\top\mathbf{A})}.

From that single ordered list of singular values, five core quantities fall out at once: the rank (the number of positive σi\sigma_i), the spectral and Frobenius norms (∥A∥2=σ1\|\mathbf{A}\|_2=\sigma_1 and ∥A∥F2=∑iσi2\|\mathbf{A}\|_F^2=\sum_i\sigma_i^2), the optimal rank-kk approximation given by the truncated SVD Ak\mathbf{A}_k (Eckart--Young, which becomes principal component analysis on centered data), the Moore--Penrose pseudoinverse A+\mathbf{A}^{+} that returns the minimum-norm least-squares solution, and the condition number κ=σ1/σr\kappa=\sigma_1/\sigma_r that bounds relative error amplification. In deep learning, the same singular spectrum sizes low-rank fine-tuning adapters, defines the polar factor used by Muon, and gives the Lipschitz constant controlled by spectral normalization.

21.5.6 Exercises#

  1. Norms and the maximum stretch. The text obtained (21.5.5) from the spectral theorem. The maximum stretch can also build the SVD on its own.

    1. Let σ1=max⁡∥x∥=1∥Ax∥\sigma_1=\max_{\|\mathbf{x}\|=1}\|\mathbf{A}\mathbf{x}\|, assume σ1>0\sigma_1>0, and build an SVD without the spectral theorem. (i) Show that the maximum is attained at some unit v1\mathbf{v}_1, and set u1=Av1/σ1\mathbf{u}_1=\mathbf{A}\mathbf{v}_1/\sigma_1. (ii) For a unit w⊥v1\mathbf{w}\perp\mathbf{v}_1, the function t↦∥A(v1+tw)∥2/(1+t2)t\mapsto\|\mathbf{A}(\mathbf{v}_1+t\mathbf{w})\|^2/(1+t^2) has a maximum at t=0t=0, so its derivative there vanishes. Deduce u1⊤Aw=0\mathbf{u}_1^\top\mathbf{A}\mathbf{w}=0: A\mathbf{A} maps v1⊥\mathbf{v}_1^\perp into u1⊥\mathbf{u}_1^\perp. (iii) Recurse on the restriction of A\mathbf{A} to v1⊥\mathbf{v}_1^\perp. Where did compactness of the unit sphere enter?
    2. Show that ∥A∥2≤∥A∥F≤r ∥A∥2\|\mathbf{A}\|_2 \le \|\mathbf{A}\|_F \le \sqrt{r}\,\|\mathbf{A}\|_2 with r=rank⁡Ar = \operatorname{rank}\mathbf{A}. Which matrices attain equality on each side?
    3. The ratio ∥A∥F2/∥A∥22\|\mathbf{A}\|_F^2/\|\mathbf{A}\|_2^2 is called the stable rank of A\mathbf{A}; by (b) it lies between 1 and rank⁡A\operatorname{rank}\mathbf{A}. Compute it in closed form for the decaying spectrum σi=e−i/12\sigma_i=e^{-i/12}, i=0,…,255i=0,\ldots,255 (a geometric series), and show that rank 18 is needed to hold 95% of the energy of this spectrum. Then estimate the stable rank of the 400×500400\times500 Gaussian matrix of Section 21.5.4.3 from ∥G∥F2≈mn\|\mathbf{G}\|_F^2\approx mn and σ1≈m+n\sigma_1\approx\sqrt m+\sqrt n, and compare it with the rank of about 270 that holds 95% of its energy. Why can the stable rank be far below the rank?
  2. Weyl perturbation bound. An update Δ\boldsymbol{\Delta}, for instance a rank-kk LoRA update BA\mathbf{B}\mathbf{A} (the paper's letters), changes the singular values of a weight matrix W\mathbf{W}. The Weyl inequality (21.5.11), proved in Section 21.5.2.1, limits how far they move.

    1. Set j=1j = 1 in (21.5.11) and apply the inequality in both directions to derive ∣σi(W+Δ)−σi(W)∣≤σ1(Δ)|\sigma_i(\mathbf{W}+\boldsymbol{\Delta})-\sigma_i(\mathbf{W})|\le\sigma_1(\boldsymbol{\Delta}) for every ii.
    2. Take W=diag⁡(1,2)\mathbf{W} = \operatorname{diag}(1, 2) and Δ=0.1 11⊤\boldsymbol{\Delta} = 0.1\,\mathbf{1}\mathbf{1}^\top. Compute the singular values of W+Δ\mathbf{W}+\boldsymbol{\Delta} and compare each change with σ1(Δ)\sigma_1(\boldsymbol{\Delta}).
    3. Now let rank⁡Δ≤k\operatorname{rank}\boldsymbol{\Delta}\le k. The Frobenius proof in Section 21.5.2.1 applies (21.5.11) with j=k+1j = k+1 to a matrix of rank at most kk. Apply the same step to Δ\boldsymbol{\Delta} to obtain the interlacing inequalities σi+k(W)≤σi(W+Δ)\sigma_{i+k}(\mathbf{W})\le\sigma_i(\mathbf{W}+\boldsymbol{\Delta}) and σi+k(W+Δ)≤σi(W)\sigma_{i+k}(\mathbf{W}+\boldsymbol{\Delta})\le\sigma_i(\mathbf{W}). Use them to show that the ranks of W+Δ\mathbf{W}+\boldsymbol{\Delta} and W\mathbf{W} differ by at most kk, and that at most kk singular values of W+Δ\mathbf{W}+\boldsymbol{\Delta} exceed σ1(W)\sigma_1(\mathbf{W}), however large σ1(Δ)\sigma_1(\boldsymbol{\Delta}) is. Why does the bound of (a) not give these conclusions?
  3. [code] Centering in PCA, and Fashion-MNIST. Let the rows of X∈Rn×d\mathbf{X}\in\mathbb{R}^{n\times d} be data points with mean row xˉ\bar{\mathbf{x}} and covariance C\mathbf{C} as in the principal component analysis of Section 21.5.2.2.

    1. Show that 1nX⊤X=C+xˉxˉ⊤\tfrac1n\mathbf{X}^\top\mathbf{X} = \mathbf{C}+\bar{\mathbf{x}}\bar{\mathbf{x}}^\top.
    2. Generate a cloud like the one of Section 21.5.2.2 (300 points with standard deviations 3 and 0.8 along axes rotated by π/5\pi/5) and shift every point by c (1,−1)/2c\,(1,-1)/\sqrt2 for c∈{0,1,3,10,30}c\in\{0, 1, 3, 10, 30\}. For each cc, compute the top right singular vector of the uncentered data, its angle to the principal axis (cos⁡π5,sin⁡π5)(\cos\frac\pi5, \sin\frac\pi5), and the ratio σ12/∑iσi2\sigma_1^2/\sum_i\sigma_i^2.
    3. Use (a) to predict, from the eigenvalues of C\mathbf{C}, the offset at which the top singular vector turns from the principal axis toward the mean.
    4. Use (a) again to approximate the ratio σ12/∑iσi2\sigma_1^2/\sum_i\sigma_i^2 for large cc, and find its limit as c→∞c\to\infty. At c=10c = 10 the ratio is close to the centered explained-variance ratio. Does this agreement reflect the data or the chosen offset?
    5. Load the Fashion-MNIST test images of t-shirts and trousers through d2l.FashionMNIST, as in Section 21.1, flatten them to vectors of length 784, center them, and compute the top two right singular vectors. Plot the two classes in the plane of the first two principal components. What fraction of the variance do these two directions hold? Compute the angle between v1\mathbf{v}_1 and the difference of the class means xˉtrouser−xˉt-shirt\bar{\mathbf{x}}_{\text{trouser}}-\bar{\mathbf{x}}_{\text{t-shirt}}, and explain why the two directions are close but not equal. Finally, reconstruct one t-shirt from its first 5, 20 and 50 components and report the relative error of each.
  4. [code] Ridgeless limit and gradient descent. An overparameterized linear model has more parameters than equations, so least squares has infinitely many minimizers. Part (a) holds for every shape and rank; (b) and (c) use A∈Rm×n\mathbf{A}\in\mathbb{R}^{m\times n} with m<nm \lt n.

    1. Use the filter form (21.5.14) to show that (A⊤A+λI)−1A⊤→A+(\mathbf{A}^\top\mathbf{A}+\lambda\mathbf{I})^{-1}\mathbf{A}^\top\to\mathbf{A}^{+} as λ→0+\lambda\to0^{+}, for a matrix A\mathbf{A} of any shape and rank. Why does (A⊤A)−1A⊤(\mathbf{A}^\top\mathbf{A})^{-1}\mathbf{A}^\top not exist when m<nm\lt n?
    2. Gradient descent on 12∥Ax−b∥2\tfrac12\|\mathbf{A}\mathbf{x}-\mathbf{b}\|^2 with step size 0<η<2/σ120 \lt \eta \lt 2/\sigma_1^2 updates xt+1=xt−η A⊤(Axt−b)\mathbf{x}_{t+1} = \mathbf{x}_t-\eta\,\mathbf{A}^\top(\mathbf{A}\mathbf{x}_t-\mathbf{b}). Show that xt−x0\mathbf{x}_t-\mathbf{x}_0 stays in the row space of A\mathbf{A} and that xt\mathbf{x}_t converges to A+b+(I−A+A)x0\mathbf{A}^{+}\mathbf{b}+(\mathbf{I}-\mathbf{A}^{+}\mathbf{A})\mathbf{x}_0. Which solution does the initialization x0=0\mathbf{x}_0 = \mathbf{0} select?
    3. Check (a) and (b) for a 20×5020\times50 Gaussian A\mathbf{A} and a Gaussian b\mathbf{b}: run gradient descent from x0=0\mathbf{x}_0 = \mathbf{0} and from a random x0\mathbf{x}_0, and compare both limits and their norms with A+b\mathbf{A}^{+}\mathbf{b}.
  5. [code] Newton--Schulz basin. The Newton--Schulz iteration X←12(3X−XX⊤X)\mathbf{X}\leftarrow\tfrac12(3\mathbf{X}-\mathbf{X}\mathbf{X}^\top\mathbf{X}) of Section 21.5.4.2 starts from X=M/∥M∥F\mathbf{X} = \mathbf{M}/\|\mathbf{M}\|_F.

    1. Let X=UΣV⊤\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top be a thin SVD. Show directly, without (21.5.18), that one step produces U p(Σ) V⊤\mathbf{U}\,p(\boldsymbol{\Sigma})\,\mathbf{V}^\top with p(σ)=12(3σ−σ3)p(\sigma) = \tfrac12(3\sigma-\sigma^3) applied to every diagonal entry.
    2. Show that (0,3)(0,\sqrt3) is the immediate basin of 1: pp maps it into (0,1](0, 1], and the iterates p(p(⋯p(σ0)))p(p(\cdots p(\sigma_0))) converge to 1 for every σ0∈(0,3)\sigma_0\in(0,\sqrt3). Show that some starting values beyond 3\sqrt3 also reach 1 (try 2.152.15) and others do not (try 2). Expand p(1−e)p(1-e) in powers of ee. How fast does the distance to 1 shrink once it is small?
    3. For a 6×46\times4 Gaussian M\mathbf{M}, count the steps until ∥X−UV⊤∥F<10−6\|\mathbf{X}-\mathbf{U}\mathbf{V}^\top\|_F \lt 10^{-6} when the iteration starts from M/c\mathbf{M}/c with c=∥M∥Fc = \|\mathbf{M}\|_F and with c=σ1(M)c = \sigma_1(\mathbf{M}). Compare both counts with log⁡3/2(1/smin⁡)+4\log_{3/2}(1/s_{\min})+4, where smin⁡s_{\min} is the smallest singular value after scaling. Why does Muon divide by ∥M∥F\|\mathbf{M}\|_F although σ1(M)\sigma_1(\mathbf{M}) saves a step?
    4. Start the iteration from M/c\mathbf{M}/c with c=σ1(M)/2c = \sigma_1(\mathbf{M})/2 and with c=σ1(M)/2.5c = \sigma_1(\mathbf{M})/2.5. What does it converge to in each case? Explain both outcomes with the polynomial pp of (b).
  6. [code] Polar factor and Procrustes. ● The polar decomposition (21.5.17) writes a square matrix as A=QP\mathbf{A} = \mathbf{Q}\mathbf{P} with Q\mathbf{Q} orthogonal and P\mathbf{P} symmetric positive semidefinite.

    1. Show that P=(A⊤A)1/2\mathbf{P} = (\mathbf{A}^\top\mathbf{A})^{1/2} is determined by A\mathbf{A}, and that Q\mathbf{Q} is determined by A\mathbf{A} when A\mathbf{A} is invertible. Give two different polar decompositions of diag⁡(1,0)\operatorname{diag}(1, 0).
    2. Show that Q=UV⊤\mathbf{Q} = \mathbf{U}\mathbf{V}^\top is an orthogonal matrix closest to A\mathbf{A} in the Frobenius norm. Reduce the problem to maximizing tr⁡(R⊤A)\operatorname{tr}(\mathbf{R}^\top\mathbf{A}) over orthogonal R\mathbf{R}.
    3. Two embedding spaces that differ by a rotation can be aligned from paired points X,Y∈Rd×N\mathbf{X},\mathbf{Y}\in\mathbb{R}^{d\times N} by minimizing ∥RX−Y∥F\|\mathbf{R}\mathbf{X}-\mathbf{Y}\|_F over orthogonal R\mathbf{R}. Use (b) to show that the minimizer is the polar factor of YX⊤\mathbf{Y}\mathbf{X}^\top. Test it with d=50d = 50, N=1000N = 1000, a random orthogonal R\mathbf{R} (the Q\mathbf{Q} factor of a QR decomposition of a Gaussian matrix), Gaussian X\mathbf{X}, and Y=RX+E\mathbf{Y} = \mathbf{R}\mathbf{X}+\mathbf{E}, where E\mathbf{E} has i.i.d. N(0,s2)\mathcal{N}(0, s^2) entries for s∈{0,0.1,1,3}s\in\{0, 0.1, 1, 3\}. Compare ∥R^−R∥F/d\|\hat{\mathbf{R}}-\mathbf{R}\|_F/\sqrt d for this estimate and for the unconstrained least-squares estimate YX+\mathbf{Y}\mathbf{X}^{+}.
  7. [code] Randomized range finder. ● The randomized SVD of Section 21.5.4.3 multiplies A\mathbf{A} by a Gaussian Ω∈Rn×(k+p)\boldsymbol\Omega\in\mathbb{R}^{n\times(k+p)}, orthonormalizes Y=AΩ\mathbf{Y} = \mathbf{A}\boldsymbol\Omega into Q\mathbf{Q}, and truncates the SVD of Q⊤A\mathbf{Q}^\top\mathbf{A} to rank kk.

    1. Implement it. Build A∈R1000×500\mathbf{A}\in\mathbb{R}^{1000\times500} as Udiag⁡(σ1,…,σ500)V⊤\mathbf{U}\operatorname{diag}(\sigma_1,\ldots,\sigma_{500})\mathbf{V}^\top with random orthonormal U\mathbf{U} and V\mathbf{V}, once with the fast decay σi=e−i/5\sigma_i = e^{-i/5} and once with the slow decay σi=1/i\sigma_i = 1/i. For k=20k = 20 and p∈{0,5,10}p\in\{0, 5, 10\}, divide the spectral-norm error of the rank-kk result by σk+1\sigma_{k+1}, the minimum of (21.5.10), and average over 10 draws of Ω\boldsymbol\Omega. Why does oversampling alone suffice for one spectrum but not for the other?
    2. Replace Y\mathbf{Y} by (AA⊤)qAΩ(\mathbf{A}\mathbf{A}^\top)^q\mathbf{A}\boldsymbol\Omega for q∈{1,2}q\in\{1, 2\}. How do the ratios change for each spectrum? Explain the effect of qq with the singular values of (AA⊤)qA(\mathbf{A}\mathbf{A}^\top)^q\mathbf{A}. How many products with A\mathbf{A} or A⊤\mathbf{A}^\top does each variant cost?
  8. [code] Optimal hard threshold. ●● The threshold 43n σnoise\tfrac{4}{\sqrt3}\sqrt n\,\sigma_{\text{noise}} of Gavish and Donoho (2014) follows from the behavior of a single signal component. Let A=θ uv⊤+N\mathbf{A} = \theta\,\mathbf{u}\mathbf{v}^\top+\mathbf{N} be n×nn\times n, with unit vectors u,v\mathbf{u},\mathbf{v}, θ>0\theta > 0, and N\mathbf{N} with i.i.d. Gaussian entries N(0,σnoise2)\mathcal{N}(0, \sigma_{\text{noise}}^2). Write x=θ/(n σnoise)x = \theta/(\sqrt n\,\sigma_{\text{noise}}) and let (σ1,u^,v^)(\sigma_1, \hat{\mathbf{u}}, \hat{\mathbf{v}}) be the top singular triple of A\mathbf{A}, with the sign of the pair chosen so that u⊤u^≥0\mathbf{u}^\top\hat{\mathbf{u}}\ge0. As n→∞n\to\infty, Benaych-Georges and Nadakuditi (2012) show that σ1\sigma_1 tends to the bulk edge 2n σnoise2\sqrt n\,\sigma_{\text{noise}} and the singular vectors become orthogonal to u\mathbf{u} and v\mathbf{v} when x≤1x\le1, and that for x>1x > 1

σ1n σnoise→x+1x,(u⊤u^)2→1−1x2,(v⊤v^)2→1−1x2.\frac{\sigma_1}{\sqrt n\,\sigma_{\text{noise}}}\to x+\frac1x,\qquad (\mathbf{u}^\top\hat{\mathbf{u}})^2\to1-\frac1{x^2},\qquad (\mathbf{v}^\top\hat{\mathbf{v}})^2\to1-\frac1{x^2}.

The transition at x=1x = 1 is the singular-value counterpart of the eigenvalue transition at β=c\beta = \sqrt c in exercise 5 of Section 21.3.

  1. Two estimates of the signal θ uv⊤\theta\,\mathbf{u}\mathbf{v}^\top are the rank-one truncation σ1u^v^⊤\sigma_1\hat{\mathbf{u}}\hat{\mathbf{v}}^\top and the zero matrix. Express the squared Frobenius error of each in terms of θ\theta, σ1\sigma_1, u⊤u^\mathbf{u}^\top\hat{\mathbf{u}} and v⊤v^\mathbf{v}^\top\hat{\mathbf{v}}.
  2. Use the limits to show that the truncation has the smaller asymptotic error exactly when x>3x > \sqrt3, and that the singular value at x=3x = \sqrt3 is 43n σnoise\tfrac{4}{\sqrt3}\sqrt n\,\sigma_{\text{noise}}. Which signal strengths produce a singular value above the noise edge that should nevertheless be discarded?
  3. Check (a) and (b) for n=500n = 500 and σnoise=1/n\sigma_{\text{noise}} = 1/\sqrt n, with x∈{0.5,1.2,1.5,3,2,3}x\in\{0.5, 1.2, 1.5, \sqrt3, 2, 3\} and 10 draws each: compare σ1\sigma_1, the squared cosines, and both errors with their limits.

Discussions