Machine Learning · 17 of 20

Autoencoder tutorial

Compresses an input through a bottleneck and learns to reconstruct it. Learn the concept, implement it from scratch, and apply it with PyTorch.

Category
Representation learning
Core idea
x̂ = gφ(fθ(x))
Typical use
Compression, denoising, anomaly detection, and feature learning.
Practical tool
PyTorch

What is Autoencoder?

Autoencoder is a representation learning technique. Compresses an input through a bottleneck and learns to reconstruct it. Its central idea is summarized by x̂ = gφ(fθ(x)).

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with PyTorch and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Autoencoder is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with PyTorch and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryPyTorch
Learning modeFrom scratch + library

How Autoencoder works

  1. 1

    Input

    Unlabelled feature vectors, images, or signals.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Encode to a compact latent code, then decode while reducing reconstruction error.

  4. 4

    Output

    A reconstruction and a lower-dimensional representation.

  5. 5

    Validate

    Measure reconstruction error on held-out examples, not only the training set.

Formula and intuition

x̂ = gφ(fθ(x))

fθ is the encoder with parameters θ, gφ is the decoder with parameters φ, and x̂ is the reconstruction of input x.

The notation captures the main operation or complexity statement behind Autoencoder. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Autoencoder

Compression, denoising, anomaly detection, and feature learning.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Autoencoder from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(200, 8))
latent_size = 2
W_encoder = rng.normal(0, .2, (8, latent_size))
W_decoder = rng.normal(0, .2, (latent_size, 8))
lr = .03

for _ in range(1000):
    latent = X @ W_encoder
    reconstruction = latent @ W_decoder
    error = reconstruction - X
    # Backpropagate reconstruction error through the linear decoder and encoder.
    W_decoder -= lr * latent.T @ error / len(X)
    W_encoder -= lr * X.T @ (error @ W_decoder.T) / len(X)

compressed = X @ W_encoder
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Autoencoder with PyTorch

PyTorch makes the encoder, bottleneck, decoder, reconstruction loss, and gradient updates explicit.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install torch
  1. Prepare the data.Unlabelled feature vectors, images, or signals. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Encode to a compact latent code, then decode while reducing reconstruction error.
  4. Inspect the result.A reconstruction and a lower-dimensional representation. Then apply the evaluation checks in the next section.
PythonPyTorch workflow
import torch
from torch import nn

torch.manual_seed(7)
X = torch.randn(1000, 12)
model = nn.Sequential(
    nn.Linear(12, 6), nn.ReLU(),
    nn.Linear(6, 2),
    nn.Linear(2, 6), nn.ReLU(),
    nn.Linear(6, 12),
)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.MSELoss()

for _ in range(500):
    optimizer.zero_grad()
    reconstruction = model(X)
    loss = loss_fn(reconstruction, X)
    loss.backward()
    optimizer.step()

print("reconstruction MSE:", loss.item())

API details and version-specific options: official PyTorch reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Measure reconstruction error on held-out examples, not only the training set.
  • Visualize or probe the latent code to determine whether it preserves useful structure.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • An overpowered decoder can reconstruct well without learning a useful bottleneck.
  • Input scaling must match the output activation and loss.
  • Low reconstruction error does not guarantee semantically meaningful features.

Before using Autoencoder in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference PyTorch

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Autoencoder in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →