A generator improves because another network challenges it
A Generative Adversarial Network, or GAN, trains two neural networks with opposing jobs. The generator converts random input into fake samples. The discriminator receives real and fake samples and estimates whether each one came from the real dataset.
Neither network receives a ready-made rule for drawing a face, shoe, or waveform. The discriminator’s changing feedback becomes the generator’s learning signal. This is why GAN training is an alternating game rather than one ordinary prediction update.
Generative Adversarial Networks (GANs) in Simple Words
Imagine an art counterfeiter (the Generator) attempting to paint a masterpiece, and a detective (the Discriminator) inspecting paintings to catch fakes. At first, both are clumsy. But as the detective learns to spot tiny flaws, the counterfeiter is forced to become extraordinarily skilled. Eventually, the counterfeiter’s work becomes so convincing that the detective cannot tell real from fake!
Generator
Draws random noise and paints a fake
Discriminator
Inspects real data and fakes to classify them
Adversarial Loss
Scores both on how well they outsmart each other
Nash Equilibrium
Generator produces fakes indistinguishable from real data
Terms to identify before following the loop
z — random latent or noise vector
Sampled from a developer-chosen distribution. It gives the generator different starting points.
G(z) — generated sample
Calculated by the generator using z and its learned parameters.
x — real sample
Drawn from the training dataset. The discriminator label 1 is supplied by the training procedure.
D(sample) — probability of real
A learned number between 0 and 1. A value near 1 means D currently believes the sample is real.
Figure 1 — The generator creates fakes; the discriminator scores real and fake samples
The generator never sees a real-or-fake label directly. Its learning signal comes from the discriminator's score on G(z).
Sampled random z enters the learned generator and becomes a fake sample. A real sample from the dataset and the fake sample both enter the same discriminator. The discriminator produces a high example real score and a low example fake score. A dashed feedback path carries the fake-score learning signal toward the generator.
The first term rewards probabilities near 1 for real samples. The second rewards probabilities near 0 for generated samples. During this phase, G(z) is detached, so only discriminator parameters receive gradients and change.
During the generator phase, fake samples are given target 1. The discriminator participates in the calculation but its optimizer is not stepped; the gradient tells G how to change its output so D is more likely to call it real. This form usually gives a stronger early learning signal than minimizing log(1 - D(G(z))).
Worked loss calculation with one real and one fake sample
| Value | Number | Source | Interpretation |
|---|---|---|---|
| Real label | 1 | Assigned by the training procedure | This sample came from the dataset |
| D(x) | 0.90 | Calculated by D for the real sample | D is confidently correct |
| Fake label for D | 0 | Assigned by the training procedure | This sample came from G |
| D(G(z)) | 0.20 | Calculated by D for the fake sample | D gives only 20% probability of real |
Discriminator phase
L_D = -ln(0.90) - ln(1 - 0.20)
= 0.105 + 0.223 = 0.328
The small loss reflects two mostly correct decisions.
Generator phase
Suppose a fresh pass gives D(G(z)) = 0.30.
L_G = -ln(0.30) = 1.204
The high loss tells G that its sample still looks fake to D.
One alternating training step
1. Sample inputs
Read a real batch x from the dataset and sample z from the chosen noise prior.
2. Create fakes
Calculate fake = G(z). The generator parameters are used, but no update has happened yet.
3. Update D
Clear D gradients. Evaluate D(x) and D(fake.detach()). Calculate labels 1 and 0, backpropagate L_D, and step only D’s optimizer.
4. Why detach?
detach keeps the discriminator update from sending gradients into G. The fake values remain the same; their connection to G’s computation graph is removed for this phase.
5. Update G
Clear G gradients. Evaluate D(fake) without detaching, use target 1, backpropagate L_G through D into G, and step only G’s optimizer.
6. Repeat and monitor
Use fresh batches and noise. Track losses, D probabilities, sample quality, and sample diversity rather than trusting one loss number.
Figure 2 — GAN training alternates which network is allowed to change
Detach is used only in the discriminator step: it keeps the fake values but cuts their gradient connection to G. In the generator step, gradients must pass through the fixed discriminator back into G.
The discriminator step sends real x with target one and a detached fake with target zero into the discriminator; only discriminator parameters update and a stop symbol marks the detached gradient. The generator step sends fresh z through the generator and fixed discriminator with target one; a dashed gradient path passes backward through the discriminator and fake sample to update only the generator.
A runnable one-dimensional GAN
This PyTorch example learns to generate numbers resembling a real normal distribution centred near 3. It is intentionally small, but the detach and two optimizer phases are the same ideas used in image GANs.
import torch
from torch import nn
torch.manual_seed(4)
G = nn.Sequential(nn.Linear(1, 16), nn.ReLU(), nn.Linear(16, 1))
D = nn.Sequential(nn.Linear(1, 16), nn.LeakyReLU(0.2), nn.Linear(16, 1), nn.Sigmoid())
g_optimizer = torch.optim.Adam(G.parameters(), lr=1e-3)
d_optimizer = torch.optim.Adam(D.parameters(), lr=1e-3)
bce = nn.BCELoss()
for step in range(1000):
real = 3.0 + 0.5 * torch.randn(64, 1) # data-supplied distribution
z = torch.randn(64, 1) # sampled generator input
fake = G(z)
# Phase 1: update D only.
d_optimizer.zero_grad()
d_real = D(real)
d_fake = D(fake.detach()) # no gradient enters G
d_loss = bce(d_real, torch.ones_like(d_real)) + bce(d_fake, torch.zeros_like(d_fake))
d_loss.backward()
d_optimizer.step()
# Phase 2: update G while D acts as a fixed differentiable judge.
for parameter in D.parameters():
parameter.requires_grad_(False)
g_optimizer.zero_grad()
d_fake_for_g = D(fake)
g_loss = bce(d_fake_for_g, torch.ones_like(d_fake_for_g))
g_loss.backward()
g_optimizer.step()
for parameter in D.parameters():
parameter.requires_grad_(True)
print("generated mean:", G(torch.randn(2000, 1)).mean().item())GAN Adversarial Convergence: Generator vs Discriminator
Tracking minimax loss and discriminator accuracy toward theoretical Nash Equilibrium (log 2 ≈ 0.693).
Early in training, the Discriminator wins easily (low D loss, high G loss). As G improves, it learns to fool D until D can only guess with ~50% accuracy (equilibrium).
Equilibrium, conditioning, and later variants
In the idealized equilibrium, the generated distribution matches the real one and D cannot reliably distinguish them, so D outputs about 0.5. This does not mean both networks failed; it means the fake samples are indistinguishable under the learned test. Real training may cycle or diverge instead of reaching that point.
A conditional GAN supplies extra information such as a class label to G and D, allowing requests like “generate class 7.” Wasserstein GANs replace the original discriminator score and objective with a critic-based formulation designed to improve gradients; treat WGAN as a later stabilization method, not as part of the basic BCE calculation above.
Common failures and useful diagnostics
| Failure | What it looks like | What to inspect |
|---|---|---|
| Mode collapse | Many z values produce nearly identical outputs | Sample diversity across a fixed grid of noise vectors |
| Discriminator dominates | D rejects nearly every fake; G receives weak or unstable gradients | D(G(z)), gradient norms, update ratio, capacity, and learning rates |
| Oscillation | Quality improves and collapses repeatedly | Fixed-noise samples over time, optimizer settings, and architecture balance |
| Memorization | Generated samples are too close to training examples | Nearest-neighbour comparisons and duplicate-heavy training data |
Summary / Key Takeaways
- A GAN pairs a generator that turns random z into fake samples with a discriminator that estimates whether samples are real.
- Training alternates two updates rather than optimizing both networks as one ordinary prediction step.
- During the discriminator update, real samples use target 1 and detached fake samples use target 0, so only D changes.
- During the generator update, the fake remains connected to G and uses target 1 through a temporarily fixed D, so only G changes.
- At ideal equilibrium, generated and real distributions match and D outputs about 0.5 because it cannot reliably distinguish them.
- Loss values alone are insufficient; monitor fixed-noise samples, discriminator probabilities, gradients, quality, and diversity.
- Mode collapse, discriminator dominance, oscillation, and memorization are central GAN failure modes to diagnose.