Key ideas
- Generative vs discriminative. A generative model captures the data distribution (or ) and can produce new instances; a discriminative model captures and only tells instances apart. Both kinds may output probabilities, so a probability output alone does not tell you which one you have2.
- A GAN (generative adversarial network) trains two networks against each other1. The generator turns a random latent vector into a sample , e.g. an image; the discriminator is a binary classifier that outputs the probability that its input is real rather than generated1,3. No labels are needed: the targets 1 (real) and 0 (fake) are created automatically.
- Alternating training. Each iteration takes steps (often 1) on with fixed, then one step on with fixed1. During the step the loss is computed from 's output, so gradients flow backward through into , but only 's weights change; during the step the fakes are detached so that no gradient reaches 3.
- Losses. minimises binary cross-entropy with label 1 for real and 0 for fake images (d2l averages the two terms)3. For , minimising saturates early in training, when rejects fakes confidently; instead maximises , the non-saturating loss, implemented as BCE on fakes with the label flipped to 11,3. So and usually use different losses.
- Theory. For a fixed the best discriminator is ; with it, the game value becomes , minimised exactly when , where everywhere1. The JSD is at most (1 bit)7 and reaches it when the two distributions do not overlap, however far apart they are8; then and the JSD gives no signal about the distance.
- The generator never writes down ; sampling is one forward pass with no Markov chain, and a vanilla GAN learns no encoder from back to (that would need an extra network)1.
- Typical failures: vanishing gradients when becomes too good, mode collapse (the generator rotates through a small set of outputs) and failure to converge4. The two players must stay balanced: a trained too long against a fixed can map many to the same output1.
- DCGAN rules5: replace pooling with strided convolutions in and fractionally strided (transposed) convolutions in ; batch normalization in both networks except the generator's output layer and the discriminator's input layer; ReLU in with a tanh output; LeakyReLU (slope 0.2) in ; real images scaled to , the range of tanh; Adam with learning rate 0.0002 and .
- LSGAN replaces the sigmoid cross-entropy by squared errors to target values; it still penalises fakes that are on the correct side of the decision boundary but far from the data, which gives the generator more gradient6.
Formulas
- LSGAN6: minimises ( = real target, = fake target), minimises . Minimising pointwise gives 6.
- With a logit and : but .
- A convolution with kernel 4, stride 2, padding 1 halves the side: , e.g. .
Worked example
gives a real image and a fake .
- Discriminator loss (average BCE): . At the equilibrium it would be , not 0.
- Generator, non-saturating: .
- Gradient with respect to the fake's logit: the saturating objective gives , the non-saturating one . For a confidently rejected fake, , the two are and : the minimax loss nearly stops teaching , the flipped-label loss does not.
In code
import torch
from torch import nn
G = nn.Sequential(nn.Linear(8, 32), nn.ReLU(), nn.Linear(32, 2), nn.Tanh())
D = nn.Sequential(nn.Linear(2, 32), nn.LeakyReLU(0.2), nn.Linear(32, 1)) # logits: no sigmoid
opt_G = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_D = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
bce, real, z = nn.BCEWithLogitsLoss(), torch.rand(64, 2) * 2 - 1, torch.randn(64, 8)
ones, zeros = torch.ones(64, 1), torch.zeros(64, 1)
fake = G(z)
d_loss = (bce(D(real), ones) + bce(D(fake.detach()), zeros)) / 2 # detach: D step leaves G alone
opt_D.zero_grad(); d_loss.backward(); opt_D.step()
w_D = D[0].weight.clone()
g_loss = bce(D(fake), ones) # non-saturating loss: fakes labelled "real"
opt_G.zero_grad(); g_loss.backward(); opt_G.step() # gradient flows through D into G
print(G[0].weight.grad is not None, torch.equal(D[0].weight, w_D)) # True True
Common pitfalls
- "The two networks only exchange data and labels" is false: the generator's gradient is backpropagated through the discriminator, which is merely not updated in that step1,3.
- The generator step uses the real label (1) on fakes. Using label 0 trains to look more fake, and real images give no gradient at all.
BCEWithLogitsLossapplies the sigmoid itself; a sigmoid at the end of as well squashes outputs into , so "fake" can never be predicted.- If ends in tanh, rescale real images from to (); otherwise separates real from fake by value range alone5.
- A loss near zero is not the goal: at the ideal equilibrium outputs 0.5 everywhere and its BCE stays at 1; a discriminator loss that drops to 0 signals vanishing gradients for 4.
- Mode collapse (few distinct outputs) and vanishing gradients (a too-strong ) are different failures4.
- Batch normalization everywhere is not better: DCGAN leaves it out of 's output and 's input layer5.
- In a conditional GAN both networks get the condition as input1: if only sees it, cannot penalise a realistic sample of the wrong class.
References
- Goodfellow et al. (2014), Generative Adversarial Nets, arXiv:1406.2661 — Sec. 3 Adversarial nets (incl. Algorithm 1); Sec. 4.1 Global Optimality of p_g = p_data; Sec. 6 Advantages and disadvantages; Sec. 7 Conclusions and future work
- Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — GAN course: Background: What is a Generative Model? (Modeling Probabilities)
- Dive into Deep Learning — Sec. 20.1 Generative Adversarial Networks
- Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — GAN course: Common Problems
- Radford, Metz & Chintala (2015), Unsupervised Representation Learning with Deep Convolutional GANs, arXiv:1511.06434 — Sec. 3 Approach and Model Architecture; Sec. 4 Details of Adversarial Training
- Mao et al. (2017), Least Squares Generative Adversarial Networks, arXiv:1611.04076 — Sec. 3.2 Least Squares Generative Adversarial Networks (Eq. 2); Sec. 3.2.1 Benefits of LSGANs; Sec. 3.2.2 relation to f-divergence (Eq. 5)
- Wikipedia: Jensen–Shannon divergence — Bounds
- Arjovsky, Chintala & Bottou (2017), Wasserstein GAN, arXiv:1701.07875 — Sec. 2 Different Distances, Example 1 (Learning parallel lines)