Singular value decomposition
奇异值分解
Factor rectangular maps into matched directions and stretches; verify shapes, numerical limits, and low-rank reconstruction errors.
svdDifferent bases for input and output
A matrix can turn two input measurements into three output coordinates. An eigenvector equation expects the input and output to inhabit the same space, so it is not even defined for that 3×2 matrix in the ordinary sense. SVD instead chooses one set of directions in the input space and another in the output space, with a nonnegative stretch between each matched pair.
Imagine mapping a unit circle into three dimensions. Its image may be an ellipse in a plane, a line segment, or a point. The singular values measure its principal stretches; the left singular vectors place the result in the output space. This geometric statement applies to any real rectangular matrix, including rank-deficient ones. MML, Sections 4.5–4.5.1
Full, reduced, and rank-based shapes
For , let and rank . A full SVD is
Here is m×m, is n×n, and is m×n, with singular values on its main diagonal and zeros elsewhere. Do not transpose only the symbol while keeping the wrong shape. Deep Learning, Section 2.8
| Form | U shape | Middle factor | V-transpose shape |
|---|---|---|---|
| Full | m×m | m×n | n×n |
| Economy, retaining p directions | m×p | p×p | p×n |
| Compact, retaining only positive values | m×r | r×r | r×n |
Naming conventions vary between texts and libraries; shapes state the intended operation unambiguously. The compact factors have orthonormal columns rather than necessarily being square orthogonal matrices.
Why does the factorization exist? is symmetric and . Its orthonormal eigenvectors have nonnegative eigenvalues. For each positive one, set to its square root and . Then
Here is one when and zero otherwise. Complete any missing zero-mode directions to orthonormal bases for the full form. The singular values are uniquely determined in sorted order, but signs and bases within repeated-value subspaces remain flexible. For a symmetric matrix, singular values are the absolute values of its eigenvalues; a negative eigenvalue does not become a negative singular value.
Factor a tall matrix with two columns
The following solver explicitly forms a 2×2 Gram matrix, finds its orthogonal directions, and normalizes their images. It is restricted to m×2 matrices with two numerically significant singular values. The mathematical SVD exists much more broadly; this short function deliberately rejects shapes and ranks it does not implement.
import math
def svd_two_columns(a, relative_cutoff=1e-10):
if len(a) < 2 or any(len(row) != 2 for row in a):
raise ValueError("an m-by-2 matrix with m >= 2 is required")
if any(not math.isfinite(x) for row in a for x in row):
raise ValueError("finite real entries required")
if not math.isfinite(relative_cutoff) or not 0 < relative_cutoff < 1:
raise ValueError("cutoff must be between zero and one")
scale = max(abs(x) for row in a for x in row)
if scale == 0:
raise ValueError("this teaching solver requires numerical rank two")
z = [[x/scale for x in row] for row in a]
p = sum(row[0]**2 for row in z)
q = sum(row[0]*row[1] for row in z)
r = sum(row[1]**2 for row in z)
theta = .5*math.atan2(2*q,p-r)
c,s = math.cos(theta),math.sin(theta)
vectors = [[c,s],[-s,c]]
images = [[row[0]*v[0]+row[1]*v[1] for row in z] for v in vectors]
lengths = [math.hypot(*image) for image in images]
order = sorted(range(2), key=lambda i: lengths[i], reverse=True)
if min(lengths) <= relative_cutoff*max(lengths):
raise ValueError("this teaching solver requires numerical rank two")
ucols = [[x/lengths[i] for x in images[i]] for i in order]
if abs(sum(x*y for x,y in zip(*ucols))) > 1e-8:
raise ArithmeticError("inaccurate basis; use a library SVD")
values = [scale*lengths[i] for i in order]
if not all(math.isfinite(x) for x in values):
raise ArithmeticError("singular value overflow")
return [list(row) for row in zip(*ucols)], values, [vectors[i] for i in order]
def reconstruct(u, values, vt, keep=2):
return [[sum(u[i][k]*values[k]*vt[k][j] for k in range(keep))
for j in range(2)] for i in range(len(u))]
a = [[3.,1.],[1.,3.],[0.,0.]]
u, values, vt = svd_two_columns(a)
assert all(abs(x-y)<1e-12 for x,y in zip(values,[4.,2.]))
restored = reconstruct(u,values,vt)
assert max(abs(x-y) for row,other in zip(a,restored) for x,y in zip(row,other)) < 1e-12
rank_one = reconstruct(u,values,vt,keep=1)
error_squared = sum((x-y)**2 for row,other in zip(a,rank_one) for x,y in zip(row,other))
assert abs(error_squared-4.) < 1e-12
for bad in ([[1.,1.],[2.,2.]], [[0.,0.],[0.,0.]], [[1.,2.,3.]]):
try:
svd_two_columns(bad)
except ValueError:
pass
else:
raise AssertionError("unsupported shape or rank accepted")
For a fixed two columns, the routine takes arithmetic operations and working space. It reconstructs with singular values four and two. Dropping the second term leaves squared Frobenius error four. A general dense economy SVD typically costs arithmetic operations; requesting complete large orthogonal factors can require additional work and storage.
A useful proof route is not always a good numerical route
Forming squares singular values. For full column rank, its 2-norm condition number is the square of that of , making small directions harder to resolve. The code’s cutoff and orthogonality check acknowledge this limitation; use a mature SVD implementation for numerical work instead of extending this Gram example indiscriminately.
SVD also gives a controlled low-rank approximation. Keeping the first k terms yields
The first error is worst-case amplification; the second sums squared entrywise errors. The spectral-norm approximation is optimal among matrices of rank at most k. Orthogonal invariance of the Frobenius norm gives the displayed sum-of-squares error. If k reaches r, reconstruction is exact in exact arithmetic. MML, Section 4.6 and Theorem 4.25
A small reconstruction error does not establish predictive value or semantic importance. Features with larger units can dominate the decomposition, and a direction important to a rare class may carry little total energy. Centering, scaling, missing-data handling, and task evaluation remain separate decisions.
Check a factorization before trusting it
- For a 7×3 matrix, what are the economy factor shapes? Answer: 7×3, 3×3, and 3×3 for U, the middle factor, and V-transpose.
- Are the singular values of negative? Answer: no; they are five and two. The sign is carried by a vector direction.
- What does rank-one truncation lose in the code example? Answer: spectral error two and squared Frobenius error four.
- Does a rank-one matrix lack an SVD because this function rejects it? Answer: no. That is an implementation restriction, not a theorem about SVD.
From decomposition to learning
The pseudoinverse uses reciprocals of nonzero singular values to solve least-squares problems. PCA applies related geometry to centered data; low-rank model compression uses truncated factors inside larger systems. Compare reconstruction, task performance, numerical stability, and storage cost separately. An algebraically optimal matrix approximation need not be an optimal deployed model.
Make a prediction, then check
With singular values 4 and 2, what is the squared Frobenius error after rank-one truncation?
Learning objectives
- Track full, economy, and compact SVD shapes and nonzero directions.
- Calculate truncation errors and explain the numerical limitations of a Gram matrix.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - Deep Learning — Chapter 2: Linear Algebra
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, derivation and numerical checks, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Checked exact Gram invariants, orthogonality, reconstruction and rank-one errors for 120 integer tall-matrix inputs, plus explicit zero/rank-one rejection tests.
- Distinguished full/economy/compact shapes, defined delta notation, and stated the two-column teaching function’s rank restriction and the squared-conditioning issue of Gram methods.
- Compared claims, assumptions, examples, exercises and citations across languages; structural validation additionally compares display equations, code and source lists.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · §§4.5–4.6, printed pp.119–124 and 129–132, SVD construction and spectral-norm truncation theorem
- Deep Learning — Chapter 2: Linear Algebra · §2.8, rectangular shapes and singular vectors
Related topics