An autoencoder learns to rebuild what it sees — and quietly reveals what it hasn't

Squeeze data through a bottleneck. What survives is the essence; what doesn't come back out is the anomaly.

Take a network and give it a deliberately silly job: reproduce your input at the output. The trick is the shape — force everything through a narrow middle layer. A 64-pixel image has to be crushed into, say, 4 numbers, and then rebuilt from only those.

Copying is impossible by memorisation, so the network is pushed into compression: find the few underlying factors that explain the data and throw away the rest. The narrow layer is the bottleneck or latent code; the first half is the encoder, the second the decoder. No labels are needed anywhere — the input is its own target.

Everything on these two pages follows from one consequence: the network can only rebuild things that look like what it was trained on.

Part 1 · Anomaly detection

Graph 1 · The hourglass

input · 64 px 32 code · 4 32 output · 64 px encoder decoder

Trained by minimising ‖ input − output ‖² — the reconstruction error. That single number is about to do double duty as an anomaly score.

Graph 2 · Reconstruction, and where it breaks

This is a real trained autoencoder running in your browser: 8×8 handwritten digits, bottleneck of 4 numbers. It was trained only on the digits 0–4. It has never seen a 5, 6, 7, 8 or 9 — nor any of the damaged images below.

input
→
→
reconstruction
=
what it got wrong
–
reconstruction error
Digits it was trained on (0–4)
Digits it has never seen (5–9)
Damaged images — noise, inverted, shifted

Click any tile. The middle bars are the 4 numbers the whole image is squeezed into. Notice the error map lights up on the strokes the network doesn't have a vocabulary for.

Graph 3 · The score separates normal from strange

Run every test image through and histogram the reconstruction errors. Familiar digits pile up on the left. Everything unfamiliar drifts right. Anomaly detection is then just a threshold.

threshold – caught – missed – false alarms – AUC –

Drag the threshold. AUC is threshold-free: the chance a random anomaly scores higher than a random normal image. Nothing here used labels during training — only afterwards, to check.

The recipe

  1. Collect only normal data. No anomaly labels needed — which is the point, since anomalies are rare and never look the same twice.
  2. Train an autoencoder to reconstruct it.
  3. Score anything new by its reconstruction error.
  4. Set the threshold at, say, the 95th percentile of normal errors, and tune from there for the false-alarm rate you can live with.

The honest caveat

It works because anomalies are structurally different. Blur that and it degrades: the same setup trained on digits 0–8 and asked to flag 9s only reaches – AUC, because a 9 is largely made of strokes it already knows.

The other failure mode is a bottleneck that's too wide — give the network enough capacity and it learns to copy anything, including the anomalies, and the score goes flat.

Part 2 · The variational autoencoder as a generator

Tempting idea: if the decoder turns short codes into images, feed it a made-up code and get a brand-new image. Free generative model.

It doesn't work. A plain autoencoder is never told to organise its latent space — it just needs distinct inputs to land in distinct places. So the codes end up sprawled across an arbitrary region, clumped, with wide empty gaps between clusters. Pick a point at random and you almost certainly land in a gap, where the decoder has never been trained and outputs mush.

Graph 4 · Two latent spaces, same data

Both models below have a 2-number bottleneck and were trained on all ten digits. Left: a plain autoencoder. Right: a VAE. Each dot is one image, coloured by its true digit.

Autoencoder. Note the axis scale — codes sprawl over tens of units, with holes.

VAE. Packed into a tidy blob centred on zero, with classes touching rather than scattered.

So sample random codes from each and decode them:

Autoencoder — random point in the region its codes occupy.

VAE — random draw from a plain bell curve.

What the VAE changes

Two modifications, and that's genuinely all:

  1. The encoder outputs a small cloud instead of a point — a mean and a spread. Training decodes a random draw from that cloud, so nearby codes must decode to sensible images. (Sampling isn't differentiable, hence the reparameterisation trick: z = μ + σ · ε, with the randomness pushed into ε so gradients flow through μ and σ.)
  2. A second loss term, the KL divergence, pulls every cloud toward a standard bell curve centred at the origin.

loss = reconstruction error + β · KL — a tug of war. Reconstruction wants codes spread far apart for clarity; KL wants them packed at the origin. The truce is a latent space that is full — no gaps to fall into — which is exactly what makes sampling work. Push β too high and everything collapses to a blur; too low and you're back to a plain autoencoder.

Graph 5 · The learned manifold

Sweep a grid across the VAE's latent plane and decode every point. Because the space is continuous, the digits morph smoothly into one another — and every location is a valid image. Click anywhere to decode that spot.

click the map

The centre is the average digit. Moving outward trades one style for another — one direction thickens strokes, another closes loops.

Graph 6 · Interpolation

Take two real images, encode both, and walk in a straight line between their codes. A plain pixel fade would ghost one digit over the other; here every intermediate step is a plausible digit, because the path stays inside the learned manifold.

Choosing between them

AutoencoderVariational autoencoder
Latent spaceArbitrary, gappySmooth, continuous, ~bell-shaped
Sample new dataNoYes
Reconstruction (2-D code, this data)– MSE– MSE
Best atCompression, denoising, anomaly detection Generation, interpolation, structured representations

The VAE reconstructs slightly worse — that's the price of the KL term, and it's the whole trade. For anomaly detection you usually want the plain autoencoder's sharper reconstructions; for generation you want the VAE's tidy space. VAEs also give you a probabilistic anomaly score of their own, via the likelihood the model assigns to a sample.