Prerequisites
Before diving into GANs, you should be comfortable with:
- Neural Network Fundamentals: Forward/backward pass, activation functions, backpropagation (see Tutorial 21)
- CNNs: Transposed convolutions (deconvolution), convolutional architectures (see Tutorial 22)
- Probability: Minimax games, Nash equilibrium, probability distributions
- Loss Functions: Cross-entropy, binary cross-entropy
- PyTorch: Training loops, gradient computation, batch normalization
Deep Learning
Generative Adversarial Networks — AI Creates Art, Faces, and More
Learn how GANs use adversarial training to generate realistic synthetic data from noise.
- Adversarial training — generator vs. discriminator dynamic
- Image synthesis — create photorealistic faces and art
- Training dynamics — Nash equilibrium, mode collapse, and convergence
Creativity is intelligence having fun.
Learning Objectives
By the end of this tutorial, you will be able to:
- Explain the minimax game between generator and discriminator
- Derive the GAN loss function and its optimal solution
- Implement DCGAN with transposed convolutions for image generation
- Identify and mitigate mode collapse in GAN training
- Understand Wasserstein GAN and its advantages over vanilla GAN
- Compare GAN variants (cGAN, Pix2Pix, CycleGAN, StyleGAN) for different tasks
- Implement a basic GAN training loop in PyTorch
GANs — Generative Adversarial Networks
GANs (Goodfellow et al., 2014) learn to generate data by framing generation as a two-player minimax game between a generator and discriminator .
Loss Functions
Training Process
GAN training alternates between optimizing D and G:
Mode Collapse
Mode collapse occurs when G learns to produce only a few outputs that reliably fool D, ignoring the full data distribution.
DCGAN Architecture
WGAN (Wasserstein GAN)
Real-World Applications
1. Photorealistic Face Generation StyleGAN2/3 generates 1024x1024 photorealistic faces that don't exist. NVIDIA's ThisPersonDoesNotExist demonstrates real-time face generation. Used in gaming, VR, and privacy-preserving data.
2. Image Super-Resolution SRGAN/ESRGAN upscale low-resolution images to high-resolution with realistic textures. Applications include old photo restoration, satellite imagery enhancement, and medical image upscaling.
3. Style Transfer and Art CycleGAN transforms photos between domains (horses to zebras, photos to paintings) without paired training data. Artists use GANs to create unique styles and generate variations.
4. Data Augmentation GANs generate synthetic training data for rare classes in medical imaging, fraud detection, and autonomous driving. When real data is scarce, synthetic examples can boost classifier performance 5-15%.
5. Image-to-Image Translation Pix2Pix converts sketches to photos, day to night, aerial to maps, and edges to objects. Used in architecture (sketch to building), fashion (design to garment), and medical imaging (MRI to CT).
6. Anomaly Detection GANs learn normal patterns and reconstruct anomalous inputs poorly. The reconstruction error signals anomalies in manufacturing quality control, medical imaging, and cybersecurity.
Common Mistakes & How to Avoid Them
Key Formulas Reference
| Formula | Expression | Use Case |
|---|---|---|
| GAN Minimax | min_G max_D E[log D(x)] + E[log(1-D(G(z)))] | Original GAN objective |
| Optimal D | D*(x) = p_data / (p_data + p_g) | Theoretical analysis |
| WGAN Loss | E[D(x)] - E[D(G(z))] | Stable training |
| FID Score | ||mu_r - mu_g||^2 + Tr(Sigma_r + Sigma_g - 2sqrt(Sigma_rSigma_g)) | Generation quality metric |
| Non-saturating G | L_G = -E[log D(G(z))] | Stronger gradients for G |
Interview Questions
Practice Exercise
import torch
import torch.nn as nn
# Task 1: Implement DCGAN Generator (noise -> 28x28 image)
class Generator(nn.Module):
def __init__(self, latent_dim=100):
super().__init__()
# Use ConvTranspose2d layers
# 100 -> 256x7x7 -> 128x14x14 -> 1x28x28
pass
def forward(self, z):
pass
# Task 2: Implement DCGAN Discriminator (image -> real/fake)
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
# Use Conv2d layers with stride 2 for downsampling
pass
def forward(self, x):
pass
# Task 3: Training loop with:
# - Non-saturating loss for G
# - BCE loss for D
# - Learning rates: G=2e-4, D=1e-4 (Adam, beta1=0.5)
# - Label smoothing: real=0.9, fake=0.1
# Task 4: Generate and save a grid of 64 samples every 10 epochs
Success criteria: Generate recognizable handwritten digits. Visualize training progression (epochs 1, 10, 50, 100). Plot D_loss and G_loss curves.
Key Takeaways
What to Learn Next
-> Autoencoders Learn about compressed representations.
-> Variational Autoencoders Generate data with probabilistic models.
-> Diffusion Models Deep Dive Master modern generative AI techniques.
-> Neural Networks Understand the foundation of deep learning.
-> CNNs Learn the convolutional architectures used in GANs.
-> Training Deep Networks Master training techniques for unstable models.
Advanced Topics
Progressive Growing (ProGAN)
ProGAN (Karras et al., 2017) trains GANs by progressively increasing resolution:
- Start with 4x4 images (1 residual block)
- Train until stable, then add layers to double resolution
- Fade in new layers smoothly using a parameter that ramps from 0 to 1
Why it works: Low-resolution images are easier to generate, so the model learns coarse structure first, then refines details. This enables training 1024x1024 generators that would otherwise be impossible.
StyleGAN Architecture
StyleGAN separates "style" from "content":
- Mapping network: Maps latent vector to intermediate latent space
- Style modulation: Each layer receives a learned affine transformation of
- Noise injection: Per-pixel noise adds stochastic variation (hair texture, freckles)
Key innovation: Styles are injected at different layers — coarse styles (pose, face shape) at early layers, fine styles (skin texture, lighting) at later layers.
GANs vs Diffusion Models
| Property | GANs | Diffusion Models |
|---|---|---|
| Training stability | Unstable (adversarial) | Stable (denoising objective) |
| Sample quality | Sharp but may miss modes | High quality, high diversity |
| Inference speed | Fast (single forward pass) | Slow (50-1000 denoising steps) |
| Mode coverage | Prone to mode collapse | Full distribution coverage |
| Current status | Style transfer, real-time apps | DALL-E 2, Stable Diffusion, Imagen |
Conditional Generation
Conditional GANs (cGAN) add auxiliary information to control generation:
Applications: Text-to-image (DALL-E, Midjourney), class-conditional generation, image-to-image translation (Pix2Pix).
Evaluation Metrics
- FID (Fréchet Inception Distance): Compares statistics of real vs generated images in Inception-v3 feature space. Lower = better. The most widely used metric.
- IS (Inception Score): Measures quality (sharp images) and diversity (various classes). Higher = better. Less reliable than FID.
- KID (Kernel Inception Distance): Bias-corrected version of FID. Better for small sample sizes.
- Precision/Recall: Precision measures quality (are generated images realistic?), Recall measures diversity (do they cover all modes?).
Comparison Table
| GAN Variant | Key Innovation | Task | Resolution |
|---|---|---|---|
| Vanilla GAN | Minimax game | MNIST generation | 28x28 |
| DCGAN | Conv architecture | General image generation | 64x64 - 128x128 |
| WGAN | Wasserstein loss | Stable training | Any |
| ProGAN | Progressive growing | High-res faces | 1024x1024 |
| StyleGAN | Style injection + mapping | Photorealistic faces | 1024x1024 |
| Pix2Pix | Paired image translation | Sketch to photo | 256x256 |
| CycleGAN | Cycle consistency loss | Unpaired translation | 256x256 |
Further Reading
- Goodfellow, I. et al. (2014). "Generative Adversarial Networks." — The original GAN paper that started the field.
- Radford, A. et al. (2015). "Unsupervised Representation Learning with Deep Convolutional GANs." — DCGAN architecture.
- Arjovsky, M. et al. (2017). "Wasserstein GAN." — Stable training with Wasserstein distance.
- Karras, T. et al. (2018). "Progressive Growing of GANs." — Training high-resolution generators.
- Karras, T. et al. (2019). "A Style-Based Generator Architecture for GANs." — StyleGAN with style injection.
- Salimans, T. et al. (2016). "Improved Techniques for Training GANs." — Practical tips for stable GAN training.
Quick Reference Cheat Sheet
| Component | Architecture | Activation |
|---|---|---|
| Generator (DCGAN) | ConvTranspose2d -> BN -> ReLU | Output: Tanh |
| Discriminator (DCGAN) | Conv2d -> BN -> LeakyReLU(0.2) | Output: Sigmoid |
| Critic (WGAN) | Conv2d -> SpectralNorm -> LeakyReLU | No activation (linear) |
| Weight Init | N(0, 0.02) for all conv layers | BN: N(1, 0.02) |
| Optimizer | Adam(G: lr=2e-4, D: lr=1e-4, beta1=0.5) | RMSprop for WGAN |