06 / 16 · Linear Algebra
The singular value decomposition
Every matrix as a rotation, a stretch along the axes and another rotation: the SVD built from the Gram matrix, rank and the four subspaces, the best low-rank approximation, the pseudoinverse, and PCA.
On this page 7
Take the matrix
Its trace is 3 and its determinant 6, so its characteristic polynomial has the complex roots . There is no real eigenvector, and the eigendecomposition of the determinants note says nothing about the geometry of this map. Yet the geometry is simple. sends the unit circle to an ellipse, and an ellipse has two perpendicular axes.
Most matrices of machine learning are worse off still. The matrix of the small digit images bundled with scikit-learn, or a weight matrix that maps 768 features to 3,072, has no eigenvalues at all, because needs and in the same space. What are the axes of the ellipse, which vectors land on them, and how do we answer that for any matrix? The previous note answered it for symmetric matrices, and that answer is the tool.
Building the SVD step by step#
We look for perpendicular input directions that keeps perpendicular. The symmetric matrix measures inner products after the map, , so its eigenvectors are the candidates. Normalizing their images gives a second set of perpendicular directions.
For of rank , the result will be
with orthogonal and , and zero except for the singular values on its diagonal. The columns of are the right singular vectors, the columns of the left singular vectors. Five steps build it.
Step 1: the eigenvectors of . The matrix is symmetric, and positive semidefinite since . By the spectral theorem it has orthonormal eigenvectors with eigenvalues . Exactly of them are positive. has the null space of : gives , and gives . That null space has dimension by rank–nullity, and it is spanned by the with , so eigenvalues are zero.
Step 2: the singular values. Set . They are the lengths of the images, since .
Step 3: the left singular vectors. For set . These vectors are orthonormal:
Step 4: complete the bases. If , extend to an orthonormal basis of , for example by Gram–Schmidt. For , , so .
Step 5: assemble. Now for every , with for . Column by column this is , and multiplying on the right by gives . Written as columns times rows, the product is the sum of rank-one terms, and only the first survive.
The construction proves that the SVD exists; it is not how the SVD is computed. Forming squares the singular values, and with them the ratio that measures sensitivity to rounding, so libraries work on directly (Golub and Kahan, 1965; Strang, 2018, lecture 6).
Example. For :
- , with trace 13 and determinant 36, so its eigenvalues are 9 and 4. The null space of gives , and is perpendicular to it.
- and .
- and . Their inner product is .
- Nothing to complete: .
- The two layers add up to :
Rotate, stretch, rotate#
Read from right to left, applies three maps. is orthogonal and takes to ; here , a rotation. stretches the -th axis by . is orthogonal and takes to . A unit vector , , goes to with , so : the unit circle becomes an ellipse with half-axes along and along :
The SVD: rotate, stretch, rotate
The count of numbers comes out right. A matrix has four entries; a rotation of the plane has one parameter, its angle, so the SVD spends on two rotations and two stretches. For a rectangular the middle step also changes the dimension: keeps the first coordinates, scaled, and drops or pads the rest, so the unit sphere of becomes a flattened ellipsoid in an -dimensional subspace of .
What the singular values measure#
The largest stretch is the square root of the largest Rayleigh quotient of , so the spectral norm is . The Frobenius norm, , squared is , because the -th diagonal entry of is . The trace is the sum of the eigenvalues of :
For a square , , because and an orthogonal matrix has determinant . In the example, , and the ellipse with half-axes 3 and 2 has area , six times that of the disc. For a symmetric , write with signs ; then with is an SVD, so the singular values are the . For a positive semidefinite one they are the eigenvalues themselves, with .
The ratio of a square invertible matrix, its condition number, says how much the map distorts shapes; the conditioning note shows that it also bounds how errors grow when solving .
The singular values are unique: any SVD gives , so its are the eigenvalues of , which alone determines. When the nonzero singular values are distinct, each is a unit vector in a one-dimensional eigenspace of , hence fixed up to sign, and follows it. So works as well as , which is why two libraries can return principal components with opposite signs. The left singular vectors are the eigenvectors of ; for a wide matrix it is cheaper to start from the smaller .
Rank and the four subspaces#
In the coordinates of the SVD a matrix is diagonal, and the four subspaces become spans of basis vectors:
| subspace | dimension | basis from the SVD |
|---|---|---|
| column space | ||
| left null space | ||
| row space | ||
| null space |
Write . It is always a combination of , and each is reached by , so these span the column space. It is zero exactly when for all , that is, when lies in the span of . The other two rows follow from . So the rank is the number of nonzero singular values, and the row space and null space are orthogonal complements in , as are the column space and the left null space in .
Example. For
start from the smaller matrix , with eigenvalues 3 and 1 and eigenvectors and . So , , and the rank is 2. The right singular vectors are : and . The third, , completes the basis of , and indeed . The null space is the line through , and the row space is the plane perpendicular to it, spanned by the two rows.
In floating point a singular value is almost never exactly zero. A matrix whose third column is the sum of the first two can come out with rather than 0. The numerical rank is the number of singular values above a tolerance; NumPy’s matrix_rank uses , with the machine epsilon . The SVD is the reliable way to compute a rank because, by the Eckart–Young theorem below, is the spectral-norm distance from to the nearest matrix of rank . Pivots carry no such guarantee. The upper triangular matrix with ones on the diagonal and above it is already triangular, so its pivots are its diagonal entries, all equal to 1; yet : a change of that size makes it singular.
The best low-rank approximation#
The sum sorts a matrix into rank-one layers in order of importance. Keeping the first gives the truncation . Is it the closest matrix of rank ?
That is less obvious than it looks. Take and . The truncation keeps 4 and 3 and misses the 2 and the 1. A cleverer rank-two matrix puts a block of four s in the top-left corner and a block of four s in the bottom-right one, each block of rank one. On the diagonal it misses every entry by only , but the off-diagonal entries of the blocks cost more: its Frobenius error is , against for the truncation (Strang, 2018, lecture 7).
The Eckart–Young theorem says that no matrix does better:
Halko, Martinsson and Tropp (2011, section 10.2) credit the Frobenius case to Eckart and Young (1936) and the spectral case to Mirsky (1960); both are proved below (Rakhuba, 2025, lecture 4).
The error of the truncation is the easy half. The difference is itself an SVD, because its and are still orthonormal, so its spectral norm is its largest singular value, . For the Frobenius norm:
Example. For , the rank-one truncation is , and the error is the other layer:
Its squared entries sum to , and its spectral norm is . Relative to the best rank-one approximation is off by : this matrix is far from rank one, because its two singular values are close.
Why no other matrix of rank k does better#
Optional depth: the proof of optimality for the spectral norm, and where the Frobenius case comes from. The rest of the note does not depend on it.
Let have rank at most . Its null space has dimension at least by rank–nullity, and the span of has dimension . Two subspaces , of with share a nonzero vector, since (Axler, 2024, 2.43). So there is a unit vector with and . Then
The last step replaces each with by the smallest of them and uses . The truncation reaches this bound, so it is optimal.
The Frobenius case follows from the spectral one. Let and be the truncations of two matrices and . Their sum has rank at most , so by the spectral case and the triangle inequality
Take , and . Since , , and the inequality reads . Summing the squares over gives (Horn and Johnson, 2013, sections 7.3 and 7.4).
Compressing a matrix#
A rank- approximation of an matrix is stored as columns , rows and numbers : numbers instead of . Whether that pays off depends on how fast the singular values fall. The test image below is a synthetic grayscale matrix of 4,096 numbers: a constant background, a smooth bump , a disc, an axis-aligned rectangle and a thin diagonal stripe. The Code section builds it from this formula.
A 64 × 64 image and its low-rank approximations
The first singular value, , carries the background and most of the bump: its square is 92% of . The next ones fall quickly, , , , , and then slowly, down to :
The singular values of the image and the error of a rank-k approximation
| rank | relative error | numbers stored | share of 4,096 |
|---|---|---|---|
| 1 | 28.3% | 129 | 3% |
| 5 | 12.1% | 645 | 16% |
| 10 | 8.1% | 1,290 | 31% |
| 20 | 4.5% | 2,580 | 63% |
Each error equals the square root of the share of that the discarded singular values carry, as the theorem says. Beyond the factors take more room than the matrix itself.
The components of the image behave differently. The rectangle and the bump are products of a function of the row and a function of the column, so each has rank one. The disc needs a handful of layers. The diagonal stripe needs nearly all of them, because a band along the diagonal is close to a multiple of the identity, whose singular values are all equal.
The SVD favours structure aligned with rows and columns, and image codecs use other transforms. It wins on matrices whose structure is genuinely low-rank: user–item ratings in recommender systems, word co-occurrence counts, and the updates of fine-tuned weights.
LoRA: a low-rank update#
LoRA fine-tunes a large model by restricting the update of each weight matrix to rank , , which needs trained numbers instead of . By Eckart–Young, no rank- update comes closer, in the Frobenius norm, to the update that full fine-tuning would make than the root of the sum of its squared singular values beyond the -th; the PEFT note covers how LoRA is set up and trained.
The pseudoinverse and minimum-norm least squares#
The system can fail in two ways. It may have no solution, when is not in the column space, and it may have infinitely many, when the null space is not . Least squares fixes the first failure by minimizing , but its formula needs independent columns, so it does not fix the second. The SVD fixes both.
Change coordinates to and . Orthogonal matrices keep lengths, so
The problem has split into scalar equations , which can be solved, residuals for , which nothing can remove, and coordinates for , which do not affect the residual. The residual is smallest when for . Among all such choices the length is smallest when for . Going back to :
where is the matrix with for the nonzero singular values and zeros elsewhere. is the pseudoinverse (Penrose, 1955), and is the least-squares solution of smallest length.
Special cases recover familiar formulas. If is square and invertible, and . If the columns are independent (), is invertible, and
because has on its diagonal: the normal equations. If the rows are independent (), the same computation with gives , and solves the system exactly with the smallest length.
Example. For and , every solves . The rows are independent, so , with . The SVD gives the same: , so and . Every other solution adds a multiple of the null-space vector, which is orthogonal to , so its squared length is by Pythagoras. The solution , at , has squared length 1.
Two training procedures land on without being asked. Ridge regression multiplies the component along by instead of (which directions ridge shrinks). As the factor tends to for and stays 0 for , so ridge tends to ; in the example, gives .
Gradient descent on is the other. Its step in the coordinates and splits into
For every factor is below 1, so for , while the null-space coordinates never move. Started at 0, descent converges to , the minimum-norm solution. Started at , it keeps that start’s component along the null space and converges to instead, with squared length 1; the Code section uses . This is the simplest case of the implicit regularization of overparameterized models.
PCA is the SVD of the centred data#
For a data matrix with centred columns, the SVD gives all of principal component analysis. The sample covariance is , so the principal directions are the right singular vectors and the variance along the -th is . The coordinates of the data in the new basis are , and the best reconstruction from components is the Eckart–Young truncation . The dimensionality reduction note derives PCA from both variance and reconstruction error and works through these formulas on data.
One numerical point belongs here. Computing the SVD of is more accurate than computing the eigenvalues of , because forming squares the singular values. Rounding the entries of perturbs it by about in norm, and by Weyl’s inequality its eigenvalues move by as much. A singular value below about is then lost: for with singular values , and , the SVD returns , the route through rounding noise, in the Code section.
Where it breaks: small singular values#
The pseudoinverse divides by every nonzero singular value, however small. Take and the right-hand side , measured with an error of in its second entry. The exact data give ; the measured data give . A singular value of multiplies the noise along its direction by , while an exact zero would have ignored it. The map is discontinuous at every matrix of rank : the pseudoinverse of contains the term , whose norm grows without bound as .
Libraries therefore treat singular values below a threshold as zero: rcond in numpy.linalg.pinv and lstsq. With rcond the example returns again. This is the truncated SVD applied to the inverse, and the threshold is a modelling choice: it decides which directions of the data count as signal. The conditioning note quantifies the trade-off, and ridge regression makes the same choice smoothly.
A full SVD of an matrix with costs on the order of operations, so large matrices get truncated or randomized methods that compute only the leading triplets (Halko, Martinsson and Tropp, 2011). Eckart–Young is about the spectral and Frobenius norms, which weigh all entries alike; an approximation robust to a few corrupted entries, or one with non-negative factors, needs other methods. And the SVD needs every entry: a ratings matrix with most entries unknown is factorized by optimizing over the known entries only, as in matrix factorization.
What you should remember#
- Every factors as : rotate, stretch along the axes, rotate.
- are the eigenvectors of , , ; compute it from , never from .
- , ; the rank is the number of nonzero , and , hold bases of the four subspaces.
- Eckart–Young: is the best rank- approximation, with error in the spectral norm and in the Frobenius norm.
- gives the least-squares solution of smallest norm, the limit of ridge and the point gradient descent reaches from zero.
- Tiny singular values blow up ; a threshold decides what counts as zero.
Code#
The SVD built by the five steps against NumPy, the norms, the four subspaces, Eckart–Young on Strang’s diagonal example, on random matrices and on the image of the figures, the pseudoinverse against ridge and gradient descent, the effect of a tiny singular value, and the two numerical points about rank and . It runs in about a second; digits in the last places can differ across platforms and library versions.
import numpy as np
# 1. the SVD built from the eigenvectors of A^T A, step by step
A = np.array([[2.0, 2.0], [-2.0, 1.0]])
lam, V = np.linalg.eigh(A.T @ A) # step 1 (ascending order)
lam, V = lam[::-1], V[:, ::-1] # sort decreasing
sig = np.sqrt(lam) # step 2
U = A @ V / sig # step 3: u_i = A v_i / sigma_i
print(lam, sig, np.allclose(U.T @ U, np.eye(2)), np.allclose(U @ np.diag(sig) @ V.T, A)) # step 5
print(np.linalg.svd(A, compute_uv=False), np.linalg.eigvals(A).round(4))
# [9. 4.] [3. 2.] True True
# [3. 2.] [1.5+1.9365j 1.5-1.9365j]
# 2. the norms and the determinant from the singular values; the image of e1
print(round(np.linalg.norm(A, 2), 6), round(np.linalg.norm(A, 'fro') ** 2, 6), round(abs(np.linalg.det(A)), 6), round(sig.prod(), 6))
Ut, s, Vt = np.linalg.svd(A)
print(np.abs(Vt @ [1.0, 0.0]).round(3), A @ [1.0, 0.0])
# 3.0 13.0 6.0 6.0
# [0.894 0.447] [ 2. -2.]
# 3. rank and the four subspaces of B
B = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]])
UB, sB, VBt = np.linalg.svd(B)
r = int((sB > sB[0] * max(B.shape) * np.finfo(float).eps).sum())
null = VBt[r:].T # basis of the null space
print(sB.round(4), r, (null[:, 0] / null[0, 0]).round(6), np.allclose(B @ null, 0))
C = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 9.0], [7.0, 8.0, 15.0]]) # third column = first + second
print([f'{v:.3g}' for v in np.linalg.svd(C, compute_uv=False)], np.linalg.matrix_rank(C))
# [1.7321 1. ] 2 [ 1. 1. -1.] True
# ['21.8', '0.585', '8.89e-16'] 2 (the last singular value is zero up to rounding; its digits vary)
# 4. Eckart-Young: Strang's diagonal example, then the truncation error on a random matrix
D = np.diag([4.0, 3.0, 2.0, 1.0]); D2 = np.diag([4.0, 3.0, 0.0, 0.0])
Bd = np.zeros((4, 4)); Bd[:2, :2] = 3.5; Bd[2:, 2:] = 1.5 # two rank-one blocks: rank 2
print(np.linalg.matrix_rank(Bd), round(float(np.linalg.norm(D - D2)), 2), round(float(np.linalg.norm(D - Bd)), 2))
rng = np.random.default_rng(0)
M = rng.normal(size=(30, 20))
Um, sm, Vmt = np.linalg.svd(M, full_matrices=False)
k = 5
Mk = (Um[:, :k] * sm[:k]) @ Vmt[:k]
print(np.isclose(np.linalg.norm(M - Mk, 2), sm[k]), np.isclose(np.linalg.norm(M - Mk, 'fro'), np.sqrt((sm[k:] ** 2).sum())))
best_in_span = []
for _ in range(200): # best approximation within a random k-dimensional column space
Q, _ = np.linalg.qr(rng.normal(size=(30, k)))
best_in_span.append(np.linalg.norm(M - Q @ (Q.T @ M), 'fro'))
print(round(float(np.linalg.norm(M - Mk, 'fro')), 4), round(min(best_in_span), 4))
# 2 2.24 5.48
# True True
# 16.5208 21.0277 (the truncation error, then the best of 200 random rank-5 column spaces)
# 5. the test image of the figures: singular values, relative errors and storage
n = 64
t = np.arange(n) / (n - 1)
x, y = np.meshgrid(t, t) # x along the columns, y along the rows
F = 0.2 + 0.5 * np.sin(np.pi * x) * np.sin(np.pi * y)
F += 0.6 * ((x - 0.35) ** 2 + (y - 0.6) ** 2 < 0.2 ** 2)
F += 0.4 * ((x >= 0.6) & (x <= 0.9) & (y >= 0.15) & (y <= 0.4))
F += 0.3 * (np.abs(x - y) < 0.05)
UF, sF, VFt = np.linalg.svd(F)
print(sF[:5].round(2), f'{sF[-1]:.1e}', round(float(np.linalg.norm(F)), 2), round(float(sF[0] ** 2 / (sF ** 2).sum()), 3))
for k in (1, 5, 10, 20):
Fk = (UF[:, :k] * sF[:k]) @ VFt[:k]
rel = np.linalg.norm(F - Fk) / np.linalg.norm(F)
print(k, round(float(rel), 4), round(float(np.sqrt((sF[k:] ** 2).sum() / (sF ** 2).sum())), 4), k * (2 * n + 1), f'{k * (2 * n + 1) / n**2:.0%}')
# [38.32 8.39 3.94 3.56 2.44] 1.6e-04 39.95 0.92
# 1 0.2832 0.2832 129 3%
# 5 0.1213 0.1213 645 16%
# 10 0.081 0.081 1290 31%
# 20 0.0448 0.0448 2580 63%
# 6. the pseudoinverse: minimum-norm solution, the limit of ridge, and gradient descent from zero
b = np.array([1.0, 1.0])
xp = np.linalg.pinv(B) @ b
print(xp.round(6), round(float(xp @ xp), 6), np.linalg.lstsq(B, b, rcond=None)[0].round(6))
print(np.linalg.solve(B.T @ B + 1e-3 * np.eye(3), B.T @ b).round(4))
for start in (np.zeros(3), np.array([1.0, 0.0, 0.0])):
w = start.copy()
for _ in range(2000):
w -= 0.3 * B.T @ (B @ w - b)
print(start, w.round(6), round(float(w @ w), 6))
# [0.333333 0.333333 0.666667] 0.666667 [0.333333 0.333333 0.666667]
# [0.3332 0.3332 0.6664]
# [0. 0. 0.] [0.333333 0.333333 0.666667] 0.666667
# [1. 0. 0.] [0.666667 0.666667 0.333333] 1.0
# 7. a tiny singular value amplifies noise; a threshold removes it
As = np.diag([1.0, 1e-8]); bs = np.array([1.0, 0.0]) + np.array([0.0, 1e-6])
print(np.linalg.pinv(As) @ bs, np.linalg.pinv(As, rcond=1e-6) @ bs)
# [ 1. 100.] [1. 0.]
# 8. pivots do not reveal near-singularity, singular values do; forming X^T X loses the small ones
T = np.eye(30) + np.triu(-np.ones((30, 30)), 1) # ones on the diagonal, -1 above it
print(np.diag(T).min(), f'{np.linalg.svd(T, compute_uv=False)[-1]:.1e}')
Ux, _ = np.linalg.qr(rng.normal(size=(100, 3))); Vx, _ = np.linalg.qr(rng.normal(size=(3, 3)))
X = Ux @ np.diag([1.0, 1e-4, 1e-10]) @ Vx.T
print(f'{np.linalg.svd(X, compute_uv=False)[-1]:.1e}', f'{np.sqrt(abs(np.linalg.eigvalsh(X.T @ X)[0])):.0e}')
# 1.0 2.8e-09
# 1.0e-10 9e-09 (the second number is rounding noise and varies with the platform)
Next#
The linear algebra of the course is complete: vectors and maps, systems and their solutions, orthogonality and projections, eigenvalues, symmetric matrices and the SVD. Machine learning uses all of it inside optimization: a loss is minimized by following its derivatives, and those derivatives are themselves linear maps, a gradient vector or a Jacobian matrix. The next note starts the calculus section with the derivative as the best linear approximation of a function, and the Taylor series that turns a smooth loss near a point into the quadratic forms of the previous note.
References#
- C. Eckart, G. Young. The approximation of one matrix by another of lower rank. Psychometrika 1(3), 211–218, 1936.
- L. Mirsky. Symmetric gauge functions and unitarily invariant norms. The Quarterly Journal of Mathematics 11(1), 50–59, 1960.
- R. Penrose. A generalized inverse for matrices. Mathematical Proceedings of the Cambridge Philosophical Society 51(3), 406–413, 1955.
- G. H. Golub, W. Kahan. Calculating the singular values and pseudo-inverse of a matrix. SIAM Journal on Numerical Analysis 2(2), 205–224, 1965.
- N. Halko, P.-G. Martinsson, J. A. Tropp. Finding structure with randomness: probabilistic algorithms for constructing approximate matrix decompositions. SIAM Review 53(2), 217–288, 2011. Section 10.2 states the two optimal truncation errors and credits them.
- M. Rakhuba. Основы матричных вычислений (Foundations of Matrix Computations), lecture course, HSE University, 2025/26. Course page; lecture 2 (the SVD and the norms it gives) and lecture 4 (the Eckart–Young–Mirsky theorem, best approximation with a given column space, the randomized SVD).
- G. Strang. Matrix Methods in Data Analysis, Signal Processing, and Machine Learning (MIT 18.065), lecture course, 2018. Lecture 6: the singular value decomposition and lecture 7: Eckart–Young, the closest rank-k matrix.
- R. A. Horn, C. R. Johnson. Matrix Analysis, 2nd ed. Cambridge University Press, 2013. Sections 7.3 (the polar and singular value decompositions) and 7.4 (their consequences).
- S. Axler. Linear Algebra Done Right, 4th ed. Springer, 2024. Result 2.43 (dimension of a sum of subspaces).