AI Wiki中文/EN

Singular value decomposition

奇异值分解

Factor rectangular maps into matched directions and stretches; verify shapes, numerical limits, and low-rank reconstruction errors.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Different 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 A∈Rm×nA\in\mathbb R^{m\times n}, let p=min⁡(m,n)p=\min(m,n) and rank r≤pr\leq p. A full SVD is

A=UΣV⊤,U⊤U=Im,V⊤V=In,σ1≥⋯≥σp≥0.A=U\Sigma V^\top,\qquad U^\top U=I_m,\quad V^\top V=I_n,\quad \sigma_1\geq\cdots\geq\sigma_p\geq0.

Here UU is m×m, VV is n×n, and Σ\Sigma 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

FormU shapeMiddle factorV-transpose shape
Fullm×mm×nn×n
Economy, retaining p directionsm×pp×pp×n
Compact, retaining only positive valuesm×rr×rr×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? A⊤AA^\top A is symmetric and x⊤A⊤Ax=∥Ax∥22≥0x^\top A^\top Ax=\|Ax\|_2^2\geq0. Its orthonormal eigenvectors viv_i have nonnegative eigenvalues. For each positive one, set σi\sigma_i to its square root and ui=Avi/σiu_i=Av_i/\sigma_i. Then

Avi=σiui,ui⊤uj=vi⊤A⊤Avjσiσj=δij(σi,σj>0).Av_i=\sigma_i u_i,\qquad u_i^\top u_j=\frac{v_i^\top A^\top Av_j}{\sigma_i\sigma_j}=\delta_{ij}\quad(\sigma_i,\sigma_j>0).

Here δij\delta_{ij} is one when i=ji=j 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 O(m)O(m) arithmetic operations and working space. It reconstructs [311300]\begin{bmatrix}3&1\\1&3\\0&0\end{bmatrix} with singular values four and two. Dropping the second term leaves squared Frobenius error four. A general dense economy SVD typically costs O(mnmin⁡(m,n))O(mn\min(m,n)) 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 A⊤AA^\top A squares singular values. For full column rank, its 2-norm condition number is the square of that of AA, 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

Ak=∑i=1kσiuivi⊤,∥A−Ak∥2=σk+1,∥A−Ak∥F2=∑i=k+1rσi2(0≤k<r).A_k=\sum_{i=1}^{k}\sigma_i u_i v_i^\top,\qquad \|A-A_k\|_2=\sigma_{k+1},\qquad \|A-A_k\|_F^2=\sum_{i=k+1}^{r}\sigma_i^2\quad(0\leq k<r).

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

  1. 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.
  2. Are the singular values of diag⁡(−5,2)\operatorname{diag}(-5,2) negative? Answer: no; they are five and two. The sign is carried by a vector direction.
  3. What does rank-one truncation lose in the code example? Answer: spectral error two and squared Frobenius error four.
  4. 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?

Choose one answer

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

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.