~/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:

  1. Build an intuition for auto-encoders through an analogy;
  2. Cover the basics of auto-encoders (structure and so on);
  3. Cover an (early) use of auto-encoders: initializing the weights of a DNN;
  4. Cover the basics of auto-encoders in computer vision (Unpooling, Deconvolution);
  5. 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.

Encoder code Decoder Textbook (600 p.) Input summarize · encode One A4 cheat sheet latent code recall · decode Recalled knowledge Output
Auto-encoders and an open-book exam: summarizing the whole textbook onto one cheat sheet is encoding, recalling the material from the sheet during the exam is decoding, and the sheet itself is the latent code.

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:

  1. Make a cheat sheet from scratch, as you did;
  2. Learn to read your cheat sheet under your guidance, especially your approach and the symbols you used;
  3. 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

Input 784-dim Encoder code < 784-dim Decoder Output Trained together Make output close to input
The encoder turns a 784-dimensional MNIST image into a shorter code, and the decoder reconstructs the image from the code. The two are trained together so that the output is as close to the input as possible.

In the example above, the encoder encodes the input (an MNIST image, 28×28=78428 \times 28=784 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:

x encode W c decode WT x minimize ( x − x )² Input layer Hidden layer (linear) Output layer
Recap: PCA. The input xx is mapped into another space by multiplying it by a transformation matrix WW, giving the signal cc. x^\hat{x} is the output reconstructed from cc, which usually just means multiplying cc by WTW^T. We typically reduce the error between xx and x^\hat{x} with least squares or similar methods, so that the information encoded in cc is more representative.

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:

… … W1 W2 W2T W1T code As close as possible x x Bottleneck
Deep Auto-encoder: the weights on the two sides are symmetric (W1W_1 and W1TW_1^T, W2W_2 and W2TW_2^T). Reference: Hinton, Geoffrey E., and Ruslan R. Salakhutdinov. "Reducing the dimensionality of data with neural networks." Science 313.5786 (2006): 504-507.

When training a Deep Auto-encoder, the goal is to make the network's input xx and output x^\hat{x} as close as possible. This needs no labels at all, so it is unsupervised learning, and training adjusts the values of W1,W2,...,WmW_1, W_2, ..., W_m. In theory there is no need to make the parameters on the two sides of the code symmetric (such as W1W_1 and W1TW_1^T), 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.

784 1000 1000 500 10 W¹ W² W³ W⁴ Target network 784 x 1000 784 x̂ W¹ W¹′ ≈ keep W¹ Step 1: train 784 → 1000 → 784
Step 1: train a 784 → 1000 → 784 auto-encoder to get W1W^1.

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 W1W^1. At this point we consider W1W^1 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.

784 1000 1000 500 10 W¹ W² W³ W⁴ Target network 784 x 1000 a¹ 1000 1000 â¹ W¹ fixed W² W²′ ≈ keep W² Step 2: fix W¹, train W²
Step 2: fix W1W^1 and train a 1000 → 1000 → 1000 auto-encoder to get W2W^2.

Next, we drop the (1000 -> 784) part on the right, attach (1000 -> 1000) following the network on the left, fix W1W^1, and train the (1000 -> 1000 -> 1000) auto-encoder.

Note that during training we still feed in the MNIST images xx, but we make the output of layer L1L_1, a1a^1, as close as possible to the output of layer L3L_3, a^1\hat{a}^1 (rather than making xx close to the output of some other layer).

After it converges, we have the parameters W2W^2.

784 1000 1000 500 10 W¹ W² W³ W⁴ Target network 784 x 1000 1000 a² 500 1000 â² W¹ fixed W² fixed W³ W³′ ≈ keep W³ Step 3: fix W¹ and W², train W³
Step 3: fix W1W^1 and W2W^2, and train a 1000 → 500 → 1000 auto-encoder to get W3W^3.

Then we repeat the same steps: fix W1W^1 and W2W^2, and train to get the (1000 -> 500) encoder parameters W3W^3.

784 1000 1000 500 10 W¹ W² W³ W⁴ Target network 784 x 1000 1000 500 10 W¹ fine-tune W² fine-tune W³ fine-tune W⁴ random init backprop Step 4: add W⁴, fine-tune all
Step 4: randomly initialize W4W^4 and fine-tune the whole network with backpropagation.

Finally, we randomly initialize the (500 -> 10) parameters W4W^4, let W1W^1, W2W^2, W3W^3 and W4W^4 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.

Retrieved using Euclidean distance in pixel intensity space. The image in the red box at the top left is the query; the others are the nearest images found by plain pixel Euclidean distance. A smaller dist means more similar. Images from Hinton’s slides on Coursera. Reference: Krizhevsky, Alex, and Geoffrey E. Hinton. "Using very deep autoencoders for content-based image retrieval." ESANN. 2011.
Retrieved using Euclidean distance in pixel intensity space. The image in the red box at the top left is the query; the others are the nearest images found by plain pixel Euclidean distance. A smaller dist means more similar. Images from Hinton’s slides on Coursera. Reference: Krizhevsky, Alex, and Geoffrey E. Hinton. "Using very deep autoencoders for content-based image retrieval." ESANN. 2011.

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:

32×32×3 = 3072-dim 8192 4096 2048 1024 512 256 code compare similarity here
Image Encoder. A photo has three channels, R, G and B, so a 32×3232 \times 32 image is actually a 3072-dimensional input. Something to think about: why first increase the dimension and then compress it?

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:

Convolution Pooling Convolution Pooling Deconvolution Unpooling Deconvolution Unpooling Deconvolution code As close as possible Encoder Decoder
Auto-encoder for CNN. Suppose we have two modules, Deconvolution and Unpooling, that decode the latent code step by step. The output of the last deconvolution layer should be as close as possible to the input photo.

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.

Feature map 4×4 1328621451342791 max Pooled 2×2 6 8 7 9 Remember max positions (switches) unpool ① Back in place, rest 0 0 0 0 8 6 0 0 0 0 0 0 0 0 7 9 0 or ② Fill with max 6688668877997799
During max pooling, remember where the maximum of each 2×2 region is (the switches). Unpooling can then restore the map in two ways. Reference: the Image Segmentation section of Leonardo Araujo dos Santos's Artificial Inteligence notes.

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 4×44 \times 4 feature map into a 2×22 \times 2 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.

Unpooling result.
Unpooling result.

The figure above shows a 14×1414 \times 14 feature map unpooled into 28×2828 \times 28.

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.

Input Output x₁ x₂ x₃ x₄ x₅ y₁ y₂ y₃ size = 5 size = 3 Kernel weights: g b r
1D convolution: the kernel slides over the 5 inputs; each time, it multiplies 3 inputs by the weights gg, bb and rr and adds them up to get one output.

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.

Input Output y₁ y₂ y₃ z₁ z₂ z₃ z₄ z₅ ← dot = one product sum each column
Deconvolution: each input in turn is multiplied by the three weights and added to the three outputs below it. The dots under each output are the products it receives, colored by weight.

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:

0 0 y₁ y₂ y₃ 0 0 z₁ z₂ z₃ z₄ z₅ Grey: padded zeros; anything × 0 = 0 (dashed)
First pad two zeros on each side, then run an ordinary convolution with the same kernel. Arrows starting from a zero (dashed) always produce 0 and have no effect.

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:

Deconvolution: inputs spread down = Pad with 0, then convolve Each output receives exactly the same products
Left: deconvolution; right: ordinary convolution after zero padding. Each output receives exactly the same products on both sides.

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:

Retrieved using 256 codes. The image in the red box at the top left is the query; the others are the nearest images found by distance between latent codes. A smaller dist means more similar. Images from Hinton’s slides on Coursera. Reference: Krizhevsky, Alex, and Geoffrey E. Hinton. "Using very deep autoencoders for content-based image retrieval." ESANN. 2011.
Retrieved using 256 codes. The image in the red box at the top left is the query; the others are the nearest images found by distance between latent codes. A smaller dist means more similar. Images from Hinton’s slides on Coursera. Reference: Krizhevsky, Alex, and Geoffrey E. Hinton. "Using very deep autoencoders for content-based image retrieval." ESANN. 2011.

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)

x x′ c x add noise encode decode As close as possible to x, not x′
De-noising auto-encoder: first add random noise to xx to get x′x', then encode and decode. The noise is different every time, but the output x^\hat{x} is compared with the clean xx.

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 x^\hat{x} is still compared with the original input xx, not with the noisy x′x'. 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.

Image code Binary classifier image + code A pair? Y N
Binary classifier: given an image and a code, decide whether they belong together.

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:

Miku Encoder Haruhi Encoder Positive: image and code matchYes Negative: image and code don’t matchNo
Left: the outputs of different images passed through the encoder; Miku's embedding code is blue and Haruhi's is yellow. Right: the labeled data used to train the classifier, with positive examples on top and negative examples below.

Once we've defined the classifier's loss function LDL_D (BCE here), we train the classifier's parameters ϕ\phi to reach the optimal value LD∗L_D^*.

Miku Encoder Haruhi Encoder The two codes look alike the classifier can’t tell → trained LD* stays large
Poor encoder: if an encoder is bad and can't encode effectively, Miku's and Haruhi's embedding codes may look very much alike.

The encoder above produces very similar embedding codes for different images, so LD∗L_D^* stays large even after the classifier converges. That is, we train the classifier's parameters ϕ\phi to minimize LDL_D:

LD∗=min⁡ϕLDL_D^* = \min_{\phi} L_D
  • Small LD∗L_D^*: the embedding codes are representative;
  • Large LD∗L_D^*: the embedding codes are not representative.

In other words, to train a good encoder, we should optimize the encoder's parameters θ\theta to make LD∗L_D^* as small as possible. Substituting the formula above gives:

θ∗=arg⁡min⁡θLD∗=arg⁡min⁡θmin⁡ϕLD\begin{aligned} \theta^* &= \arg\min_{\theta} L_D^* \\ &= \arg\min_{\theta} \min_{\phi} L_D \end{aligned}

That is, we train the encoder's parameters θ\theta and the classifier's (discriminator's) parameters ϕ\phi together to minimize LDL_D. 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:

Typical auto-encoder Encoder vector Decoder As close as possible Another view: Decoder + subtraction = a discriminator vector Discriminator − Decoder score = recon error plays the role of a loss (e.g. BCE)
Top: a typical auto-encoder. Bottom: treat the decoder plus "subtract from the original image" as one discriminator; the score it outputs is the reconstruction error.

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

BIBTEX
@misc{brandozhang2021auto,
  title  = {如何理解「自编码器(Auto-encoder)」},
  author = {Brando ZHANG},
  year   = {2021},
  url    = {https://brando.dev/zh-hans/posts/understanding-autoencoders/},
  month  = mar
}