Autoencoders
Encoder, decoder and bottleneck — what an autoencoder learns, why a linear one recovers PCA, and why without a distribution over codes it cannot generate.
Encoder, decoder and bottleneck
The topic Batch normalization, gradients and convolutions left us with the bricks: strided convolutions that shrink an image and transposed convolutions that grow it back. Now we assemble them into the first architecture on the road to models whose likelihood we can compute or at least bound: the autoencoder. It does not generate anything yet, but its two halves reappear in VAEs, VQ-VAEs and latent diffusion.
An autoencoder is trained to reproduce its own input. An encoder with parameters maps an input to a code , and a decoder with parameters maps the code back to a reconstruction :
Reproducing the input is only a pretext. What we actually want is the code. The key is the bottleneck: the code is smaller than the input, , so the network cannot pass the pixels through unchanged. It has to keep what it needs to rebuild the image and drop the rest. Every input becomes a point in a lower-dimensional latent space that is learned from the data.
The idea is old: Rumelhart, Hinton and Williams (1986) already trained a network to squeeze its input through a narrow hidden layer and back.
The reconstruction loss
Training needs a number that says how far is from . The standard choice is the mean squared error (MSE) over the components, averaged over the data:
estimated, as always, by an average over a batch of training images. Encoder and decoder are trained together by gradient descent on this one loss. Nobody tells the encoder what a good code is; a code is good if the decoder can rebuild the image from it.
Squared error is not an arbitrary choice. Read the decoder output as the mean of a Gaussian over images, with the same fixed variance in every pixel: . Its negative log-likelihood is
The second term does not depend on the network, and the factor is positive. So minimizing squared error is maximizing this Gaussian likelihood, and by the topic Entropy, cross-entropy and KL that is minimizing a cross-entropy. Other decoder likelihoods give other losses. An independent Bernoulli variable per pixel, "on" with probability , gives the binary cross-entropy, a common choice for nearly black-and-white digits. Strictly, this reading holds only for binary pixels. Resized digits have many grey values; for them BCE is still minimized at , but is no longer a normalized density on : for its integral over is , not (Loaiza-Ganem and Cunningham, 2019).
Keep in mind which likelihood this is: the probability of given its own code . It is not the likelihood of under a model of the data. The last block returns to that difference.
The linear autoencoder and PCA
To see what an autoencoder learns, start with the simplest one: no nonlinearities. The encoder is a matrix and the decoder a matrix ,
and the data are centred, (with biases, the network would learn the mean anyway).
Every reconstruction lies in the -dimensional column space of , and the closest point of a subspace to is the orthogonal projection of onto it. So the question is which subspace keeps the most. Let be the covariance, with eigenvalues (see the topic Multivariate Gaussians). Projecting onto the span of the top eigenvectors keeps the variance along them and loses the rest, and no other subspace does better:
This is principal component analysis (PCA). A linear autoencoder trained with squared error learns the PCA subspace (Bourlard and Kamp, 1988; Baldi and Hornik, 1989), provided so that the subspace is unique. PCA is the anchor for everything nonlinear that follows.
Two caveats. First, the code itself is not unique. For any invertible matrix , the pair and gives exactly the same , so the autoencoder finds the principal subspace, and its code coordinates can be any mix of the principal components. Second, a linear autoencoder can only fit a flat subspace. Nonlinear encoders and decoders can follow curved structure in the data, which is why deep autoencoders reconstruct better than PCA with codes of the same size (Hinton and Salakhutdinov, 2006).
Convolutional encoders and decoders
For images a fully connected encoder is wasteful. A dense layer from a image to a 512-dimensional code has over two million weights, and it ignores the fact that neighbouring pixels belong together. Convolutional autoencoders are built from the layers of the topic Batch normalization, gradients and convolutions instead.
Encoder: convolutions with stride 2. Recall from that topic that the output side is , so , , halves an even side. A typical encoder stacks four such blocks (convolution, batch normalization, LeakyReLU), with more channels as the side shrinks. An MNIST digit resized to becomes , then , and finally a code. In trained convolutional classifiers early layers respond to edges and deeper ones, with larger receptive fields, to parts of objects; the same growth of receptive fields lets an encoder's channels capture stroke fragments and then larger parts of a digit.
Decoder: the mirror image. Each stage doubles the side, either by a learned transposed convolution or by a fixed upsampling followed by an ordinary convolution. The second option cannot produce the checkerboard artifacts of the previous topic, so it is the safer default.
Output range. The last layer must produce values in the range of the pixels. For pixels in the decoder ends with a sigmoid, , which squashes any real number into .
What the latent space looks like
Nothing in the loss asks for an organized latent space, and no labels are used. Still, structure appears. Train the convolutional autoencoder above on MNIST, project the 512-dimensional codes of test digits to the plane with t-SNE and colour the points by digit: most digits form their own cluster, the 2s split into two groups and the 1s stretch into a band. Similar images get similar codes, because that is the cheap way to rebuild similar images.
Read such plots with care. t-SNE keeps each point's nearest neighbours nearby, but the sizes of clusters and the gaps between them carry little information (Wattenberg, Viégas and Johnson, 2016). And even a randomly initialized convolutional encoder gives visible clusters; training makes them cleaner rather than creating them.
Two experiments probe the space between codes:
- Interpolation. Encode a 7 and a 2 and decode points on the segment between their codes, . The endpoints are clean digits. The middle frames look like a 7 and a 2 drawn on top of each other, not like one digit morphing into the other.
- Other codes. Decode a point that is not the code of any training image, and you often get a smear. The decoder was trained only at the codes of training images. Between and around the clusters lie holes: regions it never had to decode, where its output means nothing.
What autoencoders are good for
A plain autoencoder does not generate, but it is useful.
- Compression. The code is a learned, lossy summary of the input, tuned to one kind of data. Latent diffusion, near the end of the course, runs a generative model in the latent space of an autoencoder instead of on pixels.
- Denoising. A denoising autoencoder (Vincent et al., 2008) corrupts the input, for example with Gaussian noise , , and asks for the clean image. The loss is , measured against , not . Copying the input is no longer a perfect solution, so even a wide code has to learn what is signal and what is noise. This idea returns in diffusion models, which train a denoiser at many noise levels.
- Features. A trained encoder turns images into compact vectors for other tasks. To measure how much a code says about, say, the digit class, freeze the encoder, train a simple classifier on the codes of labelled images and report its accuracy on held-out images. Such a classifier is called a probe (Alain and Bengio, 2016).
Why an autoencoder cannot generate
To generate, in the sense of the first topic, we must be able to draw new samples . A plain autoencoder defines no such distribution. It is a pair of deterministic maps, and to sample with it we would have to pick a code and decode it. Pick it from what?
- No distribution over codes. Training never says where codes should lie. Their location, scale and correlations are whatever the optimizer happened to find, and they change from run to run.
- No training signal away from the codes. The loss involves only the points . The decoder is never asked to make sense of a code in a hole.
- No likelihood. The reconstruction loss is at , the probability of given its own code. A model of the data needs , which averages over codes drawn from some distribution, and the autoencoder has none.
One can fit a density to the codes after training. In one MNIST experiment, a diagonal Gaussian per digit class (which needs the labels) gave six recognisable digits out of ten, one draw per class. A single Gaussian fitted to all codes is worse: when the codes form separated clusters, it puts a lot of mass into the holes between them, exactly where the decoder was never trained.
So the distribution of codes has to be part of the model, fixed in advance and enforced during training: a prior , a decoder that is a likelihood , and an encoder that keeps the codes where the prior expects them. That is the variational autoencoder, built in the next topic, Latent variables and the ELBO.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.