Exercise: principal component analysis

Goal

By the end of this exercise you should be able to:

  • treat small images as points, centre them, and compute their covariance matrix,
  • find the principal components of a 2 × 2 covariance and say what they mean for the images,
  • project an image onto the first components and rebuild it, and give the error,
  • choose a number of components from a scree plot, and say when PCA misleads,
  • compare PCA with the Fourier basis: fixed versus learned from the data.

Do the pen-and-paper part first, then the interactive part. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Word Meaning
Mean image \bar{\mathbf x} the average of each pixel over all images
Centred image \mathbf y = \mathbf x - \bar{\mathbf x}
Covariance matrix S averages of products of centred pixels: variances on the diagonal, covariances off it (divided by n here)
Score along \mathbf u s = \mathbf u \cdot (\mathbf x - \bar{\mathbf x}), for a unit vector \mathbf u
Principal components the eigenvectors of S, largest eigenvalue first; eigenvalue = variance of the scores
Reconstruction \hat{\mathbf x} = \bar{\mathbf x} + s_1\mathbf u_1 + \dots + s_k\mathbf u_k

By hand

B1. Predict where PC1 points (sketch the cloud) for two-pixel images taken from (a) two neighbouring pixels of a smooth image, (b) two pixels far apart in a busy image, with the same spread each, (c) two unrelated pixels where pixel 1 varies much more than pixel 2. In which case is PC1 hardly meaningful?

B2. Four two-pixel images, grey levels: (10, 14), (14, 10), (30, 26), (26, 30). (a) Compute the mean image and the centred images. (b) Compute the covariance matrix S (divide by 4). (c) The eigenvectors of a matrix \begin{pmatrix} a & b \\ b & a \end{pmatrix} are (1, 1)/\sqrt2 and (1, -1)/\sqrt2, with eigenvalues a + b and a - b. Give PC1, PC2, their variances, and the share of PC1. What do PC1 and PC2 mean as two-pixel images?

B3. Continue B2 with one component. (a) Give the PC1 score of each image. (b) Rebuild (10, 14) from its score. What is lost? (c) Compute the mean squared reconstruction error over the four images and compare it with the eigenvalues.

B4. A PCA of 6-pixel images has eigenvalues 50, 25, 12, 8, 3, 2. (a) Draw the scree plot. How many components keep at least 90 % of the variance? (b) What is the mean squared reconstruction error with 2 components? (c) The last two components look like random speckle. What happens to the noise in the images if you rebuild them from 4 components?

B5. You describe each cell by two features: its area in µm² (variance 400 µm⁴) and its mean intensity on a [0, 1] scale (variance 0.01), uncorrelated. Predict PC1 and its share. Is that a finding about the cells? What would you do before PCA?

B6. Colour: the pixels of a photograph of a grey street on an overcast day are points (R, G, B). Predict PC1. Why do image formats store a brightness and two colour differences instead of R, G, B?

B7. PCA and Fourier. For 8 × 8 patches, both give 64 orthonormal basis patches. (a) Which basis depends on the images, and which is the same for every image set? (b) On the micrograph’s patches, PC1 is a flat patch and PC2, PC3 are slow ramps. Which Fourier (cosine) basis patches do they resemble? (c) For which data would you expect PCA to need far fewer components than Fourier for the same error?

B1. (a) Along the diagonal: the pixels are almost equally bright, so they vary together; PC1 is the brightness of the pair, PC2 the small difference (an edge). (b) The cloud is round: the pixels are unrelated and equally spread, so every direction has about the same variance. PC1 is hardly meaningful here: its direction is decided by chance and swings when the data change a little. (c) Along the pixel 1 axis: the PCs are the pixels themselves, PC1 = pixel 1.

B2. (a) Mean (20, 20). Centred (-10, -6), (-6, -10), (10, 6), (6, 10). (b) S_{11} = (100 + 36 + 100 + 36)/4 = 68, S_{22} = 68, S_{12} = (60 + 60 + 60 + 60)/4 = 60: S = \begin{pmatrix} 68 & 60 \\ 60 & 68 \end{pmatrix}. (c) PC1 = (1, 1)/\sqrt2 with variance 68 + 60 = 128; PC2 = (1, -1)/\sqrt2 with variance 68 - 60 = 8. Share of PC1: 128/136 = 94.1\,\%. PC1: both pixels brighter together, the brightness of the pair. PC2: one brighter, the other darker, the difference between them.

B3. (a) s_1 = (y_1 + y_2)/\sqrt2: -16/\sqrt2 = -11.31, -11.31, +11.31, +11.31. (b) \hat{\mathbf x} = (20, 20) + (-11.31)\,(1, 1)/\sqrt2 = (20, 20) - (8, 8) = (12, 12). Lost: the difference between the pixels; error (10, 14) - (12, 12) = (-2, 2), squared length 8. (c) Every image loses 8, so the mean error is 8: exactly \lambda_2, the variance that was dropped. (Total 136 = 128 kept + 8 lost.)

B4. (a) Cumulative shares: 50, 75, 87, 95, 98, 100 %. So 4 components are needed for 90 % (3 keep only 87 %). The elbow is after component 2 or 3. (b) The dropped eigenvalues: 12 + 8 + 3 + 2 = 25 (25 % of the total 100). (c) The noise that lies along components 5 and 6 is removed; noise along components 1–4 stays. Rebuilding from the first components is a simple denoiser: it keeps the directions in which the images really vary.

B5. PC1 is (almost exactly) the area axis, with a share of 400/400.01 \approx 100\,\%. That is not a finding about cells: it is a choice of units. In µm² the area simply has a much larger number spread than an intensity in [0, 1]; in mm² it would be the other way round. Standardise first: divide each feature by its standard deviation (20 µm² and 0.1), so that both have variance 1. Then PCA looks at how the features vary together.

B6. PC1 \approx (1, 1, 1)/\sqrt3: in a grey scene the three channels go up and down together with the light, so most of the variance is brightness. The remaining two directions are colour differences with little variance. Storing brightness plus two colour differences puts almost all the information in one channel; the differences can be stored with fewer bits or at lower resolution, and the eye hardly notices.

B7. (a) The PCA basis depends on the images (eigenvectors of their covariance); the Fourier basis is fixed. (b) PC1 resembles the constant (zero-frequency) cosine patch; PC2 and PC3 the lowest frequency across and down: half a cosine period over the patch. (c) For a narrow, special set of images, such as aligned faces or masks of one kind of cell: their variation is concentrated in a few directions that are not waves. For “any” images, whose statistics are the same everywhere, PCA comes out close to the cosines anyway.

Math questions

B8. (math) Show that the variance of the scores along a unit vector \mathbf u is \mathbf u^\top S\mathbf u. Check it for B2 with \mathbf u = (1, 0) and with \mathbf u = (\cos 30°, \sin 30°).

B9. (math) Maximise \mathbf u^\top S\mathbf u subject to \|\mathbf u\| = 1 with a Lagrange multiplier, and show that the maximum is the largest eigenvalue \lambda_1, reached at its eigenvector.

B10. (math) Let \mathbf u_1, \mathbf u_2 be eigenvectors of the symmetric S with eigenvalues \lambda_1 \ne \lambda_2. Show that \mathbf u_1 \perp \mathbf u_2, and that the scores along \mathbf u_1 and \mathbf u_2 are uncorrelated.

B11. (math) Show that the mean squared reconstruction error with the first k components is \sum_{j > k}\lambda_j, and that the total variance \operatorname{tr}S equals \sum_j \lambda_j.

B8. The scores of centred images are s_i = \mathbf u^\top\mathbf y_i, with mean 0, so their variance is \frac1n\sum_i(\mathbf u^\top\mathbf y_i)^2 = \frac1n\sum_i \mathbf u^\top\mathbf y_i\mathbf y_i^\top\mathbf u = \mathbf u^\top\big(\frac1n\sum_i\mathbf y_i\mathbf y_i^\top\big)\mathbf u = \mathbf u^\top S\mathbf u. For B2: \mathbf u = (1, 0) gives S_{11} = 68, the variance of pixel 1. \mathbf u = (\cos 30°, \sin 30°): 68\cos^2 30° + 2\cdot 60\sin 30°\cos 30° + 68\sin^2 30° = 68 + 60\sin 60° = 119.96, between \lambda_2 = 8 and \lambda_1 = 128.

B9. \nabla_{\mathbf u}\big(\mathbf u^\top S\mathbf u - \lambda(\mathbf u^\top\mathbf u - 1)\big) = 2S\mathbf u - 2\lambda\mathbf u = 0, so S\mathbf u = \lambda\mathbf u: every stationary point is a unit eigenvector, where \mathbf u^\top S\mathbf u = \lambda\,\mathbf u^\top\mathbf u = \lambda. The maximum over the (compact) unit sphere is attained at a stationary point, hence it is the largest eigenvalue. Alternatively, write \mathbf u = \sum_j c_j\mathbf u_j in the orthonormal eigenbasis with \sum c_j^2 = 1: \mathbf u^\top S\mathbf u = \sum_j \lambda_j c_j^2 \le \lambda_1.

B10. \lambda_1\,\mathbf u_2^\top\mathbf u_1 = \mathbf u_2^\top S\mathbf u_1 = (S\mathbf u_2)^\top\mathbf u_1 = \lambda_2\,\mathbf u_2^\top\mathbf u_1, using S^\top = S. With \lambda_1 \ne \lambda_2 this forces \mathbf u_2^\top\mathbf u_1 = 0. The covariance of the scores is \frac1n\sum_i(\mathbf u_1^\top\mathbf y_i)(\mathbf u_2^\top\mathbf y_i) = \mathbf u_1^\top S\mathbf u_2 = \lambda_2\,\mathbf u_1^\top\mathbf u_2 = 0.

B11. In the orthonormal PC basis \mathbf y_i = \sum_j s_{ij}\mathbf u_j, so \|\mathbf y_i - \hat{\mathbf y}_i\|^2 = \|\sum_{j > k}s_{ij}\mathbf u_j\|^2 = \sum_{j > k}s_{ij}^2 (Pythagoras). Averaging over i: \sum_{j > k}\frac1n\sum_i s_{ij}^2 = \sum_{j > k}\lambda_j by B8. With k = 0: \frac1n\sum_i\|\mathbf y_i\|^2 = \sum_j\lambda_j; the left side is the sum of the pixel variances, \operatorname{tr}S. (Or: the trace is invariant under the rotation S = U\Lambda U^\top.) For B2: 68 + 68 = 128 + 8.

Explore

Each dot is a two-pixel image (pixel 1 across, pixel 2 up); drag any dot to change the data. The black + is the mean, the dashed ellipse has the principal components as its axes (half-lengths 2\sqrt{\lambda}), and the orange and purple arrows are PC1 and PC2. The blue line is a direction \mathbf u through the mean: drag its handle. Red segments join each image to its reconstruction from one score along \mathbf u. The plot on the right shows, for every angle of \mathbf u, the variance of the scores (blue) and the mean squared error (red); the orange tick marks PC1. The bars give the share of the variance on each PC.

E1. Preset four images (the lecture’s example). Check the readout against the lecture: mean, S, eigenvalues. Drag \mathbf u to about 30°. What are the variance along \mathbf u and the error, and what is their sum? Is the sum the same at every angle?

E2. Preset neighbouring pixels, \mathbf u at 0°. What does this direction keep, and what are the variance and the error? Turn \mathbf u to PC1 (button u = PC1). Give the angle, the share of PC1 and the error. Compare the error with \lambda_2.

E3. Preset one outlier: one “hot” pixel pair (0.95, 0.05) among neighbouring pixel pairs. Read PC1’s angle and share. Now drag the hot pixel onto the diagonal next to the others. How much do the angle, the share and \lambda_2 change? Why does one point matter so much?

E4. Preset round cloud. Compare \lambda_1 and \lambda_2. Drag one dot a short distance and watch PC1. What does that say about reporting “the direction of PC1” for such data?

E5. Preset unrelated pixels. Where does PC1 point, and what is its share? What does \mathbf u at 45° keep?

E6. Preset no centring: the line now goes through (0, 0) instead of the mean. At the PC1 angle, what is the error? Turn \mathbf u to make the error as small as possible: where does the best line through (0, 0) point, and how does its error compare with the PCA error? Tick centre again.

E1. Mean (0.500, 0.500), S = [0.05\ 0.03;\ 0.03\ 0.05], \lambda_1 = 0.08 (80 %), \lambda_2 = 0.02. At 30° the variance is 0.0760 and the error 0.0240; their sum is 0.1000, the total variance \operatorname{tr}S, at every angle. What one score does not keep, it loses: maximising the variance and minimising the error are the same problem.

E2. At 0° the score is pixel 1 minus its mean: the line keeps pixel 1 and rebuilds pixel 2 as its mean. Variance 0.0406 (S_{11}), error 0.0414. At PC1: angle 45.3°, share 92.9 %, error 0.0058, equal to \lambda_2 = 0.0058: the smallest possible.

E3. With the outlier, PC1 is at 48.6° with a share of 69.8 %, and \lambda_2 = 0.0111. Without it (the hot pixel removed, or moved onto the diagonal among the others) PC1 is at about 45.7° with a share of 93.3 % and \lambda_2 \approx 0.0019, about six times smaller. The outlier is far from the line, and the variance adds up squared distances, so one far point counts as much as many near ones. Check for outliers (or use a robust method) before trusting a PCA.

E4. \lambda_1 = 0.0129 and \lambda_2 = 0.0118, nearly equal (shares 52 % and 48 %), and PC1 is at −31.9°, a direction picked by chance. Dragging one dot a little swings PC1 by tens of degrees. When the eigenvalues are close, the individual PCs are not stable: only the plane they span together is meaningful. Report the eigenvalues before interpreting the axes.

E5. PC1 points almost along pixel 1 (−2.6°) with a share of 93.5 %: pixel 1 varies most, and the two pixels are unrelated, so the principal components are (close to) the pixels themselves. At 45°, \mathbf u keeps the brightness of the pair: variance 0.0139, error 0.0163, much worse than PC1’s error 0.0020.

E6. Through (0, 0) at the PC1 angle the error is 0.2727: the line along pixel 1 starting at black misses the whole cloud, which sits around (0.53, 0.50). The best line through (0, 0) points at about 41°, towards the mean of the cloud, with an error of about 0.0150: it describes how bright the images are on average, not how they differ. Centred PCA gets 0.0020, almost eight times smaller. Always subtract the mean first.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in images/src/pca/exercise.rs.

C1. mean_and_covariance(points) for two-pixel images (divide by n, as in the lecture). The check is the lecture’s four images, S = \begin{pmatrix}0.05 & 0.03\\ 0.03 & 0.05\end{pmatrix}.

C2. eigen2(s): the eigenvalues (largest first) and unit eigenvectors of a symmetric 2 \times 2 matrix \begin{pmatrix}a & b\\ b & d\end{pmatrix}:

λ1, λ2 = (a+d)/2 ± sqrt( ((a−d)/2)² + b² )
u1 = (b, λ1 − a), scaled to length 1        # if b = 0: the axes themselves
u2 = u1 turned by 90°

C3. project(points, mean, u): the score s = \mathbf u \cdot (\mathbf x - \bar{\mathbf x}) of every point, and the mean squared distance between each point and its reconstruction \bar{\mathbf x} + s\,\mathbf u. The check: variance plus error is the same in every direction, as in demo question E1.

C4. Principal components of real image patches, of any size:

  • patches(img, size, step): every size × size patch, flattened into a vector;
  • covariance(vectors): as C1, for vectors of any length;
  • power_iteration(s, iterations): the largest eigenvalue and its eigenvector, without solving any equation:
u = any vector of length 1
repeat:
    v = S · u
    λ = length of v
    u = v / λ

Then cargo run -p images -- pca. It finds the first 8 principal components of the 8 \times 8 patches of the micrograph. After each one, it removes that component from S, so that power iteration finds the next. It draws them side by side in out/pca/patch-pcs.png, with 0 as grey.

C5. Look at patch-pcs.png and at the printed shares of the variance. What does PC1 look like, and what do PC2 and PC3 look like? Which basis from the Fourier unit do they resemble?

C6. (math) Why does power iteration find the eigenvector of the largest eigenvalue? Write the start vector in the eigenvectors of S. What decides how fast it converges?

The model solution is images/src/pca/solution.rs in the download.

C5. PC1, about 69 % of the variance, has one sign everywhere: the overall brightness of the patch, like the long diagonal of the two-pixel cloud. PC2 and PC3, about 6 % and 4 %, are smooth ramps, one from left to right and one from top to bottom: the average slope (edge) across the patch. The later ones have more and more sign changes. Together they look much like the smooth waves of the cosine transform (the slide “PCA and Fourier: two changes of basis”). PCA learns from the data a basis close to the fixed Fourier-type basis, because natural images look similar when shifted.

C6. Write \mathbf u_0 = \sum_i c_i \mathbf e_i in the eigenvectors \mathbf e_i of S. Then S^t \mathbf u_0 = \sum_i c_i \lambda_i^t \mathbf e_i = \lambda_1^t \big(c_1 \mathbf e_1 + \sum_{i>1} c_i (\lambda_i/\lambda_1)^t \mathbf e_i\big). Every ratio \lambda_i/\lambda_1 < 1 shrinks to 0, so after rescaling only the direction of \mathbf e_1 is left (provided c_1 \neq 0). The error shrinks by about \lambda_2/\lambda_1 per step. It converges fast when PC1 clearly dominates, and slowly when \lambda_2 \approx \lambda_1, the case of demo question E4, where PC1 is not well defined anyway.

Where this leads

Principal components return all through the course: the principal axes of a segmented object are the PCs of its pixel coordinates (region properties); shape models are PCA of landmark positions (shape models); colour images are decorrelated into brightness and colour differences (colour for display); stained sections are separated into stains (stain unmixing); and an autoencoder is PCA made nonlinear (autoencoders). The Fourier basis is the fixed relative of the PCA basis, and the two meet again in image compression (the DCT).