Search

Search papers and lessons

Autoencoder

Level 3 · 8 min read

An autoencoder learns to copy its input through a narrow code, so the code must keep the most useful information, which makes it a way to compress data and learn features without labels.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Losses & regularization
  • Generative models
  • Sign in to see your progress

TL;DR

An autoencoder is a neural network trained to reproduce its own input. It has two halves: an encoder that squeezes the input into a short code, and a decoder that rebuilds the input from that code. The code is deliberately narrower than the input, so the network cannot simply copy the data and has to keep the parts that matter most for reconstruction.

Where you'll see it: compressing images and other high-dimensional data, pretraining feature extractors without labels, denoising corrupted signals, and as the conceptual ancestor of the variational autoencoder.

Intuition

Think of an autoencoder as a translator who has to describe a painting over the phone so that a second person can redraw it. The translator has only a short description to work with. A long, exact description would work, but the phone line is narrow, so the description has to capture the composition, colours and main shapes and leave out the brush strokes. The encoder is the translator, the code is the description, and the decoder is the artist.

Nothing in the training uses labels. The target for each input is the input itself, so the signal comes free with the data. That makes autoencoders a way to learn from unlabelled data.

The reason for the bottleneck is that without it the task is trivial. If the code is as wide as the input, the network can learn the identity map, copy every value through, and get zero loss without learning anything about the data. Forcing the code to be narrow, or otherwise limited, makes the network choose which structure to keep.

flowchart LR
  X[Input x, n values] --> E[Encoder f]
  E --> Z[Code z, k values, k less than n]
  Z --> D[Decoder g]
  D --> XH[Reconstruction x hat, n values]
  XH -. loss compares .-> X

The math

Let the input be x∈Rn\mathbf{x} \in \mathbb{R}^n. The encoder ff maps it to a code z=f(x)∈Rk\mathbf{z} = f(\mathbf{x}) \in \mathbb{R}^k, and the decoder gg maps the code to a reconstruction x^=g(z)∈Rn\hat{\mathbf{x}} = g(\mathbf{z}) \in \mathbb{R}^n. Both are parameterised networks, with weights ϕ\phi for the encoder and θ\theta for the decoder. Training minimises the average reconstruction error over a dataset of NN examples:

Definition: Autoencoder objective
L(ϕ,θ)=1N∑i=1N∥xi−gθ(fϕ(xi))∥2\mathcal{L}(\phi, \theta) = \frac{1}{N} \sum_{i=1}^{N} \left\lVert \mathbf{x}_i - g_\theta\big(f_\phi(\mathbf{x}_i)\big) \right\rVert^2

Here ∥⋅∥\lVert \cdot \rVert is the Euclidean norm, so this is the Mean Squared Error between each input and its reconstruction. The code dimension kk is set in advance and is the main design choice.

The loss is differentiated with respect to both sets of weights by Backpropagation, then reduced with Gradient Descent or a variant. Nothing else changes: the network is an ordinary feed-forward stack, with an encoder followed by a decoder.

Undercomplete and overcomplete codes

When k<nk \lt n the autoencoder is undercomplete: the bottleneck forces compression. When k≥nk \ge n it is overcomplete, and the identity map achieves zero loss, so some other constraint must prevent it. Two common constraints are a sparsity penalty λ∥z∥1\lambda \lVert \mathbf{z} \rVert_1 added to the loss, which pushes most code values to zero, and denoising, where the encoder sees a corrupted input x~\tilde{\mathbf{x}} and must reconstruct the clean x\mathbf{x}.

Linear autoencoders and PCA

If ff and gg are both linear maps, the autoencoder with squared error learns the same subspace as principal component analysis. Baldi and Hornik showed this in 1989. So the nonlinear case is a true generalisation: activation functions let the code capture curved structure that a flat subspace cannot.

Reconstruction error as a diagnostic

For any fixed code, the reconstruction error measures what the code failed to keep. If the decoder reconstructs well on training data but poorly on held-out data, the model has memorised rather than learned structure. The usual check is to report the error on a validation set alongside the training error.

Worked examples

Example
A linear autoencoder with one code value

Take 2-D inputs, n=2n = 2, and a code of size k=1k = 1. Use a linear encoder z=u⊤xz = \mathbf{u}^\top \mathbf{x} and a linear decoder x^=z u\hat{\mathbf{x}} = z\,\mathbf{u}, where u=(0.6,0.8)\mathbf{u} = (0.6, 0.8) is a unit vector.

  1. Input x=(3,4)\mathbf{x} = (3, 4). Code: z=0.6×3+0.8×4=1.8+3.2=5.0z = 0.6 \times 3 + 0.8 \times 4 = 1.8 + 3.2 = 5.0.
  2. Reconstruction: x^=5.0×(0.6,0.8)=(3.0,4.0)\hat{\mathbf{x}} = 5.0 \times (0.6, 0.8) = (3.0, 4.0).
  3. Error: ∥x−x^∥2=0\lVert \mathbf{x} - \hat{\mathbf{x}} \rVert^2 = 0. The input lies exactly along u\mathbf{u}, so nothing is lost.
  4. Input x=(4,3)\mathbf{x} = (4, 3). Code: z=0.6×4+0.8×3=2.4+2.4=4.8z = 0.6 \times 4 + 0.8 \times 3 = 2.4 + 2.4 = 4.8.
  5. Reconstruction: x^=4.8×(0.6,0.8)=(2.88,3.84)\hat{\mathbf{x}} = 4.8 \times (0.6, 0.8) = (2.88, 3.84).
  6. Error: (4−2.88)2+(3−3.84)2=1.2544+0.7056=1.96(4 - 2.88)^2 + (3 - 3.84)^2 = 1.2544 + 0.7056 = 1.96.
  7. Check with Pythagoras: ∥x∥2=25\lVert \mathbf{x} \rVert^2 = 25 and z2=23.04z^2 = 23.04, so the lost part is 25−23.04=1.9625 - 23.04 = 1.96. It matches.

Interpretation: the code keeps the component of each input along u\mathbf{u}, and the loss is the component that was thrown away. An optimal u\mathbf{u} for a dataset is the direction that keeps the most variance, which is the first principal component.

Example
Compressing 28 by 28 images

A grayscale image of handwritten digits has 28×28=78428 \times 28 = 784 pixel values, so n=784n = 784. Choose a code of k=32k = 32.

  1. Compression ratio: 784/32=24.5784 / 32 = 24.5. Each image is stored as 32 numbers instead of 784.
  2. A single linear layer in each direction has 784×32=25,088784 \times 32 = 25{,}088 weights, so the encoder and decoder together have 2×25,088=50,1762 \times 25{,}088 = 50{,}176 weights, ignoring biases.
  3. Training minimises the mean squared error over the training images. The decoder output is then a blurry but recognisable digit for most inputs.
  4. If the code is made wider, say k=784k = 784, the reconstruction becomes nearly perfect, but the code no longer compresses anything and may learn nothing beyond copying.

Interpretation: the choice of kk sets the trade-off between compression and fidelity. A narrower code forgets more detail and keeps only the shapes that the decoder can rebuild cheaply.

Tradeoffs and failure modes

An autoencoder is simple to train and needs no labels, but the reconstruction objective has its own pulls. The network is rewarded for reproducing every pixel equally, so it can spend capacity on noise or texture that matter little for the task.

SituationProblemBetter choice
Code as wide as the input, no other constraintLearns the identity map and no structureNarrow the code, add a sparsity penalty, or use denoising
You want to generate new samples from random codesCodes of a plain autoencoder need not fill the space, so random codes decode to noiseVariational Autoencoder
Linear encoder and decoder with squared errorSame subspace as PCA, with no extra benefitPrincipal Component Analysis
Pretraining for a classifier on imagesPixel reconstruction can over-focus on low-level detailMasked modelling, as in the [[masked-autoencoder
Data with a known, simple noise modelDenoising by reconstruction is indirectA model fitted to the noise directly

The most common failure is a code that is too wide, which gives a near-perfect reconstruction with no useful features. The second is the opposite: a code too narrow for the data, which gives blurry outputs that no amount of training fixes.

History

The idea of training a network to reproduce its input goes back to the 1980s. Rumelhart, Hinton and Williams described an encoder-style task in their 1986 work on backpropagation, using it to show that hidden units can learn useful internal representations. In 2006, Hinton and Salakhutdinov used stacked autoencoders to reduce the dimension of data, which showed that deep, nonlinear codes could beat PCA on reconstruction. Vincent and colleagues introduced the denoising autoencoder in 2008, which made the corruption-and-reconstruction idea a standard regulariser. The variational autoencoder, by Kingma and Welling in 2013, took the same encoder-decoder shape and turned it into a probabilistic generative model.

Check yourself

QuestionWhat stops an autoencoder from learning the identity map, and what determines how much it must throw away?Show answer

The bottleneck: the code has fewer values than the input, so the network cannot pass every value through unchanged. How much information is lost depends on the code size kk and on what the training data look like. For a linear autoencoder with squared error, the best code of size kk keeps the kk directions of greatest variance.

QuestionAn input is x=(0,5)\mathbf{x} = (0, 5) and the linear autoencoder uses u=(0.6,0.8)\mathbf{u} = (0.6, 0.8). Compute the code, the reconstruction and the squared error.Show answer

The code is z=0.6×0+0.8×5=4.0z = 0.6 \times 0 + 0.8 \times 5 = 4.0. The reconstruction is 4.0×(0.6,0.8)=(2.4,3.2)4.0 \times (0.6, 0.8) = (2.4, 3.2). The squared error is (0−2.4)2+(5−3.2)2=5.76+3.24=9.0(0 - 2.4)^2 + (5 - 3.2)^2 = 5.76 + 3.24 = 9.0. As a check, ∥x∥2=25\lVert \mathbf{x} \rVert^2 = 25 and z2=16z^2 = 16, and 25−16=925 - 16 = 9. The error is the component of x\mathbf{x} orthogonal to u\mathbf{u}.

QuestionWhy is a linear autoencoder with squared error no more powerful than PCA, and what does adding nonlinear activations change?Show answer

With linear maps, the composition of encoder and decoder is a linear projection, and the best projection under squared error is the one given by the top principal components. Nonlinear activations let the encoder bend the data onto a curved manifold, so the code can represent structure that a flat subspace cannot, at the cost of losing the closed-form solution that PCA gives.

QuestionApplied: you want a model that makes new handwritten digits by sampling a code and decoding it. Why might a plain autoencoder fail this, and what would you change?Show answer

A plain autoencoder maps each training image to one code, and nothing forces the codes of different digits to fill the space between them. A random code can land in a region the encoder never visited, and the decoder then outputs noise. A variational autoencoder fixes this by encoding each input as a distribution and adding a KL term that pulls the codes toward a simple prior, so that sampled codes decode to plausible digits.

Sources