AI

Autoencoders: How They Compress and Rebuild Data

Autoencoder explained: how the encoder, bottleneck and decoder work, types like variational autoencoders, autoencoder vs PCA, anomaly detection and code.

By OmniAI Editorial · Nov 22, 2026 · 10 min read

An autoencoder is a neural network that learns to compress data into a small set of numbers and then rebuild the original from that compressed version. It has two halves: an encoder that squeezes the input through a narrow "bottleneck," and a decoder that tries to reconstruct the input from it. Because the network's target is its own input, it needs no labels, and the compressed code it learns captures the most important patterns in the data. Autoencoders are used for dimensionality reduction, denoising, anomaly detection and, in their variational form, for generating new data, including inside image generators like Stable Diffusion.

This guide explains how autoencoders work and their architecture step by step, the main types, variational autoencoder vs autoencoder, autoencoder vs PCA, autoencoders for anomaly detection with a worked example, what are autoencoders used for in modern AI, and a short code example.

How an Autoencoder Works

Think of describing a photo to a friend over a bad phone line. You can only use a few words, so you pick the most important details, and your friend redraws the photo from them. An autoencoder learns to do both sides: choose the few numbers that matter (encoding) and redraw the original from them (decoding).

Training is simple:

  1. Feed an input, such as an image, into the encoder.
  2. The encoder outputs a short vector, the latent code.
  3. The decoder turns that code back into an output of the same shape as the input.
  4. Measure the reconstruction error, the difference between output and input, often with mean squared error.
  5. Adjust all weights with backpropagation to reduce that error, and repeat over many examples.

Because the input is also the target, autoencoders are a form of self-supervised learning: the data labels itself. The bottleneck forces the network to learn structure instead of copying. If the bottleneck were as large as the input, the network could learn to pass data straight through, which IBM's explainer notes is the main risk with too much capacity.

Autoencoder Architecture

PartWhat it doesTypical layers
Input layerTakes the raw data: pixels, sensor readings, a row of featuresSame size as the data
EncoderCompresses step by step, keeping what matters for reconstructionDense layers that shrink, or convolutions that downsample images
Bottleneck (latent space)The compressed code, much smaller than the inputA small dense layer or a small feature map
DecoderExpands the code back to the original shapeMirrors the encoder: dense layers that grow, or transposed convolutions
Output layerThe reconstructionSame size as the input
LossMeasures how far the reconstruction is from the inputMean squared error, binary cross-entropy, or perceptual losses for images

The autoencoder architecture often looks like an hourglass. For images, convolutional autoencoders replace dense layers with convolutions, which preserve spatial structure and need far fewer parameters.

Five columns of ink-outlined cells: tall light columns at the edges, shorter grey columns inside them, and two orange cells in the middle.
Encoder, bottleneck, decoder: data is squeezed through a small code and rebuilt.

Worked example: how much does the bottleneck compress?

DataInput sizeLatent codeCompression
28 × 28 grayscale digit, 32-number code784 values32 valuesabout 24 times smaller
512 × 512 color image in Stable Diffusion's autoencoder512 × 512 × 3 = 786,432 values64 × 64 × 4 = 16,384 values48 times smaller
Sensor log of 100 readings, 8-number code100 values8 values12.5 times smaller

The Stable Diffusion row comes from its model card, which states that the autoencoder "uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4." Working in that much smaller space is what makes image generation affordable.

Types of Autoencoders

TypeKey ideaMain use
Undercomplete (basic) autoencoderBottleneck smaller than the inputCompression, dimensionality reduction
Denoising autoencoderTrained to rebuild clean data from deliberately corrupted inputsRemoving noise from images, audio and signals; robust features
Sparse autoencoderMany latent units, but a penalty keeps most of them inactive for any inputInterpretable features, including inside large language models
Contractive autoencoderPenalizes sensitivity of the code to small input changesRobust representations
Convolutional autoencoderUses convolutions for imagesImage compression, denoising, segmentation backbones
Variational autoencoder (VAE)Encodes inputs as probability distributions in a smooth latent spaceGenerating new data, latent spaces for image generators
Masked autoencoderHides large parts of the input and learns to fill them inPretraining vision models

Variational Autoencoder vs Autoencoder

A plain autoencoder maps each input to a single point in latent space. That's fine for compression, but the space between points is meaningless: decode a random point and you usually get garbage. A variational autoencoder (VAE), introduced by Kingma and Welling in "Auto-Encoding Variational Bayes," fixes this.

How a VAE differs:

  • The encoder outputs a distribution, a mean and a spread for each latent dimension, instead of one point.
  • The model samples a point from that distribution and decodes it.
  • The loss has two parts: reconstruction error plus a term (the KL divergence) that keeps the distributions close to a standard bell curve.

The result is a smooth, continuous latent space where nearby points decode to similar outputs and random samples decode to plausible new data. You can generate new images, interpolate between two examples, or move along directions that change one attribute. VAEs produce blurrier images than GANs or diffusion models on their own, but their latent spaces are extremely useful as building blocks.

The latent diffusion paper behind Stable Diffusion describes running diffusion "in the latent space of powerful pretrained autoencoders" so models can train "on limited computational resources." In practice, the image you get from a text-to-image tool is the decoder half of an autoencoder turning a latent into pixels. Our explainers on the diffusion model and the generative adversarial network cover the generators that build on this.

Autoencoder vs PCA

Principal component analysis (PCA) is the classic way to reduce dimensions: it finds the directions in which data varies most and projects onto them.

PCAAutoencoder
Type of mappingLinearLinear or nonlinear
TrainingClosed-form solution, very fastGradient descent, slower
Data neededWorks on small datasetsNeeds more data
Captures curved structureNoYes, with nonlinear layers
InterpretabilityComponents are clear directionsLatent dimensions are harder to interpret
Reconstruction quality on complex dataLimitedOften much better
Best forQuick baselines, tabular data, visualizationImages, audio, complex sensor data

The two are closely related: an autoencoder with a single hidden layer and linear activations learns the same subspace as PCA. Adding nonlinear layers lets it capture curved structure PCA can't. Hinton and Salakhutdinov's 2006 Science paper showed deep autoencoders learning low-dimensional codes that worked "much better than principal components analysis" for reducing the dimensionality of data, a milestone in the revival of deep networks.

Practical rule: try PCA first. If it can't reconstruct your data well enough, or the structure is clearly nonlinear, move to an autoencoder.

Autoencoders for Anomaly Detection

Using autoencoders for anomaly detection relies on a simple idea: train the network only on normal data, so it learns to reconstruct normal patterns well. When something unusual arrives, the reconstruction is poor, and the high error flags it.

How to set it up:

  1. Collect data from normal operation only: healthy machine vibration, legitimate transactions, normal network traffic.
  2. Train an autoencoder to reconstruct it.
  3. Measure reconstruction error on a held-out set of normal data and pick a threshold, for example the 99th percentile of those errors.
  4. In production, flag any input whose error exceeds the threshold.

Worked example. A factory trains an autoencoder on vibration readings from healthy motors. On held-out normal data, reconstruction errors cluster around 0.010, and the 99th percentile is 0.030. Setting the threshold at 0.030 means about 1 in 100 normal readings will be flagged, a known false-alarm rate the team can live with. A failing bearing then produces readings with errors around 0.120, four times the threshold, and gets caught. If false alarms are too frequent, raise the threshold; if failures slip through, lower it or add more representative normal data.

This approach suits problems where anomalies are rare and varied, so you can't collect enough labeled examples of each failure, such as fraud, equipment faults, network intrusions and manufacturing defects in images.

A light chart panel with an ink baseline, a row of short grey bars of similar height, a dotted ink threshold line above them, and one tall orange bar crossing the line.
Normal inputs rebuild well; an anomaly's reconstruction error jumps above the threshold.

What Are Autoencoders Used For?

Beyond compression and anomaly detection, here's where autoencoders show up in modern AI:

  • Image and video generation: latent diffusion models compress images with an autoencoder, generate in the latent space, then decode.
  • Interpretability of language models: researchers train sparse autoencoders on a model's internal activations to find interpretable features. Anthropic's "Scaling Monosemanticity" work trained sparse autoencoders with up to about 34 million features on Claude 3 Sonnet and found abstract, multilingual features, including ones related to safety-relevant behavior that changed outputs when amplified.
  • Pretraining vision models: masked autoencoders learn by reconstructing hidden image patches.
  • Compression and communication: learned codecs for images and audio.
  • Recommendations and embeddings: compact representations of users, items or documents.

A Simple Autoencoder in Code

A minimal dense autoencoder for 28 × 28 images in PyTorch:

import torch
from torch import nn

class Autoencoder(nn.Module):
    def __init__(self, latent_dim=32):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, latent_dim)
        )
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 256), nn.ReLU(), nn.Linear(256, 784), nn.Sigmoid()
        )

    def forward(self, x):
        code = self.encoder(x)
        return self.decoder(code).view(-1, 1, 28, 28)

model = Autoencoder()
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

Training then loops over batches of images, computes loss_fn(model(x), x), and steps the optimizer: the input is its own target.

Common Mistakes

  • Bottleneck too large. The network learns to copy instead of compress; shrink the code or add regularization.
  • Training anomaly detectors on contaminated data. If anomalies sit in the training set, the model learns to reconstruct them too.
  • Ignoring scaling. Normalize inputs; otherwise features with large values dominate the reconstruction error.
  • Expecting a plain autoencoder to generate. Use a VAE or another generative model for sampling new data.
  • Judging only by loss. Look at reconstructions and check whether the latent space is useful for your task.

FAQ

What is an autoencoder in simple terms?

It's a neural network that learns to shrink data into a short summary and then rebuild the original from that summary. Learning to do this well teaches it what matters in the data.

What is the difference between an autoencoder and a variational autoencoder?

A regular autoencoder maps each input to one point in latent space. A variational autoencoder maps it to a probability distribution and keeps the latent space smooth, so you can sample new points and generate realistic new data.

Is an autoencoder supervised or unsupervised?

It's usually called unsupervised or self-supervised, because it learns from unlabeled data by using the input itself as the target.

When should I use an autoencoder instead of PCA?

When your data has nonlinear structure, such as images, audio or complex sensor signals, and you have enough data to train a neural network. For small, tabular datasets, PCA is faster and often good enough.

Can autoencoders detect anomalies?

Yes. Train on normal data only, then flag inputs that the model reconstructs poorly. It's widely used for fraud, equipment monitoring and defect detection.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog