The Math Behind the Methods

Singular Value Decomposition for Compression and Latent Factors

Understand what SVD does to a matrix, work a two by two case by hand, and use truncation to compress data and find latent factors.

Key takeaways

  • SVD factors A into U Σ Vᵀ, with orthonormal columns in U and V and nonnegative singular values on the diagonal of Σ.
  • The matrix equals a sum of rank-one pieces, ordered from largest to smallest singular value.
  • Keeping the first k pieces gives the best rank-k approximation in the Frobenius and spectral norms.
  • Storage drops from m · n numbers to about k(m + n + 1) when k is small.
  • Latent factors summarize patterns of co-variation; they need not have a clear meaning.

The singular value decomposition, or SVD, writes any real matrix as a sum of simple pieces, each made from one column pattern, one row pattern and a nonnegative strength. Sort the pieces by strength and keep only the first few, and you have a compressed version of the matrix. The patterns that survive are often called latent factors.

Every real matrix has an SVD, square or not. That generality is why it appears in dimension reduction, recommendation, text analysis and least squares.

The three factors

For A with shape (m, n) and rank r, the compact form is:

A  =  U      Σ      Vᵀ
(m,n) (m,r)  (r,r)  (r,n)

The columns of U are left singular vectors: perpendicular unit vectors of length m. The columns of V are right singular vectors of length n. The diagonal matrix Σ holds the singular values σ₁ ≥ σ₂ ≥ ... ≥ σ_r > 0.

Geometrically, multiplying by A does three things in turn. Vᵀ rotates or reflects the input, Σ stretches along the axes, and U places the result in the output space. A unit circle turns into an ellipse whose half-axis lengths are the singular values.

The same content can be written as a sum:

A = σ₁ u₁ v₁ᵀ + σ₂ u₂ v₂ᵀ + ... + σ_r u_r v_rᵀ

Each term u vᵀ is an m by n matrix of rank one.

A two by two case by hand

Take A with rows (3, 0) and (4, 5). The right singular vectors are eigenvectors of AᵀA, and the singular values are square roots of its eigenvalues.

AᵀA = [[25, 20], [20, 25]]
eigenvalues: 45 and 5          σ₁ = √45 ≈ 6.708,  σ₂ = √5 ≈ 2.236
v₁ = (1, 1)/√2                 v₂ = (1, −1)/√2
u₁ = A v₁ / σ₁ = (1, 3)/√10
u₂ = A v₂ / σ₂ = (3, −1)/√10

The first rank-one piece is σ₁ u₁ v₁ᵀ, which works out to rows (1.5, 1.5) and (4.5, 4.5). The remainder A minus that piece has rows (1.5, −1.5) and (−0.5, 0.5). Its squared entries add to 2.25 + 2.25 + 0.25 + 0.25 = 5, which is exactly σ₂².

What the factors tell you about a matrix

The decomposition reads off several properties directly.

Property In terms of singular values
Rank Number of nonzero singular values
Largest stretch of any unit vector σ₁
Frobenius norm Square root of the sum of σ²
Absolute value of the determinant (square case) Product of all singular values
Sensitivity of solving Ax = b Ratio of largest to smallest singular value

In the worked example, the product √45 · √5 = √225 = 15, which matches the determinant 3 · 5 − 0 · 4 = 15.

The right singular vectors with zero singular value, which exist when the columns are dependent, span the null space: inputs that A sends to zero. They appear in the full form of the decomposition, where U and V are square and the extra directions are included. The compact and reduced forms omit some or all of them, which saves memory.

In floating point, an exactly zero singular value rarely occurs. Software decides numerical rank by counting values above a small tolerance relative to σ₁, so the answer depends on the tolerance and on the scale of noise in your data.

Truncation and its error

Keeping only the first k terms gives A_k. The squared Frobenius norm of a matrix, the sum of its squared entries, splits neatly across singular values.

‖A‖²        = σ₁² + σ₂² + ... + σ_r²
‖A − A_k‖²  = σ_{k+1}² + ... + σ_r²

In the example, the total is 9 + 0 + 16 + 25 = 50 = 45 + 5. Rank one keeps 45/50 = 90% of the squared size.

No other matrix of rank k comes closer in this norm. This result, usually called the Eckart-Young theorem, is why truncated SVD is the reference point for low-rank approximation.

Compression arithmetic

A full m by n matrix stores m · n numbers. A rank-k version stores k columns of U, k rows of Vᵀ and k singular values: k(m + n + 1) numbers.

For a 1,000 by 500 matrix at k = 20, that is 20 · 1,501 = 30,020 numbers instead of 500,000, about 16.7 times fewer. Whether the result is good enough depends on how fast the singular values fall.

Truncated SVD as stacked patterns, strongest first
Leading terms Broad structure shared across many rows and columns. Middle terms Finer patterns that matter for some rows or columns. Small terms Often noise or detail you may choose to drop. Leading terms Broad structure shared across many rows and columns. Middle terms Finer patterns that matter for some rows or columns. Small terms Often noise or detail you may choose to drop.

Images show this well if you treat a grayscale picture as a matrix. A few terms give a blurry outline, and more terms sharpen it. Dedicated image formats compress far better, so view this as a teaching example.

Latent factors

Suppose A holds how many times each user played each film clip, with users as rows. A rank-k approximation describes user i by a vector of k numbers and clip j by another vector of k numbers, and predicts the entry from their dot product.

The k coordinates are the latent factors. One may happen to separate comedies from documentaries. Others may be mixtures nobody can name. Because the factors are constrained to be orthogonal and are ordered by strength, their individual meaning is partly an artifact of the method.

There is a major catch. Classical SVD needs every entry. In a ratings table most entries are missing, and filling them with zeros tells the model that unseen items were disliked. Recommender systems therefore usually fit the two factor matrices on observed entries only, with regularization, as shown in matrix factorization for ratings. With implicit signals such as clicks, unobserved entries are often included with low confidence. The choice is a modeling assumption to state openly.

Text, noise and other uses

In latent semantic analysis, SVD is applied to a document-by-term matrix of counts or TF-IDF weights. Documents that use related words can end up close in the reduced space even when they share few exact terms.

SVD also underlies principal component analysis. If X_c is a centered data matrix with n rows and X_c = U Σ Vᵀ, then the columns of V are the covariance eigenvectors and the eigenvalues are σ² / (n − 1). See eigenvectors of a covariance matrix.

For least squares, inverting the nonzero singular values gives the pseudoinverse, which returns the smallest-norm solution when several solutions fit equally well. Dividing by very small singular values amplifies noise, so they are often dropped or damped.

An example you can read: two kinds of readers

Imagine a small invented table of reading counts. Four readers are rows, and the columns are two astronomy titles and two cooking titles.

reader 1:   2  2  0  0
reader 2:   1  1  0  0
reader 3:   0  0  3  3
reader 4:   0  0  1  1

Rows 1 and 2 are multiples of one pattern, and rows 3 and 4 of another, so the rank is 2. The nonzero singular values are the square roots of 20 and 10: for each block, take the sum of its squared entries, 4 + 4 + 1 + 1 = 10 for the first and 9 + 9 + 1 + 1 = 20 for the second.

The stronger term describes the cooking block and the weaker one the astronomy block. A rank-one approximation would keep cooking and erase astronomy entirely, with squared error 10 out of 30. The method protects total squared size, so smaller groups are the first to disappear. Check errors for each group, especially minority ones, before you truncate.

Doing it in code

NumPy returns Vᵀ, already transposed, and a one-dimensional array of singular values.

import numpy as np

A = np.array([[3.0, 0], [4, 5]])
U, s, Vt = np.linalg.svd(A, full_matrices=False)

k = 1
Ak = (U[:, :k] * s[:k]) @ Vt[:k, :]
print(s.round(3))                       # [6.708 2.236]
print(Ak.round(3))                      # rows [1.5 1.5] and [4.5 4.5]
print(round(np.sum((A - Ak) ** 2), 3))  # 5.0

Computing a full SVD of a large dense matrix is expensive, roughly proportional to m · n · min(m, n). When k is small, randomized or iterative methods find the leading terms using only matrix products, which also suits sparse data. Libraries offer these as truncated SVD routines. Note that centering a sparse matrix makes it dense, so check whether a routine centers implicitly or not at all.

Choosing k and avoiding mistakes

  1. Plot singular values or the cumulative share of their squares.
  2. Pick candidate values of k and judge them by the downstream task on validation data.
  3. Fit the decomposition on training data, and project new rows with V.
  4. Compare against a simple baseline, such as keeping raw features with regularization.
  5. Do not read meaning into a factor without checking the rows and columns that load on it.

A new row x of length n is projected as x · V_k, giving k coordinates. Adding many new rows with new patterns eventually calls for refitting, and a refit may flip signs or rotate factors with similar strength. Anything downstream must be retrained together with it.

Common questions

Are singular values the same as eigenvalues?

Not in general. For a symmetric matrix with no negative eigenvalues, such as a covariance matrix, they coincide. For other matrices, singular values are the square roots of the eigenvalues of AᵀA, and they are never negative.

Is the decomposition unique?

The singular values are. Singular vectors can flip sign in pairs, and when values repeat, any rotation within the shared subspace works equally well.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 26 articles in The Math Behind the Methods →

Latest news on this topic