The idea: squeeze, then rebuild

An autoencoder is a neural network trained to output its own input. That sounds useless, until you make the middle of the network narrow. The first half, the encoder, must squeeze the input into a few numbers, the code z. The second half, the decoder, must rebuild the input from those numbers alone. The narrow middle is the bottleneck. To pass through it, the network has to learn what the inputs have in common and keep only what makes one input different from another.

A 5 by 7 pixel image of the digit 4 goes into the encoder, drawn as layers that narrow from 35 to 12 to 2 numbers. The 2 numbers z1 and z2 are the code. The decoder widens them back from 2 to 12 to 35 pixels and outputs a slightly blurred 4. The loss compares the output with the input pixel by pixel.
The network is shaped like an hourglass: 35 pixels in, 2 numbers in the middle, 35 pixels out, and the loss is how far the output is from the input.

On the canvas the data is 24 tiny images of 5 × 7 = 35 pixels: 6 copies each of the digits 0, 1, 4 and 7. The first copy is the clean digit; in the other five one ink pixel has moved. The network is 35 → 12 → 2 → 12 → 35, with tanh in the hidden layers and a sigmoid on the output so every pixel is between 0 (paper) and 1 (ink). It is trained for real in your browser with backpropagation and the Adam optimizer, from fixed random seeds, so every run gives the same numbers.

Reconstruction error

The network is scored by the mean squared error (MSE) between output x̂ and input x, averaged over the 35 pixels:

MSE(x, x̂) = (1/35) · Σ (x̂ᵢ − xᵢ)²        // 0 = perfect copy

Untrained, every output pixel is about 0.5, so each pixel is off by about 0.5 and the MSE is about 0.25: 0.253 for the digit 4 (Demo 1: one image through the untrained network). One epoch shows the network all 24 images once, in 4 shuffled mini-batches of 6, with one Adam step (learning rate 0.01) per batch. The chart plots the MSE over all 24 images after every epoch: 0.252 at the start, 0.047 after 50 epochs, 0.013 after 300 (Demo 2: train 300 epochs). The trained network rebuilds the 4 with MSE 0.006; its worst pixel is off by 0.30 (Demo 3).

No labels are used anywhere. The target is the input itself, so this is self-supervised learning: any pile of unlabelled images is training data.

Why the bottleneck matters

If the code were as wide as the input, the network could learn to copy pixel by pixel and would learn nothing about digits. With 2 numbers for 35 pixels, copying is impossible. The cheapest way to rebuild 24 images from 2 numbers each is to learn the four digit shapes, then use the code to say which shape and how it varies. Wider codes rebuild better but summarise less; real autoencoders pick the width as a trade-off, or keep a wide code and add another constraint (noise, sparsity) instead.

The code space: digits cluster

Each image's code is a point in a 2D plane, the latent space. The left plot under the pipeline shows the codes of all 24 images, coloured by digit. At epoch 0 they sit in one heap near the centre. As training goes on they spread apart into four clusters, one per digit: after 300 epochs every image's code is closer to the centre of its own digit's cluster than to any other centre. The network was never told which image is which digit; the clusters appear because images of the same digit need similar codes to be rebuilt well.

The decoder works on any code, not only the codes of training images. Decoding codes on the line from the centre of the 1s to the centre of the 7s gives a 1, then blends of both strokes, then a 7 (Demo 4: decode codes between 1 and 7). Many codes between and around the clusters decode to nothing like a digit, so a plain autoencoder is a poor generator. Making the code space smooth enough to sample from is what the variational autoencoder adds; see VAE vs GAN.

The denoising autoencoder

A denoising autoencoder (DAE) has the same shape but a different task: its input is a corrupted copy x̃ and its target is the clean x. Here each pixel is flipped with probability 0.15, with fresh noise every epoch. Both networks start from the same seeded weights and see the same images in the same order; only the input differs.

Top row, plain autoencoder: clean x goes into the network and the output is compared with the same clean x. Bottom row, denoising autoencoder: clean x is corrupted by flipping pixels into x-tilde, x-tilde goes into the network, and the output is compared with the clean x, not with x-tilde.
The only change is the input: the denoising autoencoder sees a corrupted x̃ but is still scored against the clean x.

The test set is one fixed noisy copy of every image (13.7% of its pixels flipped on average). Fed these noisy copies, the plain autoencoder rebuilds the clean images with MSE 0.072; the denoising autoencoder gets 0.038. On the noisy 4, which has 4 flipped pixels, the plain autoencoder gives MSE 0.063 and the denoising one 0.010 (Demo 5: noisy 4, plain vs denoising AE). The plain network never saw noise, so the stray pixels push its code off course. The denoising network learned to ignore them. The price: on clean images its MSE is 0.038, worse than the plain autoencoder's 0.013, because it was never asked to keep the small differences between the 6 copies of a digit.

Autoencoder vs PCA

PCA also turns each image into 2 numbers: the projections onto the two directions of largest variance, PC1 and PC2, and rebuilds the image as mean + z₁·PC1 + z₂·PC2 (see SVD and PCA). It is a linear encoder and decoder. On these 24 images the two components keep 60% of the pixel variance, and the rebuild has MSE 0.078. The autoencoder, with the same 2 numbers, passes PCA's error at epoch 33 and ends 6× lower at 0.013 (Demo 6: autoencoder vs PCA). In the PCA plot the 1s and 7s sit close together; the autoencoder pulls all four digits apart.

PCA, 2 componentsautoencoder, 2-number code
encoder2 dot products with fixed patternsa neural network (35 → 12 → 2)
decodermean + weighted sum of 2 patternsa neural network (2 → 12 → 35)
found byan exact formula (eigenvectors / SVD)gradient descent, from a random start
MSE on the 24 images0.0780.013 after 300 epochs
same answer every timeyesonly with the same seed

The two are closely related: an autoencoder with no activation functions (all linear) trained on MSE learns the same 2D subspace as PCA. The nonlinear activations are what let it bend the subspace around the data. For more on PCA as a picture of the data, see PCA vs t-SNE; for the network itself, neural networks and backpropagation.

Where autoencoders are used

  • Anomaly detection: train on normal data only; an input the network rebuilds badly (high MSE) is unusual.
  • Denoising images, audio or sensor readings, as in Demo 5.
  • Features and compression: the code is a short summary to feed another model or to search by.
  • Latent spaces for generators: image generators such as Stable Diffusion run in the code space of an autoencoder rather than on raw pixels.

See also U-Net Segmentation, a down-and-up network whose skip connections carry detail around the bottleneck.

What the page leaves out

Real autoencoders work on images of thousands of pixels with convolutional encoders and decoders, codes of tens to hundreds of numbers, and millions of training images; here everything is 35 pixels, 24 images and full knowledge of the seeds. The page leaves out sparse and contractive autoencoders, masked autoencoders that hide image patches, vector-quantized codes (VQ-VAE), the variational autoencoder's probabilistic code (covered in VAE vs GAN), binary cross-entropy as the loss, and checking for overfitting on a held-out test set.

On the mind map

Open the Machine Learning mind mapMachine LearningLearning setup: what feedback, how to scoreLearning setupLinear models: weighted sum w·x + bLinear modelsOther classic models: trees, margins, neighboursOther classic modelsUnsupervised: find structure without labelsUnsupervisedTraining: loss, gradient, small stepTrainingNeural networks: layers of σ(W·a + b)Neural networksArchitectures: how layers share informationArchitecturesLanguage models: predict the next tokenLanguage modelsLLM speed and tuning: cheaper to run, safer to useLLM speed and tuningRetrieval and agents: give the model data and toolsRetrieval and agentsConvolutionConvolutionslide a small kernel over the imageCNN layer by layerCNN layer by layerfc1 holds 78% of the weightsU-Net SegmentationU-Net SegmentationSkips concat channels; score masks with DiceCanny Edge DetectionCanny Edge DetectionBlur, gradient, thin, two thresholds, linkHarris CornersHarris CornersR = det − k·trace² large: cornerHistogram EqualizationHistogram Equalizationrunning sum of counts = new levelsFrequency-domain filteringFrequency-domain filteringSharp cut in H rings; Gaussian does notOtsu ThresholdingOtsu ThresholdingMax between-class variance picks tHough TransformHough TransformCollinear pixels' curves cross in one cellErosion and DilationErosion and DilationErode = B fits, dilate = B hitsCNN vs TransformerCNN vs Transformerlocal field vs attention to allRNN, LSTM, GRURNN, LSTM, GRUhidden state; gates fight vanishingSelf-attentionSelf-attentionsoftmax(QKᵀ/√d_k) weights the VDiffusion modelDiffusion modellearn to predict the added noiseVAE vs GANVAE vs GANELBO loss vs generator-discriminator gameAutoencoder2-number bottleneck; rebuild inputContrastive learning, CLIPContrastive learning, CLIPmatch pairs in one space, InfoNCE lossResidual connectionsResidual connectionsx + F(x) lets gradients skip layersOpen the Machine Learning mind mapMachine Learninghow layers share informationArchitecturesConvolutionConvolutionslide a small kernel over the imageCNN layer by layerCNN layer by layerfc1 holds 78% of the weightsU-Net SegmentationU-Net SegmentationSkips concat channels; score masks with DiceCanny Edge DetectionCanny Edge DetectionBlur, gradient, thin, two thresholds, linkHarris CornersHarris CornersR = det − k·trace² large: cornerHistogram EqualizationHistogram Equalizationrunning sum of counts = new levelsFrequency-domain filteringFrequency-domain filteringSharp cut in H rings; Gaussian does notOtsu ThresholdingOtsu ThresholdingMax between-class variance picks tHough TransformHough TransformCollinear pixels' curves cross in one cellErosion and DilationErosion and DilationErode = B fits, dilate = B hitsCNN vs TransformerCNN vs Transformerlocal field vs attention to allRNN, LSTM, GRURNN, LSTM, GRUhidden state; gates fight vanishingSelf-attentionSelf-attentionsoftmax(QKᵀ/√d_k) weights the VDiffusion modelDiffusion modellearn to predict the added noiseVAE vs GANVAE vs GANELBO loss vs generator-discriminator gameAutoencoder2-number bottleneck; rebuild inputContrastive learning, CLIPContrastive learning, CLIPmatch pairs in one space, InfoNCE lossResidual connectionsResidual connectionsx + F(x) lets gradients skip layers
This page on the Machine Learning mind map · 88 pages in 10 branches · open it to see the whole map and test yourself in recall mode.