The singular value decomposition
| Problem | Factor any matrix as with , unitary and diagonal and non-negative; compute singular values, low-rank approximations, ranks, condition numbers and pseudoinverses |
| Devised by | Eugenio Beltrami (1873) and Camille Jordan (1874); James Joseph Sylvester (1889); Erhard Schmidt (1907); Carl Eckart and Gale Young (1936), best approximation; Magnus Hestenes (1958), one-sided Jacobi; Gene Golub and William Kahan (1965), bidiagonalisation; Golub and Christian Reinsch (1970), the algorithm; James Demmel and Krešimir Veselić (1992), relative accuracy of Jacobi; Zlatko Drmač and Veselić (2008), preconditioned Jacobi |
| Accuracy | Golub-Kahan: backward stable, singular values accurate to about in absolute terms. One-sided Jacobi: small singular values of matrices of the form ( well conditioned, diagonal) to high relative accuracy |
| Cost | About flops for singular values, roughly with vectors; Jacobi several times more |
| Read first | Symmetric and general eigensolvers, Linear least squares |
| API | SVD (svd), SvdJacobi (svd_jacobi); reference: naive_svd |
Overview
Every matrix, square or not, maps the unit sphere onto an ellipsoid. The singular value decomposition finds its axes: the right singular vectors are the directions that map to the axes, the left singular vectors are the axis directions, and the singular values are their lengths, . The SVD is the most informative matrix factorisation. It gives the 2-norm (), the condition number (), the numerical rank (the number of singular values above the noise), orthonormal bases for the range and null space, the pseudoinverse, and the best low-rank approximations.
Its applications are everywhere: principal component analysis, latent semantic indexing, recommender systems, image and signal compression, the solution of ill-posed problems by truncation, total least squares, the Procrustes problem of aligning two point sets, and the analysis of control systems.
Where it is used
The SVD is the most useful single matrix factorisation.
- Data compression and denoising. Low-rank approximation of images, signals and data tables.
- Recommender systems and search. Latent semantic analysis and collaborative filtering are SVD of a ratings or term-document matrix.
- Pseudoinverse and least squares. Stable solutions of ill-conditioned problems in tomography, geophysics and system identification.
- Principal component analysis, rank and conditioning. Principal components are singular vectors; the ratio of the largest to smallest singular value is the condition number.
- Robotics and vision. Estimating rotations from point sets and camera geometry.
History
Eugenio Beltrami (1873) and Camille Jordan (1874) independently discovered the decomposition for square real matrices, motivated by bilinear forms; James Joseph Sylvester (1889) rediscovered it, and Erhard Schmidt (1907) extended it to integral operators, proving the approximation property that Carl Eckart and Gale Young (1936) later stated for matrices, in a paper on psychometrics. As a computational tool it waited for Gene Golub and William Kahan (1965), who showed how to reduce a matrix to bidiagonal form by Householder reflections, and Golub and Christian Reinsch (1970), whose algorithm became LINPACK’s and LAPACK’s. Magnus Hestenes (1958) had already proposed orthogonalising columns by rotations; James Demmel and Krešimir Veselić (1992) proved its superior relative accuracy, and Zlatko Drmač and Veselić (2008) made it competitive in speed by preconditioning with QR.
The idea
The decomposition
Every matrix, of any shape, can be written as a rotation, followed by a scaling along the coordinate axes, followed by another rotation. For of size with , the (thin) singular value decomposition is
where is an unitary matrix (orthogonal, in the real case), is with orthonormal columns, and with . The are the singular values, and the columns and the right and left singular vectors.
Multiplying the decomposition on the right by gives : the matrix maps each of the orthonormal directions onto an orthogonal direction , stretched by . In geometric terms, maps the unit sphere onto an ellipsoid whose semi-axes have lengths and directions . Much useful information can be read off: the largest singular value is the norm , the number of nonzero singular values is the rank, and the ratio is the condition number.
The connection with eigenvalues, and why not to use it. Substituting the decomposition,
So the are the eigenvectors of the Hermitian matrix and the are its eigenvalues.
Why every matrix has an SVD. Run the argument in the other direction. The matrix is Hermitian, so it has orthonormal eigenvectors , and its eigenvalues are non-negative, because . Write them as with in decreasing order. For each define . These are orthonormal: . If some then (since ), and the corresponding can be any vectors that complete the orthonormal set. Then for every , which in matrix form is , that is, . This suggests computing the SVD with a symmetric eigensolver. The reference crate does, and shows the flaw. An eigensolver determines eigenvalues to an absolute accuracy of about times the largest, here . A singular value with , that is , has its square buried beneath that rounding error and is lost. This is the squaring of the condition number again, as in the normal equations. The methods below work on itself.
Low-rank approximation
The sum expresses as a sum of rank-one matrices, in decreasing order of importance. Keeping only the first terms gives the truncated SVD . The Eckart-Young theorem says that no matrix of rank is closer to , in either the 2-norm or the Frobenius norm, and that the error is the first singular value left out: .
Why no rank- matrix does better (2-norm). The null space of has dimension at least , and the span of has dimension , so together they exceed and the two subspaces share a nonzero vector . For it , and . Hence , so , and attains it.
This is the basis of data compression and of principal component analysis. If the singular values decay quickly, a few terms capture almost everything, and storing pairs of vectors takes numbers instead of . Smooth functions sampled on a grid give matrices of this kind:
Figure 7.7. Low-rank approximation.
The error of the truncated SVD follows exactly, down to the level of rounding.
Golub-Kahan bidiagonalisation
The standard algorithm follows the two-phase plan of the eigensolvers: a finite reduction to a sparse form, then an iteration on that form.
Phase one. For the SVD the two sides of can be transformed by different orthogonal matrices, which gives more freedom than a similarity. A Householder reflection from the left zeroes the first column below the diagonal; one from the right zeroes the first row beyond the superdiagonal; and so on, alternately. The result is upper bidiagonal form, , nonzero only on the diagonal and the superdiagonal, in about flops. (Diagonal unitary scalings then make real and non-negative.) Because and are orthogonal, the singular values of are those of .
Phase two. The matrix is symmetric and tridiagonal, and its eigenvalues are the
squared singular values, so the tridiagonal QR algorithm could be applied to it. But forming
would square the condition number, the very thing to be avoided. The
implicit-shift QR algorithm on the bidiagonal performs the same step without forming it. Each
step applies Givens rotations alternately from the right and from the left of , chasing a
bulge down the matrix, and the result is exactly the that a QR step with Wilkinson’s shift on
would correspond to. Negligible superdiagonal entries split the problem into smaller
ones, and zero diagonal entries are chased out. The rotations accumulate into and . This
is the default method (svd), and that of LAPACK’s gesvd.
One-sided Jacobi
One-sided Jacobi (Hestenes) works on the columns of directly: for each pair of columns , , a plane rotation of the two makes them orthogonal; it is the two-sided Jacobi method applied implicitly to , without forming it. Sweeping until all pairs are orthogonal leaves : the column norms are the singular values. Demmel and Veselić showed that its relative errors depend on the conditioning of in , not of : if the columns of have very different scales but the matrix of normalised columns is well conditioned, every singular value, however small, is computed to high relative accuracy. Golub-Kahan guarantees only absolute accuracy .
The library’s svd_jacobi first factorises with column pivoting and applies Jacobi to , whose columns are already nearly
orthogonal, so that few sweeps are needed (the preconditioning of Drmač and Veselić). On a matrix with
column scales from 1 to in scrambled order, compared with singular values computed by mpmath at 50 digits:
Figure 7.8. Relative accuracy of the SVD methods.
Jacobi is accurate to rounding for every singular value; Golub-Kahan loses up to eight digits of the small ones, within its absolute guarantee . The reference route through does better here than the general warning suggests, because it diagonalises by the Jacobi eigenvalue method, which is itself relatively accurate for such graded matrices; for a matrix whose small singular values are not produced by column scaling, it loses everything below .
Speed
Figure 7.9. SVD speed.
Golub-Kahan is the fastest; Jacobi with vectors costs two to five times as much. Against OpenBLAS the Golub-Kahan SVD is faster (0.4 to 0.8 of its time in the README’s benchmarks).
Algorithm
svd (Golub-Kahan).
- Orient. If the matrix is wider than it is tall, work with and exchange the roles of and at the end.
- Bidiagonalise by Householder reflections applied alternately from the left and the right, storing the reflectors.
- Make real by diagonal unitary scalings.
- Iterate. Apply implicit-shift QR steps to the bidiagonal matrix. Before each step, set negligible superdiagonal entries to zero and work on the lowest block that is still unreduced; chase out any zero on the diagonal. If vectors are wanted, accumulate the rotations.
- Finish. Change the sign of any negative diagonal entry (and of the matching vector), and sort the singular values into descending order.
- Form and by applying the stored reflectors, in compact WY blocks, to the accumulated rotations.
The cost is , dominated by the bidiagonalisation and the forming of the vectors.
svd_jacobi.
- Precondition. For more than a few columns, factor with column pivoting and continue with , whose columns are already nearly orthogonal.
- Sweep. For every pair of columns : compute their norms and their inner product; if the inner product is not negligible relative to the norms, apply the plane rotation that makes the two columns orthogonal, to the working matrix and to the accumulated rotations.
- Repeat the sweep until one passes without any rotation.
- Read off. The singular values are the column norms, and the normalised columns are singular vectors. Sort them, and map them back through and the permutation to obtain and for the original matrix.
Implementation
Implicit-shift QR on the bidiagonal:
/// Implicit-shift QR on the real upper bidiagonal with diagonal `d` and super-diagonal `e`,
/// accumulating the left rotations into the rows of `ut` and the right ones into the rows of `vt`.
fn bidiagonal_qr<T: Scalar>(d: &mut [f64], e: &mut [f64], mut ut: Option<&mut Mat<T>>, mut vt: Option<&mut Mat<T>>) -> Result<()> {
let n = d.len();
if n < 2 {
return Ok(());
}
let scale = d.iter().chain(e.iter()).fold(0.0f64, |m, v| m.max(v.abs()));
let tiny = f64::EPSILON * scale;
let mut hi = n - 1;
let mut iterations = 0usize;
while hi > 0 {
for i in 0..hi {
if e[i].abs() <= f64::EPSILON * (d[i].abs() + d[i + 1].abs()) || e[i].abs() <= f64::MIN_POSITIVE {
e[i] = 0.0;
}
}
if e[hi - 1] == 0.0 {
hi -= 1;
continue;
}
let mut lo = hi - 1;
while lo > 0 && e[lo - 1] != 0.0 {
lo -= 1;
}
iterations += 1;
if iterations > 75 * n {
return Err(LinalgError::NoConvergence("the bidiagonal QR iteration"));
}
// A negligible diagonal entry: rotate its row's super-diagonal entry out to the right
// (or, at the bottom, its column's entry out upwards), splitting the block.
if let Some(i) = (lo..hi).find(|&i| d[i].abs() <= tiny) {
d[i] = 0.0;
let mut f = e[i];
e[i] = 0.0;
for j in i + 1..=hi {
let (c, s, r) = rotation(d[j], f);
d[j] = r;
if j < hi {
f = -s * e[j];
e[j] *= c;
}
if let Some(ut) = ut.as_deref_mut() {
rotate(ut, j, i, c, s);
}
}
continue;
}
if d[hi].abs() <= tiny {
d[hi] = 0.0;
let mut f = e[hi - 1];
e[hi - 1] = 0.0;
for j in (lo..hi).rev() {
let (c, s, r) = rotation(d[j], f);
d[j] = r;
if j > lo {
f = -s * e[j - 1];
e[j - 1] *= c;
}
if let Some(vt) = vt.as_deref_mut() {
rotate(vt, j, hi, c, s);
}
}
continue;
}
// Wilkinson shift from the trailing 2 × 2 block of BᵀB.
let t11 = d[hi - 1] * d[hi - 1] + if hi - 1 > lo { e[hi - 2] * e[hi - 2] } else { 0.0 };
let t12 = d[hi - 1] * e[hi - 1];
let t22 = d[hi] * d[hi] + e[hi - 1] * e[hi - 1];
let half = (t11 - t22) / 2.0;
let sign = if half >= 0.0 { 1.0 } else { -1.0 };
let mu = t22 - t12 * t12 / (half + sign * half.hypot(t12));
let (mut y, mut z) = (d[lo] * d[lo] - mu, d[lo] * e[lo]);
for k in lo..hi {
// From the right on columns k, k+1: zero z against y.
let (c, s, r) = rotation(y, z);
if k > lo {
e[k - 1] = r;
}
let (dk, ek, dk1) = (d[k], e[k], d[k + 1]);
let (b_kk, b_kk1, bulge, b_k1k1) = (c * dk + s * ek, -s * dk + c * ek, s * dk1, c * dk1);
if let Some(vt) = vt.as_deref_mut() {
rotate(vt, k, k + 1, c, s);
}
// From the left on rows k, k+1: zero the bulge below the diagonal.
let (c2, s2, r2) = rotation(b_kk, bulge);
d[k] = r2;
e[k] = c2 * b_kk1 + s2 * b_k1k1;
d[k + 1] = -s2 * b_kk1 + c2 * b_k1k1;
if k + 1 < hi {
y = e[k];
z = s2 * e[k + 1];
e[k + 1] *= c2;
}
if let Some(ut) = ut.as_deref_mut() {
rotate(ut, k, k + 1, c2, s2);
}
}
}
Ok(())
}
One-sided Jacobi:
/// One-sided Jacobi on a tall (`m ≥ n`) matrix.
fn jacobi_tall<T: Scalar>(a: &Mat<T>) -> Result<ThinSvd<T>> {
let (m, n) = (a.rows, a.cols);
// Work on columns: store A transposed so each column is contiguous.
let mut cols: Vec<Vec<T>> = (0..n).map(|j| (0..m).map(|i| a.at(i, j)).collect()).collect();
let mut v: Vec<Vec<T>> = (0..n).map(|j| (0..n).map(|i| if i == j { T::one() } else { T::zero() }).collect()).collect();
let tol = f64::EPSILON * (m as f64).sqrt();
let mut converged = false;
for _sweep in 0..60 {
let mut rotated = false;
// Squared column norms, recomputed each sweep and updated exactly through each rotation.
let mut norms2: Vec<f64> = cols.iter().map(|c| dot_conj(c, c).re()).collect();
for p in 0..n {
for q in p + 1..n {
let (alpha, beta) = (norms2[p], norms2[q]);
let gamma = dot_conj(&cols[q], &cols[p]); // Σ conj(a_p) a_q
let g = gamma.abs();
if g == 0.0 || g <= tol * (alpha * beta).sqrt() {
continue;
}
rotated = true;
// Remove the phase of γ from column q, then apply a real rotation.
let phase = gamma.scale(1.0 / g);
let zeta = (beta - alpha) / (2.0 * g);
// The smaller root of t² + 2ζt − 1 = 0 (the rotation angle below π/4).
let sign = if zeta >= 0.0 { 1.0 } else { -1.0 };
let t = sign / (zeta.abs() + (1.0 + zeta * zeta).sqrt());
let c = 1.0 / (1.0 + t * t).sqrt();
let s = c * t;
norms2[p] = alpha - t * g;
norms2[q] = beta + t * g;
let phase_conj = phase.conj();
for x in [&mut cols, &mut v] {
let (left, right) = x.split_at_mut(q);
let (cp, cq) = (&mut left[p], &mut right[0]);
if T::IS_COMPLEX {
for (u, w) in cp.iter_mut().zip(cq.iter_mut()) {
let wq = *w * phase_conj;
let up = *u;
*u = up.scale(c) - wq.scale(s);
*w = up.scale(s) + wq.scale(c);
}
} else {
// Real data: the phase φ is ±1, folded into the coefficients of w.
let (s_phi, c_phi) = (s * phase.re(), c * phase.re());
for (u, w) in cp.iter_mut().zip(cq.iter_mut()) {
let (up, wp) = (*u, *w);
*u = up.scale(c) - wp.scale(s_phi);
*w = up.scale(s) + wp.scale(c_phi);
}
}
}
}
}
if !rotated {
converged = true;
break;
}
}
if !converged {
return Err(LinalgError::NoConvergence("the one-sided Jacobi SVD"));
}
let norms: Vec<f64> = cols.iter().map(|c| c.iter().map(|x| x.abs_sqr()).sum::<f64>().sqrt()).collect();
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&i, &j| norms[j].total_cmp(&norms[i]));
let mut u = Mat::<T>::zeros(m, n);
let mut vm = Mat::<T>::zeros(n, n);
let mut sigma = Vec::with_capacity(n);
for (k, &j) in order.iter().enumerate() {
sigma.push(norms[j]);
for i in 0..m {
*u.at_mut(i, k) = if norms[j] > 0.0 { cols[j][i].scale(1.0 / norms[j]) } else { T::zero() };
}
for i in 0..n {
*vm.at_mut(i, k) = v[j][i];
}
}
// Columns of U for zero singular values are completed to an orthonormal set.
complete_columns(&mut u, sigma.iter().filter(|&&s| s > 0.0).count());
Ok(ThinSvd { u, sigma, v: vm })
}
The QR preconditioning:
/// The thin SVD by one-sided Jacobi (wide matrices through their adjoint): slower than
/// Golub-Kahan, but it finds small singular values to high *relative* accuracy.
///
/// Larger matrices are first factorised as `A P = Q R` with column pivoting; one-sided Jacobi
/// then runs on `Rᴴ`, whose columns are already close to orthogonal, so it converges in a few
/// sweeps (the preconditioning of Drmač and Veselić). With `Rᴴ = U₁ Σ W₁ᴴ`,
/// `A = (Q W₁) Σ (P U₁)ᴴ`.
pub(crate) fn thin_svd_jacobi<T: Scalar>(a: &Mat<T>) -> Result<ThinSvd<T>> {
if a.rows < a.cols {
let ThinSvd { u, sigma, v } = thin_svd_jacobi(&a.adjoint())?;
return Ok(ThinSvd { u: v, sigma, v: u });
}
let n = a.cols;
if n < PRECONDITION_FROM {
return jacobi_tall(a);
}
let qr = householder_pivoted(a);
let ThinSvd { u: u1, sigma, v: w1 } = jacobi_tall(&qr.upper().adjoint())?;
let u = qr.apply_to_top(&w1);
let mut v = Mat::<T>::zeros(n, n);
for (j, &p) in qr.permutation.iter().enumerate() {
v.data[p * n..(p + 1) * n].copy_from_slice(&u1.data[j * n..(j + 1) * n]);
}
Ok(ThinSvd { u, sigma, v })
}
The textbook route, for comparison:
/// The SVD via the Jacobi eigenvalue method applied to `AᵀA`.
pub fn svd_via_normal_matrix(a: &Array2<f64>) -> Result<Svd, Error> {
let (m, n) = a.dim();
let eigen = crate::jacobi_eigenvalue::jacobi_eigen(&a.t().dot(a), 1e-15)?;
// Jacobi orders eigenvalues ascending; singular values are conventionally descending.
let order: Vec<usize> = (0..n).rev().collect();
let singular_values: Array1<f64> = order.iter().map(|&i| eigen.values[i].max(0.0).sqrt()).collect();
let v = Array2::from_shape_fn((n, n), |(i, j)| eigen.vectors[[i, order[j]]]);
let av = a.dot(&v);
let u = Array2::from_shape_fn((m, n), |(i, j)| {
if singular_values[j] > 0.0 { av[[i, j]] / singular_values[j] } else { 0.0 }
});
Ok(Svd { u, singular_values, v })
}
svd(calc_u, calc_vt)returns(Option<U>, σ, Option<Vᴴ>)with full square and when requested, in the layout ofndarray-linalg; singular values descend.- Least squares uses the SVD for rank-deficient systems.
In practice
//! The singular value decomposition: low-rank approximation, rank and the pseudoinverse.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_svd`.
use lib_jsl_linalg::{SVD, SvdJacobi};
use lib_jsl_linalg_reference::naive_svd::svd_via_normal_matrix;
use ndarray::{Array2, array, s};
fn main() {
// Ratings of 4 films by 5 viewers: two "tastes" explain most of the data.
let ratings = array![[5.0, 4.0, 1.0, 1.0], [4.0, 5.0, 1.0, 2.0], [1.0, 1.0, 5.0, 4.0], [2.0, 1.0, 4.0, 5.0], [3.0, 3.0, 3.0, 3.0]];
let (u, sigma, vt) = ratings.svd(true, true).unwrap();
let (u, vt) = (u.unwrap(), vt.unwrap());
println!("singular values: {sigma:.4}");
// The best rank-2 approximation keeps the two largest singular triplets (Eckart-Young).
let rank2 = u.slice(s![.., ..2]).dot(&Array2::from_diag(&sigma.slice(s![..2]).to_owned())).dot(&vt.slice(s![..2, ..]));
println!("rank-2 approximation:\n{rank2:.2}");
let error = (&ratings - &rank2).svd(false, false).unwrap().1[0];
println!("‖A − A₂‖₂ = {error:.4} = σ₃ = {:.4}", sigma[2]);
// The 2-norm condition number.
println!("κ₂ = σ₁/σ₄ = {:.2}", sigma[0] / sigma[3]);
// Jacobi and the textbook route through AᵀA agree with Golub-Kahan on this well-scaled matrix.
println!("svd_jacobi: {:.4}", ratings.svd_jacobi(false, false).unwrap().1);
println!("reference (AᵀA): {:.4}", svd_via_normal_matrix(&ratings).unwrap().singular_values);
}
Strengths
- Backward stable and the most informative factorisation: rank, norms, conditioning, bases, best approximations.
- Two methods: the fast Golub-Kahan, and the relatively accurate Jacobi.
Weaknesses
- Dense and : for a few singular triplets of a large matrix, iterative (Lanczos) or randomised methods are far cheaper.
- No divide-and-conquer bidiagonal solver, which LAPACK uses for large matrices with vectors.
Exercises
- Show that the singular values of are the square roots of the eigenvalues of , and that .
- Prove the Eckart-Young theorem in the 2-norm.
- Compute the SVD of an image (any matrix of pixel intensities) and plot the reconstruction from triplets.
- Show that the pseudoinverse gives the minimum-norm least-squares solution.
- Construct a matrix with singular values and without column scaling, and compare
svd,svd_jacobiand the reference route through .
Hints and answers
- , so its eigenvalues are . with equality for .
- for the truncated SVD. For any rank- matrix its null space has dimension at least , so it meets in a nonzero , giving .
- Reconstruction from triplets stores numbers; plot the error against and note how quickly the singular values of natural images decay.
- Minimising gives with ; the minimum-norm choice sets the components of belonging to zero singular values to 0, which is .
- Forming squares the ratio, so the second eigenvalue is below rounding relative to and is lost. Golub-Kahan (
svd) finds the small singular value with an absolute error near , i.e. only a few correct digits; the one-sided Jacobi method (svd_jacobi) can retain high relative accuracy for well-scaled problems.
Further reading
- G. H. Golub and W. Kahan, “Calculating the singular values and pseudo-inverse of a matrix”, SIAM Journal on Numerical Analysis B2 (1965) 205–224.
- G. H. Golub and C. Reinsch, “Singular value decomposition and least squares solutions”, Numerische Mathematik 14 (1970) 403–420.
- J. Demmel and K. Veselić, “Jacobi’s method is more accurate than QR”, SIAM Journal on Matrix Analysis and Applications 13 (1992) 1204–1245.
- Z. Drmač and K. Veselić, “New fast and accurate Jacobi SVD algorithm I”, SIAM Journal on Matrix Analysis and Applications 29 (2008) 1322–1342.
- G. W. Stewart, “On the early history of the singular value decomposition”, SIAM Review 35 (1993) 551–566.