Describe the fundamental components of a Generative Adversarial Network (GAN) and elaborate on the dynamic interplay between its generator and discriminator during the training phase.
A Generative Adversarial Network (GAN) pairs a generator network that maps latent noise z to synthetic samples with a discriminator network that distinguishes real data from generated fakes. Theoretically formulated as a two-player minimax game minimizing Jensen-Shannon divergence, practical GANs typically train the generator with a non-saturating log-likelihood loss to prevent vanishing gradients early in training. Iterative alternating updates drive the generator toward realistic samples while challenging the discriminator to refine its decision boundary.
Study Card: Generative Adversarial Networks (GANs)
Direct Answer
A Generative Adversarial Network (GAN) (Goodfellow et al., 2014) consists of two neural networks trained via adversarial competition:
- Generator (): Maps random latent vectors (e.g., ) to synthetic samples approximating the real data distribution .
- Discriminator (): Classifies whether a given sample came from () or from the generator ().
In the theoretical two-player zero-sum minimax formulation, maximizes classification log-likelihood while minimizes it:
For a fixed generator , the Bayes-optimal discriminator is , reducing the outer objective to . Thus, at equilibrium (), everywhere.
In practice, minimizing suffers from vanishing gradients early in training when easily rejects poor samples (). Consequently, practitioners train with the non-saturating objective (making practical training non-zero-sum while preserving the same fixed point).
Key Terms
- Generator (): Differentiable decoder mapping latent noise to synthetic data without requiring an explicit density formula.
- Discriminator (): Binary classifier (or critic in WGANs) estimating whether inputs are real or generated, providing gradients back through .
- Minimax / Non-Saturating Loss: Theoretical zero-sum objective versus practical generator loss that maintains strong gradients early in training.
- Alternating Optimization: Fixing while updating for steps (freezing gradient flow into via
.detach()), then fixing while updating . - Jensen-Shannon Divergence (): Symmetric divergence between and minimized at the global minimax equilibrium.
Example
Consider an art forger () and an art authenticator ():
- Early on, produces obvious noise, so immediately outputs . Under the non-saturating loss , receives large gradients telling it which pixel/feature adjustments make slightly less confident.
- As improves, must inspect finer local details (edges, textures, global geometry), which in turn forces to match those finer statistics.
- Because the two players optimize simultaneous non-convex objectives rather than a single static loss, training can oscillate or suffer mode collapse if overpowers or exploits a single blind spot of .
Code Implementation
import torch
import torch.nn as nn
import torch.optim as optim
class Generator(nn.Module):
def __init__(self, latent_dim=16, hidden_dim=64, data_dim=2):
super().__init__()
self.net = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(hidden_dim, hidden_dim),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(hidden_dim, data_dim),
)
def forward(self, z):
return self.net(z)
class Discriminator(nn.Module):
def __init__(self, data_dim=2, hidden_dim=64):
super().__init__()
self.net = nn.Sequential(
nn.Linear(data_dim, hidden_dim),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(hidden_dim, hidden_dim),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(hidden_dim, 1), # Outputs raw logit for BCEWithLogitsLoss
)
def forward(self, x):
return self.net(x)
def sample_real_bimodal(batch_size):
centers = torch.tensor([[-2.0, 0.0], [2.0, 0.0]])
idx = torch.randint(0, 2, (batch_size,))
return centers[idx] + 0.25 * torch.randn(batch_size, 2)
torch.manual_seed(42)
latent_dim, batch_size = 16, 64
G = Generator(latent_dim=latent_dim)
D = Discriminator()
opt_G = optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_D = optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
bce_logits = nn.BCEWithLogitsLoss()
for step in range(1, 201):
real = sample_real_bimodal(batch_size)
real_labels = torch.ones(batch_size, 1)
fake_labels = torch.zeros(batch_size, 1)
# 1. Update Discriminator: detach fake samples so gradients do not flow to G
z = torch.randn(batch_size, latent_dim)
fake = G(z).detach()
d_loss = bce_logits(D(real), real_labels) + bce_logits(D(fake), fake_labels)
opt_D.zero_grad()
d_loss.backward()
opt_D.step()
# 2. Update Generator using non-saturating loss: -log D(G(z))
z = torch.randn(batch_size, latent_dim)
g_loss = bce_logits(D(G(z)), real_labels)
opt_G.zero_grad()
g_loss.backward()
opt_G.step()
if step in (1, 100, 200):
print(f"Step {step:3d} | D loss: {d_loss.item():.4f} | G loss: {g_loss.item():.4f}")
Related Concepts
- Variational Autoencoders (VAEs): Likelihood-based latent variable models optimizing an ELBO rather than an adversarial game—more stable to train, though prone to blurrier reconstructions without perceptual/adversarial losses.
- Mode Collapse: Failure mode where maps many inputs to a small subset of real modes, sacrificing sample diversity.
- Evaluation Metrics (FID & IS): Fréchet Inception Distance (FID) and Inception Score (IS) evaluate sample fidelity and diversity in deep feature space.
- Conditional GANs (cGANs): Condition both and on class labels, text embeddings, or source images (e.g., Pix2Pix).
- WGAN & Spectral Normalization: Wasserstein distance (WGAN-GP) and spectral normalization constrain ‘s Lipschitz constant to eliminate gradient vanishing when and have disjoint supports.