Skip to main content
LearnMLAcademy
Advanced10 min read

Generative Adversarial Networks (GANs)

Train Generative Adversarial Networks (GANs) using minimax loss and DCGAN code, with diffusion diagrams, prompt experiments, and output-quality checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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!

1

Generator

Draws random noise and paints a fake

2

Discriminator

Inspects real data and fakes to classify them

3

Adversarial Loss

Scores both on how well they outsmart each other

4

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.

Discriminator binary-cross-entropy loss
L_D = -mean(log D(x)) - mean(log(1 - D(G(z))))

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.

Non-saturating generator loss
L_G = -mean(log D(G(z)))

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

ValueNumberSourceInterpretation
Real label1Assigned by the training procedureThis sample came from the dataset
D(x)0.90Calculated by D for the real sampleD is confidently correct
Fake label for D0Assigned by the training procedureThis sample came from G
D(G(z))0.20Calculated by D for the fake sampleD 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.

Python · requires PyTorch
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

FailureWhat it looks likeWhat to inspect
Mode collapseMany z values produce nearly identical outputsSample diversity across a fixed grid of noise vectors
Discriminator dominatesD rejects nearly every fake; G receives weak or unstable gradientsD(G(z)), gradient norms, update ratio, capacity, and learning rates
OscillationQuality improves and collapses repeatedlyFixed-noise samples over time, optimizer settings, and architecture balance
MemorizationGenerated samples are too close to training examplesNearest-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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Generative Adversarial Networks (GANs)"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is G(z) detached during the discriminator update?
Question 2 of 5numerical/formula
For D(x) = 0.90 and D(G(z)) = 0.20, what discriminator loss does the lesson calculate?
Question 3 of 5debugging/diagnostic
Many different noise vectors produce almost identical samples. Which GAN failure is most likely?
Question 4 of 5interpretation
At idealized GAN equilibrium, why may the discriminator output about 0.5?
Question 5 of 5application/scenario
A team wants a GAN to generate a requested digit class. What change matches the lesson?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is G(z) detached during the discriminator update?▼

Correct Answer: To prevent discriminator gradients from updating the generator in that phase

Detaching keeps the fake values but removes their gradient connection to G, so the discriminator phase changes only discriminator parameters.

2For D(x) = 0.90 and D(G(z)) = 0.20, what discriminator loss does the lesson calculate?▼

Correct Answer: -ln(0.90) - ln(0.80) ≈ 0.328

The BCE terms are approximately 0.105 for the real sample and 0.223 for correctly rejecting the fake, giving 0.328 in total.

3Many different noise vectors produce almost identical samples. Which GAN failure is most likely?▼

Correct Answer: Mode collapse

Mode collapse means the generator covers too little of the data distribution, producing nearly the same output from many different z values.

4At idealized GAN equilibrium, why may the discriminator output about 0.5?▼

Correct Answer: Generated and real distributions match closely enough that it cannot reliably distinguish them

An output near 0.5 at equilibrium means the learned discriminator cannot tell matched real and generated distributions apart; it does not by itself mean both networks failed.

5A team wants a GAN to generate a requested digit class. What change matches the lesson?▼

Correct Answer: Supply the class label as extra information to both G and D

A conditional GAN provides information such as a class label to both networks, allowing the generator to create samples for the requested class.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next