Squeeze a picture, then rebuild it
An autoencoder is a neural network that squeezes its input into a few numbers and rebuilds the input from them. A variational autoencoder, or VAE, does the same in a way that lets you make new data.
Image generators squeeze pictures this way before they work on them. The squeezed numbers hold what matters and drop the rest.
By the end of this lesson
Note
I can make an autoencoder generate new data by sampling from its code space.
Key words
| Word | What it means |
|---|---|
| Encoder | the half that turns an input into a code |
| Decoder | the half that turns a code back into an input |
| Latent code | the few numbers in the middle |
| Reconstruction error | how far the rebuilt input is from the real one |
| VAE | an autoencoder whose codes are drawn from a bell |
| KL term | a penalty for a bell far from the standard bell |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsAn autoencoder squeezes and rebuilds
An encoder turns an input into a short latent code. A decoder turns the code back into something the size of the input. Training makes the rebuilt input as close to the real one as it can.
The reconstruction error measures the gap: the mean of the squared differences. Points that fit the pattern rebuild well. Points that do not lose what the code could not hold.
An autoencoder for two numbers
flowchart LR
I["Input (x, y)"] --> E["Encoder"]
E --> Z["Code: one number"]
Z --> D["Decoder"]
D --> O["Rebuilt (x, y)"]
O --> R["Reconstruction error"]
I --> RWorked example: points near y = 2x
| Point | Code (keep x) | Rebuilt (x, 2x) | Error |
|---|---|---|---|
| (1, 2) | 1 | (1, 2) | 0 |
| (3, 6) | 3 | (3, 6) | 0 |
| (1, 0) | 1 | (1, 2) | (0 + 4) / 2 = 2 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTry it: a hand-made autoencoder
# A hand-made autoencoder for points on the line y = 2x.
def encode(point):
return point[0] # keep one number: x
def decode(code):
return [code, 2 * code] # rebuild both numbers from it
points = [[1, 2], [3, 6], [1, 0]]
for p in points:
code = encode(p)
rebuilt = decode(code)
error = ((rebuilt[0] - p[0]) ** 2 + (rebuilt[1] - p[1]) ** 2) / 2
print(p, "code", code, "rebuilt", rebuilt, "error", error)
# Change decode to [code, 3 * code] and press Run. Which errors grow?
Make a free account to save your work and track your progress.
Training finds the encoder and decoder
Nobody writes "keep x" by hand. The encoder and decoder each start as two small random weights, and gradient descent from module 21 nudges all four to lower the reconstruction error.
The lab script does this for 200 made-up points near y = 2x. Write it into the lab, then run it.
Write the autoencoder script
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'r = np.random.default_rng(0)' 't = r.uniform(-2, 2, 200)' 'X = np.stack([t, 2 * t + r.normal(0, 0.2, 200)], axis=1)' 'enc = r.normal(0, 0.1, 2)' 'dec = r.normal(0, 0.1, 2)' 'for step in range(201):' ' z = X @ enc' ' err = np.outer(z, dec) - X' ' if step in (0, 10, 20, 50, 200):' ' print(\"step\", step, \"error\", round((err ** 2).mean(), 4))' ' g_dec = 2 * err.T @ z / err.size' ' g_enc = 2 * X.T @ (err @ dec) / err.size' ' dec -= 0.05 * g_dec' ' enc -= 0.05 * g_enc' 'for p in ([1, 2], [1, 0]):' ' print(p, \"code\", round(float(np.array(p) @ enc), 2), \"rebuilt\", (np.array(p) @ enc * dec).round(2).tolist())' 'z = X @ enc' 'print(\"codes run from\", round(z.min(), 2), \"to\", round(z.max(), 2))' > steps/ae.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Train the autoencoder
docker exec jupyter python3 steps/ae.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What ae.py printed
| Line | Value | What it means |
|---|---|---|
| Error at step 0, 10, 20 | 3.6726, 2.9697, 0.0043 | Training found the line |
| Error at step 200 | 0.0043 | Only the noise off the line is left |
| (1, 2) rebuilt | (1.0, 2.0) | On the line: rebuilt well |
| (1, 0) rebuilt | (0.24, 0.48) | Off the line: moved onto it |
| Codes run from | -4.56 to 4.53 | Where training put the codes |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsA VAE makes codes easy to sample
To generate, you would pick a random code and decode it. But a plain autoencoder puts codes wherever training found useful, here from -4.56 to 4.53, and leaves gaps in bigger models.
A VAE fixes this. Its encoder gives a mean and a spread for each input, and the code is drawn from that bell. A KL term in the loss pulls every bell towards the standard bell: mean 0, spread 1.
Worked example: one code from a bell
| Step | Value |
|---|---|
| Encoder gives a mean and a spread | mean 1.5, spread 0.5 |
| Draw noise from the standard bell | -0.8 |
| Code = mean + spread × noise | 1.5 + 0.5 × -0.8 = 1.1 |
| KL term = 0.5 × (mean² + spread² - 1 - log spread²) | 1.443 |
| To generate later | draw a code from the standard bell and decode it |
The cells students fill in are left blank in this preview.
Draw codes and work out the KL term
docker exec jupyter python3 -c "import numpy as np; mu, sigma = 1.5, 0.5; noise = np.random.default_rng(5).normal(0, 1, 4); print((mu + sigma * noise).round(2).tolist()); print(round(0.5 * (mu ** 2 + sigma ** 2 - 1 - np.log(sigma ** 2)), 3))"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think any autoencoder becomes a generator if you decode random codes. A plain one leaves gaps where no training code fell, and decoding there gives nonsense. A random code is only safe when a KL term has kept the codes near a bell you know.
Check
Have a go
Check
3 questionsTry it: the KL term
import math
# The KL term for one code: how far a bell is from the standard bell.
def kl_term(mu, sigma):
return 0.5 * (mu ** 2 + sigma ** 2 - 1 - math.log(sigma ** 2))
for mu, sigma in [[1.5, 0.5], [0.0, 0.5], [1.0, 1.0]]:
print("mean", mu, "spread", sigma, "KL", round(kl_term(mu, sigma), 3))
# Find a mean and a spread that give a KL term of exactly 0.
Make a free account to save your work and track your progress.
Assignment: an autoencoder and its KL term
Write the pieces of a tiny linear autoencoder and of a VAE, for points of two numbers and a code of one.
encode(point, enc) gives point[0] * enc[0] + point[1] * enc[1]. decode(code, dec) gives [code * dec[0], code * dec[1]]. reconstruction_error(points, enc, dec) encodes and decodes every point and gives the mean of all the squared differences, both numbers of every point, rounded to 4 places. sample_code(mu, sigma, noise) gives mu + sigma * noise. kl_term(mu, sigma) gives 0.5 * (mu ** 2 + sigma ** 2 - 1 - math.log(sigma ** 2)) rounded to 4 places.
import math
def encode(point, enc):
return 0
def decode(code, dec):
return [0, 0]
def reconstruction_error(points, enc, dec):
return 0.0
def sample_code(mu, sigma, noise):
return 0
def kl_term(mu, sigma):
return 0.0
Make a free account to save your work and track your progress.
Exit quiz
Have a go