Generative Adversarial Networks for Images

Suppose you want a computer to invent a face that has never existed. No dataset contains it. No lookup table can return it. Yet the output must look as plausible as a photograph from a camera. This is the problem of image synthesis. For most of the history of computer vision, it was intractable at high resolution. Nobody could write down an explicit probability density over natural images. Nobody could even sample from it. Generative Adversarial Networks (GANs) solved this by refusing to model the density explicitly at all. Instead, they train two neural networks against each other in a game. The idea, introduced in 2014, reframed generative modeling as a competition. A generator network tries to manufacture images that look real. Meanwhile, a discriminator network tries to catch it in the act of faking them. Neither network is told directly what a "realistic image" looks like in mathematical terms. Realism emerges as the equilibrium point of an adversarial game. This equilibrium is enforced purely through gradients flowing between the two competing networks. This sidesteps the need for an explicit likelihood function, which had stalled earlier generative approaches. GANs matter because they produce sharp, high-fidelity samples. This contrasts with the blurry averages typical of earlier pixel-wise regression losses. This sharpness comes precisely from the adversarial loss. A discriminator that can distinguish blur from texture punishes the generator for hedging its bets. That single mechanism powers deepfake detection research and synthetic data generation for training other vision models. It also drives photo restoration, super-resolution, and the entire family of conditional image translation systems that followed. This article builds the GAN framework from first principles. It covers the minimax game, the practical training loop, and the reasons the naive objective misbehaves. It also covers the specific failure mode called mode collapse that every practitioner must learn to recognize. It assumes familiarity with Backpropagation and general Image Generation Fundamentals. It sets up the machinery later needed for Image-to-Image Translation and Neural Style Transfer.

Key takeaways
  • A GAN pairs a generator GG that maps noise to images with a discriminator DD that classifies real vs. fake.
  • Training is a two-player minimax game; at the theoretical optimum GG matches the true data distribution exactly.
  • The original loss saturates early, so practitioners use the non-saturating loss for the generator instead.
  • Training alternates DD and GG updates via stochastic gradient methods, with no shared global objective being minimized.
  • Mode collapse — where GG produces only a few distinct outputs — is the signature failure mode of adversarial training.
  • Losses like Wasserstein GAN and architectural fixes (batch norm, spectral normalization) were developed specifically to stabilize this game.
The core insight

A GAN turns image generation into a two-player game where a generator and discriminator improve each other through competing gradients, with photorealism emerging as the Nash equilibrium rather than being explicitly modeled.

The idea

A Generative Adversarial Network consists of two differentiable functions, both usually convolutional neural networks. The generator Gθ:Rd→RH×W×CG_\theta: \mathbb{R}^d \to \mathbb{R}^{H\times W \times C} maps a latent noise vector z∼pzz \sim p_z (typically Gaussian or uniform) to a synthetic image G(z)G(z). The discriminator Dϕ:RH×W×C→[0,1]D_\phi: \mathbb{R}^{H\times W\times C} \to [0,1] takes an image and outputs the probability that the image came from the real data distribution pdatap_{\text{data}} rather than from GG. The two networks are trained jointly but with opposing objectives, which is what makes this "adversarial." Formally, the training objective is the minimax game

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼pz[log⁡(1−D(G(z)))].\min_G \max_D \; V(D,G) = \mathbb{E}_{x\sim p_{\text{data}}}[\log D(x)] + \mathbb{E}_{z\sim p_z}[\log(1-D(G(z)))].

The discriminator wants to push D(x)→1D(x)\to 1 for real images and D(G(z))→0D(G(z))\to 0 for fakes, maximizing VV. The generator wants the opposite: it wants D(G(z))→1D(G(z))\to 1, i.e., it wants to fool the discriminator, which corresponds to minimizing VV. Crucially there is no single loss function being jointly minimized by both networks — this is a game with a Nash equilibrium, not an optimization problem with a global minimum, and that distinction explains much of the instability discussed later. The key theoretical result, due to the original 2014 formulation, is that if DD is trained to optimality for a fixed GG, the optimal discriminator has a closed form,

DG∗(x)=pdata(x)pdata(x)+pg(x),D^*_G(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)},

where pgp_g is the distribution induced by GG. Substituting this back into V(D∗,G)V(D^*, G) reduces the generator's objective to (up to a constant) the Jensen–Shannon divergence between pdatap_{\text{data}} and pgp_g. Since the JS divergence is minimized (equal to zero) exactly when pg=pdatap_g = p_{\text{data}}, the global optimum of the game is a generator that perfectly reproduces the true data distribution, with the discriminator reduced to outputting 12\tfrac12 everywhere, unable to do better than a coin flip.

How it works

Training proceeds by alternating gradient updates: several (often one) step(s) updating DD with GG fixed, followed by one step updating GG with DD fixed, repeated until convergence or a fixed number of iterations. Each network only ever sees gradients through its own parameters, backpropagated through the other network's forward pass when needed (the generator's gradient must flow through the frozen discriminator). A critical practical modification is the non-saturating generator loss. Early in training, GG is poor and DD correctly rejects its samples with high confidence, so D(G(z))≈0D(G(z)) \approx 0. The original generator loss log⁡(1−D(G(z)))\log(1-D(G(z))) has near-zero gradient in this regime (it saturates), starving the generator of learning signal exactly when it needs it most. The fix is to instead train GG to maximize log⁡D(G(z))\log D(G(z)) directly. This has the same fixed point (both are minimized/maximized when D(G(z))=1D(G(z))=1) but provides much stronger gradients when GG is weak, because log⁡D(G(z))\log D(G(z)) is steep near D=0D=0 while log⁡(1−D(G(z)))\log(1-D(G(z))) is nearly flat there. ```

# GAN training loop (non-saturating generator loss, minibatch SGD) initialize generator parameters theta initialize discriminator parameters phi for iteration = 1 to N_iterations:

# ---- Discriminator step(s) ---- for k = 1 to k_disc_steps: sample minibatch of m real images {x_1, ..., x_m} from data sample minibatch of m noise vectors {z_1, ..., z_m} from p_z fake_images <- G(z_i; theta) for i = 1..m # no gradient needed yet

# discriminator loss: maximize log D(real) + log(1 - D(fake)) L_D <- -(1/m) sum_i [ log D(x_i; phi) + log(1 - D(fake_images_i; phi)) ] phi <- phi - lr_D gradient(L_D, phi) # gradient ASCENT on V == descent on -V

# ---- Generator step ---- sample minibatch of m noise vectors {z_1, ..., z_m} from p_z fake_images <- G(z_i; theta) for i = 1..m # gradient must flow through here

# non-saturating loss: minimize -log D(fake) instead of maximize log(1 - D(fake)) L_G <- -(1/m) sum_i [ log D(fake_images_i; phi) ] theta <- theta - lr_G gradient(L_G, theta) return G, D ``` Two implementation details matter for correctness. First, when computing `L_D`, the fake images are treated as constants with respect to ϕ\phi (gradients do not need to flow into GG), which is why many implementations detach GG's output from the computation graph during the discriminator step — this saves memory and avoids accidentally updating θ\theta with the wrong loss. Second, when computing `L_G`, the discriminator's parameters ϕ\phi must be held fixed (no update to ϕ\phi from this loss); only gradients with respect to θ\theta are taken, using ϕ\phi purely as a frozen scoring function.

Figure
The adversarial loop: noise, generator, discriminator, and the two opposing gradient signals
Noise z z ~ p_z Generator G params θ z → image Fake image G(z) Real image x ~ p_data Discriminator D params φ image → P(real) D(x) ∈ [0,1] D(x) score grad wrt θ: maximize log D(G(z)) grad wrt φ Forward pass: real/fake images → discriminator score Dashed: backward gradients driving the adversarial update

Complexity & correctness

Time complexity per iteration. A single training iteration costs one forward and backward pass through GG (cost O(PG)O(P_G) where PGP_G is the number of FLOPs in GG's architecture, dominated by convolution operations scaling with image resolution and channel width) plus kk forward/backward passes through DD for the discriminator sub-steps (cost O(k⋅PD)O(k \cdot P_D)). For a convolutional architecture operating on an H×WH\times W image with FF feature channels and LL layers, per-layer cost is roughly O(HWF2k2)O(H W F^2 k^2) for a k×kk\times k kernel, so total cost per iteration is linear in the number of pixels processed and quadratic in channel width — identical asymptotic scaling to a standard CNN classifier or Image Generation Fundamentals autoencoder, since a GAN is architecturally just two CNNs. There is no additional algorithmic complexity beyond ordinary Backpropagation through each network; the added cost relative to a single supervised network is roughly a constant factor of 1+k1+k.

Space complexity is O(PG+PD)O(P_G + P_D) for parameters plus the usual activation memory for backpropagation through both networks, proportional to batch size times the sum of feature-map sizes at every layer. Because gradients for DD's step do not need to be stored through GG (fake images can be detached), peak memory during the discriminator step only needs DD's activation graph, not GG's.

Correctness argument (why equilibrium implies matching distributions). The proof sketch has two parts, matching the derivation in "The idea" section. 1. Optimal discriminator for fixed GG. For a fixed generator distribution pgp_g, V(D,G)V(D,G) is, pointwise in xx, of the form alog⁡y+blog⁡(1−y)a\log y + b \log(1-y) with a=pdata(x)a = p_{\text{data}}(x), b=pg(x)b=p_g(x), y=D(x)y = D(x). Differentiating with respect to yy and setting to zero gives y∗=aa+by^* = \tfrac{a}{a+b}, recovering DG∗(x)=pdata(x)pdata(x)+pg(x)D^*_G(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}. This is a maximum because the second derivative of alog⁡y+blog⁡(1−y)a\log y + b\log(1-y) is negative for a,b≥0,y∈(0,1)a,b\ge 0, y\in(0,1). 2. Global minimum over GG. Substituting DG∗D^*_G back in,

V(DG∗,G)=Ex∼pdata[log⁡pdata(x)pdata(x)+pg(x)]+Ex∼pg[log⁡pg(x)pdata(x)+pg(x)]=−log⁡4+2⋅JSD(pdata ∥ pg),V(D^*_G, G) = \mathbb{E}_{x\sim p_{\text{data}}}\left[\log \frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}\right] + \mathbb{E}_{x\sim p_g}\left[\log \frac{p_g(x)}{p_{\text{data}}(x)+p_g(x)}\right] = -\log 4 + 2\cdot \mathrm{JSD}(p_{\text{data}} \,\|\, p_g),

using the definition of Jensen–Shannon divergence in terms of KL divergences to the mixture 12(pdata+pg)\tfrac12(p_{\text{data}}+p_g). Since JSD≥0\mathrm{JSD}\ge 0 with equality iff the two distributions are identical, V(DG∗,G)V(D^*_G,G) is minimized exactly at pg=pdatap_g = p_{\text{data}}, achieving the global minimum value −log⁡4-\log 4.

Honest caveats. This proof assumes DD and GG have unbounded capacity (they range over all possible functions, not just those representable by a fixed neural architecture), that DD is trained to full convergence at every step (not just a few gradient steps, as done in practice), and that the alternating gradient procedure actually converges to this equilibrium. None of these hold exactly in practice: real networks have finite capacity, DD is never trained to optimality, and simultaneous gradient descent on a non-convex-non-concave minimax game has no general convergence guarantee — the dynamics can cycle or diverge even when a Nash equilibrium exists. This gap between the elegant theory and the messy practice is exactly why GAN training is known to be finicky, and why the specific failure mode below is so important to understand.

Worked example

Consider training a GAN on a toy 2D dataset that is not images but is easy to trace by hand: pdatap_{\text{data}} is a mixture of four 2D Gaussians arranged at the corners of a square (a common diagnostic used because it is easy to visualize whether GG covers all four modes or only some). Assume z∈R2z \in \mathbb{R}^2 Gaussian noise, GG and DD are small MLPs, and we track qualitative behavior over training epochs.

EpochDiscriminator behaviorGenerator outputDiagnosis
0DD outputs ~0.5 everywhere (untrained)Random scattered points, no structureBoth networks near initialization
50DD learns a rough boundary separating real clusters from the diffuse fake cloudGG output starts clustering loosely near the real modesEarly co-adaptation, gradients informative
200DD sharply rejects points outside all 4 real clustersGG places mass on one of the four corners very confidentlyMode collapse beginning: GG has found one "safe" region that reliably fools the current DD
210DD adapts, learns to penalize that one corner specificallyGG's output jumps to a different single cornerOscillation: GG chases DD's blind spot rather than covering the full distribution
500 (with fix: minibatch discrimination / unrolled updates)DD maintains balanced rejection across all cornersGG produces samples near all four modes with roughly correct proportionsConverged behavior close to the theoretical equilibrium

This trace illustrates the central practical failure: between epochs 200 and 210, GG never learns to cover the whole distribution — it learns to win locally against whatever DD currently penalizes least, then DD catches up, and GG relocates its entire probability mass to a different single mode rather than spreading across all four. This oscillating, mode-hopping behavior is mode collapse, and it is a direct consequence of GG's objective only requiring it to fool DD on some subset of the space, not to match the full density pdatap_{\text{data}} at every training step (recall the JS-divergence equivalence only holds when DD is trained to full optimality, which never happens with a handful of gradient steps). Fixes demonstrated in row 5 of the table are real techniques used in practice: minibatch discrimination lets DD compare examples within a batch, so it can detect when a whole batch of "fakes" is suspiciously identical (real batches from a mixture of four Gaussians should show diversity; a mode-collapsed fake batch will not), giving GG a gradient signal to diversify. Unrolled GANs let GG's update account for several future steps of DD's optimization, discouraging GG from exploiting a discriminator that is about to be corrected.

Figure
Mode collapse: generator output collapsing onto a single mode of a four-mode target distribution
Target: 4-mode data distribution all 4 modes equally weighted Collapsed generator output 99% of mass nearly all samples land in one mode training

Common pitfalls & traps

PitfallWhy it happensConsequenceMitigation
Using the original saturating log⁡(1−D(G(z)))\log(1-D(G(z))) lossGradient is near zero when DD confidently rejects early fakesGenerator receives almost no learning signal at the start of trainingUse the non-saturating loss −log⁡D(G(z))-\log D(G(z))
Discriminator overpowers generatorDD is a simpler classification task and converges much faster than GG's generation taskD(G(z))→0D(G(z))\to 0 permanently; GG's gradients vanishBalance update ratios, lower DD's learning rate, add label smoothing or noise to DD's inputs
Treating mode collapse as "just needs more epochs"Mode collapse is a dynamical equilibrium of the game, not undertrainingTraining runs indefinitely producing low-diversity samplesMinibatch discrimination, unrolled updates, or switch to Wasserstein-style losses with stronger convergence properties
Forgetting to detach fake images before the discriminator stepAutograd graphs accidentally connect DD's loss to θ\thetaSilent incorrect gradient updates to GG during the "DD-only" stepExplicitly stop gradients on GG's output before computing LDL_D
Evaluating GAN quality only by eyeballing samplesNo explicit likelihood exists to compute perplexity or held-out log-likelihoodOverestimating diversity; missing subtle mode collapseUse quantitative diversity metrics (e.g., counting distinct modes recovered, Inception-based diversity scores) alongside visual inspection
Assuming convergence is guaranteed because a Nash equilibrium existsExistence of an equilibrium says nothing about whether alternating gradient descent finds itTraining can oscillate or diverge even on toy problemsUse techniques with better-understood dynamics (gradient penalty, spectral normalization, two-timescale update rules)

Pioneers & history

Origins · 1 minIan J. Goodfellow and how this was discovered
IJ
Ian J. Goodfellow
born 1985 · Deep learning researcher who introduced the GAN framework in 2014 while a doctoral student, reportedly conceiving the adversarial game format during a discussion at a bar about the difficulty of generative modeling, then implementing and validating it that same night

The GAN framework arrived at a moment when explicit generative models — density estimators, variational autoencoders' precursors, and Boltzmann machines — struggled to produce sharp, high-resolution samples because they optimized likelihood-based objectives that reward covering probability mass everywhere, including blurry averages between modes. Casting generation as a game between a forger and a detective, rather than as direct density estimation, allowed sharpness to emerge naturally: the discriminator specifically punishes blur once it learns that blurry images are a giveaway of forgery. This reframing, simple in hindsight, unlocked a decade of rapid progress in photorealistic image synthesis.

Origins · 1 minhow this was discovered
History
2014
— Ian Goodfellow and collaborators introduce the original GAN, minimax formulation, and JS-divergence equivalence proof.
2015
— Deep Convolutional GANs (DCGAN) establish stable convolutional architectural guidelines (strided convolutions, batch normalization, no fully connected layers) that make GAN training reliably work on real images.
2016-2017
— Wasserstein GAN reformulates the objective using the Earth Mover's distance to address vanishing gradients and mode collapse with a theoretically better-behaved loss.
2017-2018
— Progressive growing and spectral normalization techniques scale GANs to high resolutions (megapixel face and scene synthesis).
2018-2019
— BigGAN and StyleGAN push class-conditional and style-based synthesis to near-photorealistic quality, setting the stage for image-to-image translation and style transfer architectures.

Where this matters

GANs underpin a wide range of production and research systems in computer vision. Photo-realistic face synthesis systems (used for avatar generation, synthetic training data, and — controversially — deepfakes) are built directly on the generator-discriminator architecture described here. Super-resolution systems that upscale low-resolution images use adversarial losses layered on top of pixel-wise losses specifically because a purely pixel-wise objective produces blurry upscaling, while the discriminator's texture-sensitivity forces sharp, plausible high-frequency detail. Data augmentation pipelines in domains with scarce labeled data (medical imaging, rare-defect industrial inspection) use trained generators to synthesize additional realistic training examples for downstream classifiers. The conditional variant of the adversarial game, where both GG and DD are given an additional input (a class label, a sketch, a semantic map, or a source-domain image), is the direct foundation of Image-to-Image Translation systems that convert sketches to photos or day scenes to night scenes. The same discriminator-driven notion of a learned perceptual loss — punishing outputs that "look wrong" according to a trained critic rather than according to a fixed pixel distance — reappears as a key ingredient in Neural Style Transfer pipelines and in perceptual loss functions used throughout modern Image Generation Fundamentals research, including diffusion-model guidance and autoencoder-based compression systems.

Ask the tutor: How does the Wasserstein GAN loss change the training dynamics and specifically help mitigate mode collapse compared to the original minimax formulation?

Why can't a GAN's generator loss and discriminator loss be minimized simultaneously like a normal neural network's training loss?

Because a GAN is not solving a single optimization problem — it is playing a two-player zero-sum game where DD maximizes and GG minimizes the same value function V(D,G)V(D,G). There is no scalar objective whose gradient descent, applied to both parameter sets jointly, is guaranteed to converge, unlike ordinary supervised learning where a single loss is minimized over one set of parameters. The equilibrium concept that applies is a Nash equilibrium: a point where neither player can improve unilaterally. Standard convergence guarantees from convex optimization simply do not apply to this non-convex, non-concave minimax setting, which is precisely why alternating gradient descent on GANs can oscillate, cycle, or diverge even when a good equilibrium exists.

What causes mode collapse mechanistically, beyond "the generator gets lazy"?

Mode collapse arises because the generator's non-saturating loss only asks it to fool the current discriminator, not to match the full data density at every step. If GG finds a small region of image space that currently fools DD, gradient descent will happily push all of GG's probability mass there, since doing so directly minimizes the current-step loss. The discriminator then adapts and learns to reject that region, but by the time it does, GG may simply relocate its entire mass to a different narrow region rather than spreading out — because spreading out was never explicitly rewarded, only "not being currently caught" was. This chase-and-relocate dynamic can repeat indefinitely without ever converging to full-distribution coverage.

Is the Jensen-Shannon divergence result still considered the "correct" explanation for why GANs work?

It is the correct explanation for the idealized game — with unbounded-capacity networks and a discriminator trained to full optimality at every generator step — but it is widely understood to be a poor description of the actual training dynamics used in practice. Real discriminators are updated with only a few gradient steps between generator updates, never reach the closed-form optimum, and have finite capacity. This gap is exactly why alternative formulations such as the Wasserstein distance were introduced: they provide better-behaved gradients under the finite-step, finite-capacity conditions that actually hold during training, even though the original JS-divergence argument remains the cleanest way to understand why the game has the right answer at its ideal equilibrium.

How is a conditional GAN different from the vanilla GAN described here, and why does it matter for later topics?

A conditional GAN gives both the generator and discriminator access to extra side information yy (a class label, a segmentation map, or a source image), so the generator learns G(z,y)G(z, y) and the discriminator learns D(x,y)D(x, y), judging whether xx is a real image consistent with yy rather than just realistic in general. This single change transforms unconditional image synthesis into controllable synthesis, which is the direct mechanism behind Image-to-Image Translation (where yy is a source-domain image and GG must produce a plausible target-domain counterpart) and behind style-conditioned generation used in Neural Style Transfer pipelines that blend adversarial and perceptual losses.

Why do GANs typically produce sharper images than autoencoder-style generative models trained with pixel-wise losses?

A pixel-wise loss like mean squared error rewards the generator for being close to some plausible real image on average, and because multiple plausible outputs exist for any given latent code or condition, the loss-minimizing strategy is often to output the average of those plausible images, which looks blurry. A discriminator, in contrast, is explicitly trained to detect exactly this kind of blur and texture inconsistency, since real images have sharp high-frequency statistics that averaged images lack. The generator is therefore penalized specifically for hedging, pushing it toward committing to one sharp, plausible mode rather than averaging over many.

What role does the discriminator's capacity play in training stability?

If the discriminator is too powerful relative to the generator (e.g., it converges to near-perfect real/fake classification quickly), it produces D(G(z))≈0D(G(z))\approx 0 almost everywhere, which — even with the non-saturating loss — leaves very little useful gradient signal for GG, since the discriminator's decision boundary can become extremely sharp with vanishing gradient outside a thin margin. Conversely, if DD is too weak, it gives poor, noisy feedback that does not meaningfully guide GG toward realism. Practical stabilization techniques—spectral normalization, gradient penalties, label smoothing, and careful learning-rate balancing—exist specifically to keep the discriminator's power in a productive middle range relative to the generator throughout training.

Can GAN training be said to "converge" in the same sense as supervised learning?

Not in the same well-defined sense. Supervised learning minimizes a single loss and convergence means the loss (and typically validation metrics) stabilizes at a low value. GAN training instead tracks a moving target: as GG improves, DD's task changes, and vice versa, so neither loss curve alone indicates progress — a discriminator loss near log⁡2\log 2 (its value when DD outputs 1/2 everywhere) can indicate either a converged equilibrium or a stuck, uninformative discriminator. Practitioners instead rely on periodic qualitative sample inspection and quantitative diversity/fidelity metrics computed on generated samples, since no single scalar reliably summarizes adversarial convergence the way training loss does for ordinary networks.

Before this

Where this leads