Path: blob/master/first_edition/8.4-generating-images-with-vaes.ipynb
709 views
Generating images
This notebook contains the second code sample found in Chapter 8, Section 4 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments.
Variational autoencoders
Variational autoencoders, simultaneously discovered by Kingma & Welling in December 2013, and Rezende, Mohamed & Wierstra in January 2014, are a kind of generative model that is especially appropriate for the task of image editing via concept vectors. They are a modern take on autoencoders -- a type of network that aims to "encode" an input to a low-dimensional latent space then "decode" it back -- that mixes ideas from deep learning with Bayesian inference.
A classical image autoencoder takes an image, maps it to a latent vector space via an "encoder" module, then decode it back to an output with the same dimensions as the original image, via a "decoder" module. It is then trained by using as target data the same images as the input images, meaning that the autoencoder learns to reconstruct the original inputs. By imposing various constraints on the "code", i.e. the output of the encoder, one can get the autoencoder to learn more or less interesting latent representations of the data. Most commonly, one would constraint the code to be very low-dimensional and sparse (i.e. mostly zeros), in which case the encoder acts as a way to compress the input data into fewer bits of information.
In practice, such classical autoencoders don't lead to particularly useful or well-structured latent spaces. They're not particularly good at compression, either. For these reasons, they have largely fallen out of fashion over the past years. Variational autoencoders, however, augment autoencoders with a little bit of statistical magic that forces them to learn continuous, highly structured latent spaces. They have turned out to be a very powerful tool for image generation.
A VAE, instead of compressing its input image into a fixed "code" in the latent space, turns the image into the parameters of a statistical distribution: a mean and a variance. Essentially, this means that we are assuming that the input image has been generated by a statistical process, and that the randomness of this process should be taken into accounting during encoding and decoding. The VAE then uses the mean and variance parameters to randomly sample one element of the distribution, and decodes that element back to the original input. The stochasticity of this process improves robustness and forces the latent space to encode meaningful representations everywhere, i.e. every point sampled in the latent will be decoded to a valid output.
In technical terms, here is how a variational autoencoder works. First, an encoder module turns the input samples input_img
into two parameters in a latent space of representations, which we will note z_mean
and z_log_variance
. Then, we randomly sample a point z
from the latent normal distribution that is assumed to generate the input image, via z = z_mean + exp(z_log_variance) * epsilon
, where epsilon is a random tensor of small values. Finally, a decoder module will map this point in the latent space back to the original input image. Because epsilon
is random, the process ensures that every point that is close to the latent location where we encoded input_img
(z-mean
) can be decoded to something similar to input_img
, thus forcing the latent space to be continuously meaningful. Any two close points in the latent space will decode to highly similar images. Continuity, combined with the low dimensionality of the latent space, forces every direction in the latent space to encode a meaningful axis of variation of the data, making the latent space very structured and thus highly suitable to manipulation via concept vectors.
The parameters of a VAE are trained via two loss functions: first, a reconstruction loss that forces the decoded samples to match the initial inputs, and a regularization loss, which helps in learning well-formed latent spaces and reducing overfitting to the training data.
Let's quickly go over a Keras implementation of a VAE. Schematically, it looks like this:
Here is the encoder network we will use: a very simple convnet which maps the input image x
to two vectors, z_mean
and z_log_variance
.
Here is the code for using z_mean
and z_log_var
, the parameters of the statistical distribution assumed to have produced input_img
, to generate a latent space point z
. Here, we wrap some arbitrary code (built on top of Keras backend primitives) into a Lambda
layer. In Keras, everything needs to be a layer, so code that isn't part of a built-in layer should be wrapped in a Lambda
(or else, in a custom layer).
This is the decoder implementation: we reshape the vector z
to the dimensions of an image, then we use a few convolution layers to obtain a final image output that has the same dimensions as the original input_img
.
The dual loss of a VAE doesn't fit the traditional expectation of a sample-wise function of the form loss(input, target)
. Thus, we set up the loss by writing a custom layer with internally leverages the built-in add_loss
layer method to create an arbitrary loss.
Finally, we instantiate and train the model. Since the loss has been taken care of in our custom layer, we don't specify an external loss at compile time (loss=None
), which in turns means that we won't pass target data during training (as you can see we only pass x_train
to the model in fit
).
Once such a model is trained -- e.g. on MNIST, in our case -- we can use the decoder
network to turn arbitrary latent space vectors into images:
The grid of sampled digits shows a completely continuous distribution of the different digit classes, with one digit morphing into another as you follow a path through latent space. Specific directions in this space have a meaning, e.g. there is a direction for "four-ness", "one-ness", etc.