Generating and exploring images with a VAE

Image analysis

About this lecture

A trained VAE gives us a decoder from a small latent space to images, and an encoder back. Today we use it.

  • Generate: draw z from the prior, decode.
  • Interpolate: walk in z from one image to another; the midpoint is not the pixel average.
  • Explore: what the latent space has learned about digits and about cell shapes.
  • Apply: denoising, anomaly detection, morphology spaces. And the limits: blurry images, nonsense far from the data.

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

Generating: decode a draw from the prior

A 15 by 15 grid of images decoded from evenly spaced latent points: smoothly changing handwritten digits, with smudges near the bottom middle.

Decoding a 15 \times 15 grid of points z \in [-3, 3]^2: almost every point gives a digit-like image, and neighbours are similar. Only the bottom middle, where no training digit lies, decodes to smudges. To make a new image: draw z \sim \mathcal N(0, I) and decode.

Walking through latent space

Top row: seven images decoded along a straight latent line from a 1 to a 7. Bottom row: the pixel-wise fade between the two end images, a double exposure.

Top: decode 7 equally spaced points on the line from the centre of the 1s to the centre of the 7s, z(t) = (1 - t)\,z_A + t\,z_B. Bottom: fade the two end images into each other, pixel by pixel, (1 - t)\,x_A + t\,x_B.

  • The latent walk passes through plausible shapes (here via a 9-like stroke).
  • The pixel fade is a double exposure: a faint 1 and a faint 7 on top of each other.

Midpoint vs average, by hand

A decoder that draws a bright bar on a 3-pixel image at position z: pixel i gets \max(0,\ 1 - |z - i|), i = 0, 1, 2.

z = 0 z = 1 z = 2
decoded (1, 0, 0) (0, 1, 0) (0, 0, 1)
  • Latent midpoint of z = 0 and z = 2: z = 1, the bar in the middle, (0, 1, 0).
  • Pixel average of the two images: (0.5,\ 0,\ 0.5), two half-bright bars.

A linear decoder (PCA) would give the average; a curved decoder moves the bar.

Four 3-pixel images drawn as grey squares with their values: image A (1, 0, 0) at z = 0, image B (0, 0, 1) at z = 2, the latent midpoint z = 1 decoding to (0, 1, 0), and the pixel average (0.5, 0, 0.5) with two half-bright ends.

What the latent space has learned

  • Similar images are neighbours: in the digit VAE, 4 next to 9, and 3, 5, 8 together in the middle.
  • Two numbers are too few to keep ten digits apart: a vote among the 15 nearest test digits in z finds the right digit for 68% of test images.
  • The axes mean nothing by themselves: the KL penalty looks the same if the latent space is rotated, so “z_1” is not “thickness”. Read directions from decoded images, not from the axis labels.
  • Distances are only roughly meaningful, as in any nonlinear map.

Try it: digits

Cell shapes: a morphology latent space

A 15 by 15 grid of decoded cell masks: large round cells on the left, elongated cells at various orientations on the right, dividing cells at the bottom.

The same network trained on synthetic cell masks (28 \times 28): round, elongated, dividing, with a protrusion, at random sizes and orientations.

  • The map organises size (large round cells on the left), elongation and orientation (right) and dividing cells (bottom).
  • A walk in z is a smooth change of shape; a generated mask is a plausible new cell.
  • Thin protrusions are lost: two numbers cannot also hold their direction. Their reconstruction error is the highest of the four kinds.

A nonlinear relative of the point distribution model (PCA of landmark shapes), learned straight from pixels.

Denoising

Three rows of cell masks: the clean mask, the mask with noise added, and the decoded mask, which is clean again.

Columns: clean mask, with noise added (sd 0.3 per pixel), decoded from the code of the noisy mask.

  • The decoder can only draw cell-like images, so it cannot draw the noise.
  • Mean squared error against the clean mask: noisy input 0.045, 0.048, 0.047; decoded 0.009, 0.018, 0.016.
  • But it draws its own version of a cell: details the model never learned (a protrusion, a precise outline) are replaced by typical ones.

Denoising by “project onto what the model can draw”: the nonlinear cousin of keeping a few PCA components.

Anomaly detection

Top row: four normal cell masks, a ring, two cells and a square. Bottom row: their reconstructions; the ring and the two cells come back as one filled blob each, the square as a round cell.

Top: input masks. Bottom: their reconstructions. Four normal test cells, then a ring, two cells and a square.

  • Normal cells (the 12 test examples of the demo): error 0.004–0.023. On 2000 test masks, 99% have error below 0.045.
  • Ring 0.172, two cells 0.253: far above, flagged as unusual. Their codes land far outside the prior’s circle.
  • Square 0.030: below the threshold. It is close enough to a round cell to be rebuilt as one. The detector only sees what the model cannot draw.

Anomaly detection as pseudocode

for every normal image x (not used for training):
    error(x) = mean of (x − decode(centre of encode(x)))²
threshold = the error that 99 % of these normal images stay below
for every new image y:
    if error(y) > threshold:   flag y as unusual
  • The threshold fixes the false alarms: about 1 % of normal images are flagged.
  • The detector sees only what the decoder cannot draw (the square passes).

Try it: cell shapes

β-VAE: tidier space, blurrier images

Weight the KL more, \beta > 1:

  • Clouds are pulled harder to the prior: more overlap, a smoother latent space, and often directions that match one factor each (size, elongation, …): “disentangled”.
  • The decoder must serve wider clouds with one image each: blurrier, more average images.
  • \beta < 1: sharper reconstructions, but the gaps of a plain autoencoder start to return.

There is no free lunch: \beta trades image quality for latent-space quality.

For the one-pixel VAE of the elbo1d demo, the reconstruction term and the KL term of the best cloud against beta on a log scale from 0.1 to 10: reconstruction rises from 0.58 at beta 1 to 2.50 at beta 5, KL falls from 1.12 to 0.29.

Limits

Decoded images of the digit VAE at z = (0, 0), (1.1, -1.1), (2.2, -2.2), (3.3, -3.3), (5, -5) and (8, -8), with the prior density relative to the centre below each: 1, 0.30, 0.0079, 1.9e-5, 1.4e-11, 1.6e-28; even the far ones decode to a confident stroke.
  • Blurry outputs: the decoder outputs the average of all images that fit a given z (next slide). Fine detail and sharp edges are smeared.
  • Far from the data the decoder guesses: it always outputs an image, plausible or not. Generated images are only as good as the training images.
  • Small latent spaces lose detail (protrusions); large ones are hard to look at.
  • Sharper generators: GANs (a generator trained against a classifier that tries to tell real from fake; GANs and normalising flows) and diffusion models (learn to remove noise step by step, then start from pure noise). Both build on the same idea: a learned map from random numbers to images.

The math: why VAE images are blurry

Suppose several different images x are all encoded near the same z. The decoder outputs one image c for that z, chosen to minimise the expected squared error:

\mathbb E\big[\|x - c\|^2\big] = \|c - \mathbb E[x]\|^2 + \mathbb E\big[\|x - \mathbb E[x]\|^2\big] \quad\Rightarrow\quad c^* = \mathbb E[x \mid z].

Six sharp synthetic strokes at slightly different angles and positions, and their pixel-wise mean, a blurry fan-shaped stroke.
  • The best output is the conditional mean: an average of sharp images is a blurry image.
  • The same holds for cross-entropy on pixel “ink”: the best ink probability is the average ink.
  • The wider the clouds (larger \beta), the more images share each z, and the blurrier the mean.

The autoencoder as a tokenizer

Diagram: a 256 by 256 by 3 image goes through a trained encoder into a small grid of codes (32 by 32 by 4, 48 times fewer numbers). Three boxes model the codes: latent diffusion or drifting; a codebook turning them into discrete tokens for a transformer, like words; any model of the codes. Their output goes through the decoder back to pixels. Caption above: trained once, then frozen: the same encoder and decoder under every model built on top.
  • A trained (V)AE is reused as the compression stage of other generators: the encoder turns an image into a small grid of codes (“tokens”), the decoder turns codes back into pixels.
  • Latent diffusion runs in that latent space (guidance and latent diffusion), as do one-step generators such as drifting. With a codebook (vector quantisation, VQ-VAE) the codes become discrete tokens that a transformer models like words (attention): how many image and image–text generators work.
  • Consequences: the compression is shared by everything built on top (48× fewer numbers, cheaper models), and so are the decoder’s habits: fine detail comes from the decoder, not from the measurement (recall hallucination).

Summary

Idea In one line
Generate z \sim \mathcal N(0, I), decode
Interpolate walk z(t) = (1-t)z_A + tz_B; the midpoint is a new shape, not a double exposure
Latent structure similar images nearby; classes overlap in 2D; axes have no fixed meaning
Morphology space a VAE on cell masks orders cells by size, elongation, division
Denoising decode the code of a noisy image: only what the model can draw survives
Anomaly high reconstruction error = unlike the training images (if the model cannot draw it)
Limits blurry (conditional mean), unreliable far from the data; GANs and diffusion go further