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 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, 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 . 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 (the square root of the sum of squared entries) and the spectral norm (the largest factor by which can stretch a unit vector). In this section, both become simple functions of the singular values .
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, denotes the shear matrix and 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 maps the unit circle to an ellipse whose semi-axes lie along its eigenvectors and , 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 matrix can be written as
where and are orthogonal (, ) and is zero except for the non-negative entries on its main diagonal. The columns of are the right singular vectors, the columns of are the left singular vectors, and the diagonal entries 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 and reading off column makes the action explicit one direction at a time:
Each input direction is sent to the corresponding output direction , stretched by ; when , the extra input directions are collapsed to zero. Reading (21.5.1) from right to left, applying to a vector unfolds in three stages:
- rotates the input so that each right singular vector aligns with the coordinate axis ;
- stretches axis by and, when , either appends zero coordinates or drops excess ones to match the output dimension;
- rotates the stretched axes so that axis points along .
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 . Its singular values are and ; the first right singular vector points at above the -axis, while its image direction points at . Because the input and output frames differ, . We will derive these exact numbers in Section 21.5.1.2.
The shear acting on the unit circle, read left to right: rotates by , stretches by along and by along , and rotates by . The input frame and the output frame differ.
In dimensions, the same three stages deform the unit sphere into an ellipsoid whose semi-axes are the vectors . If only of the input directions have positive singular values, the remaining directions collapse to zero, and the image is a flat -dimensional ellipsoid lying inside the span of .
Compact and thin forms. Let be the number of positive singular values (in Section 21.5.1.5 we will verify that is precisely the rank of ). Every row and column of beyond the first is zero, so the singular vectors paired with them contribute nothing to the product. Dropping those zero entries yields the compact SVD, , where and hold the first singular vectors and . Between the full and compact forms sits the thin SVD, the default reduced form that numerical libraries return on request, which keeps columns in and and still records any zero singular values when . For a matrix of rank 2, the full factors have shapes , , and , whereas the thin factors have shapes , , and (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 matrix of rank 3, for which all three differ.
Shapes of the SVD factors of an matrix of rank , drawn to scale for , , and : (a) full, (b) thin, (c) compact, and (d) the dyadic sum of rank-one terms. Filled squares on the diagonal of are positive singular values, and the dashed square is a zero singular value. The dashed parts of and multiply only zeros of , so each smaller form drops some of them without changing the product.
The dyadic sum. Multiplying out the compact SVD column by row expresses as a weighted sum of rank-one matrices, often called dyads:
Each term 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, , splitting the matrix into one piece of weight and a second of weight . 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 , , and 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 , the matrix of dot products between the columns of . This matrix is symmetric, and it is positive semidefinite (Section 21.3.2.2) because for every vector .
Proof of (21.5.1) (existence). By the spectral theorem, has an orthonormal basis of eigenvectors with eigenvalues . Every eigenvalue is non-negative because . Define
Thus the singular values are the square roots of the eigenvalues of the Gram matrix, and counts the positive ones. For each , set . The crucial check is that these pushed-through vectors are automatically orthonormal, which follows from being an eigenvector of and the being orthonormal:
Orthonormality of the input frame therefore passes directly through to the output frame. Next we check the dimensions. Since the orthonormal vectors lie in , we have , and since there are eigenvalues in total, ; hence , and for every . Complete to an orthonormal basis of (for example, by applying Gram--Schmidt to any completion). For , , so . Comparing with column by column, column of is for (which vanishes when ) and for (where has no diagonal entry). In every case, column of matches column of . Hence , and right-multiplying by yields .
This proof is also a recipe: diagonalize the symmetric matrix , take square roots to get the singular values, and map the eigenvectors through to obtain the left singular vectors.
Let us work through the shear by hand to see every step in action. For , the Gram matrix is . It has trace 3 and determinant 1, so its characteristic polynomial is , giving eigenvalues . Introducing the golden ratio , which satisfies , these eigenvalues simplify neatly to and . The singular values are therefore and , and their product is .
Now we find the singular vectors. For the first right singular vector , the first row of reads ; using gives , so . Applying yields , so . Both vectors have length , giving at angle and at . The second pair follows by orthogonality, and , and indeed since . Both and are rotations , so the shear factors as
Geometrically, the shear rotates the plane by , stretches it by along the -axis and along the -axis, and rotates it back by only . The two angles sum to because is simply with its coordinates swapped, reflecting the symmetry for the swap matrix .
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
lies in the first quadrant and 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 and together with the two rotations of (21.5.4).
The same construction works unchanged for a rectangular matrix. Consider the
matrix with rows , , and . Its Gram matrix is
, with
eigenvalues . The next cell carries out the proof's three steps
directly (eigenvectors of , square roots, and
) 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 and . As the proof promised, the pushed-through vectors come out orthonormal, and both and 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 , which determines completely. The singular vectors, by contrast, have three kinds of freedom:
- For a simple (unrepeated) , the only choice is a joint sign flip . Both vectors must flip together, because flipping only one side would violate .
- For a repeated singular value with index set , the columns may be rotated by any orthogonal matrix of matching size, becoming , provided is rotated by the same to preserve .
- For , the null-space vectors and left-null-space vectors 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 , the top singular value has a direct geometric meaning: it is the largest factor by which can stretch any unit vector,
This follows immediately from the Rayleigh proposition of Section 21.3.2.3, which states that over unit vectors , the quadratic form of a symmetric matrix is maximized by its top eigenvector with value equal to its top eigenvalue. Taking , we see that is maximized at with value . Thus is precisely the spectral norm from Section 1.3: for the shear, no unit vector is stretched by more than , and 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: . 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 and gives
Both expressions are symmetric eigendecompositions: the right singular vectors are the eigenvectors of , the left singular vectors are the eigenvectors of , and the squares are the nonzero eigenvalues that the two Gram matrices share. When is symmetric positive semidefinite, its SVD and eigendecomposition coincide, with .
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 , whose eigenvalues are , both of modulus (Section 21.3). Its Gram matrix has trace 15 and determinant 25, yielding and therefore , far from . Still, one clean identity links the two lists for every square matrix:
The first equality holds because orthogonal matrices have determinant , and the second because the determinant is the product of all eigenvalues. For a matrix with a conjugate pair of eigenvalues of common modulus , this forces ; here indeed . The identity also recovers the volume interpretation of the determinant from Section 21.2: rotations preserve area, so the diagonal stretch accounts for the entire change of area, and our running matrix maps the unit square to a parallelogram of area .
Computing the SVD in practice. Although our existence proof constructs the SVD from , numerical libraries never form that product. Forming 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 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 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 and are invertible, multiplying by them leaves all dimensions unchanged, so , which is simply the count of nonzero diagonal entries:
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 , such as floating-point rounding error, shifts no singular value by more than (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 gives explicit orthonormal bases for all four fundamental subspaces of directly from the dyadic sum (21.5.3):
- The column space (range) of is , because every output is a linear combination of these vectors, and each one is attained via .
- The null space of is , because by the same formula holds if and only if for every (the are independent and the are positive), meaning is orthogonal to .
- The row space (column space of ) is and the left null space (null space of ) is , by applying the same two arguments to , which simply swaps the roles of the and .
This gives a remarkably clean picture of any linear map. The input space splits into two orthogonal pieces: the -dimensional row space and the -dimensional null space. Likewise, the output space splits into the -dimensional column space and the -dimensional left null space. On the row space, maps each to , 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 from Section 21.2. Its Gram matrix has eigenvalues 25 and 0, so , , and . The four subspaces are the lines spanned by
Here the column space is the line along , and the left null space is the perpendicular line along . In the input plane, the null space is the line along , perpendicular to the row 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.
The four fundamental subspaces. maps the row space one-to-one onto the column space by , and maps the null space to zero. The pseudoinverse (dashed) runs the map backwards, , 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
instead. In practice, rank is therefore decided with a threshold. NumPy's
np.linalg.matrix_rank counts singular values above
, 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 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: 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 from heaviest to lightest, so the natural candidate is to keep the first terms. This gives the truncated SVD,
The matrix has rank at most , and storing it requires only singular values, columns of length , and columns of length , for a total of numbers instead of . For our photograph with , that is 18,020 numbers out of 200,000. Two questions immediately arise: how large is the approximation error, and could some cleverer rank- 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, , sums the squared lengths of the columns of , which are the diagonal entries of ; thus . Substituting the SVD and using the cyclic property of the trace (Section 21.2) to move across, we find
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, . Meanwhile, the spectral norm is simply the largest singular value, , 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 for . For every , the smallest spectral-norm error attainable by a matrix of rank at most is
and the smallest squared Frobenius error is . Both minima are attained at the truncated SVD .
In short, no rank- matrix can beat the truncated SVD in either norm: the best rank- 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 and . Any matrix of rank one collapses an entire plane of inputs to zero, while the top two right singular vectors of span another plane. In , two planes through the origin must intersect in at least a line. Along that line, outputs zero while stretches every vector by at least , so must stretch some unit vector by at least (Figure 21.5.4). The proof below simply carries this dimension count into dimensions.
The dimension count behind Eckart--Young for , : the plane and the plane spanned by the top two right singular vectors must meet in a line. On that line vanishes while still stretches by at least .
Proof (spectral norm). First, the truncation achieves . The residual is already in compact SVD form with largest singular value , so by (21.5.5). Likewise, (21.5.9) gives .
Second, no matrix of rank at most can do better. If the error is zero and there is nothing to prove, so assume and let . By rank--nullity (Section 21.2), the null space has dimension at least . Meanwhile, the span of the top right singular vectors has dimension . Because these two dimensions add to more than , the subspaces must share a nonzero vector:
where the equality is the dimension formula for two subspaces and the inequality uses . (To verify the dimension formula, extend a basis of separately to a basis of and a basis of ; the combined vectors are linearly independent, span , and number .) Pick a unit vector and expand it as with . Then , and using together with the orthonormality of the ,
Hence .
The geometry is worth repeating in one sentence: any rank- competitor must annihilate at least one direction inside the span of the top right singular vectors, and stretches every direction in that span by at least . For the shear with , the truncation misses by 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 of the same shape and indices with ,
Proof. Let and be the truncated SVDs (21.5.8) (with ). Their sum has rank at most , so applying the spectral-norm lower bound to with gives . By the triangle inequality and the achievability half of Eckart--Young, the right-hand side is at most .
In words, adding to can lift the -th singular value above the -th singular value of by at most . Setting and applying the inequality in both directions shows that perturbing a matrix by moves no singular value by more than (Horn and Johnson, 2012); Exercise 2 works out the details.
Proof (Frobenius norm). Apply Weyl's lemma with , , and . Because , we have , which yields for every . Squaring and summing over , then applying (21.5.9),
which the truncation attains.
Uniqueness of the minimizer. One subtle difference separates the two norms. In the spectral norm, the best rank- approximation is never unique when and : for and , every matrix with gives . In the Frobenius norm, by contrast, is the unique minimizer whenever or (in which case ) (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 cat photograph. Eckart--Young
fixes the spectral error of every truncation at , but it does not
tell us how quickly the singular values of a real image decay, nor how much
worse a natural rank- 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 of Vt is , '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 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, .
Eckart--Young on a 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 with their relative Frobenius error and the fraction of the original numbers they store.
The energy ratio. The Frobenius error formula gives a practical rule for choosing . The fraction of total squared "energy" retained by the rank- truncation is
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 , while retaining 99% brings the error down to 10%. One must read this ratio with care, however. On the photograph, 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 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 matrix () consists of a low-rank signal plus random noise, , where the entries of are independent with mean zero and standard deviation . By the Marchenko--Pastur law of Section 21.3.2.4 applied to , the singular values of a large noise matrix concentrate inside the interval . 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 , sitting slightly above the noise edge (Gavish and Donoho, 2014). Exercise 8 derives the constant .
21.5.2.2 Principal Component Analysis#
Suppose we are given a dataset whose examples are the rows of , with data points and 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 -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 -dimensional subspace with orthogonal projector , and ask which offset minimizes the total squared reconstruction error . This objective is a convex quadratic in , and its gradient vanishes at the sample mean , regardless of . The best affine subspace therefore always passes through the mean, so we begin by centering the data: . Its empirical covariance is the symmetric positive semidefinite matrix . (Using the unbiased factor 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 , the projected variance is maximized by the top eigenvector of , which is the top right singular vector of , with maximal variance .
Proof. Projecting a centered point onto yields the scalar coordinate , whose empirical variance is . By the Rayleigh proposition of Section 21.3.2.3, this quadratic form is maximized by the top eigenvector of , with value . By (21.5.6), , so the eigenvectors of are the right singular vectors of and its eigenvalues are .
Among unit vectors orthogonal to , the variance is maximized by , and continuing inductively gives the top principal directions , with component explaining variance . Now check the reconstruction error. Projecting every centered point onto corresponds to right-multiplying by . Since selects the first columns of the identity,
Projecting onto the top principal directions is therefore identical to taking the rank- truncated SVD of the centered data. By Eckart--Young in the Frobenius norm, no other projection, and indeed no other rank- matrix at all, can reconstruct the centered points with smaller squared error. The discarded variance equals the mean squared reconstruction error, and the explained-variance ratio is simply the energy ratio (21.5.12) of .
Figure 21.5.6 shows a cloud of 300 points with standard deviations 3 and 0.8 along axes rotated by , together with its two principal axes. In the population, the first direction holds of the variance and aligns with the long axis. The cell below checks how accurately a finite sample of 300 points recovers these values.
A cloud of 300 points centered at with standard deviations 3 and 0.8 along axes rotated by , and its principal axes drawn from the mean, each two standard deviations 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 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 instead of ),
and whenever multiple 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, . Its solutions form an entire line, and the residual is zero everywhere on it. Which point on the line should we pick? Here , which has one nonzero singular value , right singular vector , and . The equation fixes the coordinate of along to , while the coordinate along the null-space direction does not affect the residual at all. Setting that free coordinate to zero yields , the foot of the perpendicular from the origin to the line, with norm ; every other solution has strictly larger squared norm (Figure 21.5.7).
Least squares with one equation and two unknowns. Every point of the line solves ; 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 is
where has shape , the transpose shape of . Geometrically, reverses every stretch that can be reversed and sends the left null space to zero. For the shear, ; for , , so .
Proposition (minimum-norm least squares). Among all minimizers of , the unique one of smallest norm is .
Proof. Change variables to the singular bases by setting and . Because is orthogonal, it preserves Euclidean norms, so
Rotating into the singular bases decouples the system into independent scalar equations. The first sum is minimized term by term by setting for . The second sum is a fixed constant, the component of outside the column space, which no choice of can reduce. Meanwhile, the coordinates for do not enter the residual at all, and since , setting them to zero gives the unique minimizer of smallest norm. That choice is , which translates back to .
In the singular bases, minimizing the residual and minimizing the norm govern completely disjoint coordinates ( versus ), so both goals are achieved simultaneously. When is square and invertible, every is positive and . Yet the same formula also exposes the main danger of least squares: dividing by a tiny multiplies any noise in along by .
Two standard remedies tame these unstable directions. Ridge regression minimizes for , giving . The truncated pseudoinverse instead keeps only the first singular terms of . Substituting the SVD and noting that , both solutions take a transparent filter form:
Both start from the unregularized pseudoinverse terms . Ridge regression scales component by the smooth filter factor , which stays near 1 when and shrinks toward 0 when ; truncation applies a sharp step function of 1 or 0. For , singular values , , and receive filter factors , , and . 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 . For any , its solutions are the least-squares minimizers (since states that the residual is orthogonal to the column space), and the solution is unique whenever has full column rank. Numerically, however, forming 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 to the four observations at ; the second is our single equation .
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 ,
with residual , and for the single equation the
pseudoinverse returns the foot of the perpendicular, .
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 system reveals how dramatic the amplification can be. Consider with and . Its exact solution is . Now nudge by just , to : the solution jumps all the way to . A perturbation of roughly three parts in in the data has completely changed the answer. The singular values of , roughly and , tell us why.
The condition number of a matrix of rank is the ratio of its largest to its smallest nonzero singular value,
Geometrically, measures how unevenly stretches different directions: for it is about , whereas for the shear it is only . When is symmetric positive definite, its singular values coincide with its eigenvalues, so , recovering the condition number for quadratic bowls in Section 21.3.2.3. The next proposition shows that is the exact worst-case amplification factor for relative errors in a linear solve.
Proposition (error amplification). Let be square and invertible, with , and let a perturbation shift the solution to . Then
and for every there exist and that attain equality.
Proof. From we have . The largest singular value of is , so (21.5.5) gives . Likewise, gives . Combining the two inequalities yields
Equality holds in both bounds simultaneously when (making as short as possible for a unit right-hand side) and (making as large as possible for a perturbation of size ).
The relative error in the data is therefore amplified by at most . With , a relative error of in can grow into in , costing four digits of accuracy. In our example, the relative change in is , so the bound allows a relative change of in , and the realized change is . The perturbation places of its length along the most amplified direction , while points almost directly along .
At the ideal extreme, an orthogonal matrix has all singular values equal to 1, so : rotations and reflections never amplify error. That is why computing with the orthogonal factors and 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,
because (21.5.6) is the SVD of , with singular values (for any matrix of any rank). For the shear, jumps from to . The cell below verifies our example and compares with 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 to , with . Even for the modest line-fitting matrix, , so forming the normal equations would already inflate the condition number to .
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 , the Hessian is , whose level sets are ellipsoids with semi-axes proportional to along the . The contours therefore have axis ratio , while the Hessian itself has condition number . 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 that we derive in Section 23.1.
Gradient descent on a well-conditioned quadratic bowl (, near-circular contours, an almost straight path) versus an ill-conditioned one (, a zig-zag trajectory across the narrow valley). The panel titles give the condition number of the Hessian; the contours are elongated by its square root, a factor of about 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 and learning only a rank- correction , where and (here follows the paper's notation for the down-projection, not the generic matrix of earlier subsections). The adapter uses trainable parameters instead of . For a layer with , that drops the parameter count from to , 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.
The LoRA architecture for one layer. The pretrained (all M parameters for ) stays frozen; a parallel bypass first compresses the input to dimensions with and then expands back with , so only K parameters (about ) are trained. The two branches add: . After training, can be merged into , 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 , then Eckart--Young guarantees that no rank- adapter can approximate that specific update closer than in the spectral norm or 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- 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- adapter can perturb the singular values of .
21.5.4.2 Orthogonalized Updates#
The Muon optimizer (Jordan et al., 2024) updates a weight matrix not along its raw momentum matrix , but along the polar factor of , the matrix that keeps the singular vectors of 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 , inserting into the SVD splits it into an orthogonal factor times a symmetric stretch:
Here is orthogonal (as a product of orthogonal matrices) and is symmetric positive semidefinite with eigenvalues . 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 . Note that need not be a pure rotation: when is invertible, , so includes a reflection whenever . For the shear , (21.5.4) yields (since ) and . Checking the product confirms and .
For a rectangular matrix with thin SVD , the polar factor is still : it shares the singular vectors of and has all singular values equal to 1, so its columns (when ) or its rows (when ) are orthonormal. When is rank-deficient (), the polar factor is not unique, and the natural canonical choice is from the compact SVD. Exercise 6 shows that for a square matrix, is also the closest orthogonal matrix to 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 be a thin SVD and let be an odd polynomial. Then
Proof. Since , taking powers gives , and left-multiplying by gives . Summing over completes the proof.
Any odd matrix polynomial therefore leaves and untouched while applying the scalar function independently to each singular value. To reach the polar factor , we simply need an odd polynomial whose repeated application drives every positive singular value to 1.
Newton--Schulz. The classic Newton--Schulz iteration applies the cubic polynomial to every singular value. Its fixed points are and . On , pushes every value upward without ever overshooting 1, since and reaches its maximum . In fact, maps the entire interval into , 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 guarantees that every singular value starts inside , because . Any zero singular value stays zero (since ), so a rank-deficient converges cleanly to .
How many iterations does this take? Near 0, , so a small singular value grows by a factor of per step and needs roughly steps to reach order one. Near 1, expanding gives : the error roughly squares at every step, shrinking from order one to in about four additional steps. Gluing the two phases together predicts roughly steps, governed by the smallest normalized singular value . Let us test this rough estimate on a random 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 of the exact polar factor from a full SVD. Because varies across random draws, so does the step count; a nearly rank-deficient 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 satisfies , with equality whenever aligns with . The smallest constant bounding how much a map can amplify input differences is its Lipschitz constant, so here the Lipschitz constant is simply . Dividing by 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, is estimated via power iteration on (Section 21.4.1.2). In practice, one alternates and , normalizing at each half-step; together they perform one multiplication by , with as the estimate of . Each round pulls closer to , shrinking the error by roughly . 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 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 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- approximation using only a handful of matrix--vector products with . Its core ingredient is a range finder: multiply by a random Gaussian matrix with slightly more than columns, orthonormalize the columns of into , and compute the SVD of the much smaller matrix . Whenever the singular values decay, the top singular directions dominate every random linear combination of the columns of , so 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 operations (roughly for a single 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 , regardless of its shape, admits an orthonormal input basis and an orthonormal output basis between which it acts as a simple list of non-negative stretches, with . The factorization follows from applying the spectral theorem to the Gram matrix , with .
From that single ordered list of singular values, five core quantities fall out at once: the rank (the number of positive ), the spectral and Frobenius norms ( and ), the optimal rank- approximation given by the truncated SVD (Eckart--Young, which becomes principal component analysis on centered data), the Moore--Penrose pseudoinverse that returns the minimum-norm least-squares solution, and the condition number 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#
-
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.
- Let , assume , and build an SVD without the spectral theorem. (i) Show that the maximum is attained at some unit , and set . (ii) For a unit , the function has a maximum at , so its derivative there vanishes. Deduce : maps into . (iii) Recurse on the restriction of to . Where did compactness of the unit sphere enter?
- Show that with . Which matrices attain equality on each side?
- The ratio is called the stable rank of ; by (b) it lies between 1 and . Compute it in closed form for the decaying spectrum , (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 Gaussian matrix of Section 21.5.4.3 from and , 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?
-
Weyl perturbation bound. An update , for instance a rank- LoRA update (the paper's letters), changes the singular values of a weight matrix . The Weyl inequality (21.5.11), proved in Section 21.5.2.1, limits how far they move.
- Set in (21.5.11) and apply the inequality in both directions to derive for every .
- Take and . Compute the singular values of and compare each change with .
- Now let . The Frobenius proof in Section 21.5.2.1 applies (21.5.11) with to a matrix of rank at most . Apply the same step to to obtain the interlacing inequalities and . Use them to show that the ranks of and differ by at most , and that at most singular values of exceed , however large is. Why does the bound of (a) not give these conclusions?
-
[code] Centering in PCA, and Fashion-MNIST. Let the rows of be data points with mean row and covariance as in the principal component analysis of Section 21.5.2.2.
- Show that .
- 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 ) and shift every point by for . For each , compute the top right singular vector of the uncentered data, its angle to the principal axis , and the ratio .
- Use (a) to predict, from the eigenvalues of , the offset at which the top singular vector turns from the principal axis toward the mean.
- Use (a) again to approximate the ratio for large , and find its limit as . At the ratio is close to the centered explained-variance ratio. Does this agreement reflect the data or the chosen offset?
- 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 and the difference of the class means , 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.
-
[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 with .
- Use the filter form (21.5.14) to show that as , for a matrix of any shape and rank. Why does not exist when ?
- Gradient descent on with step size updates . Show that stays in the row space of and that converges to . Which solution does the initialization select?
- Check (a) and (b) for a Gaussian and a Gaussian : run gradient descent from and from a random , and compare both limits and their norms with .
-
[code] Newton--Schulz basin. The Newton--Schulz iteration of Section 21.5.4.2 starts from .
- Let be a thin SVD. Show directly, without (21.5.18), that one step produces with applied to every diagonal entry.
- Show that is the immediate basin of 1: maps it into , and the iterates converge to 1 for every . Show that some starting values beyond also reach 1 (try ) and others do not (try 2). Expand in powers of . How fast does the distance to 1 shrink once it is small?
- For a Gaussian , count the steps until when the iteration starts from with and with . Compare both counts with , where is the smallest singular value after scaling. Why does Muon divide by although saves a step?
- Start the iteration from with and with . What does it converge to in each case? Explain both outcomes with the polynomial of (b).
-
[code] Polar factor and Procrustes. ● The polar decomposition (21.5.17) writes a square matrix as with orthogonal and symmetric positive semidefinite.
- Show that is determined by , and that is determined by when is invertible. Give two different polar decompositions of .
- Show that is an orthogonal matrix closest to in the Frobenius norm. Reduce the problem to maximizing over orthogonal .
- Two embedding spaces that differ by a rotation can be aligned from paired points by minimizing over orthogonal . Use (b) to show that the minimizer is the polar factor of . Test it with , , a random orthogonal (the factor of a QR decomposition of a Gaussian matrix), Gaussian , and , where has i.i.d. entries for . Compare for this estimate and for the unconstrained least-squares estimate .
-
[code] Randomized range finder. ● The randomized SVD of Section 21.5.4.3 multiplies by a Gaussian , orthonormalizes into , and truncates the SVD of to rank .
- Implement it. Build as with random orthonormal and , once with the fast decay and once with the slow decay . For and , divide the spectral-norm error of the rank- result by , the minimum of (21.5.10), and average over 10 draws of . Why does oversampling alone suffice for one spectrum but not for the other?
- Replace by for . How do the ratios change for each spectrum? Explain the effect of with the singular values of . How many products with or does each variant cost?
-
[code] Optimal hard threshold. ●● The threshold of Gavish and Donoho (2014) follows from the behavior of a single signal component. Let be , with unit vectors , , and with i.i.d. Gaussian entries . Write and let be the top singular triple of , with the sign of the pair chosen so that . As , Benaych-Georges and Nadakuditi (2012) show that tends to the bulk edge and the singular vectors become orthogonal to and when , and that for
The transition at is the singular-value counterpart of the eigenvalue transition at in exercise 5 of Section 21.3.
- Two estimates of the signal are the rank-one truncation and the zero matrix. Express the squared Frobenius error of each in terms of , , and .
- Use the limits to show that the truncation has the smaller asymptotic error exactly when , and that the singular value at is . Which signal strengths produce a singular value above the noise edge that should nevertheless be discarded?
- Check (a) and (b) for and , with and 10 draws each: compare , the squared cosines, and both errors with their limits.