Tutorial on Variational Autoencoders

Carl Doersch

Introduction

“Generative modeling” is a broad area of machine learning which deals with models of distributions P(X)P(X), defined over datapoints XX in some potentially high-dimensional space X\mathcal{X}. For instance, images are a popular kind of data for which we might create generative models. Each “datapoint” (image) has thousands or millions of dimensions (pixels), and the generative model’s job is to somehow capture the dependencies between pixels, e.g., that nearby pixels have similar color, and are organized into objects. Exactly what it means to “capture” these dependencies depends on exactly what we want to do with the model. One straightforward kind of generative model simply allows us to compute P(X)P(X) numerically. In the case of images, XX values which look like real images should get high probability, whereas images that look like random noise should get low probability. However, models like this are not necessarily useful: knowing that one image is unlikely does not help us synthesize one that is likely.

Instead, one often cares about producing more examples that are like those already in a database, but not exactly the same. We could start with a database of raw images and synthesize new, unseen images. We might take in a database of 3D models of something like plants and produce more of them to fill a forest in a video game. We could take handwritten text and try to produce more handwritten text. Tools like this might actually be useful for graphic designers. We can formalize this setup by saying that we get examples XX distributed according to some unknown distribution Pgt(X)P_{gt}(X), and our goal is to learn a model PP which we can sample from, such that PP is as similar as possible to PgtP_{gt}.

Training this type of model has been a long-standing problem in the machine learning community, and classically, most approaches have had one of three serious drawbacks. First, they might require strong assumptions about the structure in the data. Second, they might make severe approximations, leading to sub-optimal models. Or third, they might rely on computationally expensive inference procedures like Markov Chain Monte Carlo. More recently, some works have made tremendous progress in training neural networks as powerful function approximators through backpropagation . These advances have given rise to promising frameworks which can use backpropagation-based function approximators to build generative models.

One of the most popular such frameworks is the Variational Autoencoder , the subject of this tutorial. The assumptions of this model are weak, and training is fast via backpropagation. VAEs do make an approximation, but the error introduced by this approximation is arguably small given high-capacity models. These characteristics have contributed to a quick rise in their popularity.

This tutorial is intended to be an informal introduction to VAEs, and not a formal scientific paper about them. It is aimed at people who might have uses for generative models, but might not have a strong background in the variatonal Bayesian methods and “minimum description length” coding models on which VAEs are based. This tutorial began its life as a presentation for computer vision reading groups at UC Berkeley and Carnegie Mellon, and hence has a bias toward a vision audience. Suggestions for improvement are appreciated.

When training a generative model, the more complicated the dependencies between the dimensions, the more difficult the models are to train. Take, for example, the problem of generating images of handwritten characters. Say for simplicity that we only care about modeling the digits 0-9. If the left half of the character contains the left half of a 5, then the right half cannot contain the left half of a 0, or the character will very clearly not look like any real digit. Intuitively, it helps if the model first decides which character to generate before it assigns a value to any specific pixel. This kind of decision is formally called a latent variable. That is, before our model draws anything, it first randomly samples a digit value zz from the set [0,...,9][0,...,9], and then makes sure all the strokes match that character. zz is called ‘latent’ because given just a character produced by the model, we don’t necessarily know which settings of the latent variables generated the character. We would need to infer it using something like computer vision.

Before we can say that our model is representative of our dataset, we need to make sure that for every datapoint XX in the dataset, there is one (or many) settings of the latent variables which causes the model to generate something very similar to XX. Formally, say we have a vector of latent variables zz in a high-dimensional space Z\mathcal{Z} which we can easily sample according to some probability density function (PDF) P(z)P(z) defined over Z\mathcal{Z}. Then, say we have a family of deterministic functions f(z;θ)f(z;\theta), parameterized by a vector θ\theta in some space Θ\Theta, where f:Z×ΘXf:\mathcal{Z}\times\Theta\to\mathcal{X}. ff is deterministic, but if zz is random and θ\theta is fixed, then f(z;θ)f(z;\theta) is a random variable in the space X\mathcal{X}. We wish to optimize θ\theta such that we can sample zz from P(z)P(z) and, with high probability, f(z;θ)f(z;\theta) will be like the XX’s in our dataset.

To make this notion precise mathematically, we are aiming maximize the probability of each XX in the training set under the entire generative process, according to:

Here, f(z;θ)f(z;\theta) has been replaced by a distribution P(Xz;θ)P(X|z;\theta), which allows us to make the dependence of XX on zz explicit by using the law of total probability. The intuition behind this framework—called “maximum likelihood”—is that if the model is likely to produce training set samples, then it is also likely to produce similar samples, and unlikely to produce dissimilar ones. In VAEs, the choice of this output distribution is often Gaussian, i.e., P(Xz;θ)=N(Xf(z;θ),σ2I)P(X|z;\theta)=\mathcal{N}(X|f(z;\theta),\sigma^{2}*I). That is, it has mean f(z;θ)f(z;\theta) and covariance equal to the identity matrix II times some scalar σ\sigma (which is a hyperparameter). This replacement is necessary to formalize the intuition that some zz needs to result in samples that are merely like XX. In general, and particularly early in training, our model will not produce outputs that are identical to any particular XX. By having a Gaussian distribution, we can use gradient descent (or any other optimization technique) to increase P(X)P(X) by making f(z;θ)f(z;\theta) approach XX for some zz, i.e., gradually making the training data more likely under the generative model. This wouldn’t be possible if P(Xz)P(X|z) was a Dirac delta function, as it would be if we used X=f(z;θ)X=f(z;\theta) deterministically! Note that the output distribution is not required to be Gaussian: for instance, if XX is binary, then P(Xz)P(X|z) might be a Bernoulli parameterized by f(z;θ)f(z;\theta). The important property is simply that P(Xz)P(X|z) can be computed, and is continuous in θ\theta. From here onward, we will omit θ\theta from f(z;θ)f(z;\theta) to avoid clutter.

Variational Autoencoders

The mathematical basis of VAEs actually has relatively little to do with classical autoencoders, e.g. sparse autoencoders or denoising autoencoders . VAEs approximately maximize Equation 1, according to the model shown in Figure 1. They are called “autoencoders” only because the final training objective that derives from this setup does have an encoder and a decoder, and resembles a traditional autoencoder. Unlike sparse autoencoders, there are generally no tuning parameters analogous to the sparsity penalties. And unlike sparse and denoising autoencoders, we can sample directly from P(X)P(X) (without performing Markov Chain Monte Carlo, as in ).

To solve Equation 1, there are two problems that VAEs must deal with: how to define the latent variables zz (i.e., decide what information they represent), and how to deal with the integral over zz. VAEs give a definite answer to both.

First, how do we choose the latent variables zz such that we capture latent information? Returning to our digits example, the ‘latent’ decisions that the model needs to make before it begins painting the digit are actually rather complicated. It needs to choose not just the digit, but the angle that the digit is drawn, the stroke width, and also abstract stylistic properties. Worse, these properties may be correlated: a more angled digit may result if one writes faster, which also might tend to result in a thinner stroke. Ideally, we want to avoid deciding by hand what information each dimension of zz encodes (although we may want to specify it by hand for some dimensions ). We also want to avoid explicitly describing the dependencies—i.e., the latent structure—between the dimensions of zz. VAEs take an unusual approach to dealing with this problem: they assume that there is no simple interpretation of the dimensions of zz, and instead assert that samples of zz can be drawn from a simple distribution, i.e., N(0,I)\mathcal{N}(0,I), where II is the identity matrix. How is this possible? The key is to notice that any distribution in dd dimensions can be generated by taking a set of dd variables that are normally distributed and mapping them through a sufficiently complicated functionIn one dimension, you can use the inverse cumulative distribution function (CDF) of the desired distribution composed with the CDF of a Gaussian. This is an extension of “inverse transform sampling.” For multiple dimensions, do the stated process starting with the marginal distribution for a single dimension, and repeat with the conditional distribution of each additional dimension. See the “inversion method” and the “conditional distribution method” in Devroye et al. . For example, say we wanted to construct a 2D random variable whose values lie on a ring. If zz is 2D and normally distributed, g(z)=z/10+z/zg(z)=z/10+z/||z|| is roughly ring-shaped, as shown in Figure 2. Hence, provided powerful function approximators, we can simply learn a function which maps our independent, normally-distributed zz values to whatever latent variables might be needed for the model, and then map those latent variables to XX. In fact, recall that P(Xz;θ)=N(Xf(z;θ),σ2I)P(X|z;\theta)=\mathcal{N}(X|f(z;\theta),\sigma^{2}*I). If f(z;θ)f(z;\theta) is a multi-layer neural network, then we can imagine the network using its first few layers to map the normally distributed zz’s to the latent values (like digit identity, stroke weight, angle, etc.) with exactly the right statistics. Then it can use later layers to map those latent values to a fully-rendered digit. In general, we don’t need to worry about ensuring that the latent structure exists. If such latent structure helps the model accurately reproduce (i.e. maximize the likelihood of) the training set, then the network will learn that structure at some layer.

Now all that remains is to maximize Equation 1, where P(z)=N(z0,I)P(z)=\mathcal{N}(z|0,I). As is common in machine learning, if we can find a computable formula for P(X)P(X), and we can take the gradient of that formula, then we can optimize the model using stochastic gradient ascent. It is actually conceptually straightforward to compute P(X)P(X) approximately: we first sample a large number of zz values {z1,...,zn}\{z_{1},...,z_{n}\}, and compute P(X)1niP(Xzi)P(X)\approx\frac{1}{n}\sum_{i}P(X|z_{i}). The problem here is that in high dimensional spaces, nn might need to be extremely large before we have an accurate estimate of P(X)P(X). To see why, consider our example of handwritten digits. Say that our digit datapoints are stored in pixel space, in 28x28 images as shown in Figure 3. Since P(Xz)P(X|z) is an isotropic Gaussian, the negative log probability of XX is proportional squared Euclidean distance between f(z)f(z) and XX. Say that Figure 3(a) is the target (XX) for which we are trying to find P(X)P(X). A model which produces the image shown in Figure 3(b) is probably a bad model, since this digit is not much like a 2. Hence, we should set the σ\sigma hyperparameter of our Gaussian distribution such that this kind of erroneous digit does not contribute to P(X)P(X). On the other hand, a model which produces Figure 3(c) (identical to XX but shifted down and to the right by half a pixel) might be a good model. We would hope that this sample would contribute to P(X)P(X). Unfortunately, however, we can’t have it both ways: the squared distance between XX and Figure 3(c) is .2693 (assuming pixels range between 0 and 1), but between XX and Figure 3(b) it is just .0387. The lesson here is that in order to reject samples like Figure 3(b), we need to set σ\sigma very small, such that the model needs to generate something significantly more like XX than Figure 3(c)! Even if our model is an accurate generator of digits, we would likely need to sample many thousands of digits before we produce a 2 that is sufficiently similar to the one in Figure 3(a). We might solve this problem by using a better similarity metric, but in practice these are difficult to engineer in complex domains like vision, and they’re difficult to train without labels that indicate which datapoints are similar to each other. Instead, VAEs alter the sampling procedure to make it faster, without changing the similarity metric.

Is there a shortcut we can take when using sampling to compute Equation 1? In practice, for most zz, P(Xz)P(X|z) will be nearly zero, and hence contribute almost nothing to our estimate of P(X)P(X). The key idea behind the variational autoencoder is to attempt to sample values of zz that are likely to have produced XX, and compute P(X)P(X) just from those. This means that we need a new function Q(zX)Q(z|X) which can take a value of XX and give us a distribution over zz values that are likely to produce XX. Hopefully the space of zz values that are likely under QQ will be much smaller than the space of all zz’s that are likely under the prior P(z)P(z). This lets us, for example, compute EzQP(Xz)E_{z\sim Q}P(X|z) relatively easily. However, if zz is sampled from an arbitrary distribution with PDF Q(z)Q(z), which is not N(0,I)\mathcal{N}(0,I), then how does that help us optimize P(X)P(X)? The first thing we need to do is relate EzQP(Xz)E_{z\sim Q}P(X|z) and P(X)P(X). We’ll see where QQ comes from later.

The relationship between EzQP(Xz)E_{z\sim Q}P(X|z) and P(X)P(X) is one of the cornerstones of variational Bayesian methods. We begin with the definition of Kullback-Leibler divergence (KL divergence or D\mathcal{D}) between P(zX)P(z|X) and Q(z)Q(z), for some arbitrary QQ (which may or may not depend on XX):

We can get both P(X)P(X) and P(Xz)P(X|z) into this equation by applying Bayes rule to P(zX)P(z|X):

Here, logP(X)\log P(X) comes out of the expectation because it does not depend on zz. Negating both sides, rearranging, and contracting part of EzQE_{z\sim Q} into a KL-divergence terms yields:

Note that XX is fixed, and QQ can be any distribution, not just a distribution which does a good job mapping XX to the zz’s that can produce XX. Since we’re interested in inferring P(X)P(X), it makes sense to construct a QQ which does depend on XX, and in particular, one which makes D[Q(z)P(zX)]\mathcal{D}\left[Q(z)\|P(z|X)\right] small:

This equation serves as the core of the variational autoencoder, and it’s worth spending some time thinking about what it says Historically, this math (particularly Equation 5) was known long before VAEs. For example, Helmholtz Machines (see Equation 5) use nearly identical mathematics, with one crucial difference. The integral in our expectations is replaced with a sum in Dayan et al. , because Helmholtz Machines assume a discrete distribution for the latent variables. This choice prevents the transformations that make gradient descent tractable in VAEs. . In two sentences, the left hand side has the quantity we want to maximize: logP(X)\log P(X) (plus an error term, which makes QQ produce zz’s that can reproduce a given XX; this term will become small if QQ is high-capacity). The right hand side is something we can optimize via stochastic gradient descent given the right choice of QQ (although it may not be obvious yet how). Note that the framework—in particular, the right hand side of Equation 5—has suddenly taken a form which looks like an autoencoder, since QQ is “encoding” XX into zz, and PP is “decoding” it to reconstruct XX. We’ll explore this connection in more detail later.

Now for a bit more detail on Equatinon 5. Starting with the left hand side, we are maximizing logP(X)\log P(X) while simultaneously minimizing D[Q(zX)P(zX)]\mathcal{D}\left[Q(z|X)\|P(z|X)\right]. P(zX)P(z|X) is not something we can compute analytically: it describes the values of zz that are likely to give rise to a sample like XX under our model in Figure 1. However, the second term on the left is pulling Q(zx)Q(z|x) to match P(zX)P(z|X). Assuming we use an arbitrarily high-capacity model for Q(zx)Q(z|x), then Q(zx)Q(z|x) will hopefully actually match P(zX)P(z|X), in which case this KL-divergence term will be zero, and we will be directly optimizing logP(X)\log P(X). As an added bonus, we have made the intractable P(zX)P(z|X) tractable: we can just use Q(zx)Q(z|x) to compute it.

2 Optimizing the objective

So how can we perform stochastic gradient descent on the right hand side of Equation 5? First we need to be a bit more specific about the form that Q(zX)Q(z|X) will take. The usual choice is to say that Q(zX)=N(zμ(X;ϑ),Σ(X;ϑ))Q(z|X)=\mathcal{N}(z|\mu(X;\vartheta),\Sigma(X;\vartheta)), where μ\mu and Σ\Sigma are arbitrary deterministic functions with parameters ϑ\vartheta that can be learned from data (we will omit ϑ\vartheta in later equations). In practice, μ\mu and Σ\Sigma are again implemented via neural networks, and Σ\Sigma is constrained to be a diagonal matrix. The advantages of this choice are computational, as they make it clear how to compute the right hand side. The last term—D[Q(zX)P(z)]\mathcal{D}\left[Q(z|X)\|P(z)\right]—is now a KL-divergence between two multivariate Gaussian distributions, which can be computed in closed form as:

where kk is the dimensionality of the distribution. In our case, this simplifies to:

The first term on the right hand side of Equation 5 is a bit more tricky. We could use sampling to estimate EzQ[logP(Xz)]E_{z\sim Q}\left[\log P(X|z)\right], but getting a good estimate would require passing many samples of zz through ff, which would be expensive. Hence, as is standard in stochastic gradient descent, we take one sample of zz and treat logP(Xz)\log P(X|z) for that zz as an approximation of EzQ[logP(Xz)]E_{z\sim Q}\left[\log P(X|z)\right]. After all, we are already doing stochastic gradient descent over different values of XX sampled from a dataset DD. The full equation we want to optimize is:

If we take the gradient of this equation, the gradient symbol can be moved into the expectations. Therefore, we can sample a single value of XX and a single value of zz from the distribution Q(zX)Q(z|X), and compute the gradient of:

We can then average the gradient of this function over arbitrarily many samples of XX and zz, and the result converges to the gradient of Equation 8.

There is, however, a significant problem with Equation 9. EzQ[logP(Xz)]E_{z\sim Q}\left[\log P(X|z)\right] depends not just on the parameters of PP, but also on the parameters of QQ. However, in Equation 9, this dependency has disappeared! In order to make VAEs work, it’s essential to drive QQ to produce codes for XX that PP can reliably decode. To see the problem a different way, the network described in Equation 9 is much like the network shown in Figure 4 (left). The forward pass of this network works fine and, if the output is averaged over many samples of XX and zz, produces the correct expected value. However, we need to back-propagate the error through a layer that samples zz from Q(zX)Q(z|X), which is a non-continuous operation and has no gradient. Stochastic gradient descent via backpropagation can handle stochastic inputs, but not stochastic units within the network! The solution, called the “reparameterization trick” in , is to move the sampling to an input layer. Given μ(X)\mu(X) and Σ(X)\Sigma(X)—the mean and covariance of Q(zX)Q(z|X)—we can sample from N(μ(X),Σ(X))\mathcal{N}(\mu(X),\Sigma(X)) by first sampling ϵN(0,I)\epsilon\sim\mathcal{N}(0,I), then computing z=μ(X)+Σ1/2(X)ϵz=\mu(X)+\Sigma^{1/2}(X)*\epsilon. Thus, the equation we actually take the gradient of is:

This is shown schematically in Figure 4 (right). Note that none of the expectations are with respect to distributions that depend on our model parameters, so we can safely move a gradient symbol into them while maintaning equality. That is, given a fixed XX and ϵ\epsilon, this function is deterministic and continuous in the parameters of PP and QQ, meaning backpropagation can compute a gradient that will work for stochastic gradient descent. It’s worth pointing out that the “reparameterization trick” only works if we can sample from Q(zX)Q(z|X) by evaluating a function h(η,X)h(\eta,X), where η\eta is noise from a distribution that is not learned. Furthermore, hh must be continuous in XX so that we can backprop through it. This means Q(zX)Q(z|X) (and therefore P(z)P(z)) can’t be a discrete distribution! If QQ is discrete, then for a fixed η\eta, either hh needs to ignore XX, or there needs to be some point at which h(η,X)h(\eta,X) “jumps” from one possible value in QQ’s sample space to another, i.e., a discontinuity.

3 Testing the learned model

At test time, when we want to generate new samples, we simply input values of zN(0,I)z\sim\mathcal{N}(0,I) into the decoder. That is, we remove the “encoder,” including the multiplication and addition operations that would change the distribution of zz. This (remarkably simple) test-time network is shown in Figure 5.

Say that we want to evaluate the probability of a testing example under the model. This is, in general, not tractable. Note, however, that D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)\|P(z|X)] is positive, meaning that the right hand side of Equation 5 is a lower bound to P(X)P(X). This lower bound still can’t quite be computed in closed form due to the expectation over zz, which requires sampling. However, sampling zz from QQ gives an estimator for the expectation which generally converges much faster than sampling zz from N(0,I)\mathcal{N}(0,I) as discussed in section 2. Hence, this lower bound can be a useful tool for getting a rough idea of how well our model is capturing a particular datapoint XX.

4 Interpreting the objective

By now, you are hopefully convinced that the learning in VAEs is tractable, and that it optimizes something like logP(X)\log P(X) across our entire dataset. However, we are not optimizing exactly logP(X)\log P(X), so this section aims to take a deeper look at what the objective function is actually doing. We address three topics. First, we ask how much error is introduced by optimizing D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)\|P(z|X)] in addition to logP(X)\log P(X). Second, we describe the VAE framework—especially the r.h.s. of Equation 5—in terms of information theory, linking it to other approaches based on Minimum Description Length. Finally, we investigate whether VAEs have “regularization parameters” analogous to the sparsity penalty in sparse autoencoders.

The tractability of this model relies on our assumption that Q(zX)Q(z|X) can be modeled as a Gaussian with some mean μ(X)\mu(X) and variance Σ(X)\Sigma(X). P(X)P(X) converges (in distribution) to the true distribution if and only if D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)\|P(z|X)] goes to zero. Unfortunately, it’s not straightforward to ensure that this happens. Even if we assume μ(X)\mu(X) and Σ(X)\Sigma(X) are arbitrarily high capacity, the posterior P(zX)P(z|X) is not necessarily Gaussian for an arbitrary ff function that we’re using to define PP. For fixed PP, this might mean that D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)\|P(z|X)] never goes to zero. However, the good news is that given sufficiently high-capacity neural networks, there are many ff functions that result in our model generating any given output distribution. Any of these functions will maximize logP(X)\log P(X) equally well. Hence, all we need is one function ff which both maximizes logP(X)\log P(X) and results in P(zX)P(z|X) being Gaussian for all XX. If so, D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)\|P(z|X)] will pull our model towards that parameterization of the distribution. So, does such a function exist for all distributions we might want to approximate? I’m not aware of anyone proving this in general just yet, but it turns out that one can prove that such a function does exist, provided σ\sigma is small relative to the curvature of the ground truth distribution’s CDF (at least in 1D; a proof is included in Appendix A). In practice such a small σ\sigma might cause problems for existing machine learning algorithms, since the gradients would become badly scaled. However, it is comforting to know that VAEs have zero approximation error in at least this one scenario. This fact suggests that future theoretical work may show us how much approximation error VAEs have in more practical setups. (It seems to me like it should be possible to extend the proof technique in Appendix A to multiple dimensions, but this is left for future work.)

4.2 The information-theoretic interpretation

Another important way to look at the right hand side of Equation 5 is in terms of information theory, and in particular, the “minimum description length” principle which motivated many of the VAE’s predecessors like Helmholtz Machines , the Wake-Sleep Algorithm , Deep Belief Nets , and Boltzmann Machines . logP(X)-\log P(X) can be seen as the total number of bits required to construct a given XX under our model using an ideal encoding. The right hand side of Equation 5 views this as a two-step process to construct XX. We first use some bits to construct zz. Recall that a KL-divergence is in units of bits (or, more precisely, nats). Specifically, D[Q(zX)P(z)]\mathcal{D}[Q(z|X)||P(z)] is the expected information that’s required to convert an uninformative sample from P(z)P(z) into a sample from Q(zX)Q(z|X) (the so-called “information gain” interpretation of KL-divergence). That is, it measures the amount of extra information that we get about XX when zz comes from Q(zX)Q(z|X) instead of from P(z)P(z) (for more details, see the “bits back” argument of ). In the second step, P(Xz)P(X|z) measures the amount of information required to reconstruct XX from zz under an ideal encoding. Hence, the total number of bits (logP(X)-\log P(X)) is the sum of these two steps, minus a penalty we pay for QQ being a sub-optimal encoding (D[Q(zX)P(zX)]\mathcal{D}[Q(z|X)||P(z|X)]).

4.3 VAEs and the regularization parameter

Looking at Equation 5, it’s interesting to view the D[Q(zX)P(z)]\mathcal{D}[Q(z|X)||P(z)] as a regularization term, much like the sparsity regularization in sparse autoencoders . From this standpoint, it’s interesting to ask whether the variational autoencoder has any “regularization parameter.” That is, in the sparse autoencoder objective, we have a λ\lambda regularization parameter in an objective function that looks something like this:

where ψ\psi and ϕ\phi are the encoder and decoder functions, respectively, and 0\|\cdot\|_{0} is an L0L_{0} norm that encourages the encoding to be sparse. This λ\lambda must be set by hand.

A variational autoencoder, however, does not, in general, have such a regularization parameter, which is good because that’s one less parameter that the programmer needs to adjust. However, for certain models, we can make it appear like such a regularization parameter exists. It’s tempting to think that this parameter can come from changing zN(0,I)z\sim\mathcal{N}(0,I) to something like zN(0,λI)z^{\prime}\sim\mathcal{N}(0,\lambda*I), but it turns out that this doesn’t change the model. To see this, note that we can absorb this constant into PP and QQ by writing them in terms of f(z)=f(z/λ)f^{\prime}(z^{\prime})=f(z^{\prime}/\lambda), μ(X)=μ(X)λ\mu^{\prime}(X)=\mu(X)*\lambda, and Σ(X)=Σ(X)λ2\Sigma^{\prime}(X)=\Sigma(X)*\lambda^{2}. This will produce an objective function whose value (right hand side of Equation 5) is identical to the loss we had with zN(0,I)z\sim\mathcal{N}(0,I). Also, the model for sampling XX will be identical, since z/λN(0,I)z^{\prime}/\lambda\sim\mathcal{N}(0,I).

However, there is another place where a regularization parameter can come from. Recall that a good choice for the output distribution for continuous data is P(Xz)N(f(z),σ2I)P(X|z)\sim\mathcal{N}(f(z),\sigma^{2}*I) for some σ\sigma we supply. Therefore, logP(Xz)=C12Xf(z)2/σ2\log P(X|z)=C-\frac{1}{2}\|X-f(z)\|^{2}/\sigma^{2} (where CC is a constant that does not depend on ff, and can be ignored during optimization). When we write the full optimization objective, σ\sigma appears in the second term on the r.h.s. of Equation 5, but not the first; in this sense, the σ\sigma we choose behaves like a λ\lambda controlling the weighting of the two terms. Note, however, that the existence of this parameter relies on our choice of the distribution of XX given zz. If XX is binary and we use a Bernoulli output model, then this regularization parameter disappears, and the only way to bring it back is to use hacks like replicating the dimensions of XX. From an information theory standpoint, this makes sense: when XX is binary, we can actually count the number of bits that are required to encode XX, and both terms on the right hand side of Equation 5 are using the same units to count these bits. However, when XX is continuous, each sample contains infinite information. Our choice of σ\sigma determines how accurately we expect the model to reconstruct XX, which is necessary so that the information content can become finite.

Conditional Variational Autoencoders

Let’s return to our running example of generating handwritten digits. Say that we don’t just want to generate new digits, but instead we want to add digits to an existing string of digits written by a single person. This is similar to a truly practical problem in computer graphics called hole filling: given an existing image where a user has removed an unwanted object, the goal is to fill in the hole with plausible-looking pixels. An important difficulty with both problems is that the space of plausible outputs is multi-modal: there are many possibilities for the next digit or the extrapolated pixels. A standard regression model will fail in this situation, because the training objective generally penalizes the distance between a single prediction and the ground truth. Faced with a problem like this, the best solution the regressor can produce is something which is in between the possibilities, since it minimizes the expected distance. In the case of digits, this will most likely look like a meaningless blur that’s an “average image” of all possible digits and all possible styles that could occur The denoising autoencoder can be seen as a slight generalization of the regression model, which might improve on its behavior. That is, we would say that the “noise distribution” simply deletes pixels, and so the denoising autoencoder must reconstruct the original image given the noisy version. Note, however, that this still doesn’t solve the problem. The standard denoising autoencoder still requires that the conditional distribution of the original sample given the noisy sample follow a simple, parametric distribution. This is not the case for complex data like image patches. . What we need is an algorithm that takes in a string or an image, and produces a complex, multimodal distribution that we can sample from. Enter the conditional variational autoencoder (CVAE) , which modifies the math in the previous section by simply conditioning the entire generative process on an input. CVAEs allow us to tackle problems where the input-to-output mapping is one-to-manyOften called “structured prediction” in machine learning literature., without requiring us to explicitly specify the structure of the output distribution.

Given an input XX and an output YY, we want to create a model P(YX)P(Y|X) which maximizes the probability of the ground truth (I apologize for re-defining XX here. However, standard machine learning notation maps XX to YY, so I will too). We define the model by introducing a latent variable zN(0,I)z\sim\mathcal{N}(0,I), such that:

where ff is a deterministic function that we can learn from data. We can rewrite Equations 2 through 5 conditioning on XX as follows:

Note that P(zX)P(z|X) is still N(0,I)\mathcal{N}(0,I) because our model assumes zz is sampled independently of XX at test time. The structure of this model is shown in Figure 6.

At test time, we can sample from the distribution P(YX)P(Y|X) by simply sampling zN(0,I)z\sim\mathcal{N}(0,I).

Examples

Implementations for these examples using Caffe can be found online at: http://github.com/cdoersch/vae_tutorial

To demonstrate the distribution learning capabilities of the VAE framework, let’s train a variational autoencoder on MNIST. To show that the framework isn’t heavily dependent on initialization or network structure, we don’t use existing published VAE network structures, but instead adapt the basic MNIST AutoEncoder example that’s included with Caffe . (However, we use ReLU non-linearities and ADAM , since both are standard techniques to speed convergence.) Although MNIST is real-valued, it is constrained between 0 and 1, so we use the Sigmoid Cross Entropy loss for P(Xz)P(X|z). This has a probabilistic interpretation: imagine that we created a new datapoint XX^{\prime} by independently sampling each dimension as Xi\mboxBernoulli(Xi)X^{\prime}_{i}\sim\mbox{Bernoulli}(X_{i}). Cross entropy measures the expected probability of XX^{\prime}. Thus we’re actually modeling XX^{\prime}, the randomly binarized version of MNIST, but we’re only giving qq a summary of this data XX. Admittedly this is not quite what the VAE framework prescribes but works well in practice, and is used in other VAE literature . Even though our model is considerably deeper than and , training the model was not difficult. The training was run to completion exactly once (though the training was re-started the 5 times to find the learning rate which made the loss descend the fastest). Digits generated from noise are shown in Figure 7. It’s worth noting that these samples are difficult to evaluate since there’s no simple way to measure how different these are from the training set . However, the failure cases are interesting: while most of the digits look quite realistic, a significant number are ‘in-between’ different digits. For example, the seventh digit from the top in the leftmost column is clearly in-between a 7 and a 9. This happens because we are mapping a continuous distribution through a smooth function.

In practice, the model seems to be quite insensitive to the dimensionality of zz, unless zz is excessively large or small. Too few zz’s means the model can no longer capture all of the variation: less than 4 zz dimensions produced noticeably worse results. Results with 1,000 zz’s were good, but with 10,000 they were also degraded. In theory, if a model with nn zz’s is good, then a model with m>>nm>>n should not be worse, since the model can simply learn to ignore the extra dimensions. However, in practice, it seems stochastic gradient descent struggles to keep D[Q(zX)P(z)]\mathcal{D}[Q(z|X)||P(z)] low when zz is extremely large.

MNIST conditional variational autoencoder

I had originally intended to show a conditional variational autoencoder completing MNIST digits given only half of each digit. While a CVAE works quite well for this purpose, unfortunately a regressor actually works quite well also, producing relatively crisp samples. The apparent reason is the size of MNIST. A network with similar capacity to the one in section 4.1 can easily memorize the entire dataset, and so the regressor overfits badly. Thus, at test time, it produces predictions that behave something like nearest-neighbor matching, which are actually quite sharp. CVAE models are most likely to outperform simple regression when the output is ambiguous given a training example. Therefore, let’s make two modifications to the problem to make it more ambiguous, at the cost of making it somewhat more artificial. First, the input is a single column of pixels taken from the middle of the digit. In MNIST, each pixel has a value between 0 and 1, meaning that there is still enough information even in this single column of pixels for the network to identify a specific training example. Therefore, the second modification is to replace each pixel in our column with a binary value (0 or 1), choosing 1 with probability equal to the pixel intensity. These binary values were resampled each time a digit was passed to the network. Figure 8 shows the results. Note that the regressor model handles the ambiguity by blurring its output (although there are cases where the regressor is suspiciously confident when making wrong guesses, suggesting overfitting is still an issue). The blur in the regressor’s output minimizes the distance to the set of many digits which might have produced the input. The CVAE, on the other hand, generally picks a specific digit to output and does so without blur, resulting in more believable images.

Acknowledgements: Thanks to everyone in the UCB CS294 Visual Object And Activity Recognition group and CMU Misc-Read group, and to many others who encouraged me to convert the presentation I gave there into a tutorial. I would especially like to thank Philipp Krähenbühl, Jacob Walker, and Deepak Pathak for helping me formulate and refine my description of the method, and Kenny Marino for help editing. I also thank Abhinav Gupta and Alexei Efros for helpful discussions and support, and Google for their fellowship supporting my research.

Appendix A Proof in 1D that VAEs have zero approximation error given arbitrarily powerful learners.

Let Pgt(X)P_{gt}(X) be a 1D distribution that we are trying to approximate using a VAE. We assume that Pgt(X)>0P_{gt}(X)>0 everywhere, that it is infinitely differentiable, and all the derivatives are bounded. Recall that a variational autoencoder optimizes

where Pσ(Xz)=N(Xf(z),σ2)P_{\sigma}(X|z)=\mathcal{N}(X|f(z),\sigma^{2}) for zN(0,1)z\sim\mathcal{N}(0,1), Pσ(X)=zPσ(Xz)P(z)dzP_{\sigma}(X)=\int_{z}P_{\sigma}(X|z)P(z)dz, and Qσ(zX)=N(zμσ(X),Σσ(X))Q_{\sigma}(z|X)=\mathcal{N}(z|\mu_{\sigma}(X),\Sigma_{\sigma}(X)). We make the dependence on σ\sigma explicit here since we will send it to 0 to prove convergence. The theoretical best possible solution is where Pσ=PgtP_{\sigma}=P_{gt} and D[Qσ(zX)Pσ(zX)]=0\mathcal{D}[Q_{\sigma}(z|X)\|P_{\sigma}(z|X)]=0. By “arbitrarily powerful” learners, we mean that if there exist ff, μ\mu and Σ\Sigma which achieve this best possible solution, then the learning algorithm will find them. Hence, we must merely show that such an ff, μσ\mu_{\sigma}, and Σσ\Sigma_{\sigma} exist. First off, PgtP_{gt} can actually be described arbitrarily well as Pgt(X)=zN(Xf(z),σ2)P(z)dzP_{gt}(X)=\int_{z}\mathcal{N}(X|f(z),\sigma^{2})P(z)dz as σ\sigma approaches 0. To show this, let FF be the cumulative distribution function (CDF) of PgtP_{gt}, and let GG be the CDF of N(0,1)\mathcal{N}(0,1), which are both guaranteed to exist. Then G(z)G(z) is distributed Unif(0,1)Unif(0,1) (the uniform distribution), and therefore f(z)=F1(G(z))f(z)=F^{-1}(G(z)) is distributed Pgt(X)P_{gt}(X). This means that as σ0\sigma\rightarrow 0, the distribution P(X)P(X) converges to PgtP_{gt}.

From here, we must simply show that D[Qσ(zX)Pσ(zX)]0\mathcal{D}[Q_{\sigma}(z|X)\|P_{\sigma}(z|X)]\rightarrow 0 as σ0\sigma\rightarrow 0. Let g(X)=G1(F(X))g(X)=G^{-1}(F(X)), i.e., the inverse of ff, and let Qσ(zX)=N(zg(X),(g(X)σ)2)Q_{\sigma}(z|X)=\mathcal{N}(z|g(X),(g^{\prime}(X)*\sigma)^{2}). Note that D[Qσ(zX)Pσ(zX)]\mathcal{D}[Q_{\sigma}(z|X)||P_{\sigma}(z|X)] is invariant to affine transformations of the sample space. Hence, let Q0(z0X)=N(z0g(X),g(X)2)Q^{0}(z^{0}|X)=\mathcal{N}(z^{0}|g(X),g^{\prime}(X)^{2}) and Pσ0(z0X)=Pσ(z=g(X)+(z0g(X))σX)σP^{0}_{\sigma}(z^{0}|X)=P_{\sigma}(z=g(X)+(z^{0}-g(X))*\sigma|X)*\sigma. When I write P(z=...)P(z=...), I am using the PDF of zz as a function, and evaluating it at some point. Then:

where Q0(z0X)Q^{0}(z^{0}|X) does not depend on σ\sigma, and its standard deviation is greater than . Therefore, it is sufficient to show that Pσ0(z0X)Q0(z0X)P^{0}_{\sigma}(z^{0}|X)\rightarrow Q^{0}(z^{0}|X) for all zz. Let r=g(X)+(z0g(X))σr=g(X)+(z^{0}-g(X))*\sigma. Then:

Here, Pσ(X)Pgt(X)P_{\sigma}(X)\rightarrow P_{gt}(X) as σ0\sigma\rightarrow 0, which is a constant, and rg(X)r\rightarrow g(X) as σ0\sigma\rightarrow 0, so P(r)P(r) also tends to a constant. Together with σ\sigma, they ensure that the whole distribution normalizes. We will wrap them both in the constant CC.

Next, we do a Taylor expansion of ff around g(X)g(X):

Note that N(Xμ,σ)=(2πσ)1exp((xμ)22σ2)\mathcal{N}(X|\mu,\sigma)=(\sqrt{2\pi}\sigma)^{-1}\exp\left(\frac{-(x-\mu)^{2}}{2\sigma^{2}}\right). We rewrite the above using this formula, rearrange terms, and re-write the result as a Gaussian to obtain:

Note 1/f(g(X))=g(X)1/f^{\prime}(g(X))=g^{\prime}(X), since f=g1f=g^{-1}. Furthermore, since f(n)f^{(n)} is bounded for all nn, all terms in the sum tend to 0 as σ0\sigma\rightarrow 0. CC must make the distribution normalize, so we have that the above expression:

Looking at Equation 21, the bulk of the approximation error in this setup comes from the curvature of gg, which is mostly determined by the curvature of the c.d.f. of the ground truth distribution.

References