PCA: Minimum Reconstruction Error
There is a second, equally natural way to ask for PCA: compress each -dimensional point to 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 of an -dimensional subspace. For centred data:
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 to an orthonormal basis . The error of each point is its component in the discarded directions, so
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 eigenvectors of , and
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 and decoding with is a two-layer linear autoencoder with a bottleneck of width . 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
Plot the explained variance ratio, or pick the smallest that keeps, say, 95% of the variance. For images, a few dozen components often reconstruct recognizable pictures from hundreds of pixels.
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 to keep 95% of the variance;inverse_transformreconstructs.- 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 . What is the average squared reconstruction error with ?
Answer
.
Solution
.
Exercise 2: Encode and decode by hand
With and , encode and reconstruct the centred point .
Answer
; .
Solution
and . The error vector is orthogonal to .
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
versus , about .
Solution
Codes , basis , mean .
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 components equals…
- the sum of the discarded eigenvalues
- zero
Minimizing reconstruction error and maximizing projected variance…
- give different subspaces
- give the same subspace
- are unrelated
- only agree for
PCA is equivalent to which neural network?
- A deep CNN
- A linear autoencoder with a bottleneck trained on squared error
- A recurrent network
- A softmax classifier