Exercise: from PCA to autoencoders
Before this unit: Day 36: Neural networks.
See also: Day 30: Snakes and active shape models.
Goal
By the end of this exercise you should be able to:
- treat a (small) image as a vector, and use PCA as an encoder and a decoder,
- compute a reconstruction error, and say which images are rebuilt perfectly and which as the mean image,
- explain why the bottleneck must be narrow,
- explain why a curved family of images needs a nonlinear decoder.
The questions under By hand and Explore are for everyone. The Math questions (derive, prove) are for students who want the full treatment.
Background
PCA is taught in the unit Principal component analysis; here it is used as an encoder and a decoder.
| Word | Meaning |
|---|---|
| Image as a vector | the grey values, one after the other: a 28\times28 image is a point in \mathbb R^{784} |
| Mean image \bar{\mathbf x} | the pixel-wise average of all images |
| Principal component \mathbf u_k | a unit vector (itself an image, an “eigen-image”); \mathbf u_1 points along the largest spread |
| Encode (PCA) | scores s_k = \mathbf u_k \cdot (\mathbf x - \bar{\mathbf x}) |
| Decode (PCA) | \hat{\mathbf x} = \bar{\mathbf x} + s_1\mathbf u_1 + \dots + s_k\mathbf u_k |
| Reconstruction error | \|\mathbf x - \hat{\mathbf x}\|^2, the squared length of what is lost |
| Autoencoder | encoder and decoder are neural networks; trained so that \hat{\mathbf x} \approx \mathbf x |
By hand
Part A — PCA as an encoder and a decoder
Two-pixel images, mean already subtracted. PC1 is \mathbf u = (0.8,\ 0.6), a unit vector.
B1. Encode \mathbf x = (3,\ 1): compute its score. Decode it again. What is the reconstruction error vector, and its squared length?
B2. Do the same for \mathbf y = (-1.6,\ -1.2) and \mathbf w = (-0.6,\ 0.8). Which one is rebuilt perfectly, and which one is rebuilt as the mean image (0, 0)? Explain both with the PC1 line.
B3. Now keep two components, with PC2 = (-0.6,\ 0.8). What is the reconstruction error of \mathbf x now? What does that say about an autoencoder whose bottleneck is as wide as its input?
Part B — brightness and edges
Two neighbouring pixels of a smooth image. The mean image is (0.5,\ 0.5), PC1 is \mathbf u_1 = (1, 1)/\sqrt2 and PC2 is \mathbf u_2 = (1, -1)/\sqrt2.
B4. Describe in words what \mathbf u_1 and \mathbf u_2 look like as two-pixel images, and what their scores measure.
B5. Encode the image (0.8,\ 0.6) with one component and decode it. What is lost? Give the error. What is the score on PC2?
B6. A 28\times28 image is encoded by PCA with 50 components. How many numbers are stored per image? What does the decoder add up to rebuild the image?
Part C — curved families
B7. A bright spot moves past two pixels (the lecture’s horseshoe). Explain in your own words why one PCA score cannot tell all spot positions apart, while one autoencoder number can.
B8. An autoencoder with no ReLU in its networks is trained on images. What will it find? (Use the collapse argument of Neural networks.)
B1. Score = 0.8 \cdot 3 + 0.6 \cdot 1 = 3.0. Decoded 3.0 \cdot (0.8, 0.6) = (2.4,\ 1.8). Error (3, 1) - (2.4, 1.8) = (0.6,\ -0.8), squared length 0.36 + 0.64 = 1.0.
B2. \mathbf y: score = -1.28 - 0.72 = -2.0, decoded (-1.6,\ -1.2) = \mathbf y: error 0. \mathbf y lies on the PC1 line, so nothing is lost. \mathbf w: score = -0.48 + 0.48 = 0, decoded (0, 0), the mean image; error 0.36 + 0.64 = 1.0. \mathbf w is perpendicular to PC1: its one number carries no information about it.
B3. Scores 3.0 and -0.6 \cdot 3 + 0.8 \cdot 1 = -1.0. Decoded 3.0\,(0.8, 0.6) - 1.0\,(-0.6, 0.8) = (2.4 + 0.6,\ 1.8 - 0.8) = (3, 1): error 0. With as many numbers as pixels, encoding is a rotation and decoding rotates back. Nothing is lost, but nothing is summarised either: the bottleneck has to be narrower than the input to be useful.
B4. \mathbf u_1: both pixels equally bright, the score measures the overall brightness of the pair. \mathbf u_2: one pixel brighter, the other darker by the same amount, the score measures the difference, a tiny edge.
B5. \mathbf x - \bar{\mathbf x} = (0.3,\ 0.1). Score s_1 = (0.3 + 0.1)/\sqrt2 = 0.2828. Decoded \bar{\mathbf x} + s_1\mathbf u_1 = (0.5, 0.5) + (0.2, 0.2) = (0.7,\ 0.7). Error (0.1,\ -0.1), squared length 0.02. The edge between the two pixels is lost; its score on PC2 is (0.3 - 0.1)/\sqrt2 = 0.1414, and 0.1414^2 = 0.02 is exactly the lost error.
B6. 50 scores per image instead of 784 grey values. The decoder adds the mean image and 50 eigen-images, each multiplied by its score.
B7. One PCA score is a position along one straight line. The images of the moving spot lie on a bent curve, so when the curve is projected onto a line it folds: two different spot positions (for example -0.5 and 0.2) project to almost the same score, and the decoder must give them the same image. An autoencoder’s decoder is a curve, not a line: one number says where along the curve the image is, and different positions get different numbers.
B8. Without bends, the encoder is one matrix and the decoder is one matrix (plus shifts): a linear autoencoder. Trained on squared error, the best it can do is PCA: its decoder spans the same directions as the top principal components.
Math questions
B9. (math) Let S be the covariance matrix of centred data \mathbf y_i and \mathbf u a unit vector. Show that the mean squared error of the one-number linear autoencoder along \mathbf u is \operatorname{tr}S - \mathbf u^\top S\mathbf u. For S = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}, compute this error for \mathbf u = (1, 0) and for \mathbf u = (1, 1)/\sqrt2, and find the best \mathbf u.
B9. (math) For a unit \mathbf u, \mathbf y = (\mathbf u^\top\mathbf y)\mathbf u + \mathbf r with \mathbf r \perp \mathbf u, so by Pythagoras \|\mathbf r\|^2 = \|\mathbf y\|^2 - (\mathbf u^\top\mathbf y)^2. Averaging over the data: \frac1n\sum\|\mathbf y_i\|^2 = \operatorname{tr}S and \frac1n\sum(\mathbf u^\top\mathbf y_i)^2 = \mathbf u^\top S\mathbf u. For the given S: \operatorname{tr}S = 4. \mathbf u = (1, 0): \mathbf u^\top S\mathbf u = 2, error 2. \mathbf u = (1, 1)/\sqrt2: \mathbf u^\top S\mathbf u = (2 + 1 + 1 + 2)/2 = 3, error 1. The eigenvalues of S are 3 (eigenvector (1,1)/\sqrt2) and 1 (eigenvector (1,-1)/\sqrt2); \mathbf u^\top S\mathbf u \le 3 for every unit vector, so (1,1)/\sqrt2 is best, with error equal to the dropped eigenvalue, 1.
Explore
Each dot is a two-pixel image (pixel 1 across, pixel 2 up). The blue line through the mean is a linear autoencoder that keeps one number: drag the handle u to turn it. Red segments join each image to its reconstruction. The small plot shows the mean squared error for every angle of \mathbf u; PCA jumps to the best angle. Click a dot to see that image and its reconstructions as two grey squares. On moving spot, train nonlinear autoencoder trains a 2 \to 16 \to 1 \to 16 \to 2 network (fixed seed) and draws its decoder curve in green.
E1. At the start, \mathbf u points along pixel 1 (angle 0°). What does this encoder keep, and what does the decoder do with pixel 2? Read the error. Check it against the readout’s “keep nothing” error and the covariance S (the same data as the “neighbouring pixels” preset of the PCA unit’s demo).
E2. Turn \mathbf u slowly through all angles. At which angle is the error smallest, and at which largest? Press PCA to check. What do the two directions mean for a pair of neighbouring pixels?
E3. With PCA selected, click a few dots. Compare the image and its linear reconstruction as grey squares: what is always lost?
E4. Choose moving spot, then spot: PCA. Where are the red segments longest? Find two dots far apart along the curve that land on almost the same point of the line.
E5. Press train nonlinear autoencoder. Watch the green curve during training. Compare its final error with the PCA error. Why is the curve still one-dimensional (one number per image)?
E1. At 0° the score is pixel 1 minus its mean: the encoder keeps pixel 1 and throws pixel 2 away. The decoder rebuilds pixel 1 exactly and sets pixel 2 to its mean, 0.511 (for the selected image (0.439, 0.466) it gives (0.439, 0.511)). Error 0.0414, half of the “keep nothing” error 0.0820. In the math: \operatorname{tr}S - S_{11} = 0.0820 - 0.0406 = 0.0414.
E2. Smallest at 45.3° (error 0.0058, the PCA direction): both pixels together, the brightness. Largest at −45° (0.0762): keeping only the difference of the two pixels and losing the brightness. Neighbouring pixels mostly differ in overall brightness from pair to pair, much less from each other.
E3. The reconstruction always has two (almost) equally bright pixels: the small difference between them, the local edge, is lost. Images that already have equal pixels are rebuilt almost perfectly.
E4. PCA error 0.0170. The red segments are longest at the two ends of the horseshoe (spot far left or far right, both pixels fairly dark), where the curve bends back towards the mean and is furthest from the line. The images at the start of the curve (spot far left, pixel 1 medium, pixel 2 dark) and those a little past pixel 1 (pixel 1 bright, pixel 2 a bit brighter) project to nearby points of the line: the line folds the curve.
E5. After 1500 steps the error is 0.0006, against 0.0170 for PCA: almost thirty times smaller. The green curve starts roughly straight and bends during training until it follows the horseshoe. It is still one number per image: the decoder maps one number z to one point of the plane, so all its outputs lie on one curve; the bends of the ReLU units let that curve bend.
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 vae/src/autoencoder/exercise.rs.
C1. pca_encode(x, mean, components) and pca_decode(scores, mean, components): PCA as an encoder and a decoder, for images (vectors) of any length and any number of components:
encode: for every component u_k: s_k = Σ_i u_k[i] · (x[i] − mean[i])
decode: x̂ = mean
for every component u_k: x̂ = x̂ + s_k · u_k
The checks are your answers to B1, B2 and B3.
C2. reconstruction_error(images, mean, components): encode and decode every image, and average the squared length \|\mathbf x - \hat{\mathbf x}\|^2 of what is lost. The checks use B1, B5 and the matrix S of B9.
C3. The autoencoder of the lecture, encoder 2 \to 16 \to 1 and decoder 1 \to 16 \to 2: dense(layer, input, relu) computes one layer, and forward(ae, x) runs all four and returns their outputs h_1, z, h_2, \hat{\mathbf x}:
one layer: out[o] = b[o] + Σ_i w[o][i] · in[i]
if the layer bends: out[o] = max(0, out[o])
forward: h1 = layer 1 (x), bent; z = layer 2 (h1)
h2 = layer 3 (z), bent; x̂ = layer 4 (h2)
C4. train_step(ae, images, rate): one step downhill on the mean squared reconstruction error, by backpropagation as in the unit Neural networks:
for every image x (n images):
run forward; the input of layer 1 is x, of layer k the output of layer k − 1
g = 2 (x̂ − x) / n # how the error changes with x̂
for layer k = 4, 3, 2, 1:
grad w[o][i] += g[o] · input[i]; grad b[o] += g[o]
g_in[i] = Σ_o w[o][i] · g[o] # back to the layer's input
if that input came out of a bend: g_in[i] = 0 where input[i] = 0
g = g_in
for every layer: w = w − rate · grad w, b = b − rate · grad b
One check changes single weights a little and compares the change of the error with your gradient; another trains on the moving spot and expects an error below that of PCA.
Then cargo run -p vae -- autoencoder and open the pictures in out/autoencoder/. The program uses 300 pairs of neighbouring pixels of the micrograph as two-pixel images, then PCA of the 8 \times 8 patches of the whole micrograph (patches-k1.png, -k4, -k16), and finally trains the autoencoder on the moving spot for 20,000 steps (spot.png: data black, PC1 line blue with the errors in red, the decoder curve green).
C5. Read the three printed errors for the neighbouring pixels: keeping pixel 1, keeping PC1, keeping nothing. Compare them with E1 and E2. What is PC1 of the micrograph’s pixel pairs?
C6. Open patches-k1.png, patches-k4.png and patches-k16.png. Each patch of 64 pixels is stored as 1, 4 or 16 numbers. What does the image with one number per patch look like, and why? What is lost with 4 numbers, and what with 16?
C7. Compare the error of PCA on the moving spot with that of the trained autoencoder. In spot.png, where are the red PCA errors longest? Count the cost: how many numbers does the autoencoder store per image, and how many weights does it have?
The model solution is vae/src/autoencoder/solution.rs in the download.
C5. Keeping pixel 1: 0.0497; keeping PC1: 0.0057; keeping nothing: 0.1011. As in E1, keeping one pixel loses about half of “keep nothing”, and PC1 loses only the smaller eigenvalue (0.0057). PC1 is (0.71, 0.70), close to (1, 1)/\sqrt2: the brightness of the pair, as in E2 and B4. The micrograph’s pairs spread a little more than the demo’s, so the numbers are a little larger.
C6. With one number per patch the image is a mosaic of 8 \times 8 squares, each nearly flat: PC1 of the patches is “all pixels together”, so one score is about the mean brightness of the patch. The mean squared error is 0.0171 per pixel. With 4 numbers the squares also get a slope (the next components are ramps), so the outline of the nucleus and the large dark regions come back, but the fine texture is smoothed away (0.0099). With 16 numbers the image looks close to the original; only the finest grain and sharpest edges are softened (0.0038).
C7. PCA: 0.0178; the autoencoder: 0.0010 after 20,000 steps (0.0082 after 5,000), almost twenty times smaller. The red PCA segments are longest at the two ends of the horseshoe, where the curve bends back and is furthest from the line. Both store one number per image. PC1 has 2 numbers (plus the 2 of the mean); the autoencoder has (2 \cdot 16 + 16) + (16 + 1) + (16 + 16) + (16 \cdot 2 + 2) = 131 weights and shifts, and needs thousands of training steps, where PCA needs one eigenvector.
Where this leads
A plain autoencoder rebuilds its training images, but its latent space can have gaps: decode a point between training images and nothing guarantees a sensible image. The variational autoencoder (next unit) turns each image into a small cloud and keeps all clouds near one standard bell shape, so that the whole latent space decodes to plausible images and new images can be generated.