Linear Algebra for ML: Eigenvectors & the SVD
Spectral theorems, low-rank approximation and why the SVD is everywhere.
Three facts carry a remarkable share of machine learning: symmetric matrices diagonalize in an orthonormal basis, every matrix has a singular value decomposition, and truncating that decomposition gives the best low-rank approximation there is. This lesson proves all three, then uses them to explain least squares, conditioning, the stability of eigenvectors and the randomized algorithms that make the SVD affordable at scale.
What you’ll learn
- Prove the spectral theorem for real symmetric matrices, characterize positive semidefinite matrices, and show that every Gram matrix is positive semidefinite.
- Derive the Rayleigh-quotient and Courant–Fischer characterizations of eigenvalues, and use them to prove Weyl's perturbation bound; state the Davis–Kahan bound for eigenvectors.
- Construct the SVD from the spectral theorem and prove the Eckart–Young–Mirsky theorem.
- Express least squares through the pseudoinverse, quantify conditioning, derive key matrix-calculus identities, and state the error bound of randomized SVD.
The spectral theorem and positive semidefinite matrices
Eigenvalues are real. Let with nonzero, and write for the conjugate transpose. Because is real and symmetric, , so
Eigenvectors of distinct eigenvalues are orthogonal. Move across the inner product:
Induction on . The characteristic polynomial has a root, real by the first step, so there is a real unit eigenvector . Its orthogonal complement is invariant under , because for :
restricted to the -dimensional space is again symmetric, so by induction has an orthonormal eigenbasis . Together with it diagonalizes :
For symmetric the following are equivalent, and define a positive semidefinite (PSD) matrix, written : (i) for every ; (ii) every eigenvalue is ; (iii) for some matrix (take ); (iv) is a Gram matrix, for some vectors (the columns of ). Strict inequalities give positive definite matrices, exactly those with a Cholesky factorization , lower triangular with positive diagonal. Cholesky costs about operations, half of a general LU factorization, and is how positive definite systems are solved, how Gaussian samples are drawn and how is computed.
Machine learning is full of PSD matrices. A covariance matrix is one, since is a variance. So is any kernel Gram matrix , because , the fact behind every kernel method. So is the Hessian of a twice-differentiable convex function.
Which of these symmetric matrices is not positive semidefinite?
Show the answer
C.
Its eigenvalues are and (eigenvectors and ): gives . Positive entries do not make a matrix PSD; the off-diagonal entries must be small relative to the diagonal, for a matrix with nonnegative diagonal.
Rayleigh quotients, Courant–Fischer and perturbation
Sort the eigenvalues of a symmetric as . In the eigenbasis, , the Rayleigh quotient is a weighted average of the eigenvalues, , so , with equality at the bottom and top eigenvectors. This is PCA in one line: the unit direction of greatest variance maximizes , so it is the top eigenvector of the covariance, and the best -dimensional subspace maximizes over orthonormal , attained by the top eigenvectors.
Eigenvalues are stable. For symmetric and , and . Feeding this into both sides of Courant–Fischer gives Weyl's inequality: for every . A sample covariance that is off by in spectral norm has every eigenvalue within of the truth.
Eigenvectors are not, unless the eigenvalues are separated. If , any direction in their span is a top eigenvector, and an arbitrarily small perturbation decides which one you get. The Davis–Kahan theorem (Davis & Kahan, 1970) bounds the rotation by the perturbation divided by an eigengap. In the form of Yu, Wang & Samworth (2015), which needs only the population gap: for symmetric , with top eigenvectors , ,
The SVD and the best low-rank approximation
is symmetric and PSD, so with orthonormal and . Set and, for , . These are orthonormal:
For , , so . Expanding the identity in the basis of the finishes the construction:
Spectral norm. has rank at most , so its null space has dimension at least and meets the -dimensional span of in some unit vector . Then , and
Frobenius norm. Weyl's inequality for singular values (from Courant–Fischer applied to ) gives . Take , and , where :
A matrix has singular values . Its best rank-2 approximation has what relative error , in percent?
Show the answer
19.6 %
and , so the relative error is . The rank-2 approximation keeps of the "energy" , yet its relative error in norm is about 20%: energy fractions are squares, and they flatter. In spectral norm the error is , also 20% of .
For centered data , the right singular vectors are the principal directions, the variances along them and the scores. Eckart–Young says that projecting onto the top directions minimizes the total squared reconstruction error among all rank- approximations, not just projections, and computing them from the SVD of avoids forming , which, as the next step shows, squares the condition number.
Least squares, conditioning and matrix calculus
Write with and square orthogonal, and rotate: , . Orthogonal maps preserve norms, so the residual splits coordinate by coordinate:
The minimizers have for , with free (they span the null space of ). Setting the free ones to zero gives the minimum-norm solution, the pseudoinverse applied to :
Noise in along is multiplied by , so tiny singular values make the solution unstable. Ridge regression replaces by , a filter that is close to for large and close to for small ones:
The condition number quantifies that instability. For a square invertible system , a perturbation moves the solution by , so , while . Dividing,
Double precision stores numbers to a relative accuracy of about , so as a rule of thumb you lose about significant digits. The normal equations use , whose condition number is ; Householder QR (, then solve ) and the SVD work on itself, which is why least-squares software uses them.
| Function of or | Gradient | Where it appears |
|---|---|---|
| linear models | ||
| , which is for symmetric | quadratic losses, Gaussian log-densities | |
| least squares | ||
| trace manipulations | ||
| (for ) | Gaussian likelihoods, log-determinant penalties | |
| covariance estimation |
Factor out ; for a small , the eigenvalues of are small, and :
Since , the gradient is . Apply it to the Gaussian log-likelihood in the precision matrix , with the average of :
The log-likelihood is concave in (log det is concave on positive definite matrices), so the stationary point is the maximum: the maximum-likelihood covariance is the sample covariance with divisor , whenever is invertible.
Randomized SVD, and the frontier
A full SVD of an matrix costs on the order of operations, too much for large data even when only the top components matter. Randomized SVD (Halko, Martinsson & Tropp, 2011) first finds the range: multiply by random Gaussian vectors, a small oversampling such as 5 or 10. The products are random combinations of the columns, dominated by the top singular directions, so an orthonormal basis of them nearly spans the top- left singular subspace. Everything else happens in the small matrix .
import numpy as np
def randomized_svd(A, k, p=10, q=2, seed=0):
rng = np.random.default_rng(seed)
Omega = rng.standard_normal((A.shape[1], k + p)) # random test matrix
Q, _ = np.linalg.qr(A @ Omega) # basis for the sampled range
for _ in range(q): # power iterations, re-orthonormalized
Q, _ = np.linalg.qr(A.T @ Q)
Q, _ = np.linalg.qr(A @ Q)
B = Q.T @ A # small (k + p) x n matrix
U_small, s, Vt = np.linalg.svd(B, full_matrices=False)
return (Q @ U_small)[:, :k], s[:k], Vt[:k]The whole algorithm touches only through a few matrix products, passes in all, so it works for matrices too large for memory and parallelizes well. After power iterations the sampled matrix is , whose singular values are : the top dominate the rest far more sharply.
Think first For , and , how large is the bracket in the bound? And what do two power iterations do to the corresponding factor ?
: a pessimistic worst-case factor. With power iterations the factor is : about 3.9 for and 2.3 for . When the singular values decay, the actual error is usually much closer to than any of these bounds, and the paper's refined bounds explain why.
Key takeaways
- Symmetric matrices diagonalize as with real eigenvalues and orthonormal eigenvectors. PSD matrices are exactly the Gram matrices ; covariances, kernel matrices and convex Hessians are PSD, and positive definite ones factor as (Cholesky).
- Rayleigh quotients and Courant–Fischer characterize eigenvalues variationally, which gives PCA and Weyl's bound . Eigenvectors are stable only relative to the eigengap: .
- Every matrix has an SVD , built from the spectral theorem of . The truncated SVD is the best rank- approximation, with errors (spectral) and (Frobenius).
- The pseudoinverse gives the minimum-norm least-squares solution ; small singular values amplify noise and rounding by up to , and the normal equations square .
- Randomized SVD sketches the range with random vectors and is within a modest factor of in expectation; a few power iterations drive that factor toward 1.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
The singular values of are . What is the smallest possible spectral-norm error over all matrices of rank at most ?
Show the answer
B.
Eckart–Young–Mirsky: the truncated SVD is optimal, with , the largest singular value left out. The square-root sum is the optimal error in the Frobenius norm.
You perturb a symmetric matrix by a symmetric with . Which statement is guaranteed?
- Every eigenvalue and every eigenvector moves by at most about
- Eigenvalues can move arbitrarily, but eigenvectors are stable
- Nothing can be said without knowing the dimension
- Every eigenvalue moves by at most , but an eigenvector can rotate a lot if its eigenvalue is close to another one
Show the answer
D. Every eigenvalue moves by at most , but an eigenvector can rotate a lot if its eigenvalue is close to another one
Weyl's inequality bounds every eigenvalue shift by , whatever the spectrum. Eigenvectors are controlled only relative to the eigengap: Davis–Kahan bounds the rotation by about , which is large when eigenvalues nearly coincide, and when they coincide, the eigenvector is not even unique.
A design matrix has condition number . Why do careful solvers avoid forming for least squares?
- Because is not symmetric
- Because can be singular even when has full column rank
- Because , which can cost about 12 of double precision's 16 significant digits
- Because forming costs more than an SVD
Show the answer
C. Because , which can cost about 12 of double precision's 16 significant digits
The singular values of are the squares , so the condition number squares. Rounding errors of relative size are amplified by up to , so leaves only a few reliable digits. QR or SVD works on directly, where the amplification is governed by (with a term only when the residual is large).
has more columns than rank, so least squares has infinitely many minimizers. Which one is , with ?
- The minimizer of smallest Euclidean norm, the one with no component in the null space of
- An arbitrary one, depending on the SVD routine
- The one with the smallest residual, which is unique
- The one with the fewest nonzero coefficients
Show the answer
A. The minimizer of smallest Euclidean norm, the one with no component in the null space of
In the rotated coordinates , the residual depends only on , which must equal ; the remaining coordinates span the null space and are free. sets them to zero, which minimizes . It is also the limit of ridge regression as and the point gradient descent from zero converges to.
Further reading
- C. Eckart & G. Young, "The approximation of one matrix by another of lower rank," Psychometrika 1, 211–218 (1936).
- Y. Yu, T. Wang & R. J. Samworth, "A useful variant of the Davis–Kahan theorem for statisticians," Biometrika 102(2), 315–323 (2015).
- 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).
- L. N. Trefethen & D. Bau, Numerical Linear Algebra (SIAM, 1997).
- R. A. Horn & C. R. Johnson, Matrix Analysis, 2nd ed. (Cambridge University Press, 2012).