Tuesday , December 1 2026
GANs explained: generator vs discriminator, the adversarial training loop in PyTorch, mode collapse and fixes, GAN variants and GANs vs diffusion models.

Generative Adversarial Networks (GANs) Explained with PyTorch

Updated: 29 November 2026Level: AdvancedReading time: about 10 minutesPyTorch

A Generative Adversarial Network (GAN) trains two networks against each other: a generator that creates fake data and a discriminator that tries to tell fake from real. As they compete, the generator learns to produce realistic images, audio or data.

What You Will Learn

  • Generator and discriminator roles
  • The adversarial training loop
  • A minimal GAN in PyTorch
  • Training problems such as mode collapse
  • GAN variants and how GANs compare with diffusion models

Prerequisites

Loss Functions, Backpropagation.

How It Works

Network Input Output Goal
Generator G Random noise vector z Fake sample G(z) Fool the discriminator
Discriminator D Real or fake sample Probability it is real Classify correctly

It is a two-player game: D minimises its classification loss while G maximises D’s mistakes. At the ideal equilibrium the fakes are indistinguishable and D outputs 0.5 for everything.

Minimal GAN for MNIST Digits

PyTorch (not run here – loader is a DataLoader of flattened MNIST images)
import torch, torch.nn as nn

G = nn.Sequential(nn.Linear(64, 256), nn.LeakyReLU(0.2),
                  nn.Linear(256, 784), nn.Tanh())              # noise -> 28x28 image in [-1, 1]
D = nn.Sequential(nn.Linear(784, 256), nn.LeakyReLU(0.2),
                  nn.Linear(256, 1))                           # image -> real/fake logit
loss = nn.BCEWithLogitsLoss()
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))

for real in loader:                                            # real: (batch, 784), scaled to [-1, 1]
    b = real.size(0)
    fake = G(torch.randn(b, 64))
    # 1) train discriminator: real -> 1, fake -> 0
    d_loss = loss(D(real), torch.ones(b, 1)) + loss(D(fake.detach()), torch.zeros(b, 1))
    opt_d.zero_grad(); d_loss.backward(); opt_d.step()
    # 2) train generator: make D say "real" for fakes
    g_loss = loss(D(fake), torch.ones(b, 1))
    opt_g.zero_grad(); g_loss.backward(); opt_g.step()

Explanation: fake.detach() stops discriminator updates from changing the generator. The generator is trained with labels of “real” (1), so its gradient pushes fakes towards what D considers real. Adam with β₁ = 0.5 and LeakyReLU are standard GAN choices from DCGAN.

Training Problems

Problem Symptom Common fixes
Mode collapse Generator produces only a few similar outputs Minibatch discrimination, WGAN-GP, unrolled GANs
Discriminator too strong Generator loss stops improving Label smoothing (0.9), add noise, fewer D steps
Instability / oscillation Losses swing, quality fluctuates Lower lr, spectral normalisation, WGAN loss
Hard to evaluate Loss values are not meaningful Inspect samples; use FID score

Variants

GAN Idea
DCGAN Convolutional generator and discriminator
Conditional GAN Generate a requested class (e.g. digit “7”)
CycleGAN Translate images without paired data (horse ↔ zebra)
StyleGAN High-resolution, controllable faces
WGAN / WGAN-GP Wasserstein loss for more stable training

GANs vs Diffusion Models

Modern image generators such as Stable Diffusion and Midjourney use diffusion models, which learn to remove noise step by step. They are more stable to train and produce more diverse outputs; GANs remain faster at generation and are still used for super-resolution, image editing and real-time applications. See Generative AI and Multimodal AI.

Note: Generated faces and voices can be misused for deepfakes. Label synthetic media and respect consent and copyright when training on images.

Series

Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow

Interview Questions

Q: How does a GAN train?
A generator and a discriminator are trained alternately: D learns to separate real and fake, G learns to fool D.

Q: What is mode collapse?
The generator produces limited variety, mapping many noise vectors to similar outputs.

Q: GAN vs VAE?
GANs give sharper samples but are unstable to train; VAEs train stably with a likelihood-based loss but samples are often blurrier.

Practice Exercises

  1. Run the GAN on MNIST for 20 epochs and save a grid of samples every 5 epochs.
  2. Turn it into a conditional GAN by concatenating a one-hot label to the inputs of both networks.

Summary

GANs pit a generator against a discriminator. They can create realistic data but are tricky to train; diffusion models now lead image generation while GANs remain useful for fast synthesis and editing.

Next: Introduction to Generative AI · PyTorch vs TensorFlow

About Machine Learning

Check Also

AI Agent Frameworks Compared: LangGraph vs CrewAI vs OpenAI Agents SDK

Compare AI agent frameworks in 2026: LangGraph, CrewAI, OpenAI Agents SDK, Claude Agent SDK, Google ADK and Microsoft Agent Framework, with code and how to choose.