Generative Adversarial Nets in TensorFlow (Part I)
This post was first published on 12/29/15, and has since been migrated to Blogger.
This is a tutorial on implementing Ian Goodfellow's Generative Adversarial Nets paper in TensorFlow. Adversarial Nets are a fun little Deep Learning exercise that can be done in ~80 lines of Python code, and exposes you (the reader) to an active area of deep learning research (as of 2015): Generative Modeling!
Scenario: Counterfeit Money
To help explain the motivations behind the paper, here's a hypothetical scenario: Danielle is a teller at a bank, and one of her job responsibilities is to discriminate between real money and counterfeit money. George is a crook and is trying to make some counterfeit money, becase free money would be pretty radical.
Let's simplify things a bit and assume the only distinguishing feature of currency is one unique number, , printed on the each bill. These numbers are randomly sampled from a probability distribution, whose density function is only known to the Treasury (i.e. neither Danielle nor George know the function). For convenience, this tutorial uses to refer to both the distribution and the density function (though semantically a distribution and its density function are not the same).
George's goal is to generate samples from , so his counterfeit currency is indistinguishable from "real" currency. You might ask: how can George generate samples from if he doesn't know in the first place?
We can create computationally indistinguishable samples without understanding the "true" underlying generative process [1]. The underlying generative process is the method that the Treasury itself is using to generate samples of - perhaps some efficient algorithm for sampling that relies on the analytical formula for the pdf.
We can think of this algorithm as the "natural (function) basis", the straightforward method the Treasury would actually use to print our hypothetical currency. However, a (continuous) function can be represented as a combination of a different set of basis functions; George can express the same sampler algorithm in a "neural network basis" or "Fourier basis" or other basis that can be used to build a universal approximator. From an outsider's perspective, the samplers are computationally indistinguishable, and yet George's model doesn't reveal to him the structure of the "natural" sampler basis or the analytical formula of .
Background: Discriminative vs. Generative Models
Let , be the "observed" and "target" random variables. The joint distribution for and is , which we can think of as a probability density over 2 (possibly dependent) variables.
A Discriminative model allows us to evaluate the conditional probability . For instance, given a vector of pixel values , what is the probability that ? (where "6" corresponds to the categorical class label for "tabby cat"). MNIST LeNet, AlexNet, and other classifiers are examples of a discriminative models.
On the other hand, a Generative model can allows us to evaluate the joint probability . This means that we can propose value pairs and do rejection-sampling to obtain samples , from . Another way to put this is that with the right generative model, we can convert a random number from into a picture of a rabbit. That's awesome.

Of course, generative models are much harder to construct than discriminative models, and both are active areas of research in statistics and machine learning.
Generative Adversarial Networks
Goodfellow's paper proposes a very elegant way to teach neural networks a generative model for any (continuous) probability density function. We build two neural networks (Danielle) and (George), and have them play an adversarial cat-and-mouse game: is a generator and attempts to counterfeit samples from and is a decider that tries to not get fooled. We train them simultaneously, so that they both improve by competing with each other. At convergence, we hope that has learned to sample exactly from , at which point (random guessing).
Advesarial Nets have been used to great success to synthesize the following from thin air:

In this tutorial we won't be doing anything nearly as amazing, but hopefully you'll come away with a better fundamental understanding of adversarial nets.
Implementation
We'll be training a neural network to sample from the simple 1-D normal distribution

Let , be small 3-layer perceptrons, each with a meager 11 hidden units in total. takes as input a single sample of a noise distribution: . We want to map points to , in such a way that mapped points cluster densely where is dense. Thus, G takes in and generates fake data .

Meanwhile, the discriminator , takes in input and outputs a likelihood of the input belonging to . Let and be copies of (they share the same parameters so ). The input to is a single sample of the legitimate data distribution: , so when optimizing the decider we want the quantity to be maximized. takes as input (the fake data generated by ), so when optimizing we want to to be minimized. The value function for is:
Here's the Python code:
batch=tf.Variable(0)
obj_d=tf.reduce_mean(tf.log(D1)+tf.log(1-D2))
opt_d=tf.train.GradientDescentOptimizer(0.01)
.minimize(1-obj_d,global_step=batch,var_list=theta_d)The reason we go through the trouble of specifying copies and is that in TensorFlow, we need one copy of to process the input and another copy to process the input ; the same section of the computational graph can't be re-used for different inputs. When optimizing , we want the quantity to be maximized (successfully fooling ). The value function for is:
batch=tf.Variable(0)
obj_g=tf.reduce_mean(tf.log(D2))
opt_g=tf.train.GradientDescentOptimizer(0.01)
.minimize(1-obj_g,global_step=batch,var_list=theta_g)Instead of optimizing with one pair at a time, we update the gradient based on the average of loss gradients computed for different pairs. The stochastic gradient estimated from a minibatch is closer to the true gradient across the training data. The training loop is straightforward:
# Algorithm 1, GoodFellow et al. 2014
for i in range(TRAIN_ITERS):
x= np.random.normal(mu,sigma,M) # sample minibatch from p_data
z= np.random.random(M) # sample minibatch from noise prior
sess.run(opt_d, {x_node: x, z_node: z}) # update discriminator D
z= np.random.random(M) # sample noise prior
sess.run(opt_g, {z_node: z}) # update generator GManifold Alignment
Following the above recipe naively will not lead to good results, because we are sampling and independently each iteration. Nothing is enforcing that adjacent points in the domain are being mapped to adjacent points in the domain; in one minibatch, we might train to map $0.501 \to -1.1$, $0.502 \to 0.01$, and $0.503 \to -1.11$. The mapping arrows cross each other too much, making the transformation very bumpy. What's worse, the next minibatch might map $0.5015 \to 1.1$, $0.5025 \to -1.1$, and $0.504 \to 1.01$. This implies a completely different mapping from the previous minibatch, so the optimizer will fail to converge.

To remedy this, we want to minimize the total length of the arrows taking points from to , because this will make the transformation as smooth as possible and easier to learn. Another way of saying this is that the "vector bundles" carrying to should be correlated between minibatches.
First, we'll stretch the domain of to the same size of . The normal distribution centered at -1 has most of its probability mass lying between , so we should sample from . Doing this means no longer needs to learn how to "stretch" the domain by a factor of 10. The less has to learn, the better.
Next, we'll align the samples of and within a minibatch by sorting them both from lowest to highest.
Instead of sampling via np.random.random(M).sort(), we'll use via stratified sampling - we generate equally spaced points along the domain and then jitter the points randomly. This preserves sorted order and also increases the representativeness the entire training space. We then match our stratified, sorted samples to our sorted samples.

Of course, for higher dimensional problems it's not so straightforward to align the input space with the target space , since sorting points doesn't really make sense in 2D and higher. However, the notion of minimizing the transformation distance between the and manifolds still holds [2].
The modified algorithm is as follows:
for i in range(TRAIN_ITERS):
x= np.random.normal(mu,sigma,M).sort()
z= np.linspace(-5.,5.,M)+np.random.random(M)*.01 # stratified
sess.run(opt_d, {x_node: x, z_node: z})
z= np.linspace(-5.,5.,M)+np.random.random(M)*.01
sess.run(opt_g, {z_node: z})This step was crucial for me to get this example working: when dealing with random noise as input, failing to align the transformation map properly will give rise to a host of other problems, like massive gradients that kill ReLU units early on, plateaus in the objective function, or performance not scaling with minibatch size.
Pretraining D
The original algorithm runs steps of gradient descent on for every step of gradient descent on . I found it more helpful to pre-train a larger number of steps prior to running the adversarial net, using a mean-square error (MSE) loss function to fit to . This loss function is nicer to optimize than the log-likelihood objective function for (since the latter has to deal with stuff from ). It's easy to see that is the optimal likelihood decision surface for its own distribution.
Here is the decision boundary at initialization.

After pretraining:

Close enough, lol.
Other Troubleshooting Comments
- Using too many parameters in the model often leads to overfitting, but in my case making the network too big failed to even converge under the minimax objective - the network units saturated too quickly from large gradients. Start with a shallow, tiny network and only add extra units/layers if you feel that the size increase is absolutely necessary.
- I started out using ReLU units but the units kept saturating (possibly due to manifold alignment issues). The Tanh activation function seemed to work better.
- I also had to tweak the learning rate a bit to get good results.
Results
Before training, here is , the pre-trained decision surface of , and the generative distribution .
.

Here's the loss function as a function of training iterations.

After training, approximates , and the discriminator is about uniformly confused () for all values of .

And there you have it! has learned how to sample (approximately) from to the extent that can no longer separate the "reals" from the forgeries.
Footnotes
- Here's a more vivid example of computational indistinguishability: suppose we train a super-powerful neural network to sample from the distribution of cat faces. The underlying (generative) data distribution for "true" cat faces involves 1) a cat being born and 2) somebody eventually taking a photograph of the cat. Clearly, our neural network isn't learning this particular generative process, as no real cats are involved. However, if our neural network can generate pictures that we cannot distinguish from "authentic" cat photos (armed with polynomial-time computational resources), then in some ways these photos are "just as legitimate" as regular cat photos. This is worth pondering over, in the context of the Turing Test, Cryptography, and fake Rolexes.
- Excessive mapping crossover can be viewed from the perspective of "overfitting", where the learned regression/classification function has been distorted in "contradictory" ways by data samples (for instance, a picture of a cat classified as a dog). Regularization techniques implicitly discourage excessive "mapping crossover", but do not explicitly implement a sorting algorithm to ensure the learned transformation is continuous / aligned in -space with respect to -space. Such a sorting mechanism might be very useful for improving training speeds...

