Week 06 · Singular value decomposition

See how singular directions compress a matrix and calculate the error left by a rank-one reconstruction.

Subject contents · Week 5 · Week 7

See how singular directions compress a matrix and calculate the error left by a rank-one reconstruction.

Keep the strongest patterns in a matrix

A grayscale image can be represented as a table of intensities. A four-by-four image has sixteen entries, but those entries may share a simple pattern. The singular value decomposition (SVD) describes the matrix as a sum of patterns and orders the patterns by strength. You can then see what is lost when you keep fewer.

This lesson connects three views of the same decomposition. A matrix stretches special input directions, it can be reconstructed from rank-one patterns, and its discarded singular values quantify the best possible squared reconstruction error at a chosen rank.

The idea

The singular value decomposition writes A = UΣVᵀ. The columns of V are orthonormal input directions. A maps each direction vᵢ to σᵢuᵢ, where uᵢ is an output direction and σᵢ ≥ 0 measures the stretch. This works for rectangular matrices too.

You can also read the decomposition as a sum of outer products: A = Σᵢ σᵢ uᵢvᵢᵀ. Each term is a matrix of rank at most one. Keep the k largest singular values and their directions to get the best rank-k approximation in Frobenius norm, the square root of the sum of squared entry errors. The squared approximation error is the sum of the discarded singular values squared.

This connects back to PCA. For centered X = UΣVᵀ, the covariance is V(Σ²/n)Vᵀ. The right singular vectors are the principal axes, and each component’s variance is σᵢ²/n. PCA needs the centering step. The image example below decomposes pixel intensities directly.

Explain the pieces of a rank-one pattern

For an m-by-n matrix A, an input direction vᵢ has n entries and an output direction uᵢ has m entries. Both have unit length. The singular value σᵢ is the nonnegative factor in A vᵢ = σᵢ uᵢ. In the reduced decomposition, put the directions into columns of U and V and the factors on the diagonal of Σ.

The matrix uᵢvᵢᵀ is an outer product. Entry (j, k) is the jth entry of uᵢ times the kth entry of vᵢ. Each column is a scalar multiple of uᵢ, so it contributes at most one independent output direction. For a two-entry example, (1, 2)ᵀ(3, 4) gives [[3, 4], [6, 8]]. The second row is twice the first.

For the image below, take the unit vector u = (1, 1, 1, 1)/2 and the unit contrast direction v = (1, 1, −1, −1)/2. They are perpendicular. The image is 4uuᵀ + 2vvᵀ. The first term contributes 1 everywhere. The second contributes either +0.5 or −0.5, depending on the row and column. That gives a direct check on the singular values 4 and 2.

Work it out

Think of a grayscale image made of two patterns. The first adds the same brightness everywhere. The second makes two opposite quadrants brighter and the other two darker. In the example, the patterns have singular values 4 and 2.

Keeping only the first pattern replaces all pixels with the average intensity 1. The original has pixels 1.5 and 0.5, so each of its sixteen pixels contributes 0.5² to the squared error. The total is 4, which matches the discarded singular value squared. Keeping both patterns recovers the image.

Three panels show a four-by-four checkerboard of quadrant brightness, the flat rank-one reconstruction, and the recovered rank-two image, all on the same intensity scale.

All panels use the same intensity scale. The second singular component restores the contrast.

Run the Python lab

import numpy as np

uniform = np.array([1., 1., 1., 1.]) / 2
contrast = np.array([1., 1., -1., -1.]) / 2
A = 4 * np.outer(uniform, uniform) + 2 * np.outer(contrast, contrast)
U, s, Vt = np.linalg.svd(A, full_matrices=False)

print("leading singular values:", np.round(s[:2], 6).tolist())
for k in (1, 2):
    approximation = (U[:, :k] * s[:k]) @ Vt[:k, :]
    error = np.linalg.norm(A - approximation, ord="fro")
    print(f"rank {k}: squared error {error**2:.1f}")
    assert np.isclose(error**2, np.sum(s[k:]**2))

Expected output

leading singular values: [4.0, 2.0]
rank 1: squared error 4.0
rank 2: squared error 0.0

Connect the approximation to the measured error

np.linalg.svd returns the singular values in descending order and returns Vt, the transpose of V. Use row i of Vt when building the ith outer product. The first component gives a flat image, and the second restores the quadrant contrast.

The Frobenius norm squares and sums the difference at every pixel, then takes a square root. The lab compares squared errors, so discarding σ = 2 gives an error of 2² = 4. The corresponding norm is 2. Keep the distinction when reporting results. For centered data in Week 5, squared singular values divided by the row count are component variances. For this direct image approximation, no centering or row-count division is used.

Try it yourself

  1. Reduce the contrast coefficient from 2 to 0.5. Predict the rank-one squared error.
  2. A grayscale image is 100 × 80. Compare the number of scalar entries needed to store all pixels with a rank-five factorization.

Check your work. The new squared error is 0.25. The raw image stores 8,000 scalars. The factors and singular values store 5(100 + 80 + 1) = 905 scalars, before considering file encoding or metadata.

Further reading

NumPy documentation

Subject contents · Week 5 · Week 7