The Singular Value Decomposition
Every matrix, square or not, can be written as a rotation, then a stretch along the axes, then another rotation: . This singular value decomposition (SVD) reveals a matrix's rank, its most important directions and how much it can amplify errors, and it powers image compression, PCA, recommender systems and least squares solvers.
The statement
Theorem (SVD). Every real matrix can be factored as
Equivalently : maps an orthonormal basis of the input space onto an orthogonal set in the output space, scaling the -th vector by .
Where it comes from. is symmetric and positive semidefinite, so by the spectral theorem it has orthonormal eigenvectors with eigenvalues . Put . For define . These are orthonormal:
Complete the to an orthonormal basis of (with Gram-Schmidt) and you have .
The geometry: circles become ellipses
Read right to left on the unit circle: rotates (or reflects) it, still a circle; stretches it into an ellipse with semi-axes , along the coordinate axes; rotates the ellipse into place. So the image of the unit sphere under is an ellipsoid whose semi-axes are , and the are the input directions that land on those axes.
import numpy as np
A = np.array([[3.0, 0.0],
[4.0, 5.0]])
U, s, Vt = np.linalg.svd(A)
print("singular values:", np.round(s, 4))
print("sqrt of eigenvalues of A^T A:", np.round(np.sqrt(np.linalg.eigvalsh(A.T @ A))[::-1], 4))
print("U Σ V^T = A:", np.allclose(U @ np.diag(s) @ Vt, A))
for i in range(2):
print(f"A v{i+1} = {np.round(A @ Vt[i], 4)} = σ{i+1} u{i+1} = {np.round(s[i] * U[:, i], 4)}")
t = np.linspace(0, 2 * np.pi, 2000)
image = A @ np.vstack([np.cos(t), np.sin(t)])
r = np.linalg.norm(image, axis=0)
print("longest / shortest image of a unit vector:", round(float(r.max()), 4), round(float(r.min()), 4))
print("|det A| = product of singular values:", abs(np.linalg.det(A)).round(4), np.prod(s).round(4))singular values: [6.7082 2.2361]
sqrt of eigenvalues of A^T A: [6.7082 2.2361]
U Σ V^T = A: True
A v1 = [-2.1213 -6.364 ] = σ1 u1 = [-2.1213 -6.364 ]
A v2 = [-2.1213 0.7071] = σ2 u2 = [-2.1213 0.7071]
longest / shortest image of a unit vector: 6.7082 2.2361
|det A| = product of singular values: 15.0 15.0
and : no unit vector is stretched more than 6.7082 or less than 2.2361. In general over unit , the operator norm .
What the SVD tells you
| Quantity | From the SVD |
|---|---|
| number of nonzero (numerically: above a tolerance) | |
| column space, null space | span ; span (Column, Row and Null Space) |
| (largest stretch) | |
| Frobenius norm | |
| condition number | (Numerical Linear Algebra) |
| pseudoinverse | , with inverting the nonzero |
| best rank- approximation | keep the largest terms (Low-Rank Approximation) |
The pseudoinverse gives the minimum-norm least squares solution even when is rank-deficient; that is what np.linalg.lstsq and np.linalg.pinv compute.
The outer-product form and image compression
Multiplying out gives as a sum of rank-one matrices, ordered by importance:
Keeping only the first terms gives , which needs numbers instead of . A grayscale image is a matrix of brightness values, and natural images have rapidly decaying singular values, so a small already looks right. We build a synthetic "photo" (smooth shapes plus noise) so the example needs no files:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(5)
y, x = np.mgrid[0:120, 0:160] / 40.0
img = (np.sin(2 * x) * np.cos(1.5 * y) + ((x - 2.2)**2 + (y - 1.4)**2 < 0.5)
+ 0.5 * (y > 2.2) + 0.08 * rng.normal(size=x.shape))
U, s, Vt = np.linalg.svd(img, full_matrices=False)
m, n = img.shape
print("first singular values:", np.round(s[:6], 2))
fig, axes = plt.subplots(1, 4, figsize=(10, 2.6))
axes[0].imshow(img, cmap="gray"); axes[0].set_title("original")
for ax, k in zip(axes[1:], (1, 5, 20)):
Ak = U[:, :k] * s[:k] @ Vt[:k]
err = np.linalg.norm(img - Ak) / np.linalg.norm(img)
ratio = k * (m + n + 1) / (m * n)
print(f"k={k:2d}: storage {ratio:6.1%} of original, relative error {err:.3f}")
ax.imshow(Ak, cmap="gray"); ax.set_title(f"rank {k}")
for ax in axes: ax.axis("off")first singular values: [92.5 31.93 12.64 11.55 6.52 4.88]
k= 1: storage 1.5% of original, relative error 0.392
k= 5: storage 7.3% of original, relative error 0.141
k=20: storage 29.3% of original, relative error 0.093
At rank 20 the picture is visually clean; most of the remaining error is the noise we added, which is spread over all the small singular values. (Real codecs such as JPEG use fixed cosine bases instead, because they are faster and work block by block, but the "keep the big coefficients" idea is the same.)
Tip: For a big matrix where you only need the top singular triplets, use
scipy.sparse.linalg.svdsor randomized SVD (sklearn.utils.extmath.randomized_svd) instead of a fullnp.linalg.svd.
In software
- PCA in scikit-learn is an SVD of the centred data (PCA).
- Recommenders. A ratings matrix is approximated by a low-rank SVD; the mini project builds one.
- NLP. Latent semantic analysis is a truncated SVD of a term-document matrix, an ancestor of modern embeddings.
- Robotics and graphics. The best rotation aligning two point clouds (Kabsch / Procrustes, used in ICP and motion capture) is from the SVD of a cross-covariance matrix.
- Deep learning. The spectrum of weight matrices is monitored for stability, and LoRA relies on updates having low rank (Low-Rank Approximation).
Go further: Principal Component Analysis computes PCA through the SVD and uses the components on real data.
Exercises
Exercise 1: Singular values of a diagonal matrix
What are the singular values of ?
Answer
3 and 2.
Solution
, whose eigenvalues' square roots are 3 and 2. The sign goes into : .
Exercise 2: By hand
Find the singular values of .
Answer
, (rank 1).
Solution
, eigenvalues 4 and 0. is rank one: with and .
Exercise 3: Storage
A image is stored as its rank-50 SVD. What fraction of the original numbers is needed?
Answer
.
Solution
.
Exercise 4: Rank from the SVD (code)
Use the SVD to find the rank of and a basis vector of its null space.
Answer
Rank 2; the null space is spanned by (up to scaling and sign).
Solution
The third singular value is 0 up to rounding, and the last row of spans the null space.
import numpy as np
A = np.arange(1, 10, dtype=float).reshape(3, 3)
U, s, Vt = np.linalg.svd(A)
print(np.round(s, 6) + 0, "rank:", int(np.sum(s > 1e-10 * s[0])))
v = Vt[-1] / Vt[-1][0]
print(np.round(v, 6) + 0, "A v ≈ 0:", np.allclose(A @ v, 0))[16.848103 1.06837 0. ] rank: 2
[ 1. -2. 1.] A v ≈ 0: True
Test yourself
The singular values of are…
- the eigenvalues of
- the square roots of the eigenvalues of
- the diagonal entries of
- the eigenvalues of
Under , the unit circle is mapped to…
- another circle
- an ellipse with semi-axes and
- a square
- a line always
Which matrices have an SVD?
- Only symmetric ones
- Only square invertible ones
- Every real matrix
- Only diagonalizable ones