🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

GANs — Generative Adversarial Networks Complete Guide

Deep LearningGANs🟢 Free Lesson

Advertisement

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:

  1. Explain the minimax game between generator and discriminator
  2. Derive the GAN loss function and its optimal solution
  3. Implement DCGAN with transposed convolutions for image generation
  4. Identify and mitigate mode collapse in GAN training
  5. Understand Wasserstein GAN and its advantages over vanilla GAN
  6. Compare GAN variants (cGAN, Pix2Pix, CycleGAN, StyleGAN) for different tasks
  7. 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

FormulaExpressionUse Case
GAN Minimaxmin_G max_D E[log D(x)] + E[log(1-D(G(z)))]Original GAN objective
Optimal DD*(x) = p_data / (p_data + p_g)Theoretical analysis
WGAN LossE[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 GL_G = -E[log D(G(z))]Stronger gradients for G

Interview Questions

Q1: What is the Nash equilibrium of a GAN?
The Nash equilibrium occurs when G perfectly matches the data distribution (p_g = p_data) and D outputs 0.5 for all inputs. At this point, neither network can improve unilaterally — G generates perfect samples and D cannot distinguish real from fake. In practice, GANs only approximate this equilibrium.

Q2: Why is GAN training unstable compared to VAEs?
GANs optimize a minimax game (two networks competing), making optimization inherently unstable. VAEs optimize a single ELBO objective. GAN training suffers from mode collapse, vanishing gradients (when D is too good), and oscillating losses. VAEs have stable training but generate blurrier samples.

Q3: How does WGAN improve upon vanilla GAN?
WGAN uses Wasserstein distance instead of JS divergence, which: (1) Provides meaningful loss correlated with sample quality, (2) Eliminates mode collapse by encouraging diversity, (3) Has smoother gradients even when distributions don't overlap, (4) Allows monitoring convergence via the loss metric.

Q4: What is mode collapse and how do you detect it?
Mode collapse is when G produces limited variety, generating only a few outputs. Detection: (1) Visual inspection shows identical/similar samples, (2) Low diversity metrics, (3) D loss drops to near 0 while G loss stays high. Solutions: WGAN loss, minibatch discrimination, unrolled GANs.

Q5: How do you evaluate GAN quality without human judgment?
FID (Fréchet Inception Distance) compares feature statistics of real vs generated images — lower is better. IS (Inception Score) measures quality and diversity — higher is better. FID is preferred because it correlates well with human judgment and penalizes mode collapse.

Q6: How do GANs compare to diffusion models for image generation?
Diffusion models (DALL-E 2, Stable Diffusion) now outperform GANs in quality and diversity: they have more stable training, no mode collapse, and scale better. GANs still win for real-time applications (single forward pass vs 50-1000 denoising steps) and style transfer tasks.

Q7: What is spectral normalization and why is it used in GANs?
Spectral normalization divides each weight matrix by its spectral norm (largest singular value), constraining the Lipschitz constant of D. This stabilizes training by preventing D from becoming too sensitive to small input changes, which would cause G's gradients to vanish or become unreliable.


Practice Exercise

Challenge: Train a DCGAN on MNIST
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:

  1. Start with 4x4 images (1 residual block)
  2. Train until stable, then add layers to double resolution
  3. 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":

  1. Mapping network: Maps latent vector to intermediate latent space
  2. Style modulation: Each layer receives a learned affine transformation of
  3. 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

PropertyGANsDiffusion Models
Training stabilityUnstable (adversarial)Stable (denoising objective)
Sample qualitySharp but may miss modesHigh quality, high diversity
Inference speedFast (single forward pass)Slow (50-1000 denoising steps)
Mode coverageProne to mode collapseFull distribution coverage
Current statusStyle transfer, real-time appsDALL-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 VariantKey InnovationTaskResolution
Vanilla GANMinimax gameMNIST generation28x28
DCGANConv architectureGeneral image generation64x64 - 128x128
WGANWasserstein lossStable trainingAny
ProGANProgressive growingHigh-res faces1024x1024
StyleGANStyle injection + mappingPhotorealistic faces1024x1024
Pix2PixPaired image translationSketch to photo256x256
CycleGANCycle consistency lossUnpaired translation256x256

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

ComponentArchitectureActivation
Generator (DCGAN)ConvTranspose2d -> BN -> ReLUOutput: Tanh
Discriminator (DCGAN)Conv2d -> BN -> LeakyReLU(0.2)Output: Sigmoid
Critic (WGAN)Conv2d -> SpectralNorm -> LeakyReLUNo activation (linear)
Weight InitN(0, 0.02) for all conv layersBN: N(1, 0.02)
OptimizerAdam(G: lr=2e-4, D: lr=1e-4, beta1=0.5)RMSprop for WGAN

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement