Skip to content

Module 16

Anurag Prasad edited this page Nov 8, 2026 · 9 revisions

Module 16 — Autoencoders and Representation Learning

⬅️ Module 15 · 🗺️ Curriculum · 🏠 Home · Module 17 ➡️

Level: Intermediate · Prerequisites: Modules 01, 07, 03 · Time: about 6–7 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Labels are expensive; raw data are plentiful. Representation learning asks a network to discover useful features from unlabeled data. The autoencoder is the simplest such model: compress the input to a low-dimensional code and reconstruct it. Variants (undercomplete, sparse, denoising, contractive) differ in how they prevent the trivial identity solution, and each connects to classical ideas: PCA, sparse coding and score estimation.

After this module you should be able to:

  • write the autoencoder objective and explain why a bottleneck or regulariser is needed;
  • show that a linear autoencoder with MSE recovers the PCA subspace;
  • derive the sparse-autoencoder KL penalty and explain denoising/contractive objectives;
  • evaluate whether a representation is useful (probing, retrieval) beyond reconstruction error.

Beginner: the big picture

Imagine summarising a page in one sentence so that someone could rewrite the page from the summary. If the summary is good it must capture the essential content. An encoder $f$ maps $\mathbf{x}\to\mathbf{z}$ (the summary), a decoder $g$ maps $\mathbf{z}\to\hat{\mathbf{x}}$ (the rewrite), and training minimises the reconstruction error.

flowchart LR
    X["Input x (d dims)"] --> ENC["Encoder f"] --> Z["Code z (k << d dims)"] --> DEC["Decoder g"] --> XH["Reconstruction x_hat"]
    XH --> LOSS["Loss: ||x - x_hat||^2"]
    X --> LOSS
Loading

Core concepts and derivations

Representation learning and the autoencoder objective

$$ \min_{f,g}\ \frac1N\sum_{i=1}^N\ell\bigl(\mathbf{x}_i,,g(f(\mathbf{x}_i))\bigr),\qquad\ell=\lVert\mathbf{x}-\hat{\mathbf{x}}\rVert_2^2\ \text{(real-valued)}\ \text{ or binary cross-entropy (pixels in }[0,1]). $$

Without constraints, an over-complete model can copy its input. Constraints include a narrow bottleneck, sparsity, noise corruption or a contractive penalty.

Undercomplete autoencoders and PCA

Let $X\in\mathbb{R}^{N\times d}$ be centred. A linear autoencoder $\hat X=XW_e W_d$ ($W_e\in\mathbb{R}^{d\times k}$, $W_d\in\mathbb{R}^{k\times d}$) minimises $\lVert X-XW_eW_d\rVert_F^2$. The product $W_eW_d$ has rank $\le k$, so by Eckart–Young (Module 01) the optimum reconstructs $X$ with its best rank-$k$ approximation $X_k=U_k\Sigma_kV_k^\top$, i.e. $W_eW_d=V_kV_k^\top$ — the orthogonal projection onto the top-$k$ principal components. The learned subspace equals PCA's (Baldi & Hornik 1989), although individual code axes need not be orthogonal. Nonlinear autoencoders learn a curved manifold, a nonlinear generalisation of PCA (Hinton & Salakhutdinov 2006).

Overcomplete representations and sparse autoencoders

If $k\ge d$, add a sparsity penalty so that few code units are active. With target mean activation $\rho$ (e.g. 0.05) and observed $\hat\rho_j=\frac1N\sum_ia_j(\mathbf{x}_i)$,

$$ L=L_{rec}+\beta\sum_{j}\Bigl[\rho\ln\frac\rho{\hat\rho_j}+(1-\rho)\ln\frac{1-\rho}{1-\hat\rho_j}\Bigr] $$

(the KL divergence between Bernoulli($\rho$) and Bernoulli($\hat\rho_j$)); an $\ell_1$ penalty $\beta\lVert\mathbf{z}\rVert_1$ is the common alternative. Sparse codes give interpretable, part-like features; modern sparse autoencoders are used to decompose LLM activations into candidate interpretable features.

Denoising autoencoders

Corrupt the input, $\tilde{\mathbf{x}}=\mathbf{x}+\boldsymbol\varepsilon$ (or mask pixels, drop tokens), and reconstruct the clean $\mathbf{x}$: $L=\lVert\mathbf{x}-g(f(\tilde{\mathbf{x}}))\rVert^2$. The identity no longer works; the model must learn the structure of the data. For small Gaussian noise $\sigma^2$, the optimal denoiser satisfies $r(\mathbf{x})-\mathbf{x}\approx\sigma^2\nabla_{\mathbf{x}}\ln p(\mathbf{x})$ (Alain & Bengio 2014; Vincent 2011), i.e. it estimates the score — the idea that returns in diffusion models (Module 20) and masked pretraining (BERT, MAE).

Contractive autoencoders

Penalise the Jacobian of the encoder: $L=L_{rec}+\lambda\lVert\partial f/\partial\mathbf{x}\rVert_F^2$. The code then changes little in directions that do not matter for reconstruction (insensitive to noise) but remains sensitive along the data manifold (Rifai et al. 2011).

Latent geometry, reconstruction and downstream usefulness

Low reconstruction error does not imply a useful representation: a model may spend capacity on pixel-level detail irrelevant to semantics. Evaluate with linear probes (train a linear classifier on frozen $\mathbf{z}$), nearest-neighbour retrieval, clustering and few-label fine-tuning. Interpolating between codes tests smoothness; a plain autoencoder has no guarantee that random $\mathbf{z}$ decode to valid samples (motivating VAEs, Module 18).

Worked example

Sparsity penalty. Target $\rho=0.05$, a unit with $\hat\rho=0.2$: $0.05\ln\frac{0.05}{0.2}+0.95\ln\frac{0.95}{0.8}=-0.0693+0.1633=0.0939$; it is $0$ at $\hat\rho=\rho$ and grows as the unit fires too often.

Bottleneck sizes. MNIST $784\to128\to32\to128\to784$: parameters $\approx784\cdot128+128+128\cdot32+32+32\cdot128+128+128\cdot784+784\approx210{,}000$; compression ratio $784/32=24.5$.

Implementation

import numpy as np

def pca_ae_check(X, k):
    X = X - X.mean(0)
    U, S, Vt = np.linalg.svd(X, full_matrices=False)
    Xk = (U[:, :k] * S[:k]) @ Vt[:k]                         # optimal rank-k reconstruction
    return np.linalg.norm(X - Xk) ** 2, np.sum(S[k:] ** 2)  # equal: error = sum of dropped sigma^2

X = np.random.default_rng(0).normal(size=(200, 10)) @ np.random.default_rng(1).normal(size=(10, 10))
print(pca_ae_check(X, 3))
import torch, torch.nn as nn
class DAE(nn.Module):
    def __init__(s, d=784, k=32):
        super().__init__(); s.f = nn.Sequential(nn.Linear(d, 256), nn.ReLU(), nn.Linear(256, k))
        s.g = nn.Sequential(nn.Linear(k, 256), nn.ReLU(), nn.Linear(256, d))
    def forward(s, x): return s.g(s.f(x))
# loss = F.mse_loss(model(x + 0.3 * torch.randn_like(x)), x)       # denoising objective

Advanced topics

  • Convolutional/U-Net autoencoders for images; masked autoencoders (MAE) mask 75% of patches and reconstruct, a strong self-supervised vision pretraining (He et al. 2022).
  • Disentanglement (β-VAE, Module 18) and its identifiability limits.
  • Vector-quantised autoencoders (VQ-VAE) learn discrete codes used by image/audio generators.
  • Anomaly detection: high reconstruction error flags outliers — but expressive decoders can reconstruct anomalies too.
  • Information bottleneck view: trade compression of $\mathbf{x}$ against retained task-relevant information.
  • Deep autoencoder pretraining historically enabled training deep nets (Hinton & Salakhutdinov 2006).

Pitfalls and best practices

  • An over-powerful decoder with no constraint copies the input.
  • Judging a representation by reconstruction error alone.
  • Using MSE on binary/categorical inputs (use cross-entropy).
  • Forgetting to evaluate on corrupted and clean inputs for DAEs.
  • Treating the learned code axes as meaningful without validation.

Conceptual questions and answers

Q1. Why does an autoencoder need a bottleneck or regulariser?

Otherwise $g\circ f=\mathrm{id}$ achieves zero loss without learning anything useful. Constraints force the code to capture structure.

Q2. How is a linear autoencoder related to PCA?

With MSE it learns the same $k$-dimensional subspace as the top-$k$ principal components (Eckart–Young), though not necessarily orthonormal axes.

Q3. Why does a denoising autoencoder learn the data distribution's structure?

To undo noise it must know which perturbations lead off the data manifold; the optimal denoiser points along $\nabla\ln p(\mathbf{x})$ (the score).

Q4. What does the sparse KL penalty enforce?

That each hidden unit is active on only a small fraction $\rho$ of examples on average, yielding specialised, part-like features.

Q5. Can a plain autoencoder generate new samples?

Not reliably: its latent space is unconstrained, so most codes decode to garbage. VAEs add a prior and a regulariser to fix this.

Q6. How would you test that learned features are useful?

Linear probing, k-NN retrieval, clustering quality, and fine-tuning with few labels compared with a supervised baseline.

Q7. What is the difference between sparse and undercomplete autoencoders?

Undercomplete restricts dimension ($k&lt;d$); sparse allows $k\ge d$ but restricts how many units are active.

Sources and further reading

  • Baldi, P., & Hornik, K. (1989). Neural networks and principal component analysis. Neural Networks, 2(1).
  • Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the dimensionality of data with neural networks. Science, 313.
  • Vincent, P., Larochelle, H., Bengio, Y., & Manzagol, P.-A. (2008). Extracting and composing robust features with denoising autoencoders. ICML.
  • Vincent, P. (2011). A connection between score matching and denoising autoencoders. Neural Computation, 23(7).
  • Alain, G., & Bengio, Y. (2014). What regularized auto-encoders learn from the data-generating distribution. JMLR, 15.
  • Rifai, S., et al. (2011). Contractive auto-encoders. ICML.
  • Ng, A. (2011). Sparse autoencoder. CS294A lecture notes, Stanford.
  • Bengio, Y., Courville, A., & Vincent, P. (2013). Representation learning: a review and new perspectives. IEEE TPAMI, 35(8).
  • He, K., et al. (2022). Masked autoencoders are scalable vision learners. CVPR. arXiv:2111.06377.

⬅️ Module 15 · 🗺️ Curriculum · 🏠 Home · Module 17 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally