TExcelTAD
Home › Math for Machine Learning › PCA: Minimum Reconstruction Error

PCA: Minimum Reconstruction Error

There is a second, equally natural way to ask for PCA: compress each DD-dimensional point to MM numbers and then reconstruct it, so that the average reconstruction error is as small as possible. The answer is the same subspace as the maximum-variance view, and the error is exactly the sum of the discarded eigenvalues.

Encode and decode

Pick an orthonormal basis B=[b1,…,bM]∈RD×MB = [\mathbf{b}_1, \ldots, \mathbf{b}_M] \in \mathbb{R}^{D \times M} of an MM-dimensional subspace. For centred data:

zn=BTxn∈RM(code),x~n=Bzn=BBTxn(reconstruction)\mathbf{z}_n = B^T\mathbf{x}_n \in \mathbb{R}^M \quad \text{(code)}, \qquad \tilde{\mathbf{x}}_n = B\mathbf{z}_n = BB^T\mathbf{x}_n \quad \text{(reconstruction)}

BBTBB^T is the orthogonal projection onto the subspace, which is the best reconstruction for a fixed subspace. The question is which subspace.

The error is the variance you throw away

Complete BB to an orthonormal basis b1,…,bD\mathbf{b}_1, \ldots, \mathbf{b}_D. The error of each point is its component in the discarded directions, so

JM=1N∑n∥xn−x~n∥2=∑j=M+1DbjTS bjJ_M = \frac{1}{N}\sum_{n}\lVert \mathbf{x}_n - \tilde{\mathbf{x}}_n \rVert^2 = \sum_{j=M+1}^{D}\mathbf{b}_j^TS\,\mathbf{b}_j

This is the variance in the discarded directions. Minimizing it is the same as maximizing the variance kept, so the optimal subspace is spanned by the top MM eigenvectors of SS, and

JM=∑j=M+1DλjJ_M = \sum_{j=M+1}^{D}\lambda_j
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
A = rng.normal(size=(6, 6))
X = rng.normal(size=(1000, 6)) @ A.T * np.array([3, 2, 1, 0.5, 0.2, 0.1])
Xc = X - X.mean(axis=0)
S = Xc.T @ Xc / len(Xc)
lam, Q = np.linalg.eigh(S); lam, Q = lam[::-1], Q[:, ::-1]
for M in (1, 2, 3, 5):
    B = Q[:, :M]
    rec = Xc @ B @ B.T
    err = np.mean(np.sum((Xc - rec) ** 2, axis=1))
    print(f"M={M}: reconstruction error {err:.4f}   sum of discarded eigenvalues {lam[M:].sum():.4f}")
# any other M-dim subspace does worse
B_rand, _ = np.linalg.qr(rng.normal(size=(6, 2)))
print("random 2-D subspace error:", round(np.mean(np.sum((Xc - Xc @ B_rand @ B_rand.T) ** 2, axis=1)), 4))
M=1: reconstruction error 16.8568   sum of discarded eigenvalues 16.8568
M=2: reconstruction error 5.4941   sum of discarded eigenvalues 5.4941
M=3: reconstruction error 0.8261   sum of discarded eigenvalues 0.8261
M=5: reconstruction error 0.0017   sum of discarded eigenvalues 0.0017
random 2-D subspace error: 26.4782

PCA as a linear autoencoder

Encoding with BTB^T and decoding with BB is a two-layer linear autoencoder with a bottleneck of width MM. Training such a network to minimize squared reconstruction error recovers the PCA subspace (though not necessarily the individual eigenvectors). Nonlinear autoencoders generalize PCA to curved manifolds.

Choosing MM

Plot the explained variance ratio, or pick the smallest MM that keeps, say, 95% of the variance. For images, a few dozen components often reconstruct recognizable pictures from hundreds of pixels.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
# 16x16 "images": blurred random blobs, flattened to 256 pixels
yy, xx = np.mgrid[0:16, 0:16]
imgs = []
for _ in range(400):
    cx, cy, s = rng.uniform(4, 12, 2).tolist() + [rng.uniform(1.5, 3.5)]
    imgs.append(np.exp(-((xx - cx)**2 + (yy - cy)**2) / (2 * s**2)).ravel())
X = np.array(imgs); Xc = X - X.mean(axis=0)
s = np.linalg.svd(Xc, compute_uv=False)
ratio = np.cumsum(s**2) / np.sum(s**2)
for keep in (0.9, 0.95, 0.99):
    print(f"components for {keep:.0%} of the variance: {int(np.searchsorted(ratio, keep) + 1)} of 256")
components for 90% of the variance: 6 of 256
components for 95% of the variance: 8 of 256
components for 99% of the variance: 15 of 256

In software

  • PCA(n_components=0.95) in scikit-learn picks MM to keep 95% of the variance; inverse_transform reconstructs.
  • Eigenfaces, a classic face recognition method, is PCA on face images.
  • PCA-compressed features speed up nearest-neighbour search in vector databases.

Exercises

Exercise 1: Error from eigenvalues

A covariance matrix has eigenvalues 10,4,1,0.510, 4, 1, 0.5. What is the average squared reconstruction error with M=2M = 2?

Answer

1.51.5.

Solution

J2=λ3+λ4=1+0.5J_2 = \lambda_3 + \lambda_4 = 1 + 0.5.

Exercise 2: Encode and decode by hand

With b1=12(1,1)\mathbf{b}_1 = \frac{1}{\sqrt{2}}(1, 1) and M=1M = 1, encode and reconstruct the centred point (3,1)(3, 1).

Answer

z=22z = 2\sqrt{2}; x~=(2,2)\tilde{\mathbf{x}} = (2, 2).

Solution

z=b1Tx=42=22z = \mathbf{b}_1^T\mathbf{x} = \frac{4}{\sqrt{2}} = 2\sqrt{2} and x~=zb1=(2,2)\tilde{\mathbf{x}} = z\mathbf{b}_1 = (2, 2). The error vector (1,−1)(1, -1) is orthogonal to b1\mathbf{b}_1.

Exercise 3: Storage (code)

1,000 images of 256 pixels are stored as 20 PCA codes each plus the basis and mean. How many numbers is that, compared with the raw data?

Answer

25 37625\,376 versus 256 000256\,000, about 9.9%9.9\%.

Solution

Codes 1000⋅201000 \cdot 20, basis 256⋅20256 \cdot 20, mean 256256.

python · try it yourself
codes, basis, mean = 1000 * 20, 256 * 20, 256
total = codes + basis + mean
print(total, 1000 * 256, f"{total / (1000 * 256):.1%}")
25376 256000 9.9%

Test yourself

The PCA reconstruction error with MM components equals…

  1. λM\lambda_M
  2. the sum of the discarded eigenvalues ∑j>Mλj\sum_{j > M}\lambda_j
  3. ∑j≤Mλj\sum_{j \le M}\lambda_j
  4. zero

Minimizing reconstruction error and maximizing projected variance…

  1. give different subspaces
  2. give the same subspace
  3. are unrelated
  4. only agree for M=1M = 1

PCA is equivalent to which neural network?

  1. A deep CNN
  2. A linear autoencoder with a bottleneck trained on squared error
  3. A recurrent network
  4. A softmax classifier