AI Logic

Architectures

Autoencoder

Updated:

Architecture of an autoencoder. On the left, the overall flow: an MNIST image is compressed to a 30-dimensional code by a 784-1000-500-250 encoder and reconstructed by a symmetric decoder. On the right, three techniques that prevent the network from simply copying its input (undercomplete, sparse, and denoising)

Background and overview

An autoencoder is a neural network trained to convert its input into a small code with an encoder and to reconstruct the input from that code with a decoder. It needs no ground-truth labels: the input itself serves as the target output.

Simply copying the input to the output would be pointless. Autoencoders are therefore built so that they cannot copy perfectly, for example by making the intermediate code small. Then only the information useful for reconstruction, that is, the important features of the data, remains in the code. It is like practicing summarizing a long text into a memo of fixed length and then rewriting the original text from the memo alone. Because the length is limited, you learn to keep only the key points.

The idea itself is old and has been studied since the late 1980s (LeCun 1987, Bourlard and Kamp 1988, and others). It became widely known through a 2006 paper in Science by Hinton and Salakhutdinov. They made it possible to train deep autoencoders with many layers by pretraining one layer at a time and then fine-tuning the whole network, and showed that they compress data into few dimensions far more accurately than principal component analysis (PCA).

The main uses of autoencoders are:

  • Dimensionality reduction and visualization: Compress high-dimensional data into a few to a few dozen numbers.
  • Feature learning: Use an encoder trained on unlabeled data for another task such as classification.
  • Similarity search: Find similar documents or images by how close their codes are.
  • Foundation for generative models: VAE extends the autoencoder structure into a probabilistic model, and Latent Diffusion compresses images with an autoencoder before generating them.

Theory

An autoencoder consists of two parts (left side of the figure at the top of the article).

  • Encoder ff: Converts the input x\boldsymbol{x} into a code (latent representation) h=f(x)\boldsymbol{h} = f(\boldsymbol{x}).
  • Decoder gg: Produces a reconstruction r=g(h)\boldsymbol{r} = g(\boldsymbol{h}) with the same shape as the input from the code.

The training procedure is as follows.

  1. Take an input x\boldsymbol{x} from the training data.
  2. Convert it into the code h\boldsymbol{h} with the encoder and into the reconstruction r\boldsymbol{r} with the decoder.
  3. Compute the difference between the input and the reconstruction (the reconstruction error) L(x,r)L(\boldsymbol{x}, \boldsymbol{r}).
  4. Use backpropagation to compute gradients through the decoder and then the encoder, and update the weights of both together.

The quantity minimized during training is:

min⁡f, g  ∑tL(x(t),  g(f(x(t))))\min_{f,\,g} \; \sum_{t} L\big(\boldsymbol{x}^{(t)},\; g(f(\boldsymbol{x}^{(t)}))\big)

The encoder and decoder are ordinary neural networks. The most basic form is a single fully connected layer each:

h=sf(Wx+b),r=sg(W′h+d)\boldsymbol{h} = s_f(\boldsymbol{W}\boldsymbol{x} + \boldsymbol{b}), \qquad \boldsymbol{r} = s_g(\boldsymbol{W}'\boldsymbol{h} + \boldsymbol{d})

sf,sgs_f, s_g are activation functions, W,W′\boldsymbol{W}, \boldsymbol{W}' are weight matrices, and b,d\boldsymbol{b}, \boldsymbol{d} are biases. The encoder and decoder sometimes share weights, as in W′=W⊤\boldsymbol{W}' = \boldsymbol{W}^\top (tied weights). For images, convolutions are often used in the encoder and transposed convolutions in the decoder.

Choosing the reconstruction error

The reconstruction error is chosen to match the type of input values.

Input valuesDecoder outputReconstruction error
Unbounded real numbersLinear (no activation)Mean squared error ∥x−r∥2\lVert \boldsymbol{x} - \boldsymbol{r} \rVert^2
Values in 0–1 (pixel intensities, etc.)Sigmoid functionBinary cross-entropy −∑i[xilog⁡ri+(1−xi)log⁡(1−ri)]-\sum_i \big[x_i \log r_i + (1 - x_i)\log(1 - r_i)\big]

Preventing the network from copying its input

If the code dimension is equal to or larger than the input and the encoder and decoder are expressive enough, the network can drive the reconstruction error to 0 by simply copying the input. It then learns nothing about the features of the data. To prevent this, constraints such as the following are imposed (right side of the figure at the top of the article).

  • Undercomplete (bottleneck): Make the code dimension smaller than the input. This is the most basic approach.
  • Sparse: Add to the reconstruction error a penalty Ω(h)\Omega(\boldsymbol{h}) that pushes many components of the code toward 0. The loss is L(x,g(f(x)))+Ω(h)L(\boldsymbol{x}, g(f(\boldsymbol{x}))) + \Omega(\boldsymbol{h}).
  • Denoising: Feed the encoder a corrupted input x~\tilde{\boldsymbol{x}}, for example with some entries set to 0, and have it reconstruct the original x\boldsymbol{x}. The loss is L(x,g(f(x~)))L(\boldsymbol{x}, g(f(\tilde{\boldsymbol{x}}))) (Vincent et al. 2008).
  • Contractive: Penalize the magnitude of the encoder's derivative with respect to the input, λ∥∂f(x)/∂x∥F2\lambda \lVert \partial f(\boldsymbol{x}) / \partial \boldsymbol{x} \rVert_F^2, so that the code changes little when the input changes slightly (Rifai et al. 2011).

The sparse, denoising, and contractive approaches can be used even when the code dimension is larger than the input.

An autoencoder reconstructs well only inputs similar to its training data. For inputs of a different kind, the reconstruction error becomes large. This property can also be exploited by treating inputs with large reconstruction error as "unusual data."

Training deep autoencoders (the 2006 method)

Stacked autoencoders were known to be hard to train directly. According to Hinton and Salakhutdinov, large initial weights lead to poor local minima, while small ones make the gradients in layers near the input very small (vanishing gradients). The paper solved this with the following procedure.

  1. Pretraining: Train two-layer models called restricted Boltzmann machines (RBMs) one layer at a time, starting from the bottom. The features of the first RBM are used as the input to the next RBM.
  2. Unrolling: Stack the trained RBMs to form the encoder, and arrange the same weights in reverse order to form the decoder.
  3. Fine-tuning: Treat the whole as a single autoencoder and minimize the reconstruction error with backpropagation.

For MNIST, a 784-1000-500-250-30 encoder and a symmetric decoder were used. Only the 30 code units are linear; the rest are logistic (sigmoid) units.

According to the paper, shallow autoencoders with a single hidden layer in each of the encoder and decoder can be trained without pretraining. However, pretraining greatly reduced the training time. Also, with the same number of parameters, deep autoencoders achieved lower reconstruction error on test data than shallow ones, but this gap disappeared as the number of parameters increased.

Why can it learn features?

Autoencoders can learn the features of data because they force only the information needed for reconstruction through the narrow passage of the code.

A linear autoencoder learns the same subspace as PCA

When the encoder and decoder are linear and the reconstruction error is the mean squared error, an undercomplete autoencoder learns the same subspace as principal component analysis (PCA). PCA represents data along the directions of greatest variance. However, the autoencoder's weights are not necessarily orthogonal or ordered by size like PCA's principal components; only the spanned space is the same.

Adding nonlinear activation functions to the encoder and decoder lets an autoencoder represent curved low-dimensional structures as well. This is why it is called "a nonlinear generalization of PCA." For example, data lying on a rolled-up sheet of paper is hard to represent with a plane (PCA) but can be represented with few numbers using curved coordinates (an autoencoder).

Data concentrates near low-dimensional "surfaces"

If you pick image pixels at random, almost every result looks like noise. Real images are thought to concentrate near a tiny, low-dimensional surface (manifold) within the high-dimensional space.

  • An undercomplete autoencoder learns to represent positions on that surface with a few numbers (the code).
  • A denoising autoencoder learns to map corrupted inputs that have strayed off the surface back to nearby points on it. Simply copying the input cannot fix corrupted inputs, so the model has to learn the shape of the data distribution.

Too much capacity means nothing is learned

If the encoder and decoder are too expressive, an extreme solution is theoretically possible even with a one-dimensional code, such as memorizing the training data by assigning index ii to the ii-th example. This hardly ever happens in practice, but keep in mind that a small reconstruction error is not the same as having learned good features.

Experimental results

Hinton and Salakhutdinov (2006) compared the error of reconstructing inputs from codes of the same dimension with deep autoencoders and PCA. The values are the average squared error per test image (lower is better).

DataMethodCode dimensionAverage squared error
Synthetic curve images (28×28)Deep autoencoder61.44
Logistic PCA67.64
Logistic PCA182.45
PCA185.90
MNIST (handwritten digits)Deep autoencoder303.00
Logistic PCA308.01
PCA3013.87
Face image patches (Olivetti)Deep autoencoder30126
PCA30135

On the curve images, the 6-dimensional autoencoder reconstructed with lower error than PCA using three times as many dimensions (18). These images were generated from three 2D points (six numbers), so the autoencoder essentially recovered information corresponding to those six numbers.

The paper also reports the following results.

  • Visualization: Reducing MNIST to 2 dimensions with a 784-1000-500-250-2 autoencoder separated the digit classes much more clearly than the first two principal components of PCA.
  • Document retrieval: In an experiment that compressed just over 800,000 news articles (proportions of the 2,000 most frequent words) to 10 dimensions and retrieved articles of the same category by the angle between codes, it outperformed latent semantic analysis (LSA), which is based on PCA.
  • Classification: Pretraining a 784-500-500-2000-10 network in the same way and then training it with backpropagation gave an MNIST error rate of 1.2%, better than backpropagation from random initialization (1.6%) and SVMs (1.4%).
  • Effect of pretraining: Without pretraining, a very deep autoencoder for the curve images could output only the average training image, even after long training.

Practical considerations

Keep the following in mind when using autoencoders.

  • Choose the code size: Too small and reconstructions become coarse; too large and the network can easily copy its input. When the autoencoder is not undercomplete, always apply constraints such as sparsity or denoising.
  • Match the output and reconstruction error to the input: Combine, for example, the sigmoid function with binary cross-entropy if inputs are scaled to 0–1, or a linear output with mean squared error for standardized real values. Do not give a sigmoid output targets outside its range.
  • Do not judge by reconstruction quality alone: If the features are used for another task, evaluate them by accuracy on that task. A small reconstruction error does not guarantee useful features.
  • Not suited to generating new data: In an ordinary autoencoder, where the data lies in code space is not specified. Feeding an arbitrary code into the decoder does not necessarily produce a meaningful output. For generation, use a model that fixes the code distribution during training, such as a VAE.

If a denoising autoencoder is implemented to add noise only during training, make sure no noise is added when extracting features or evaluating. In PyTorch, using nn.Dropout as the input mask stops it under model.eval(). If you build the mask yourself with random numbers, switch on self.training.

Comparison with other methods

The table compares autoencoders with other methods that have similar goals, from the same viewpoints.

MethodMappingConstraint on the codeGenerating new dataTraining objective
PCALinearOrthogonal principal components (ordered by size)Not possibleMaximize variance (closed-form solution)
Autoencoder (undercomplete)Can be nonlinearOnly the dimension is fixedNot suitedMinimize reconstruction error
Denoising autoencoderCan be nonlinearDimension may be largeNot suitedReconstruct the original input from a corrupted one
VAENonlinear, probabilisticPushed toward a standard normal distributionPossibleMaximize a lower bound on the log-likelihood
GANNonlinear (generator only)No encoderPossibleFool the discriminator

Rough guidelines for choosing:

  • First check whether linear is enough: If data is scarce or interpretability matters, start with PCA. It is fast and gives the same result every time.
  • To compress nonlinear structure or learn features: Use an autoencoder. If the input is noisy, a denoising autoencoder is a good fit.
  • To generate new data: Use a VAE, a GAN, or a diffusion model (such as DDPM).
  • To learn features of large images with self-supervised learning: Methods such as MAE, which extend the idea of masking part of the input and reconstructing it to Transformers, are used.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

"""
A fully connected autoencoder that compresses MNIST images into a 30-dimensional code and reconstructs them
(the 784-1000-500-250-30 shape from Hinton & Salakhutdinov 2006, with the now-common ReLU as the activation)
Setting noise_p > 0 turns it into a denoising autoencoder that zeros out part of the input
"""

device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"

# Keep pixels in 0–1 (sigmoid output, binary cross-entropy loss)
transform = transforms.ToTensor()
train_loader = DataLoader(datasets.MNIST("./data", train=True, download=True, transform=transform),
                          batch_size=128, shuffle=True)
test_loader = DataLoader(datasets.MNIST("./data", train=False, download=True, transform=transform),
                         batch_size=256)


class AutoEncoder(nn.Module):
  def __init__(self, in_dim=784, code_dim=30, noise_p=0.0):
    super().__init__()
    self.encoder = nn.Sequential(
      nn.Flatten(),                        # [B, 1, 28, 28] -> [B, 784]
      nn.Linear(in_dim, 1000), nn.ReLU(),
      nn.Linear(1000, 500), nn.ReLU(),
      nn.Linear(500, 250), nn.ReLU(),
      nn.Linear(250, code_dim),            # the code layer is linear (as in the paper)
    )
    self.decoder = nn.Sequential(
      nn.Linear(code_dim, 250), nn.ReLU(),
      nn.Linear(250, 500), nn.ReLU(),
      nn.Linear(500, 1000), nn.ReLU(),
      nn.Linear(1000, in_dim),             # the sigmoid is computed inside the loss function
    )
    self.noise_p = noise_p

  def corrupt(self, x):
    # Denoising: only during training, set a fraction noise_p of the pixels to 0
    if self.training and self.noise_p > 0:
      keep = (torch.rand_like(x) >= self.noise_p).float()
      return x * keep
    return x

  def forward(self, x):
    h = self.encoder(self.corrupt(x))      # code [B, code_dim]
    logits = self.decoder(h)               # reconstruction logits [B, 784]
    return logits, h


model = AutoEncoder(noise_p=0.25).to(device)
criterion = nn.BCEWithLogitsLoss(reduction="sum")   # the target is the input "before corruption"
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(10):
  model.train()                            # add noise
  for x, _ in train_loader:                # labels are not used
    x = x.to(device)
    logits, _ = model(x)
    loss = criterion(logits, x.flatten(1)) / x.size(0)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

  model.eval()                             # turn off noise for evaluation
  total, n = 0.0, 0
  with torch.no_grad():
    for x, _ in test_loader:
      x = x.to(device)
      logits, _ = model(x)
      r = torch.sigmoid(logits)            # reconstruction in 0–1
      total += ((r - x.flatten(1)) ** 2).sum().item()
      n += x.size(0)
  print(f"epoch {epoch + 1}: test squared error per image {total / n:.2f}")

# After training, the encoder alone can be used for feature extraction
model.eval()
with torch.no_grad():
  x, y = next(iter(test_loader))
  codes = model.encoder(x.to(device))      # [256, 30]

FAQ

Q. How does an autoencoder differ from PCA?
A.

Both represent high-dimensional data with fewer numbers, but PCA can use only linear transformations. By including activation functions, an autoencoder can also represent curved structures. An autoencoder with a linear encoder and decoder trained with mean squared error learns the same subspace as PCA. On the other hand, PCA is fast and gives the same result every time, so it is safest to first check whether PCA is enough.

Q. Can an autoencoder create new images?
A.

An ordinary autoencoder is trained without specifying where codes are distributed, so feeding an arbitrary code into the decoder does not necessarily produce a meaningful image. To create new data, use a VAE, which is trained to push the code distribution toward a standard normal distribution, or a GAN.

Q. How should I choose the code dimension?
A.

There is no fixed value. Decide while monitoring the reconstruction error and the performance of the downstream task that uses the code (classification, retrieval, etc.). Hinton and Salakhutdinov (2006) used 30-dimensional codes for MNIST, 2 dimensions for visualization, and 10 dimensions for document retrieval. When the code is larger than the input, apply constraints such as sparsity or denoising.

References

  1. Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the Dimensionality of Data with Neural Networks. Science, 313(5786), 504–507.
  2. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, Chapter 14: Autoencoders. MIT Press.
  3. Bengio, Y., Courville, A., & Vincent, P. (2013). Representation Learning: A Review and New Perspectives. IEEE TPAMI, 35(8), 1798–1828. arXiv:1206.5538.
  4. Vincent, P., Larochelle, H., Bengio, Y., & Manzagol, P.-A. (2008). Extracting and Composing Robust Features with Denoising Autoencoders. ICML 2008.