Skip to content
ml-recall

Topic notes

Generative Adversarial Networks

A generator and a discriminator trained against each other in a minimax game; the losses, the optimal discriminator, DCGAN design rules and the usual training failures.

3-min read AI-checked

Practise 29 questions Take a test

Key ideas

Formulas

min⁡Gmax⁡DV(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼pz[log⁡(1−D(G(z)))]\min_G \max_D V(D, G) = \mathbb{E}_{x \sim p_{\text{data}}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))] D∗(x)=pdata(x)pdata(x)+pg(x),C(G)=max⁡DV(D,G)=−log⁡4+2 JSD(pdata ∥ pg)D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)}, \qquad C(G) = \max_D V(D, G) = -\log 4 + 2\,\mathrm{JSD}(p_{\text{data}} \,\|\, p_g)

Worked example

DD gives a real image D(x)=0.8D(x) = 0.8 and a fake D(G(z))=0.2D(G(z)) = 0.2.

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

References

  1. 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
  2. Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — GAN course: Background: What is a Generative Model? (Modeling Probabilities)
  3. Dive into Deep Learning — Sec. 20.1 Generative Adversarial Networks
  4. Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — GAN course: Common Problems
  5. 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
  6. 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)
  7. Wikipedia: Jensen–Shannon divergence — Bounds
  8. Arjovsky, Chintala & Bottou (2017), Wasserstein GAN, arXiv:1701.07875 — Sec. 2 Different Distances, Example 1 (Learning parallel lines)