◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

Autoencoders

An autoencoder is a neural network trained to copy its input through a narrow middle layer. To succeed, it has to discover a compact code for the data. Those codes are useful for compression, denoising, anomaly detection, and as the starting point for generative models.

Level
●●●●● Easy
Reading
11 min
To learn it well
40 minutes to read, an hour to practise
↗ Plan a path here

Read first

Neural Networks

This leads to

Variational Autoencoders
The full path from zero — 14 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks
  15. Autoencoders

Read them roughly in this order. See it on the concept map →

Why it matters

Most of the data AI works with is wastefully stored. An 8×8 picture of a handwritten digit is 64 numbers, but you could describe it far more briefly: "a 7, slightly slanted, with a thick stroke." A photo, a sound clip or a sensor log is mostly predictable. The interesting information fits in far fewer numbers than the raw data uses.

An autoencoder is a neural network that learns such a short description by itself, with no labels. Variations of this one idea do many jobs:

  • Compression. The encoder in Stable Diffusion shrinks a 512×512 colour image (786,432 numbers) into a 64×64×4 code (16,384 numbers), 48 times smaller. The diffusion model then works on the small code. See Latent Diffusion and Stable Diffusion.
  • Tokenizers for images and sound. Neural audio codecs and image tokenizers are autoencoders whose codes are lists of discrete symbols. They are how language-model-style systems generate music and speech (Music and Voice Generation).
  • Anomaly detection. An autoencoder trained only on normal data rebuilds normal data well and unusual data badly. A large rebuilding error flags a fault, a fraud or a defect. See Anomaly Detection.
  • Denoising. Trained to rebuild clean data from corrupted copies, it learns to remove noise. This is the seed of Diffusion Models.
  • Representation learning and interpretability. The compact code is often a better input for other models, and "sparse autoencoders" are now a main tool for reading the internals of language models (Mechanistic Interpretability).

It is also the first step towards the variational autoencoder, one of the main generative model families.

The intuition

Think of the children's game where one person describes a drawing over the phone and the other tries to redraw it. If the describer may say anything, it's easy. Now allow only eight words. The describer has to pick the eight words that matter most ("seven, tall, slanted, thick, ..."), and both players must agree on what the words mean. Over many rounds they develop a private, efficient code.

An autoencoder is that game played by two networks:

  • The encoder looks at the input and writes a short code.
  • The decoder sees only the code and tries to redraw the input.
  • They are trained together, with one score: how close the redrawing is to the original.

The trick is the narrow middle. Data has to pass through a layer much smaller than the input, called the bottleneck. If the bottleneck were as wide as the input, the network could just pass every number straight through and learn nothing. Because it is narrow, the network is forced to keep what matters and throw away what doesn't.

Input x8×8 digit = 64 numbers Reconstruction x̂rebuilt from 8 numbers Encoder64 → 32 → 8 Decoder8 → 32 → 64 Bottleneck zthe latent code:8 numbers loss = mean (x − x̂)²
Fig. 1 An autoencoder for 8×8 digits. The encoder squeezes 64 pixel values down to an 8-number code at the bottleneck; the decoder rebuilds 64 pixels from that code. The reconstruction on the right is the real output of the network trained below. (Circles are drawn for only some of the 64 and 32 units.)

The code at the bottleneck is called the latent code, and the space of all possible codes is the latent space. "Latent" means hidden. These numbers are never given in the data. The network invents them. Nobody tells it what each number should mean, but after training, nearby codes tend to decode to similar-looking inputs.

Key idea An autoencoder learns to compress then reconstruct. The narrow bottleneck forces it to discover a compact code for the data, with no labels needed: the input is its own target.

How it works

The two halves

Write the input as a vector x\mathbf{x}. For our digits it holds 64 pixel brightnesses between 0 and 1. The encoder is a function ff with its own weights, and the decoder is a function gg with its own weights. Both are ordinary neural networks.

z=f(x),x^=g(z)\mathbf{z} = f(\mathbf{x}), \qquad \hat{\mathbf{x}} = g(\mathbf{z})
  • z\mathbf{z} is the latent code, a vector of length kk (the bottleneck size). Here kk is 2, 8 or 16, much smaller than 64.
  • x^\hat{\mathbf{x}} ("x-hat") is the reconstruction. The hat is the usual mark for "the model's estimate of".

The loss: reconstruction error

Training compares the reconstruction with the input. The usual measure is the reconstruction error, the mean squared difference over all dd input numbers:

L=1d∑j=1d(xj−x^j)2L = \frac{1}{d} \sum_{j=1}^{d} \left(x_j - \hat{x}_j\right)^2

Here xjx_j is the jj-th pixel of the input, x^j\hat{x}_j the same pixel in the reconstruction, and d=64d = 64. The loss is averaged over a batch of images and minimised with Gradient Descent and Backpropagation through both networks at once. For binary or 0-to-1 data, binary cross-entropy is a common alternative.

Notice what is missing: labels. The target is the input itself. That makes an autoencoder an example of Self-Supervised Learning: the data supervises itself.

A worked example with real numbers

Train three autoencoders on 1,500 of scikit-learn's 1,797 handwritten digits, with bottlenecks of 2, 8 and 16 numbers, and test them on the 297 digits they never saw. Each uses the layer sizes in the picture: 64 → 32 → kk → 32 → 64.

Bottleneck kk Compression Test MSE (autoencoder) Test MSE (PCA, kk components)
— (predict the average digit) — 0.074 —
2 32× 0.045 0.053
8 8× 0.020 0.025
16 4× 0.015 0.012

Reading the table:

  • A reconstruction error of 0.020 means the typical pixel is off by about 0.020≈0.14\sqrt{0.020} \approx 0.14 on a 0-to-1 scale. That is enough to read the digit easily.
  • More room in the bottleneck means better reconstructions. Two numbers keep only the rough shape. Sixteen keep most details.
  • PCA is the classic linear way to compress. In fact, a linear autoencoder trained with squared error learns the same subspace as PCA. With tight bottlenecks, the nonlinear autoencoder wins (0.045 against 0.053). At 16 numbers, our small network, trained for only 300 steps, loses to PCA. Nonlinearity is not automatically better, and a quick baseline is always worth running.
Original three test digits Bottleneck 2 test MSE 0.045 Bottleneck 8 test MSE 0.020 Bottleneck 16 test MSE 0.015
Fig. 2 Three test digits (1, 7 and 4) and their reconstructions through bottlenecks of 2, 8 and 16 numbers. With 2 numbers the network keeps only a blurry "average" shape. With 16 it keeps most of the strokes.

Anomaly detection with the same model

The 16-number autoencoder reconstructs a typical test digit with error 0.0125, and its worst test digit has 0.047. Feed it a square of random static instead and the error jumps to 0.200, four times worse than any real digit. The network only knows how to draw digits. Anything else comes out wrong. Setting a threshold on reconstruction error, for example the 99th percentile of errors on normal data, turns the autoencoder into an anomaly detector that never needed examples of anomalies.

Variations worth knowing

  • An undercomplete autoencoder is the basic kind above: the bottleneck is smaller than the input.
  • A denoising autoencoder gets a corrupted input (random noise added, or pixels blanked out) and must reconstruct the clean original. It can't just copy, so it has to learn what real data looks like. That makes even a wide bottleneck useful. Learning to undo noise is the core of Diffusion Models.
  • A sparse autoencoder may have a wide middle layer but is penalised for using more than a few units at once. Each unit then tends to respond to one recognisable feature. Interpretability researchers train them on the internal activations of LLMs to find human-readable features.
  • A convolutional autoencoder uses convolutions in the encoder and transposed convolutions or upsampling in the decoder. This is the standard choice for images.
  • A VQ-VAE forces each code to be one entry from a learned codebook, turning images or audio into sequences of discrete tokens.

Why a plain autoencoder is not a good generator

It is tempting to generate new digits by picking a random code and decoding it. This usually gives garbage. A plain autoencoder only learns to decode the codes it actually produced in training. They lie scattered in odd clumps, with gaps in between that the decoder has never been trained on. Nothing makes the latent space smooth or tells you where to sample. The Variational Autoencoders fixes exactly this. It makes the encoder output a small cloud instead of a point, and gently pulls all the clouds towards a standard bell curve. You can then sample from that bell curve and decode.

In code

A complete autoencoder in PyTorch, trained on scikit-learn's digits. It runs in a few seconds on a laptop CPU.

import torch, torch.nn as nn
from sklearn.datasets import load_digits

torch.manual_seed(0)
X = torch.tensor(load_digits().data, dtype=torch.float32) / 16.0  # 1797 images, 64 pixels in [0, 1]
X_train, X_test = X[:1500], X[1500:]

def make_autoencoder(latent_dim):
    encoder = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, latent_dim))
    decoder = nn.Sequential(nn.Linear(latent_dim, 32), nn.ReLU(), nn.Linear(32, 64), nn.Sigmoid())
    return encoder, decoder

for latent_dim in [2, 8, 16]:
    encoder, decoder = make_autoencoder(latent_dim)
    opt = torch.optim.Adam([*encoder.parameters(), *decoder.parameters()], lr=1e-2)
    for epoch in range(300):                                  # full-batch training
        loss = ((decoder(encoder(X_train)) - X_train) ** 2).mean()
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        test_err = ((decoder(encoder(X_test)) - X_test) ** 2).mean().item()
    print(f"bottleneck {latent_dim:2d}: train MSE {loss.item():.4f}  test MSE {test_err:.4f}")

with torch.no_grad():                                        # anomaly detection
    errors = ((decoder(encoder(X_test)) - X_test) ** 2).mean(1)
    noise = torch.rand(1, 64)                                 # random static, not a digit
    noise_err = ((decoder(encoder(noise)) - noise) ** 2).mean().item()
print(f"typical digit error {errors.median():.4f}, worst digit {errors.max():.4f}, random static {noise_err:.4f}")

# bottleneck  2: train MSE 0.0389  test MSE 0.0454
# bottleneck  8: train MSE 0.0174  test MSE 0.0203
# bottleneck 16: train MSE 0.0126  test MSE 0.0148
# typical digit error 0.0125, worst digit 0.0467, random static 0.1996

The final Sigmoid keeps output pixels between 0 and 1, like the inputs. To make it a denoising autoencoder, change one thing: feed X_train + 0.2 * torch.randn_like(X_train) to the encoder but still compare the output with the clean X_train.

Common pitfalls

  • Bottleneck too wide. With a wide bottleneck and a powerful network, the autoencoder can learn something close to the identity function. Reconstructions look perfect, but the code is useless. Shrink the bottleneck, add noise to the inputs (denoising), or add a sparsity penalty.
  • Bottleneck too narrow. Reconstructions turn into blurry averages, as with k=2k=2 above.
  • Blurry outputs. Squared error rewards predicting the average of all plausible answers, and an average of sharp images is blurry. This is a basic limit of reconstruction losses, and one reason GANs and diffusion models exist.
  • Skipping the baseline. Always compare with PCA. If a linear method does as well, use it.
  • Anomaly threshold set on contaminated data. If the "normal" training data already contains anomalies, the autoencoder learns to rebuild them too. Clean the training set as well as you can.

Watch out Don't sample random codes from a plain autoencoder and expect realistic outputs. Its latent space has gaps that decode to nonsense. If you want to generate, use a Variational Autoencoders or another proper generative model.

Where it leads

A bit of history

Autoencoders date back to the 1980s neural network revival. Networks trained to reproduce their input through a narrow hidden layer appear in work by Rumelhart, Hinton and Williams (1986) and in studies of "auto-association". In 1989 Baldi and Hornik showed that a linear autoencoder learns the same subspace as PCA.

The idea became famous in 2006, when Hinton and Salakhutdinov published in Science that deep autoencoders, trained layer by layer, compressed images and documents far better than PCA. That paper was one of the sparks of the deep learning revival. Vincent and colleagues introduced denoising autoencoders in 2008. In 2013 Kingma and Welling turned the autoencoder into a generative model, the Variational Autoencoders. In 2017 VQ-VAE introduced discrete codes, which led to today's image and audio tokenizers. Since 2023, sparse autoencoders have become a central tool for reading features inside large language models.

Try it

  1. Turn the code into a denoising autoencoder as described below the code. Feed it a noisy test digit and compare its error against the clean original with the error of the noisy input itself.
  2. Train with latent_dim=2 and plot the 2-D codes of all test digits, coloured by their true label (load_digits().target). Do the digits form clusters even though the network never saw a label?
  3. Replace both networks with a single nn.Linear layer each and no activations (a linear autoencoder) and compare its test error with PCA's at k=8k=8.

Hint for 2: plt.scatter(z[:, 0], z[:, 1], c=labels, cmap="tab10").

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You build an autoencoder whose bottleneck is as wide as its input, using a powerful network. Reconstructions look perfect. What is likely wrong?

  2. An autoencoder trained only on normal digits reconstructs a typical digit with error 0.0125 and its worst digit with 0.047. A new input gives error 0.200. What is the sensible conclusion?

  3. At a bottleneck of 16 numbers, the chapter's small autoencoder had test error 0.015 while PCA had 0.012. What lesson does this teach?

  4. You pick a random code and decode it with a plain autoencoder, hoping for a new digit. It comes out as garbage. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Article

From Autoencoder to Beta-VAE

Lilian Weng · 2018 · Intermediate · Free

A clear tour of autoencoders, denoising and sparse autoencoders, VAEs, beta-VAE and VQ-VAE, with the derivations.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Hands-On Machine Learning (code notebooks)

Aurélien Géron · Beginner · notebooks free, book paid

A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/autoencoders.md