~/writing/Research/Machine Learning $ cat understanding-autoencoders.md
🌟 Understanding Auto-encoders
- DATE
- READ
- 17 MIN
- NO.
- 004
An auto-encoder (AE) is a neural network structure commonly used in generative tasks. It encodes its input into a piece of data called the latent code, then decodes that code back into an output. The training goal is to make the output as close to the input as possible, which usually makes it unsupervised learning. We usually train an auto-encoder because we want to use its ability to encode the input.
Overview
Most articles about auto-encoders explain them from the angle of signal encoding. That does deepen your understanding of the theory behind them, but it can be hard to follow, since many of those articles lean on terminology from signal processing.
This post is organized as follows:
- Build an intuition for auto-encoders through an analogy;
- Cover the basics of auto-encoders (structure and so on);
- Cover an (early) use of auto-encoders: initializing the weights of a DNN;
- Cover the basics of auto-encoders in computer vision (Unpooling, Deconvolution);
- Briefly introduce some extensions of auto-encoders.
A scenario: your exam cheat sheet
Imagine this: you are taking a hard course called "Cloud Computing", and the teacher lets everyone bring one A4 cheat sheet to the exam. The exam covers the whole textbook, and the textbook is over 600 pages, so you can't bring it in. You have to summarize the whole book onto one fixed-size sheet of paper, and hope that during the exam the sheet helps you recall what the book says, so that you pass.
As the figure shows, we can call preparing the cheat sheet before the exam encoding, and recalling the book's content from the sheet during the exam decoding. The sheet that condenses the best of the book is the latent code. Any sensible student wants what they decode to be as close to the original textbook as possible, so they make fewer mistakes in the exam.
So can we think of encoding as compression?
Not quite. In theory, encoding is a broader idea than compression: compression is one kind of encoding, but encoding is not just compression. Compression does encode its input, and it tries to store that input in less space with as little loss as possible. Encoding itself doesn't care whether the result is smaller, and may not even care whether information is lost (denoising, for example). It simply turns the information into another form that the target model finds easier to "read".
Back to our scenario: compression usually makes the encoded information unreadable (which is why we often have to unzip files first), but we want our cheat sheet to be readable. Going further, compression algorithms often sample global information, so decompressing means restoring the full original data first. In an exam, though, time is short. We want the cheat sheet to hold precise local content, so we can use it to answer questions without reconstructing the whole book.
After four years of undergraduate exams (training), you have become very good at making cheat sheets: you know space on the sheet is precious, what is worth writing down and what isn't, and how to phrase things so they can't be misread. You know it's a good idea to read the sheet back after making it and see how far it is from the original, to make sure the small differences won't hurt you in the exam. You've even learned to lay out the sheet so you can find things quickly. And when an earlier course is related to this exam, a few small adjustments let you write down or recall the key points quickly.
You finish your cheat sheet and try it on past exam papers (test). The mock exam goes well. You tell your good friend Deep about it. Seeing your score, Deep says he doesn't have time to make his own cheat sheet and asks whether he can photocopy yours for the exam. You happily agree.
Deep isn't careless, so before the real exam he takes a mock exam with your cheat sheet, and completely falls apart 🤯.
The two of you have different backgrounds and foundations (maybe even differently wired brains), so your cheat sheet reads like gibberish to him, and his mock exam goes terribly. He now has a few options:
- Make a cheat sheet from scratch, as you did;
- Learn to read your cheat sheet under your guidance, especially your approach and the symbols you used;
- Adjust the content of the cheat sheet based on his own understanding to get through the exam.
Deep doesn't think he has time to read the whole textbook again, so he picks option 3. He works out what the symbols on your sheet mean, uses those clues to look up the few things he doesn't know in the textbook, and revises his photocopy to suit himself.
After a lot of practice, he finishes his own cheat sheet and does well in the exam. Compared with starting from scratch (option 1), Deep says your sheet saved him a lot of time and many detours.
Another friend of yours, Tran, is taking a course close to Cloud Computing, called "Distributed and Parallel Computing". Tran is a time-management master who spends her days on things unrelated to her major, yet somehow manages to do them all reasonably well. One day she asks for your Cloud Computing cheat sheet: she has no time to prepare either, and plans to use it for the parallel computing exam. Since the scope of Cloud Computing covers the material of the parallel computing course, Tran thinks this will work.
Half doubtful, you give her the sheet. To your surprise, Tran doesn't change a single word, and still passes the parallel computing quiz with your Cloud Computing cheat sheet. She says she is good at transfer learning: she just took your sheet and ground through a pile of parallel computing exercises, adjusting her own way of thinking to fit the coming exam. She adds with a grin that from now on she'll be able to read any cheat sheet she borrows from you 😎.
This scenario shows the basic idea, properties and uses of auto-encoders intuitively. Below I'll go through auto-encoders again in a more rigorous, academic way.
AE Basics
In the example above, the encoder encodes the input (an MNIST image, dimensions) into a code. The code usually has fewer than 784 dimensions, so it is a compact representation of the original input. We also have a decoder, which takes a code as input and tries to reconstruct the information contained in that compact representation.
Unfortunately, it is hard to design a loss function for either one alone, so the encoder and decoder are hard to train separately. Instead we connect the two networks and train them together, hoping the whole network's output equals its input as closely as possible. This brings PCA to mind:
If we implement a similar structure with a neural network, stack more layers and make a few adjustments, we get the following Deep Auto-encoder:
When training a Deep Auto-encoder, the goal is to make the network's input and output as close as possible. This needs no labels at all, so it is unsupervised learning, and training adjusts the values of . In theory there is no need to make the parameters on the two sides of the code symmetric (such as and ), but doing so halves the number of parameters to train and also reduces the risk of overfitting. Back then, training such a deep network also required initializing it with RBMs, which I won't go into here.
AE for DNN Pre-training
An early use of auto-encoders was initializing the parameters of deep neural networks.
As the left side of the figure shows, our goal is a (784 -> 1000 -> 1000 -> 500 -> 10) DNN that classifies handwritten MNIST digits.
In the past, training such a network directly from random initialization often failed to converge. So we can first build the auto-encoder on the right side of the figure, train it self-supervised until it converges, and keep the (784 -> 1000) parameters . At this point we consider an encoder: it extracts the features of the input into 1000 dimensions.
In general, it isn't recommended to make the code larger than the input and output when designing an auto-encoder. The network may well "slack off" and simply copy the input to the output, learning nothing and ending up with something close to an identity matrix. If you really need a larger dimension, add regularization during training to constrain the distribution of the parameters.
Next, we drop the (1000 -> 784) part on the right, attach (1000 -> 1000) following the network on the left, fix , and train the (1000 -> 1000 -> 1000) auto-encoder.
Note that during training we still feed in the MNIST images , but we make the output of layer , , as close as possible to the output of layer , (rather than making close to the output of some other layer).
After it converges, we have the parameters .
Then we repeat the same steps: fix and , and train to get the (1000 -> 500) encoder parameters .
Finally, we randomly initialize the (500 -> 10) parameters , let , , and all be updated by backpropagation, and train on (input image, digit label) pairs. This gives us the target network we wanted.
Back when training techniques were less mature, almost every DNN needed pre-training like this. Today, if the training set is small (few labels), we can still use this method to initialize the network's parameters well.
AE for CNN
So far we have only covered the general framework of auto-encoders. Next, let's look at how auto-encoders are structured in real computer vision (CV) tasks.
Searching Similar Images
A common task in CV is reverse image search. Say we have a photo of Michael Jackson but don't know his name, and we want to find similar pictures online. We would expect the search engine to take our uploaded picture as a reference and search for similar ones.
So how do we decide whether two images are similar?
The first way is to compute their similarity directly at the pixel level (distance in pixel intensity space), for example the inner product of the two pixel matrices, or the Euclidean distance between them.

The images retrieved this way do have similar colors and color layouts, but their content is far from what we wanted.
From what we've learned about auto-encoders so far, the latent code captures the high-level features of the input image. So can we judge how similar two images are by directly comparing their codes?
If so, the encoder we'd want looks like this:
In CV, the most common feature extractor is a network of alternating convolution and pooling layers. Since an auto-encoder is symmetric around the code, an auto-encoder built on a CNN looks like this:
Now we have a brilliant idea; all we need is a programmer. The question is how to design the Deconvolution and Unpooling modules.
Unpooling Layer
There are many ways to do unpooling; here are two common ones.
The first way is to record the position of each maximum during max pooling (called the "max location switches"), and fill the non-maximum positions with 0 during unpooling.
As the figure shows, when we pool a feature map into a pooled map, we record where the maximum of each subregion is (the black cells in the figure). To unpool the pooled map, we look up the max location switches, put each maximum back where it was, and fill everything else with 0 (no intensity on that channel). This is ① in the figure.

The figure above shows a feature map unpooled into .
Another option is to drop the max location switches altogether, and fill each subregion of the unpooled map with that region's maximum. This is ② in the figure.
Deconvolution Layer
Deconvolution is actually still implemented with convolution. Let's first look at how convolution works, using a one-dimensional convolution to keep things simple.
As shown above, the input is a one-dimensional vector of size 5. With a kernel size of 3, one convolution step multiplies the values at different positions of the input by different weights (the green, blue and red arrows stand for the three weights) and adds them up. After the kernel has gone over the whole input, it outputs a vector of size 3.
Naturally, we'd like the corresponding deconvolution to turn each value back into the input before the convolution, as in the figure below (note the direction of the arrows): each input is multiplied by the three weights and added to three outputs.
When it's done, the outputs at the two ends each receive one term, and the one in the middle receives three.
Now for a clever trick: pad the code we want to deconvolve with zeros on both sides, and run an ordinary convolution on it:
Since 0 times anything is 0, the arrows starting from the padded zeros have no effect, and each output receives exactly the same products as in the previous figure.
Let's compare the deconvolution we wanted with the convolution we just did:
They do exactly the same thing! In other words, deconvolution can be implemented by padding and then convolving; the two are essentially equivalent (which is why the decoder in CNN auto-encoder code is built with convolution layers too).
Now we train this auto-encoder and use its 256-dimensional latent code to compute similarity. The retrieved results look like this:

Searching with the latent code not only saves computation (from 3072 dimensions down to 256), it also works better (at least every result is a face).
Further Research on AE
De-noising Auto-Encoder (DAE)
To make the encoder more robust (and avoid overfitting), we can add random noise to the input before feeding it to the encoder being trained. Note that when training a DAE, the output is still compared with the original input , not with the noisy . An encoder trained this way learns to remove noise.
How to evaluate an encoder?
Besides reconstruction error, is there another way to measure how good an encoder is? We can say that the better an encoder is, the better it encodes information (especially distinguishing features), so the more different two inputs are, the less alike their embedding codes should be.
Now we give an image and a code as a pair of inputs to a trained binary classifier. If the image and the embedding code belong together, it outputs Y; otherwise N.
Such a classifier is easy to train: use binary cross entropy (BCE) as the loss and feed it some positive and negative examples:
Once we've defined the classifier's loss function (BCE here), we train the classifier's parameters to reach the optimal value .
The encoder above produces very similar embedding codes for different images, so stays large even after the classifier converges. That is, we train the classifier's parameters to minimize :
- Small : the embedding codes are representative;
- Large : the embedding codes are not representative.
In other words, to train a good encoder, we should optimize the encoder's parameters to make as small as possible. Substituting the formula above gives:
That is, we train the encoder's parameters and the classifier's (discriminator's) parameters together to minimize . This is the idea behind Deep InfoMax (DIM, 2019); by comparison, a typical auto-encoder trains the encoder and decoder to minimize reconstruction error. Since BCE is differentiable, the whole expression is differentiable too.
So we can optimize the encoder by optimizing the classifier's loss.
From this point of view, a typical auto-encoder is just a special case that ignores negative examples:
Acknowledge
The structure of this post and its original figures are mainly based on Prof. Hung-yi Lee's course, together with my own understanding and my report on the topic. If you spot any mistakes, please let me know.
Cite this post
@misc{brandozhang2021auto,
title = {如何理解「自编码器(Auto-encoder)」},
author = {Brando ZHANG},
year = {2021},
url = {https://brando.dev/zh-hans/posts/understanding-autoencoders/},
month = mar
}