Generative adversarial networks
Generative Adversarial Networks (GANs) are a framework where two neural networks — a generator and a discriminator — play a minimax game so the generator learns to produce realistic data.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Generative Adversarial Networks (GANs) let engineers create realistic synthetic data (images, audio, text embeddings) that help data augmentation, domain adaptation, privacy-preserving data release and creative applications (image synthesis, style transfer). GANs are used in computer vision pipelines (see CNN architecture, transfer learning) and as building blocks for generative AI systems taught elsewhere in this course.
Key ideas
Discriminator (D): a parametric function D(x; θ_d) that outputs a scalar in [0,1], interpreted as probability that x comes from the real data distribution p_data. D is trained to distinguish real samples from generated samples.
Minimax game: the training objective is a two-player minimax problem. D maximises the log-likelihood of correct labels while G minimises the same objective (tries to fool D). The original GAN objective (Goodfellow et al., 2014) is:
- D maximises V(G,D) with respect to θ_d
- G minimises V(G,D) with respect to θ_g This is a zero-sum game; an equilibrium occurs when p_g = p_data (the generator reproduces the true distribution) and D(x)=1/2 everywhere.
Optimal discriminator (D): For a fixed generator distribution p_g, the discriminator that maximises the value function pointwise is D(x) = p_data(x) / (p_data(x) + p_g(x)). Proof: treat V(G,D) as expectation over x and maximise the integrand in D(x) which is a concave function of D(x); differentiate and set to zero.
Value at D* and connection to divergence: Substituting D* into V(G,D) gives a function of p_g and p_data that relates to the Jensen-Shannon divergence (JSD). At optimum D*, V(G,D*) = -log 4 + 2 · JSD(p_data || p_g). Since JSD ≥ 0 and equals 0 iff p_data = p_g, minimising V(G,D*) over G pushes p_g toward p_data.
Practical training: We do alternating gradient updates: update D using real and fake samples, then update G (usually by maximising log D(G(z)) or minimising -log D(G(z)) or using alternative losses to improve gradient behaviour). Training is unstable: problems include mode collapse (generator produces limited modes), vanishing gradients (if D too strong) and oscillations (no convergence to a single point but cycles).
Variants: To improve stability and metric properties, many variants exist: Wasserstein GAN (WGAN) uses Earth-Mover (Wasserstein-1) distance with a critic (no sigmoid) and enforces 1-Lipschitz continuity via weight clipping; Least-Squares GAN replaces BCE by least-squares loss; Conditional GAN (cGAN) conditions both G and D on labels y; WGAN-GP replaces weight clipping with a gradient penalty to enforce Lipschitz continuity.
Diagram to draw for exams: draw horizontal axis x (data space) and vertical axis probability density. Plot two curves: p_data(x) (label it) and p_g(x) (label it). For a chosen x0 mark the values p_data(x0) and p_g(x0) vertically. Draw an arrow to D*(x0) = p_data/(p_data+p_g) and write that formula. Also sketch discriminator output as a function D(x) between 0 and 1 for several x.
Formulas
V(G,D) = E_{x~p_data}[log D(x)] + E_{z~p_z}[log(1 - D(G(z)))] — V(G,D) is the minimax objective; dimensionless probabilities; applies to original GAN formulation.
L_D = - E_{x~p_data}[log D(x)] - E_{z~p_z}[log(1 - D(G(z)))] — discriminator loss to minimise (equivalently, maximising V).
L_G (non-saturating) = - E_{z~p_z}[log D(G(z))]; L_G (minimax) = E_{z~p_z}[log(1 - D(G(z)))] — the non-saturating loss is commonly used to avoid vanishing gradients.
D*(x) = p_data(x) / (p_data(x) + p_g(x)) — optimal discriminator for fixed generator; p_data and p_g are probability density functions (units: 1 / (data units)).
V(G,D*) = - log 4 + 2 · JSD(p_data || p_g) — connects training objective at optimal D to Jensen-Shannon divergence; JSD is dimensionless; applies when densities exist.
JSD(P||Q) = (1/2) KL(P || M) + (1/2) KL(Q || M) where M = (P+Q)/2 and KL is Kullback–Leibler divergence; all are dimensionless.
Wasserstein-1 distance W(P,Q) = inf_{γ ∈ Π(P,Q)} E_{(x,y)~γ} [||x - y||] — Earth-Mover distance used in WGAN; units: same as data (e.g., metres if x is position).
sigmoid(a) = 1/(1+exp(-a)) — used in discriminator output; dimensionless.
Worked examples
Derive the optimal discriminator D*(x)
- Write value function per x: f(D(x)) = p_data(x) log D(x) + p_g(x) log(1 - D(x)).
- Differentiate w.r.t. D(x): df/dD = p_data(x)/D(x) - p_g(x)/(1 - D(x)).
- Set derivative = 0 ⇒ p_data(x)/D(x) = p_g(x)/(1 - D(x)).
- Solve: D(x) (p_g(x)) = (1 - D(x)) p_data(x) ⇒ D(x) (p_g + p_data) = p_data ⇒ D*(x) = p_data(x) / (p_data(x) + p_g(x)).
- Check second derivative: d2f/dD2 = - p_data/D^2 - p_g/(1-D)^2 < 0, so maximum.
- Substitute D* back into V to get the JSD expression; standard algebra leads to V(G,D*) = -log 4 + 2 JSD.
Minimal runnable Python example (PyTorch): forward pass and deterministic loss values
- This is a didactic minimal GAN forward computation (no training). We fix network weights so outputs and printed losses are exact.
# save as minimal_gan_example.py
import torch
import torch.nn as nn
import torch.nn.functional as F
# deterministic small example, no randomness
class Generator(nn.Module):
def __init__(self):
super().__init__()
# G(z) = z (identity) implemented as linear with weight=1, bias=0
self.linear = nn.Linear(1, 1, bias=True)
self.linear.weight.data.fill_(1.0)
self.linear.bias.data.fill_(0.0)
def forward(self, z):
return self.linear(z)
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
# D(x) = sigmoid(2*x + 0.5)
self.linear = nn.Linear(1, 1, bias=True)
self.linear.weight.data.fill_(2.0)
self.linear.bias.data.fill_(0.5)
def forward(self, x):
return torch.sigmoid(self.linear(x))
G = Generator()
D = Discriminator()
# fixed real and noise batches
real = torch.tensor([[1.0], [-1.0]])
noise = torch.tensor([[0.5], [-0.5]])
fake = G(noise)
D_real = D(real)
D_fake = D(fake)
# binary cross-entropy losses (averaged over batch)
real_loss = -torch.log(D_real).mean()
fake_loss = -torch.log(1 - D_fake).mean()
total_loss = real_loss + fake_loss
print(f"D_real = {D_real.detach().numpy().ravel().tolist()}")
print(f"D_fake = {D_fake.detach().numpy().ravel().tolist()}")
print(f"real_loss = {real_loss.item():.6f}")
print(f"fake_loss = {fake_loss.item():.6f}")
print(f"total_loss = {total_loss.item():.6f}")
Sample input: none (script runs as is) Sample exact output when run with PyTorch CPU (values shown): D_real = [0.9241418242454529, 0.18242552816867828] D_fake = [0.8175744414329529, 0.37754067730903625] real_loss = 0.889524 fake_loss = 1.087081 total_loss = 1.976605
(These numeric values come from exact sigmoid/log computations with the fixed weights above.)
- Model-answer theory question: "Show why training stops when p_g = p_data."
- Explain: At equilibrium p_g = p_data ⇒ D*(x) = 1/2 for all x ⇒ V(G,D*) = -log 4 + 2·JSD(p_data||p_g) = -log 4 (since JSD=0). This is minimum possible value w.r.t. G, so G cannot further reduce the objective; discriminator cannot do better than random guessing.
Common mistakes
- Incorrect derivative when deriving D*: forgetting to treat p_data and p_g as constants w.r.t. D and differentiating pointwise.
- Claiming KL divergence instead of Jensen-Shannon: the original GAN objective relates to JSD, not plain KL.
- When writing code, assuming D output is unbounded; original GAN uses sigmoid output in (0,1) and BCE loss.
- Confusing WGAN critic (no sigmoid) with original discriminator (has sigmoid).
For your exam
Kinds of questions:
- Definitions: define GAN, generator, discriminator, minimax game, mode collapse, Wasserstein distance.
- Short notes: training instability and remedies (WGAN, gradient penalty, feature matching, minibatch discrimination).
- Derivations: show D*(x) = p_data/(p_data + p_g); derive V(G,D*) relation to JSD. Exams expect the differentiation step and a check of the second derivative.
- Numericals/programs: small forward-pass computation like the worked example above; you may be asked to compute discriminator outputs and BCE loss for given activations.
- Diagrams: plot p_data and p_g and label D*(x) at a point.
What a full-marks answer includes:
- Clear definition of terms with notation (p_data, p_g, p_z, G, D).
- Correct objective V(G,D) and correct roles (who minimises, who maximises).
- Step-by-step derivation (differentiate integrand, solve for D*(x), second derivative test).
- Clear statement of the JSD result and explanation of convergence condition p_g = p_data.
- For programming/numerical question include exact arithmetic or a deterministic forward pass as above.
Quick check
- What is the role of the discriminator in a GAN?
- Write the expression for the GAN value function V(G,D).
- Give the formula for the optimal discriminator D*(x) for fixed G.
Answers: 1) To estimate probability that a sample is real vs generated (train to distinguish real from fake). 2) V(G,D) = E_{xp_data}[log D(x)] + E_{zp_z}[log(1 - D(G(z)))]. 3) D*(x) = p_data(x) / (p_data(x) + p_g(x)).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?