The variational autoencoder

Image analysis

About this lecture

An autoencoder gives every image a point z. A variational autoencoder (VAE) gives every image a small cloud, and keeps all clouds near one standard bell shape.

  • Why: so that every point of the latent space decodes to a plausible image, and we can generate new ones.
  • How: the decoder is trained on random draws from each cloud (the reparameterisation trick).
  • The loss has two parts: rebuild the image + stay close to the standard cloud (a KL divergence).

Slides titled The math give the formulas and proofs; the ideas are complete without them.

What a plain autoencoder lacks

A plain autoencoder only has to rebuild its training images. It may place them anywhere in z.

  • Nothing says what lies between two training images: decode a point in a gap and the result can be anything, often a smudge that is no digit at all.
  • Nothing says where the images are: to generate a new image, which z should we pick?
  • Each image is one point, with no notion of how sure the encoder is.

We want: similar images nearby, no gaps, and a known region to draw new z from.

Sketch of a plain autoencoder's 2D latent space: three tight groups of points for 0s, 1s and 7s far apart, axes running to plus and minus 8, and a question mark in the empty gap between them where the decoder was never trained.

A cloud instead of a point

The encoder outputs, for each image x, a centre \mu(x) and a spread \sigma(x): a Gaussian cloud q(z \mid x) = \mathcal N\big(\mu(x),\ \sigma(x)^2\big).

  • During training the decoder is handed a random point of the cloud, not the centre, and must still rebuild this image.
  • So every point near an image must decode to something like it: the space around each image gets trained.
  • A penalty pulls every cloud towards one standard cloud \mathcal N(0, I), the prior. Clouds overlap, gaps fill.

Two forces: rebuild well (small, separate clouds) against look like the prior (wide, overlapping clouds near 0).

Sketch of a VAE's 2D latent space: the same three groups, now as overlapping ellipse-shaped clouds packed inside the dashed circle of the prior, axes running to plus and minus 3.

The result on handwritten digits

The 2D latent space of the digit VAE: cloud centres of 1000 test digits coloured by digit, labelled 0 to 9, six small orange clouds, and the dashed circle of radius 2 of the prior.

A VAE with a 2D latent space trained on 60,000 handwritten digits (MNIST). Dots: the cloud centres of 1000 test digits; orange: the clouds (±2 sd) of six test digits.

  • Digits of one kind sit together; similar digits (4, 9; 3, 5, 8) are neighbours.
  • Almost everything lies inside the prior’s dashed circle: no big gaps.
  • The clouds are small (sd about 0.07): the image says a lot about z.

The reparameterisation trick

How do we draw “a random point of the cloud” and still train by walking downhill?

z = \mu + \sigma\,\varepsilon, \qquad \varepsilon \sim \mathcal N(0, 1).

  • Draw the randomness \varepsilon first, from a fixed bell curve; then shift and stretch it.
  • Example: \mu = 1, \sigma = 0.5: \varepsilon = -1 gives z = 0.5; \varepsilon = 0.5 gives z = 1.25.
  • z is now an ordinary formula in \mu and \sigma, so the gradient flows back through it to the encoder.

Twenty draws of epsilon from the standard normal on a top axis, each joined by a line to its value z = 1 + 0.5 epsilon on a bottom axis under the narrower bell curve N(1, 0.25); epsilon = -1 maps to z = 0.5 and epsilon = 0.5 maps to z = 1.25.

How far is a cloud from the prior?

The penalty is the Kullback–Leibler divergence \mathrm{KL}(q \,\|\, p): zero when the two distributions are equal, positive otherwise. For a 1D cloud \mathcal N(\mu, s^2) and the prior \mathcal N(0, 1):

\mathrm{KL} = \tfrac12\big(\mu^2 + s^2 - 1 - \ln s^2\big)

The prior N(0, 1) as a dashed bell curve and two encoder clouds: mu 1.2, s 0.45 with KL 1.12, and a narrow one at mu -1.5, s 0.15 with KL 2.52.

Moving the centre away from 0 costs \tfrac12\mu^2; a cloud much narrower (or wider) than 1 costs too.

The math: KL of two Gaussians

\mathrm{KL}(q\,\|\,p) = \mathbb E_{q}\big[\ln q(z) - \ln p(z)\big]. With q = \mathcal N(\mu, s^2) and p = \mathcal N(0, 1):

\ln q(z) = -\tfrac12\ln(2\pi s^2) - \frac{(z-\mu)^2}{2s^2}, \qquad \ln p(z) = -\tfrac12\ln(2\pi) - \frac{z^2}{2}.

Use \mathbb E_q[(z-\mu)^2] = s^2 and \mathbb E_q[z^2] = \mu^2 + s^2:

\mathrm{KL} = -\tfrac12\ln s^2 - \tfrac12 + \tfrac12(\mu^2 + s^2) = \tfrac12\big(\mu^2 + s^2 - 1 - \ln s^2\big).

  • \ge 0, with equality only at \mu = 0, s = 1 (since s^2 - 1 - \ln s^2 \ge 0).
  • Not symmetric: \mathrm{KL}(q\|p) \ne \mathrm{KL}(p\|q) in general.

The VAE loss

For every training image x, with z = \mu(x) + \sigma(x)\,\varepsilon:

\text{loss}(x) = \underbrace{\text{reconstruction error of } \text{decode}(z)}_{\text{rebuild this image}} \;+\; \beta\cdot\underbrace{\mathrm{KL}\big(q(z\mid x)\,\|\,\mathcal N(0, I)\big)}_{\text{stay near the prior}}

The VAE on a real test digit 0: the encoder gives a cloud with centre (-2.19, -2.03) and spread (0.08, 0.07); a draw z = mu + sigma epsilon goes through the decoder to a blurry 0; the KL term compares the cloud with the prior, the reconstruction term compares the output with the input.
  • Reconstruction: squared pixel error (Gaussian pixel noise), or the cross-entropy when the decoder outputs an “ink probability” per pixel, as for digits.
  • \beta = 1 is the standard VAE. Larger \beta: tidier latent space, blurrier images. Smaller \beta: sharper, but gaps return.
  • Encoder and decoder are trained together, downhill on the average loss.

One training step as pseudocode

for every training image x:
    mu, s = encoder(x)                       # the cloud
    eps = a random number from N(0, 1)
    z = mu + s · eps                         # reparameterisation
    x̂ = decoder(z)
    loss = error(x, x̂) + β · ½ Σ (mu² + s² − 1 − ln s²)
change all weights a little, downhill on the average loss
  • The only randomness is eps, drawn before the formula: the loss has a gradient in mu and s.
  • The error of one draw is a noisy estimate; averaged over many images and steps, the noise cancels.

The math: where the loss comes from (ELBO)

Model: z \sim p(z) = \mathcal N(0, I), image x \sim p(x\mid z) (the decoder). We would like to maximise \ln p(x) = \ln\int p(x\mid z)\,p(z)\,dz, but the integral is intractable. For any q(z):

\ln p(x) = \ln \mathbb E_{q}\!\left[\frac{p(x\mid z)\,p(z)}{q(z)}\right] \;\ge\; \mathbb E_{q}\big[\ln p(x\mid z)\big] - \mathrm{KL}\big(q\,\|\,p\big) \;=:\; \text{ELBO}

by Jensen’s inequality (\ln is concave). The gap is exactly \mathrm{KL}\big(q(z)\,\|\,p(z\mid x)\big) \ge 0.

  • Maximising the ELBO over the decoder makes the images likely; over q it makes q approach the posterior p(z\mid x). The VAE loss is -\text{ELBO} (with \beta = 1).
  • Gaussian decoder p(x\mid z) = \mathcal N(\text{decode}(z), \sigma_x^2 I): -\ln p(x\mid z) = \frac{\|x - \text{decode}(z)\|^2}{2\sigma_x^2} + \text{const}, the squared error.
  • “Variational”: q is chosen from a family (Gaussians) to make the bound tight; the encoder outputs it in one pass for every x (“amortised”).

A VAE you can solve by hand

One grey value x and a 1D latent z. Decoder: \hat x = w z with w = 1 and pixel noise \sigma_x = 0.5. Observed x = 1.5.

cloud q rebuild KL total
\mu = 0,\ s = 1 (the prior) 6.500 0 6.500
\mu = 1.5,\ s = 0.05 (too confident) 0.005 3.622 3.627
\mu = 1.2,\ s = 0.45 (best) 0.580 1.125 1.705

Ignoring the image costs reconstruction; being too sure costs KL. The best cloud sits between the prior and the image.

The total loss as a map over the cloud's centre mu (horizontal) and spread s (vertical), darker is lower; the prior at (0, 1) has loss 6.50, the too confident cloud at (1.5, 0.05) has 3.63, and the darkest valley holds the best cloud at (1.2, 0.45) with 1.705.

Try it: the two forces

The math: the best cloud

L(\mu, s) = \frac{(x - w\mu)^2 + w^2 s^2}{2\sigma_x^2} + \frac{\beta}{2}\big(\mu^2 + s^2 - 1 - \ln s^2\big)

  • \partial L/\partial\mu = 0: \ \mu^* = \dfrac{w\,x}{w^2 + \beta\sigma_x^2}. \qquad\partial L/\partial (s^2) = 0: \ s^{*2} = \dfrac{\beta\sigma_x^2}{\beta\sigma_x^2 + w^2}.
  • Numbers (w = 1, \sigma_x = 0.5, x = 1.5): \beta = 1: \mu^* = 1.2, s^{*2} = 0.2. \beta = 5: \mu^* = 0.667, s^{*2} = 0.556.
  • For \beta = 1 this is exactly the Bayesian posterior of z given x (a product of two Gaussians): here the bound is tight. Larger \beta pulls q towards the prior.

Densities over z: the prior N(0, 1), the likelihood of x = 1.5 centred at z = 1.5 with sd 0.5, the best cloud for beta = 1 (mean 1.2, variance 0.2) between and narrower than both, and the best cloud for beta = 5 (mean 0.67, variance 0.56) pulled towards the prior.

Summary

Idea In one line
Cloud the encoder gives each image a centre \mu and a spread \sigma
Reparameterisation z = \mu + \sigma\varepsilon: randomness first, so gradients flow
Prior one standard cloud \mathcal N(0, I) that all clouds are pulled towards
KL \tfrac12(\mu^2 + s^2 - 1 - \ln s^2) per dimension; 0 only for the prior
Loss reconstruction +\ \beta\cdotKL; \beta = 1 is the standard VAE
Two forces rebuild well (small, separate clouds) vs. look like the prior (wide, overlapping)

Next: use the trained decoder to generate, interpolate and detect unusual images.