Ran Wei/ Linear Algebra
中文
Linear Algebra · Spectra and data

Module 12Low-rank approximation and PCA

Compress a matrix, derive principal component analysis, and check a complete reconstruction by hand and in Python.

95 minYou need Modules 8, 10 and 11

In this module you will

  • Predict the error of a truncated SVD
  • Centre data and find its principal component directions
  • Reconstruct data and judge the effect of changing feature units
1

Keep the strongest directions

The Frobenius norm ∥A∥F\|A\|_F is the square root of the sum of squared entries. The rank-kk truncation Ak=∑i=1kσiuiviTA_k=\sum_{i=1}^k\sigma_i\mathbf u_i\mathbf v_i^\mathsf T drops the smaller singular directions. Orthogonal changes of coordinates preserve Euclidean lengths of columns, and also rows, so ∥A−Ak∥F2=∑i>kσi2.\|A-A_k\|_F^2=\sum_{i>k}\sigma_i^2\mathclose{\text{.}} The truncation attains the smallest Frobenius error among matrices of rank at most k.k\mathclose{\text{.}}

To see optimality, let PP project onto the columns of a competing matrix B.B\mathclose{\text{.}} The squared error is at least ∥(I−P)A∥F2,\|(I-P)A\|_F^2\mathclose{\text{,}} since removing its component in the range of PP can only shorten it. The energy retained by PP is ∥PA∥F2=∑iσi2∥Pui∥2.\|PA\|_F^2=\sum_i \sigma_i^2\|P\mathbf u_i\|^2\mathclose{\text{.}} The weights lie in [0,1][0,1] and sum to rank⁡P≤k\operatorname{rank}P\le k over a complete orthonormal output basis, by taking the trace of P,P\mathclose{\text{,}} the sum of its diagonal entries in any orthonormal basis. The largest possible weighted sum puts weight one on each of the first kk directions. That choice gives Ak.A_k\mathclose{\text{.}}

Try it

Increase the retained rank. Compare the reconstruction with the original matrix and notice the error contributed by each discarded singular value.

2

Find the directions of greatest sample variance

Store m>1m>1 observations as rows. Subtract each column mean to get the centred matrix X.X\mathclose{\text{.}} Its sample covariance matrix is C=XTX/(m−1).C=X^\mathsf TX/(m-1)\mathclose{\text{.}} A unit direction v\mathbf v gives scores Xv,X\mathbf v\mathclose{\text{,}} with sample variance vTCv.\mathbf v^\mathsf TC\mathbf v\mathclose{\text{.}} In eigenvector coordinates this is a weighted average of the covariance eigenvalues. The maximum is the largest eigenvalue. Restricting each additional direction to be perpendicular to the previous ones gives the following principal components.

The first kk right singular vectors of XX therefore span a principal subspace. Form the score matrix XVkXV_k and reconstruct the centred observations as XVkVkT.XV_k V_k^\mathsf T\mathclose{\text{.}} Add the mean back to recover the original coordinates. The covariance eigenvalues are the squared singular values divided by m−1.m-1\mathclose{\text{.}} When the total variance is positive, the fraction explained by a component is its eigenvalue divided by their sum.

Example 12.1Four centred observations✓ Checked

Take (3,0),(−3,0),(0,1),(0,−1).(3,0),(-3,0),(0,1),(0,-1)\mathclose{\text{.}} Both means are zero. The scatter matrix XTXX^\mathsf TX has diagonal entries 18,218,2 and zero off-diagonal entries. The first component lies along the first coordinate and explains 18/(18+2)=9/1018/(18+2)=9/10 of the variance. Reconstruction with one component sends the last two observations to the origin. The squared reconstruction error is 2.2\mathclose{\text{.}}

PCA depends on units. A column measured in millimetres has larger numerical variance than the same measurements in metres. Standardise when you mean to compare relative variation across nonconstant features. Keep physical units when their relative variation is meaningful. Explained variance measures reconstruction in the chosen coordinates, so assess prediction or classification separately.

Compute itCentring, scoring and reconstructing
Python
from sympy import Matrix, ones

data = Matrix([[13, 5], [7, 5], [10, 6], [10, 4]])
mean = ones(1, 4) * data / 4
X = data - ones(4, 1) * mean
v = Matrix([1, 0])
scores = X * v
reconstruction = scores * v.T + ones(4, 1) * mean
print(list(mean))
print(list(scores))
print(reconstruction.tolist())
print(sum(t**2 for t in data - reconstruction))
Output
[10, 5]
[3, -3, 0, 0]
[[13, 5], [7, 5], [10, 5], [10, 5]]
2
Compute itFind the component numerically

A numerical SVD can choose either sign for a singular vector. The reconstruction uses both the score and the direction, so a sign flip cancels. The code keeps one component and computes the squared reconstruction error in the original coordinates.

Python
import numpy as np

data = np.array([[13., 5.], [7., 5.], [10., 6.], [10., 4.]])
mean = data.mean(axis=0)
X = data - mean
_, singular, vt = np.linalg.svd(X, full_matrices=False)
direction = vt[0]
scores = X @ direction
restored = scores[:, None] * direction + mean
explained = singular[0] ** 2 / np.dot(singular, singular)
print(f"first component explains {explained:.1%}")
print(f"squared reconstruction error = {np.sum((data - restored)**2):.0f}")
Output
first component explains 90.0%
squared reconstruction error = 2
3

Exercises

Exercise 12.1★Discarded energy

If the singular values are 5,3,1,5,3,1\mathclose{\text{,}} find the Frobenius error of the best rank-one approximation.

Show solution✓ Checked

Discard 33 and 1.1\mathclose{\text{.}} Their squared sum is 10,10\mathclose{\text{,}} so the error is 10.\sqrt{10}\mathclose{\text{.}}

Exercise 12.2★★Change the units

In the worked example, multiply the second coordinate by 4.4\mathclose{\text{.}} Which axis now gives the first component, and what fraction of variance does it explain?

Show solution✓ Checked

The squared scatter values become 1818 and 16⋅2=32.16\cdot2=32\mathclose{\text{.}} The second axis leads, explaining 32/(18+32)=16/25.32/(18+32)=16/25\mathclose{\text{.}}

Exercise 12.3★★★A rotated principal component

For centred observations (2,2),(−2,−2),(1,−1),(−1,1),(2,2),(-2,-2),(1,-1),(-1,1)\mathclose{\text{,}} find a unit first component and the squared one-component reconstruction error.

Show solution✓ Checked

The scatter matrix has rows (10,6)(10,6) and (6,10).(6,10)\mathclose{\text{.}} Along (1,1)T/2(1,1)^\mathsf T/\sqrt2 its eigenvalue is 16.16\mathclose{\text{.}} Along (1,−1)T/2(1,-1)^\mathsf T/\sqrt2 the eigenvalue is 4.4\mathclose{\text{.}} The first direction leads. Projecting onto it drops the last two observations, each of squared length 2,2\mathclose{\text{,}} so the total squared error is 4.4\mathclose{\text{.}}

4

Check yourself

1
What does subtracting column means do before PCA?
2
Which quantity gives the squared Frobenius error of the rank-kk truncation?
3
How do you return a centred PCA reconstruction to the original coordinates?
Finished this module?