A dense weight matrix may store millions of coefficients even when most of its action fits into a much smaller subspace. The singular value decomposition, or SVD, shows which input directions the matrix amplifies, where they land, and which directions can be dropped under a stated error budget. The same tools help you reason about image compression, ill-conditioned least squares, and feature matrices before PCA.
By the end you can derive a small rectangular SVD, reconstruct its factors in NumPy, quantify truncation error in two norms, and turn a retained rank into a concrete storage and quality test. You need matrix multiplication, Euclidean norms and the eigenbasis idea from the preceding lesson.
Describe a rectangular map with two bases#
Let a real matrix A have m rows and n columns. It maps a column input x with n coordinates to an output with m. Define r=min(m,n). The reduced SVD writes
Here U has shape [m,r] and V has shape [n,r]. Their columns are orthonormal within each matrix. Σ is a diagonal [r,r] matrix whose entries σ₁,…,σᵣ are nonnegative and ordered from largest to smallest. The columns vᵢ of V are input directions and uᵢ of U are output directions. Their relationship is Avᵢ=σᵢ uᵢ. The letter r here counts returned values. The exact rank counts only the strictly positive values.
To apply A, first compute dot products against the columns of V, then multiply each coordinate by its singular value and assemble the output from the corresponding columns of U. When m<n, an input can have a component outside the columns of reduced V. That component is sent to zero. Full SVD returns square bases [m,m] and [n,n] and uses a rectangular diagonal matrix [m,n]. Use it when you need the extra basis vectors, for example to describe the whole null space of a wide matrix. A zero singular value gives a collapsed input mode, and its paired output vector has no effect on reconstruction.
This follows from orthonormality of the output vectors. If ‖x‖₂=1, the squared input coordinates in the sum add to at most one. So the maximum output length is σ₁, attained by v₁. The largest eigenvalue magnitude cannot substitute for this one-step bound on a nonsymmetric matrix. For instance the shear from the preceding lesson sends (0,1)ᵀ to (2,1)ᵀ, with length √5, even though both eigenvalues equal one.
Find a rectangular SVD by hand#
Use a map from two input coordinates to three output coordinates,
Compute AᵀA by taking pairwise column dot products. Each column has squared length 2²+1²+2²=9, and their dot product is 4-1+4=7. Thus AᵀA has rows (9,7) and (7,9). The vector v₁=(1,1)ᵀ/√2 has eigenvalue 9+7=16. The vector v₂=(1,-1)ᵀ/√2 has eigenvalue 9-7=2. They are orthogonal and have unit length.
The eigenvalues of AᵀA are the squares of the singular values because
The singular values are 4 and √2. Compute the output directions by dividing each image by its positive singular value. The first image is (4,0,4)ᵀ/√2, so u₁=(1,0,1)ᵀ/√2. The second image is (0,2,0)ᵀ/√2, so u₂=(0,1,0)ᵀ. A third full output basis vector can be (1,0,-1)ᵀ/√2. It is perpendicular to all outputs, so the reduced decomposition can omit it.
For input x=(3,1)ᵀ, the coordinates in the right basis are v₁ᵀx=4/√2 and v₂ᵀx=2/√2. Scale these to 16/√2 and 2, respectively. Adding the weighted left vectors yields (8,2,8)ᵀ, the same result as multiplying A by x directly.
Diagram key and text version
- Entry
- Process
- Outcome
- Input (3, 1) → Right basis
- Right basis → Scale coordinates
- Scale coordinates → Output (8, 2, 8)
The Gram matrix AᵀA is useful for deriving the geometry. In numerical code, call an SVD solver directly. Forming AᵀA squares the ratio of the largest to smallest positive singular value on the supported subspace, so small modes can be harder to distinguish from roundoff. The identity uᵢ=Avᵢ/σᵢ also becomes sensitive when σᵢ approaches zero and is undefined at zero.
Keep the leading rank-one contributions#
The outer product uᵢvᵢᵀ makes an [m,n] matrix from one output vector and one input vector. On any input, that matrix first computes the scalar vᵢᵀx and then returns the scalar times uᵢ. The original map is a sum of these rank-one contributions weighted by σᵢ. Keeping only the first k gives
In the hand example the first contribution yields rows (2,2), (0,0), and (2,2). The difference A-A₁ has one nonzero row, (1,-1). It changes the output of (3,1)ᵀ by (0,2,0)ᵀ. The approximation erased the second output coordinate for every input. If that coordinate carries an essential signal, excellent scores on average examples can still hide a deployment failure.
Two matrix norms quantify distinct error budgets. The Frobenius norm, ‖E‖_F, is the square root of the sum of all squared entries of a residual matrix E. The spectral norm, ‖E‖₂, is the maximum Euclidean output error over all unit-length inputs. For k<r,
Both errors are zero once k includes all positive modes. In the example the squared Frobenius error is 2 and the worst unit-vector error is √2. The approximation retains 16/(16+2)=8/9 of the squared Frobenius norm of A. When A is an uncentered dataset, this fraction includes the contribution from the mean.
Why truncation achieves both bounds
For the spectral norm, any competitor B of rank at most k must send some unit vector x in the span of v₁,…,vₖ₊₁ to zero. The restriction of B to this (k+1)-dimensional span has at most k independent outputs, so it has a nonzero null vector. On that vector (A-B)x=Ax, whose length is at least σₖ₊₁. Truncation achieves that limit.
For the Frobenius norm, fix the column space of a candidate B. The best approximation to each column of A in that fixed space is its orthogonal projection. If P projects onto the space, the squared energy retained by PA is ∑ᵢ σᵢ²‖Puᵢ‖₂². Each projection weight is between zero and one, and the sum of the weights is at most k because P has rank at most k. The largest possible retained energy comes from allocating weight one to the k largest squared singular values. The span of their uᵢ achieves it, and its projection of A is Aₖ.
These optimality guarantees assume equal treatment of matrix entries or all unit input directions, respectively. A weighted entrywise loss, missing observations, or a prediction metric changes the optimization problem. A boundary tie σₖ=σₖ₊₁ can also yield more than one optimal choice of leading subspace.
Reconstruct the factors and test them#
import numpy as np
A = np.array([[2., 2.], [1., -1.], [2., 2.]])
U, s, Vh = np.linalg.svd(A, full_matrices=False)
A1 = (U[:, :1] * s[:1]) @ Vh[:1]
assert U.shape == (3, 2) and s.shape == (2,) and Vh.shape == (2, 2)
assert np.allclose((U * s) @ Vh, A)
assert np.isclose(np.linalg.norm(A - A1, ord="fro") ** 2, 2)
assert np.isclose(np.linalg.norm(A - A1, ord=2), np.sqrt(2))
The returned Vh contains right vectors as rows for real data. NumPy uses the conjugate transpose for complex data. Multiplying U * s scales columns. For batched input [B,m,n], multiply by s[..., None, :] to keep each batch's values on its own columns. full_matrices=False saves the extra basis vectors but still computes all r singular values. If only the spectrum matters, use compute_uv=False. PyTorch's torch.linalg.svd(A, full_matrices=False) has the same three-output shape convention. Eigenvectors and singular vectors may change sign, and repeated singular values permit basis rotations. Compare reconstructions, projectors, or residual norms instead of raw vectors. If backpropagation uses the vectors, inspect near-colliding values and the library's gradient limitations.
Download the lab above and run python3 06-svd-low-rank.py with NumPy installed. It also checks rank-zero truncation, batched reconstruction, and the truncated pseudoinverse. That inverse solves only the retained directions. For an output coordinate uᵢᵀy it divides by σᵢ and maps back along vᵢ. Truncating very small values avoids large noise amplification but discards information. Tune the cutoff against the application's noise and precision budget. On the zero matrix every rank gives zero error, while a retained-energy percentage is undefined because the denominator vanishes.
Distinguish rank, numerical rank, and compression rank
Exact rank counts how many independent outputs a map can produce. Numerical rank counts singular values distinguishable at a stated precision or tolerance. Compression rank is a choice you make to meet a quality, memory or latency budget. A matrix with singular values 10, 10⁻⁵, and zero has exact rank two. With an absolute cutoff of 10⁻⁴, the second mode is treated as zero. If the matrix entries are all multiplied by one hundred, the numerical answer under the same absolute cutoff can change. Choose the threshold in units that reflect the data or relative to an agreed scale, and record it with the fitted model.
In the least-squares lesson, the residual is orthogonal to the column space of A. The SVD tells you exactly what the column space contributes. For a response y, compute uᵢᵀy for each active output direction and return (uᵢᵀy/σᵢ)vᵢ in the input space. Any component of y orthogonal to the active uᵢ remains in the residual. The pseudoinverse sets null-space input coordinates to zero, giving the minimum-norm least-squares solution. Skipping additional weak modes changes the fitted subspace and can increase the residual in exchange for smaller coefficients.
Take A=diag(1,10⁻⁸) and observe y=(1,10⁻⁵)ᵀ. The untruncated inverse returns (1,1000)ᵀ. If the second measurement is noise, that estimate makes the noise look like a large signal. Retain only the first mode and you get (1,0)ᵀ, with an output residual of (0,10⁻⁵)ᵀ. Estimate the noise floor before preferring this trade-off. A reliable second measurement would change the decision.
Decide whether low rank helps production#
For a weight matrix with m output features and n input features, precombine U[:, :k] * s[:k], leaving factors with k(m+n) scalars. Reconstructing the dense matrix at startup forfeits the per-inference compute advantage. For row-batched inputs X with shape [B,n], multiply X @ Vh[:k].T to get [B,k], then multiply by the transpose of the combined left factor. Keep the original bias after both multiplications.
A 4096 × 2048 matrix stores 8,388,608 scalars. At rank 128 the factors store 128(4096+2048)=786,432 scalars, about 10.7 times fewer at the same precision. The theoretical multiply count shrinks by the same ratio. Two kernels add launch and intermediate-memory costs. Benchmark the real batch sizes and devices before reporting an inference speedup.
Evaluate several ranks on held-out traffic. Compare the residual norm, an absolute worst-case budget, and downstream quality sliced by important input groups. A small global residual can still degrade rare classes or exact decisions. Include the uncompressed model as the baseline, keep the weights and chosen rank versioned, and check whether error compounds across several compressed layers before switching all of them at once.
Inspect a failed compression experiment
Check shapes first, particularly which array axis carries the singular values. If the reconstructed matrix has the correct shape yet large error at full reduced rank, verify that the implementation scales columns of U and multiplies by Vᵀ. A rank-one output close to the original on sampled rows can still miss a whole mode. Compare the measured spectral residual against the first omitted singular value, then test the omitted direction directly when it has a meaningful interpretation.
For a dataset stored as rows, ask whether the goal is to preserve the raw entries or deviations from the mean. Raw SVD can devote its first component to a common offset. To preserve centered variation, subtract the feature mean, factor the centered data, and add the mean back when decoding. The next lesson turns that procedure into a fitted model.
Try it yourself
Pick the rank for two distinct error budgets
A matrix has singular values 8, 3, and 0.5. Find the smallest rank with worst unit-input error at most 1 and squared Frobenius residual at most 1.
Reveal solution
At rank one, the spectral error is 3 and the squared Frobenius error is 9.25. At rank two, they are 0.5 and 0.25, so rank two is the smallest passing both budgets.
Try it yourself
Find the missing null direction
A reduced SVD of a 2 by 5 matrix returns two positive singular values. How many independent input directions does the map send to zero?
Reveal solution
Rank is two and the input dimension is five, so rank–nullity gives three. Both returned right vectors describe active modes. The additional three right vectors of a full orthogonal basis span the null space.
Memory chart#
| Task | Rule |
|---|---|
| Apply the map | Project with the right basis, scale, and combine the left vectors |
| Reconstruct with NumPy | (U * s) @ Vh |
| Approximate with rank k | Keep the first k singular triplets |
| Bound unit-input error | Read the first omitted singular value |
| Measure squared entrywise error | Sum the squares of all omitted singular values |
| Validate deployment | Benchmark factors and measure downstream quality by slice |
Next, PCA, t-SNE, and UMAP uses the right basis of a centered data matrix to find principal components and introduces two nonlinear methods for inspecting neighborhoods.
References#
- Mathematics for Machine Learning, Sections 4.5–4.6 covers SVD geometry and truncation.
- Deep Learning, Sections 2.8–2.9 connects SVD to the pseudoinverse.
- NumPy SVD API documents reduced, full and stacked factors.
- PyTorch SVD API documents tensor shapes and differentiation caveats.