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
- Builds on
- 14 concepts →
- Quiz
- 4 questions ↓
Read first
Neural NetworksThis leads to
Variational AutoencodersThe full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- 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.
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 . For our digits it holds 64 pixel brightnesses between 0 and 1. The encoder is a function with its own weights, and the decoder is a function with its own weights. Both are ordinary neural networks.
- is the latent code, a vector of length (the bottleneck size). Here is 2, 8 or 16, much smaller than 64.
- ("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 input numbers:
Here is the -th pixel of the input, the same pixel in the reconstruction, and . 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 → → 32 → 64.
| Bottleneck | Compression | Test MSE (autoencoder) | Test MSE (PCA, 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 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.
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 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
- Variational Autoencoders turns the autoencoder into a true generative model with a smooth latent space.
- Latent Diffusion and Stable Diffusion uses an autoencoder to compress images so diffusion can run 48 times more cheaply.
- Diffusion Models grew out of the denoising idea: learn to remove noise, many times over.
- Self-Supervised Learning covers the wider family of methods that learn from unlabelled data, including masked autoencoders for vision.
- Anomaly Detection and PCA and Dimensionality Reduction are the classical neighbours.
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
- 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.
- Train with
latent_dim=2and 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?- Replace both networks with a single
nn.Linearlayer each and no activations (a linear autoencoder) and compare its test error with PCA's at .Hint for 2:
plt.scatter(z[:, 0], z[:, 1], c=labels, cmap="tab10").
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
From Autoencoder to Beta-VAE
A clear tour of autoencoders, denoising and sparse autoencoders, VAEs, beta-VAE and VQ-VAE, with the derivations.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Hands-On Machine Learning (code notebooks)
A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.
Reducing the Dimensionality of Data with Neural Networks
Deep autoencoders trained layer by layer compress images far better than PCA. A landmark of the deep learning revival.
Neural Discrete Representation Learning (VQ-VAE)
An autoencoder whose latent codes are entries from a learned codebook: the root of image and audio tokenizers.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/autoencoders.md