06 / 34 · Foundations
Autoencoders
A network trained to reproduce its input through a narrow code: a convolutional autoencoder on MNIST, its reconstruction loss, denoising and sparse variants, and why its codes do not yet give a way to generate.
On this page 7
A digit written by hand and resized to is 4096 numbers, yet almost all of them are predictable from a few facts: which digit it is, how thick the stroke is, how it slants. Can a network find such a short description on its own, without labels? Train it to reproduce its input after squeezing it through a layer of 512 numbers. The copy is only the pretext. What we want is the code the network is forced to build on the way, and later, a way to make new digits from codes (Hinton and Salakhutdinov, 2006; Goodfellow, Bengio and Courville, 2016, chapter 14).
Such a network is an autoencoder. Training a network to pass its input through a narrow hidden layer and back already appears as the “encoding problem” of Rumelhart, Hinton and Williams (1986). It uses the convolution, batch-norm and LeakyReLU blocks of the previous note.
Architecture: downsample, bottleneck, upsample#
An encoder with parameters maps an image to a latent code , and a decoder with parameters maps the code back to a reconstruction :
The letters follow the VAE: belongs to the encoder and to the decoder. The code is smaller than the input, so the network cannot pass the pixels through unchanged; it must keep what it needs to rebuild the image and drop the rest. Every image becomes a point in a learned, lower-dimensional latent space.
With a linear encoder and decoder and squared error, the best the network can do is project onto the top principal components: a linear autoencoder learns the PCA subspace (autoencoders as nonlinear PCA). Nonlinear layers let the code follow curved structure that PCA cannot.
The MNIST digits are resized from to , with pixel values in . The encoder halves the side four times with stride-2 convolutions, (the output-size formula), and the decoder doubles it four times. A side divisible by makes the mirrored decoder return to the input size. At 28 the encoder would give , and four doublings would end at 32.
The convolutional autoencoder, layer by layer
Every encoder block is a convolution with stride 2, batch norm and LeakyReLU with slope 0.2; a last stride-1 convolution produces the code. Every decoder block upsamples by 2 with bilinear interpolation and then applies a convolution, batch norm and LeakyReLU. A final convolution maps 16 channels to 1, followed by a sigmoid.
| Tensor | Shape (channels × height × width) | Numbers |
|---|---|---|
| input | ||
| encoder blocks 1, 2, 3 | , , | , , |
| code after block 4 and the last convolution | ||
| decoder blocks 1, 2, 3 | , , | , , |
| decoder block 4 | ||
| output |
The code holds 512 numbers: 8 times fewer than the resized image, but only 1.5 times fewer than the original 784 pixels. The compression is mild. What matters is how the code is organized.
How to read the encoder and decoder#
No layer is told to compress. The first encoder block even expands 4096 values to 16384 activations; the code becomes small only because the shapes narrow toward the bottleneck. Each halving is a learned stride-2 convolution, so the network decides what survives it, where max or average pooling would apply a fixed rule. In image classifiers, replacing max pooling by a stride-2 convolution cost no accuracy (Springenberg et al., 2015).
The decoder is not an upscaler. Bilinear upsampling has no parameters; the learned convolution after it fills in the detail. In trained convolutional classifiers, early layers respond to edges and deeper layers, whose receptive fields are larger, to parts (Zeiler and Fergus). The same growth of receptive fields lets these channels encode stroke fragments and larger parts of a digit; this run did not visualize them.
Reconstruction loss#
The standard loss is the mean squared error between output and input, averaged over the values of a batch:
PyTorch’s nn.MSELoss() averages over every pixel of the batch: for 64 images. Since pixels lie in , binary cross-entropy is the natural alternative:
Each loss is a negative log-likelihood. A Gaussian decoder with fixed variance on pixels has the density ; taking minus its logarithm,
so MSE is the Gaussian negative log-likelihood up to a positive factor and a constant. BCE is the negative log-likelihood of independent Bernoulli pixels with means . That reading holds only for binary pixels. The resized digits have many grey values. For those BCE is still minimized at : its derivative in , , vanishes there. But it is no longer the log of a normalized density on : for , , not 1 (Loaiza-Ganem and Cunningham, 2019). The VAE builds on this reading of the loss as a likelihood.
Two practical traps follow. With a sigmoid already applied in forward, BCE must be nn.BCELoss: nn.BCEWithLogitsLoss applies its own sigmoid, and the pair would apply it twice. The stabler option is to drop the sigmoid and pass logits to BCEWithLogitsLoss. And the input range must suit the output: colour images are often mapped to by , which rules out a sigmoid output and BCE, whose targets must lie in .
Emergent structure#
Nothing in the loss asks for an organized latent space, and no labels are used. Still, structure emerges. A t-SNE projection (van der Maaten and Hinton, 2008) of the 512-dimensional codes of the test set, coloured by digit, shows clusters by class that are cleaner than before training. Most digits form one compact cluster; the 2s split into two groups and the 1s form an elongated band.
t-SNE draws neighbourhoods. It keeps each code’s nearest neighbours near it in the plane, with the perplexity, 30 here, setting roughly how many count. Cluster sizes and the gaps between clusters carry little information (Wattenberg, Viégas and Johnson, 2016; reading t-SNE). The plot shows whether a code’s neighbours share its label, and even that only qualitatively.
A number comes from a probe: freeze the encoder, compute the codes of labelled images, train a simple classifier on them and report its accuracy on held-out images (Alain and Bengio, 2016; the linear probe of the Deep Learning course). The classifier sees only the code, so its accuracy measures how much class information the code keeps in an easily readable form. The fair baseline is the same probe on an untrained encoder of the same architecture. The same codes can also replace Inception features in FID when the images are unlike ImageNet.
Why the codes do not generate#
Two experiments ask whether the latent space can be used to make images.
Interpolation encodes a 7 and a 2 and decodes for eight values of from 0 to 1. The endpoints are clean digits; the middle frames are overlays of the two strokes, not digits morphing into each other.
Sampling fits an axis-aligned Gaussian to the training codes of each digit, using the per-coordinate mean and standard deviation, draws one code per class and decodes it. In the saved run six of the ten samples are recognisable; the 2, 4, 5 and 8 are badly distorted.
Both failures have the same cause. Training asks only that the codes of training images decode back to those images. It says nothing about where in the codes sit or what lies between them, so an arbitrary point can decode to anything. The codes follow no distribution we know how to sample from: the diagonal Gaussians ignore correlations between coordinates, and they needed labels. A plain autoencoder learns a representation; it is not yet a generative model. The variational autoencoder closes this gap by making the distribution of codes part of the training objective.
Variants#
Denoising autoencoder#
A denoising autoencoder (Vincent et al., 2008) changes the task and keeps the architecture. It corrupts the input with a random , reconstructs from the corrupted version, , and compares the result with the clean . The original paper zeroes a random fraction of the input; additive Gaussian noise is the other common choice (Vincent et al., 2010). Copying the input no longer works, so the network must learn which structure is signal and which is noise.
Denoising autoencoder: corrupt the input, score against the clean image
Here the corruption is with , without clipping, and every block also applies Dropout2d(0.3), which drops whole feature maps during training. After 5 epochs the training loss is against the plain model’s . The task is harder, so the numbers are not directly comparable. On noisy test digits the model removes the noise completely, with slightly thicker strokes and lost small details such as a short hook at the top of a 0. Its codes cluster like the plain model’s.
The idea returns later in the course. With Gaussian corruption, training a denoiser is equivalent to score matching on a smoothed data density (Vincent, 2011; derived in the score-matching note), and a diffusion model’s noise-prediction objective trains one denoiser for many noise levels.
Sparse autoencoder#
A sparse autoencoder adds a penalty that makes each hidden unit active for only a small fraction of inputs (Ng, 2011). The hidden layer can then be large, even larger than the input, without the network simply copying. Two forms are common.
The KL penalty reads a sigmoid unit’s mean activation over a batch as a firing rate and compares it with a target rate through the KL divergence between two coins:
with and here. Ng (2011) averages over the training set; the batch mean estimates it. The penalty fixes only each unit’s average rate, which a unit firing weakly at 0.05 for every input also satisfies; sparsity per input has to come from the interplay with the reconstruction loss. This model’s decoder uses transposed convolutions with kernel 4, stride 2 and padding 1, which double the side: the output size becomes .
Dense and sparse codes: what the sparsity penalty aims for
The L1 penalty adds times the mean absolute value of the 512 code entries:
Its subgradient has constant size, so it keeps pulling small entries toward zero where a squared penalty’s pull vanishes. One coordinate shows the effect: minimizing , the subgradient condition gives , exactly zero whenever (Goodfellow, Bengio and Courville, 2016, section 7.1.2). Plain gradient training steps past zero instead of landing on it, so it only drives entries close to zero.
Where the sparsity penalties break#
Neither penalty works here, for opposite reasons, and both are worth computing.
The KL penalty is too heavy. It sums over every channel and position of the four intermediate encoder layers:
At initialization batch norm centres the sigmoids’ inputs at , and puts the mean of a sigmoid of a roughly symmetric input near 0.5. With , the penalty starts at about
The plain model’s reconstruction error is , nearly four orders of magnitude smaller. The logged sum of both terms falls from in the first epoch to in the fifth and is still falling fast, so training has not converged; only the sum was logged, and logging the terms separately would show the split. The result is visible anyway: worse reconstructions, a fragmented t-SNE plot, and class-wise samples that are only fragments of strokes. With 27136 terms, a weight near would start the penalty at , on the scale of the reconstruction loss in the first epoch.
The L1 penalty is too light, and it can be dodged. Its loss ends at , within noise of the plain model’s , and the codes and reconstructions look the same. The first decoder block applies bilinear upsampling and a bias-free convolution, both linear, and then batch norm, which divides out the scale of its input. Replacing by for any leaves the decoder’s output unchanged, up to batch norm’s , and scales the penalty by , so the encoder can lower the penalty by shrinking without making it sparse. This run did not measure the scale of ; comparing the mean of before and after training would show whether it happened. A sparsity penalty needs a weight tuned against the reconstruction loss and an architecture in which it cannot be bypassed.
Transposed convolution or upsample + conv?#
Both double the size. A transposed convolution learns its own upsampling filter, but when the kernel size is not divisible by the stride the kernel footprints overlap unevenly and produce checkerboard artifacts; resizing followed by a convolution avoids the uneven overlap and is the safer default (Odena, Dumoulin and Olah, 2016). Two caveats from the same study: its best results came with nearest-neighbour resizing, and bilinear resizing, which the plain model here uses, gave the authors trouble. A kernel divisible by the stride, such as 4 with stride 2 in the KL model, removes the uneven overlap: every output pixel then receives exactly taps per dimension. Learned kernels can still produce artifacts. The two decoders here differ in other ways too, so they are not a controlled comparison.
Why a sigmoid at the output?#
Inside the network the blocks use LeakyReLU, (Maas, Hannun and Ng, 2013), for the gradient reasons of the previous note. The output needs something else: the decoder’s last convolution is unbounded, and the targets are pixel intensities in . The sigmoid maps any real number into that range,
with . In the KL-sparse model it is also the hidden activation, because the Bernoulli penalty needs activations readable as rates.
LeakyReLU and sigmoid
For targets in the sigmoid can never produce a negative value. The usual output is then
a sigmoid stretched to (multiply the numerator and denominator of by to get ), as at the end of the DCGAN generator, whose images are scaled to (Radford, Metz and Chintala, 2016, sections 3–4). With MSE a linear output also works, clipped to the valid range for display.
What you should remember#
- An autoencoder learns and by reconstruction; the code is the product.
- MSE is a Gaussian negative log-likelihood, BCE a Bernoulli one, exact only for binary pixels.
- Codes cluster by class without labels, but random encoders already cluster; compare against them with a probe.
- Arbitrary points of the latent space decode to garbage: nothing in training says where codes lie.
- Denoising changes the task and connects to score matching; sparsity penalties need their weight matched to the reconstruction loss.
Notebook#
The experiments follow the autoencoder notebook of the HSE-LAMBDA Deep Generative Models repository. Every training loss and plot described above comes from the run saved with the course. The counts and penalty sizes of Where the sparsity penalties break, 27,136 terms, about 13 and 0.013, are computed from the architecture.
- Data: MNIST resized to , batches of 64 with
drop_last=True, 937 batches per epoch. - The plain autoencoder of the shape table, MSE and Adam at for 5 epochs. The notebook names the encoder and the decoder , the opposite of the letters used here. Its markdown suggests
BCEWithLogitsLossas an alternative, which would apply the sigmoid twice. - Latent experiments: t-SNE (perplexity 30) before and after training, test reconstructions, an 8-frame interpolation and per-class diagonal-Gaussian sampling. The “before” plot runs in
eval()mode, where the untrained batch norms, with running mean 0, running variance 1, and , are identity maps up to . - Denoising: Gaussian noise with factor 0.2 in training and testing (the helper’s default is 0.1) and
Dropout2d(0.3)in every block. - KL-sparse and L1-sparse models with , and . The KL model also passes its code through a sigmoid. Both training loops run the encoder a second time to get the activations for the penalty, which doubles its cost and updates batch norm’s running averages twice per step.
Saved training losses, averaged over each epoch:
| Model | Epoch 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| plain | 0.0103 | 0.0034 | 0.0026 | 0.0023 | 0.0021 |
| denoising | 0.0313 | 0.0137 | 0.0116 | 0.0107 | 0.0102 |
| KL-sparse (sum of both terms) | 8.8531 | 4.4430 | 2.3315 | 0.7877 | 0.2141 |
| L1-sparse (sum of both terms) | 0.0095 | 0.0034 | 0.0028 | 0.0024 | 0.0022 |
Homework 1 of the same repository has no saved outputs and empty solution cells, so it documents a procedure. Its second half is described in the FID note.
- CIFAR-10 (, ten classes) mapped to , so the decoder needs a or linear output. The student writes an encoder whose flattened code has fewer than 3072 numbers.
- The probe: a
GradientBoostingClassifier(50 trees of depth 5) trained on the codes of 5000 random training images and scored on the 10 000 validation images. The trained encoder must beat an untrained one by 5%. A new random subset is drawn at every call, which makes the comparison noisier than it needs to be. - Training with
AdamWat its defaults for 30 epochs, with training and validation MSE plotted per epoch, the validation pass ineval()mode undertorch.no_grad(), and seeds and cuDNN flags set as in the previous note. A function namedevalshadows Python’s built-in.
Next#
A plain autoencoder learns useful codes but specifies no distribution over them, so it cannot sample. The next note makes the distribution of codes part of the model and trains it with a lower bound on the log-likelihood, which turns the autoencoder into a generator.
References#
- D. E. Rumelhart, G. E. Hinton, R. J. Williams. Learning internal representations by error propagation. In Parallel Distributed Processing, vol. 1, chapter 8, MIT Press, 1986. Section “The encoding problem”.
- G. E. Hinton, R. R. Salakhutdinov. Reducing the dimensionality of data with neural networks. Science, 313(5786), 2006.
- I. Goodfellow, Y. Bengio, A. Courville. Deep Learning. MIT Press, 2016. Section 7.1.2: L1 regularization; chapter 14: autoencoders.
- J. T. Springenberg, A. Dosovitskiy, T. Brox, M. Riedmiller. Striving for simplicity: the all convolutional net. ICLR Workshop, 2015.
- G. Loaiza-Ganem, J. P. Cunningham. The continuous Bernoulli: fixing a pervasive error in variational autoencoders. NeurIPS, 2019.
- L. van der Maaten, G. Hinton. Visualizing data using t-SNE. JMLR, 9, 2008.
- M. Wattenberg, F. Viégas, I. Johnson. How to use t-SNE effectively. Distill, 2016.
- A. Saxe, P. W. Koh, Z. Chen, M. Bhand, B. Suresh, A. Ng. On random weights and unsupervised feature learning. ICML, 2011.
- G. Alain, Y. Bengio. Understanding intermediate layers using linear classifier probes. arXiv:1610.01644, 2016.
- P. Vincent, H. Larochelle, Y. Bengio, P.-A. Manzagol. Extracting and composing robust features with denoising autoencoders. ICML, 2008.
- P. Vincent, H. Larochelle, I. Lajoie, Y. Bengio, P.-A. Manzagol. Stacked denoising autoencoders: learning useful representations in a deep network with a local denoising criterion. JMLR, 11, 2010.
- P. Vincent. A connection between score matching and denoising autoencoders. Neural Computation, 23(7), 2011.
- A. Ng. Sparse autoencoder. CS294A lecture notes, Stanford, 2011.
- A. Odena, V. Dumoulin, C. Olah. Deconvolution and checkerboard artifacts. Distill, 2016.
- A. L. Maas, A. Y. Hannun, A. Y. Ng. Rectifier nonlinearities improve neural network acoustic models. ICML Workshop on Deep Learning for Audio, Speech and Language Processing, 2013.
- A. Radford, L. Metz, S. Chintala. Unsupervised representation learning with deep convolutional generative adversarial networks. ICLR, 2016. Section 3: output of the generator; section 4: images scaled to .
- HSE-LAMBDA, Deep Generative Models course repository:
autoencoders.ipynband01_hw_AE-and-FID.ipynb.