Generative Models/Autoencoders

Lesson 8.22,573 words

Autoencoders

An autoencoder is a network trained to copy its input to its output through a narrow channel; the useful product is the bottleneck representation hh, not the reconstruction. We derive the undercomplete autoencoder and prove its linear case recovers PCA, then trade the bottleneck for explicit regularization (sparse, denoising, contractive) and show how a denoising autoencoder learns the low-dimensional manifold the data lives on.

╌╌╌╌

An autoencoder is a network trained to copy its input to its output. Stated that baldly the task is absurd: the identity function copies perfectly and learns nothing. The task becomes useful when the identity is forbidden: route the copy through a channel too narrow, too sparse, or too constrained to pass the input verbatim, so the network must instead discover a compressed code from which the input can be approximately rebuilt. The reconstruction is a pretext; the code is what matters.1

The model factors into two maps. An encoder compresses the input to a code (or latent representation) , and a decoder expands the code back to a reconstruction :

The autoencoder hourglass: encoder compresses to a code , decoder expands it back to .

The training objective averages the reconstruction loss over the data,

and is optimized by the same minibatch gradient descent that trains any other feedforward net: an autoencoder is a feedforward net whose target is its own input. What distinguishes the variants below is not the loss but the constraint that stops from collapsing to the identity. We organize them by that constraint.

variantconstraint on the codewhat it learns
undercomplete (bottleneck)a compressing subspace; PCA when linear
sparsepenalty a few active features per input
denoisingreconstruct clean from corrupted the data manifold / a score field
contractivepenalty a locally flat, noise-robust code

Undercomplete autoencoders

The most direct way to forbid the identity is to make the code smaller than the input. If and with , then must discard dimensions' worth of information, and the only way to reconstruct well is to discard the dimensions that matter least. The code is a bottleneck.

An undercomplete autoencoder squeezes input through a narrow code and expands it back to .

The linear case is PCA

When both maps are linear and the loss is squared error, the autoencoder is not merely like principal component analysis: it spans the same subspace. This is the foundational result of the chapter and ties the autoencoder back to the linear factor models that precede it.

The autoencoder recovers the PCA subspace, not necessarily an orthonormal, variance-ordered basis: can be any matrix whose rows span , since (and therefore the loss) is invariant to an invertible change of basis , inside the code. The latent coordinates are fixed only up to a linear transformation. The value of the autoencoder framing is what comes next: make and nonlinear and the model learns a curved, -dimensional manifold rather than a flat -dimensional subspace, a strict generalization of PCA.2

linear AE / PCAnonlinear AE
encoder deep nonlinear net
learned seta flat -plane through the origina curved -manifold
code meaningprojection onto principal axesnonlinear coordinates on the manifold
capacity risknone (linear)can memorize if over-powered

That last cell is the catch. A sufficiently powerful nonlinear encoder can route the input through a 1-D code by abusing precision, encoding the index of a training example as a single real number and having the decoder look it up, copying the data without learning any useful structure. Capacity must be constrained, which the bottleneck does only crudely. The regularized autoencoders below constrain it directly, and in doing so can afford codes that are as large as, or larger than, the input.

Regularized autoencoders

An overcomplete autoencoder has . Without a bottleneck nothing stops it from learning the identity, so we add an explicit penalty to the loss. The general regularized objective is

and the choice of decides what kind of structure the code acquires. Three choices dominate.

Sparse autoencoders

A sparse autoencoder penalizes the magnitude of the code, typically with an term . Most code units are then driven to zero on any given input, and each input is explained by a small active subset of an otherwise large dictionary of features.

The penalty admits a clean probabilistic reading. If we treat as a latent variable with a factorial prior (a Laplace prior, which is sharply peaked at zero), then maximizing the joint log-likelihood recovers exactly a Gaussian reconstruction term plus the penalty:

Sparsity is thus a MAP estimate under a sparse prior, not an arbitrary add-on: the same logic that makes regression select few features.3

A sparse code over an overcomplete dictionary: most units are off (light), a few fire (filled) per input, and different inputs recruit different active subsets.

Denoising autoencoders

The denoising autoencoder (DAE) changes the task rather than adding a penalty. Corrupt each input with noise, , feed the corrupted to the network, and require it to reconstruct the clean :

Copying is now impossible, since the input it sees is not the target it must produce, so even an overcomplete DAE cannot learn the identity. To undo the corruption it must learn where clean data plausibly lies and pull a corrupted point back toward it.

A denoising autoencoder maps a corrupted input back toward the clean target ; it cannot copy, so it learns structure.

The geometry is the payoff. If clean data concentrates near a low-dimensional manifold, corruption with small Gaussian noise , , pushes points off the manifold; the optimal denoiser maps them back onto it. Under squared-error loss the reconstruction is the conditional mean , and a short expansion connects the residual to the score, the gradient of the log data density:

The denoiser's correction vector points up the density gradient, toward higher- probability regions, that is, back toward the manifold. A DAE trained with Gaussian noise is, implicitly, a score estimator: it learns the vector field that flows any point onto the data manifold.4

Contractive autoencoders

The contractive autoencoder (CAE) penalizes the sensitivity of the code to its input, the squared Frobenius norm of the encoder's Jacobian:

This pressures the encoder to be locally constant: small moves in should barely move . The encoder cannot be constant everywhere — it must still vary enough to reconstruct — so the optimum stays flat in directions that leave the manifold (noise directions, which reconstruction does not need) and varies only along the manifold (the directions that carry data). The Jacobian's singular values collapse except along the tangent space of the data manifold.5

penalty targetsparse AEcontractive AE
what is penalizedthe code value the code's derivative
effect on codefew units activeunits locally insensitive to
manifold readingsparse dictionaryflat across normal directions

The DAE and CAE converge on the same idea from opposite ends. Denoising forces robustness to noise explicitly, by training against corrupted inputs; the contractive penalty forces it analytically, by shrinking the Jacobian. For small Gaussian noise the two are equivalent to first order (both penalize how much the representation reacts to perturbation), and both, as the next section shows, are really statements about a manifold.

The manifold perspective

The unifying picture behind every variant is the manifold hypothesis: real high-dimensional data (natural images, speech, text) does not fill its ambient space but concentrates near a much lower-dimensional, curved manifold. A -pixel image lives in , yet the set of natural images is a vanishingly thin sheet inside that cube; almost every point in is noise.

An autoencoder is a parameterization of such a manifold: the decoder maps the -dimensional code space onto a -dimensional surface in , the image , and the encoder assigns intrinsic coordinates to points near it. Reconstruction error is small exactly for points on the manifold and large for points off it, so minimizing it shapes the manifold to hug the data.

The manifold view of denoising: reconstruction vectors (red) point corrupted points back onto the data manifold (blue), tracing the score .

This is why denoising is so natural a training signal. Corruption is a sample of off the manifold; the clean target is on the manifold; learning to reconstruct is learning the projection onto . The contractive penalty arrives at the same surface analytically, by flattening the encoder normal to , and the undercomplete bottleneck approximates it crudely with a flat -plane. All four variants are estimating the same object: the manifold the data lives on.

varianthow it finds the manifold
undercompleterestricts the code to dimensions; linear case is the best -plane
sparsetiles the manifold with a sparse, overcomplete dictionary of local features
denoisinglearns to project off-manifold points back on — estimates the score
contractiveflattens the encoder normal to the manifold, varies only along it

Training a denoising autoencoder

The training loop is ordinary minibatch gradient descent with one extra step: draw fresh corruption for each example on each pass, so the network sees a different for the same every epoch and cannot memorize a fixed noise pattern.

Algorithm:TrainDAE(fθ,gϕ,D,C,η)\textsc{TrainDAE}(f_\theta, g_\phi, \mathcal{D}, C, \eta) — denoising autoencoder training
  1. 1
    initialize encoder params θ\theta, decoder params ϕ\phi
  2. 2
    repeat
  3. 3
    sample a minibatch {x(1),,x(m)}D\{x^{(1)}, \dots, x^{(m)}\} \sim \mathcal{D}
  4. 4
    for each example x(i)x^{(i)} do
  5. 5
    draw corruption x~(i)C(x~x(i))\tilde x^{(i)} \sim C(\tilde x \mid x^{(i)})
    e.g. add Gaussian noise / mask pixels
  6. 6
    h(i)fθ(x~(i))h^{(i)} \gets f_\theta(\tilde x^{(i)})
    encode the corrupted input
  7. 7
    x^(i)gϕ(h(i))\hat x^{(i)} \gets g_\phi(h^{(i)})
    decode toward the clean target
  8. 8
    L1mix(i)x^(i)22L \gets \frac{1}{m}\sum_i \lVert x^{(i)} - \hat x^{(i)}\rVert_2^2
    reconstruct CLEAN x
  9. 9
    (θ,ϕ)(θ,ϕ)ηθ,ϕL(\theta, \phi) \gets (\theta, \phi) - \eta\,\nabla_{\theta,\phi} L
    joint gradient step
  10. 10
    until converged
  11. 11
    return θ,ϕ\theta, \phi

The only line that differs from a vanilla autoencoder is the corruption draw; set (no corruption) and the loop reduces to the plain reconstruction objective. Common corruption processes are additive Gaussian noise, masking a random subset of inputs to zero (as in masked pretraining), and salt-and-pepper flips.

The latent space

What does the learned code actually look like? Train an autoencoder on clustered data and the encoder lays the codes out so that the structure reconstruction needs is preserved: inputs that are alike map to nearby codes, distinct groups separate. The bottleneck's geometry becomes a usable feature space: the codes are what you feed a downstream classifier, retrieval index, or visualizer.6

A 2-D latent space: each point is a code colored by cluster; a good autoencoder maps similar inputs to nearby codes.

This is the bridge to generative modeling. An ordinary autoencoder organizes its latent space but leaves gaps: sample a random and the decoder may produce garbage, because nothing forced the codes to fill the space according to a known distribution. Imposing such a distribution on the code, so that sampling and decoding yields a fresh, plausible , is the step the variational autoencoder takes — turning the autoencoder from a compressor into a generator.

Autoencoders in current practice

The autoencoder outlived its 2006-era role as a deep-net pretrainer and became a staple in three modern settings, each a direct descendant of a variant above.

Masked autoencoding is self-supervised pretraining at scale. The denoising idea — reconstruct a clean signal from a corrupted one — became the dominant pretraining objective when the corruption is masking: BERT masks tokens and predicts them, and the masked autoencoder (MAE) masks a large fraction of image patches and reconstructs the pixels, learning representations that transfer across vision tasks.7 Masking to zero is the corruption process named in the training loop above, scaled to Transformers and very high mask ratios.

The score connection became a generative model. The theorem that a Gaussian-denoising autoencoder's residual estimates is the seed of denoising score matching and, through it, of diffusion models: a diffusion model is a denoising autoencoder trained at many noise levels at once, and sampling walks the learned score field back toward the data manifold.8 The manifold picture drawn above — reconstruction arrows pointing off-manifold points back on — is literally the reverse diffusion trajectory.

Discrete-code autoencoders compress for downstream generators. The VQ-VAE's learned discrete codebook turned the bottleneck into a compact token language, and modern image and audio generators (including latent diffusion) run their expensive generative model on these autoencoder codes rather than on raw pixels, using the autoencoder purely as a perceptual compressor.9 The bottleneck that began as a way to force compression is now the standard front-end that makes large-scale generation affordable.

Takeaways

  • An autoencoder is encoder plus decoder , trained to minimize reconstruction error . The copy is a pretext; the code is the point.
  • An undercomplete autoencoder () compresses through a bottleneck. The linear case with squared error recovers the PCA subspace, the top eigenvectors of the data covariance (Eckart–Young).
  • Regularized autoencoders drop the bottleneck for an explicit constraint: sparse ( on , a MAP estimate under a Laplace prior), denoising (reconstruct clean from corrupted ), contractive (penalize the encoder Jacobian ).
  • A denoising autoencoder learns the data manifold: its reconstruction residual estimates the score , the field that flows off-manifold points back on.
  • The unifying view is the manifold hypothesis: data lives near a low-dimensional curved surface, and every autoencoder variant is a way of estimating that surface.
  • Organizing the latent space generatively (sampling codes from a known prior) is the leap to the variational autoencoder.

Footnotes

  1. Goodfellow, Deep Learning, Ch. 14 — autoencoders as feedforward nets trained to reconstruct their input through a constrained code; the representation, not the copy, is the object of interest.
  2. Goodfellow, Deep Learning, §14.1 — an undercomplete autoencoder with linear maps and squared-error loss spans the same subspace as PCA (the top eigenvectors of the data covariance).
  3. Goodfellow, Deep Learning, §14.2.1 — sparse autoencoders, where the code penalty is read as a MAP estimate under a factorial Laplace prior on the latent units.
  4. Goodfellow, Deep Learning, §14.5 — denoising autoencoders, and the result that the reconstruction residual estimates the score of the data-generating density.
  5. Goodfellow, Deep Learning, §14.2.3 / §14.7 — contractive autoencoders penalize the Frobenius norm of the encoder Jacobian, flattening the code off the manifold's tangent directions.
  6. Chollet, Deep Learning with Python, Ch. 8 — using a learned bottleneck code as a downstream feature space, and the gap between a plain autoencoder's latent space and a samplable generative one.
  7. He et al., Masked Autoencoders Are Scalable Vision Learners, CVPR 2022, and Devlin et al., BERT, NAACL 2019 — masking as the corruption process, scaled to Transformer pretraining.
  8. Vincent, A Connection Between Score Matching and Denoising Autoencoders, Neural Computation 2011 — the denoising residual as a score estimator, the basis of denoising score matching and diffusion.
  9. Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models, CVPR 2022 — running a generative model on an autoencoder's compressed latent codes rather than raw pixels.

╌╌ END ╌╌