Equations · Goodfellow et al., “Generative Adversarial Nets” (2014)

The GAN minimax objective, explained term by term

A two-player game. The discriminator DD tries to tell real data from generated data; the generator GG tries to fool it. DD maximizes the value VV, GG minimizes it, and training alternates between them.

min⁡Gmax⁡DV(D,G)=Ex∼pdata(x)[log⁡D(x)]+Ez∼pz(z)[log⁡(1−D(G(z)))]\min_G \max_D V(D, G) = \mathbb{E}_{\mathbf{x} \sim p_{\mathrm{data}}(\mathbf{x})}\left[\log D(\mathbf{x})\right] + \mathbb{E}_{\mathbf{z} \sim p_{\mathbf{z}}(\mathbf{z})}\left[\log\left(1 - D(G(\mathbf{z}))\right)\right]

Open in the decoder →

Term by term

  1. min⁡Gmax⁡D\min_G \max_D

    Read from the inside out: for a given generator, the best discriminator maximizes VV; the generator then minimizes that best-case value. The subscripts say who controls each step.

  2. D(x)D(\mathbf{x})

    The discriminator: a network outputting the probability that its input is real.

  3. G(z)G(\mathbf{z})

    The generator: a network that turns a noise vector z\mathbf{z} into a fake data point.

  4. Ex∼pdata[log⁡D(x)]\mathbb{E}_{\mathbf{x} \sim p_{\mathrm{data}}}[\log D(\mathbf{x})]

    Average over real data: high when DD says "real" to real examples. The subscript data\mathrm{data} is a label.

  5. Ez∼pz[log⁡(1−D(G(z)))]\mathbb{E}_{\mathbf{z} \sim p_{\mathbf{z}}}[\log(1 - D(G(\mathbf{z})))]

    Average over noise drawn from a simple prior (Gaussian or uniform): high when DD says "fake" to generated examples. Only this term depends on GG.

A small worked example

If DD gives a real image 0.90.9 and a fake one 0.20.2: V=ln⁡0.9+ln⁡0.8≈−0.105−0.223=−0.33V = \ln 0.9 + \ln 0.8 \approx -0.105 - 0.223 = -0.33. At the game's equilibrium, GG matches the data and D=0.5D = 0.5 everywhere, so V=2ln⁡0.5=−log⁡4≈−1.39V = 2\ln 0.5 = -\log 4 \approx -1.39. Early on log⁡(1−D(G(z)))\log(1 - D(G(\mathbf{z}))) gives GG weak gradients, so the paper suggests training GG to maximize log⁡D(G(z))\log D(G(\mathbf{z})) instead.

In code

import torch

def gan_losses(D, G, x, z):
    real, fake = D(x), D(G(z))     # probabilities in (0, 1)
    # for the D step, compute fake from G(z).detach()
    d_loss = -(torch.log(real) + torch.log(1 - fake)).mean()
    g_loss = -torch.log(fake).mean()          # the non-saturating version
    return d_loss, g_loss

Every symbol in it

max⁡(0,x)\max(0, x)Max and miny=Wx+by = Wx + bItalic letters (variables)x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)Ex∼p[f(x)]\mathbb{E}_{x \sim p}[f(x)]Expectationx∼pdatax \sim p_{\text{data}}Distributed as (tilde)log⁡pθ(x)\log p_\theta(x)Logarithmxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)p(x),  q(z)p(\mathbf{x}), \; q(\mathbf{z})Probability p(x)

Other equations