Sign in

Generative adversarial network (GAN)

Generative Adversarial Network

A generative adversarial network: a generator learns to produce rows that a discriminator cannot tell from real data.

Overview

A GAN trains two networks against each other. The generator turns random noise into fake rows. The discriminator looks at a row and estimates the probability that it is real. The discriminator is trained to get this right, and the generator is trained to make it wrong. The generator never sees the real data directly: it only learns from the discriminator's gradient, which tells it how to change a fake row so that it looks more real. If training goes well, the fakes become so close to the real distribution that the discriminator can do no better than answer one half.

A short history

Ian Goodfellow and colleagues introduced GANs in 2014. Instead of writing down a likelihood, they trained a generator against a discriminator in a two-player game, which produced much sharper samples than the methods of the time. Later work, such as DCGAN in 2015 and StyleGAN from Nvidia in 2018, made photorealistic faces possible. GANs are hard to train, and since about 2021 diffusion models have replaced them for much image work.

How it works

  1. Draw a batch of real rows and a batch of noise vectors z\mathbf{z}, and let the generator turn the noise into fake rows.
  2. Discriminator step: score real and fake rows, compute the cross-entropy loss with real labelled 1 and fake labelled 0, and update the discriminator only.
  3. Generator step: generate fakes again and score them with the discriminator.
  4. Compute the non-saturating loss −log⁡D(G(z))-\log D(G(\mathbf{z})) and backpropagate through the discriminator into the generator, updating the generator only.
  5. Repeat for train_steps rounds, both networks using Adam with β1=0.5\beta_1 = 0.5.
  6. To generate new data, call generate, which feeds fresh noise through the generator and returns rows in the data's original units.

Watch out for

  • The generator can collapse onto a few outputs that fool the discriminator and ignore the rest of the data. This is called mode collapse, and the loss values do not reveal it.
  • Neither loss is a measure of quality. The two networks chase each other, so both losses can hover or oscillate while the samples get better or worse.
  • If the discriminator becomes much stronger than the generator, its outputs saturate and the generator gets little useful gradient. The non-saturating loss reduces this but does not remove it.
  • This is a small dense GAN for rows of a few numbers. It has none of the stabilisers larger GANs need, such as spectral normalisation, a gradient penalty or a Wasserstein loss.

Use cases

When to use it

To learn adversarial training, to generate synthetic rows from a simple continuous distribution, or as a reference to test a framework implementation against.

In industry

Finance and healthcare
Synthetic tabular data: generating realistic rows to share or test with when the real records are sensitive.
Media and gaming
Image super-resolution and texture generation, where a discriminator pushes outputs towards sharp, realistic detail.
Machine learning teams
Augmenting a rare class with generated examples when real ones are scarce, checked carefully against held-out real data.

Choosing it: what must hold

  • Many real examples of the data to imitate.
  • Time to tune and monitor training, since the two networks can fall out of balance or collapse to a few outputs.
  • A way to judge sample quality, because the losses do not tell you when the generator is good.

When to choose something else

IfUse instead
Training stability and coverage of the data matter more than sampling speedA diffusion model
You need an encoder and a smooth latent spaceA variational autoencoder (VAE)
You only need to rebalance a tableSimple oversampling or class weights before trying a generative model

Math foundations

  1. 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}_{\mathbf{x} \sim p_{\text{data}}} \big[ \log D(\mathbf{x}) \big] + \mathbb{E}_{\mathbf{z} \sim p_z} \big[ \log \big( 1 - D(G(\mathbf{z})) \big) \big]

    The discriminator wants VV large: high scores on real rows, low on fakes. The generator wants it small. Training alternates between the two.

  2. Discriminator loss

    LD=−Ex[log⁡D(x)]−Ez[log⁡(1−D(G(z)))]\mathcal{L}_D = -\mathbb{E}_{\mathbf{x}} \big[ \log D(\mathbf{x}) \big] - \mathbb{E}_{\mathbf{z}} \big[ \log \big( 1 - D(G(\mathbf{z})) \big) \big]

    Ordinary binary cross-entropy with real rows as the positive class. It is −V-V, so minimising it is the inner maximisation.

  3. Non-saturating generator loss

    LG=−Ez[log⁡D(G(z))]\mathcal{L}_G = -\mathbb{E}_{\mathbf{z}} \big[ \log D(G(\mathbf{z})) \big]

    The generator maximises the discriminator's belief that fakes are real. It has the same goal as minimising VV but gives a strong gradient early on, when the discriminator rejects fakes easily.

  4. The best discriminator for a fixed generator

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

    Where real data is denser than generated data the score is above one half, and where it is sparser the score is below.

  5. Equilibrium

    pg=pdata  ⟹  D∗(x)=12,V(D∗,G)=−log⁡4p_g = p_{\text{data}} \;\Longrightarrow\; D^{*}(\mathbf{x}) = \tfrac{1}{2}, \qquad V(D^{*}, G) = -\log 4

    When the generator matches the data exactly, the best discriminator can only guess. This is the global optimum of the game.

Symbols

GG
the generator network
DD
the discriminator; D(x) is its probability that x is real
x\mathbf{x}
a real data row
z\mathbf{z}
a noise vector of length latent_size
pdatap_{\text{data}}
the distribution of the real data
pzp_z
the noise distribution, a standard normal
pgp_g
the distribution of the generator's outputs
V(D,G)V(D, G)
the value of the game
E\mathbb{E}
expected value, estimated by a batch average

Worked by hand

On one batch the discriminator gives real rows D(x)=0.8D(\mathbf{x}) = 0.8 and fake rows D(G(z))=0.3D(G(\mathbf{z})) = 0.3. Compute both losses, then the discriminator loss at equilibrium.

LD=−ln⁡0.8−ln⁡(1−0.3)=0.223+0.357=0.580\mathcal{L}_D = -\ln 0.8 - \ln (1 - 0.3) = 0.223 + 0.357 = 0.580
LG=−ln⁡0.3=1.204\mathcal{L}_G = -\ln 0.3 = 1.204
at equilibrium:LD=−ln⁡0.5−ln⁡0.5=ln⁡4=1.386,LG=ln⁡2=0.693\text{at equilibrium:} \quad \mathcal{L}_D = -\ln 0.5 - \ln 0.5 = \ln 4 = 1.386, \qquad \mathcal{L}_G = \ln 2 = 0.693

The discriminator is currently ahead: its loss of 0.58 is well below 1.386 and the generator's loss of 1.20 is above 0.693. As the generator improves, both move toward the equilibrium values.

Visual example

Loading the example.

Try this

  • Press Run and watch the fake curve walk toward the real one while the dashed line flattens toward 0.5.
  • Switch the real data to two bumps and see whether the generator learns to cover both.
  • Raise learning_rate to 0.03 and run again: training gets rougher, and the fakes can crowd into a narrow spike.

Code sample

import numpy as np
from impl import GAN
from config import GANConfig

rng = np.random.default_rng(0)
X = rng.normal(size=(2000, 2)) @ np.array([[1.0, 0.8], [0.0, 0.6]]) * [2.0, 0.5] + [4.0, -1.0]
model = GAN(GANConfig(train_steps=2000)).fit(X)
fake = model.generate(1000, seed=1)                      # (1000, 2) new rows
print(X.mean(axis=0).round(2), fake.mean(axis=0).round(2))
print(model.predict(fake[:3]).round(2))                  # discriminator's "real" probability, near 0.5
Read the implementation (136 lines)
"""GAN: generative adversarial network for small vector data.

NumPy only, manual backpropagation. Two networks are trained against each other:

    generator      G: noise z -> a fake row
    discriminator  D: a row -> logit of "this row is real"

D minimises  -log sigmoid(D(x)) - log(1 - sigmoid(D(G(z)))).
G minimises  -log sigmoid(D(G(z)))  (the non-saturating loss): its gradient flows back through D into G.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import GANConfig
except ImportError:  # run from the template's own folder
    from config import GANConfig


def _sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))


class _MLP:
    """A dense network with (leaky) ReLU hidden layers and a linear output, with its own Adam state."""

    def __init__(self, sizes: list, rng: np.random.Generator, slope: float = 0.0) -> None:
        self.slope = slope  # negative-side slope of the hidden activation; 0 is plain ReLU
        self.W = [rng.normal(0.0, np.sqrt(2.0 / a), size=(a, b)) for a, b in zip(sizes[:-1], sizes[1:])]
        self.b = [np.zeros(b) for b in sizes[1:]]
        self._m = [np.zeros_like(p) for p in self.params()]
        self._v = [np.zeros_like(p) for p in self.params()]
        self._step = 0

    def params(self) -> list:
        return self.W + self.b

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (n, sizes[0]) -> (n, sizes[-1]). Keeps the activations for `backward`."""
        self._acts = [x]
        for i, (W, b) in enumerate(zip(self.W, self.b)):
            z = self._acts[-1] @ W + b
            self._acts.append(z if i == len(self.W) - 1 else np.where(z > 0, z, self.slope * z))
        return self._acts[-1]

    def backward(self, d: np.ndarray) -> tuple[np.ndarray, list]:
        """d: gradient at the output of the last `forward`. Returns (gradient at the input, parameter gradients)."""
        gW, gb = [None] * len(self.W), [None] * len(self.W)
        for i in range(len(self.W) - 1, -1, -1):
            if i < len(self.W) - 1:
                d = d * np.where(self._acts[i + 1] > 0, 1.0, self.slope)
            gW[i] = self._acts[i].T @ d
            gb[i] = d.sum(axis=0)
            d = d @ self.W[i].T
        return d, gW + gb

    def adam_step(self, grads: list, lr: float, beta1: float = 0.9) -> None:
        self._step += 1
        for p, g, m, v in zip(self.params(), grads, self._m, self._v):
            m *= beta1
            m += (1 - beta1) * g
            v *= 0.999
            v += 0.001 * g * g
            p -= lr * (m / (1 - beta1**self._step)) / (np.sqrt(v / (1 - 0.999**self._step)) + 1e-8)


class GAN:
    """`fit(X)` trains both networks on the rows of X; `generate(n)` draws new rows; `predict(X)` asks the
    discriminator how real rows look. The data is standardised per column inside the model."""

    def __init__(self, config: GANConfig | None = None) -> None:
        self.config = config or GANConfig()
        self.generator: _MLP | None = None
        self.discriminator: _MLP | None = None
        self.mean_: np.ndarray | float = 0.0
        self.std_: np.ndarray | float = 1.0
        self.d_loss_history: list[float] = []
        self.g_loss_history: list[float] = []

    def _init_nets(self, n_features: int) -> None:
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        self.generator = _MLP([cfg.latent_size, cfg.hidden_size, cfg.hidden_size, n_features], rng)
        self.discriminator = _MLP([n_features, cfg.hidden_size, cfg.hidden_size, 1], rng, slope=0.2)

    def discriminator_loss_and_grads(self, real: np.ndarray, fake: np.ndarray) -> tuple[float, list]:
        """D's loss on a batch of real and fake rows (standardised units) and the gradients of D's parameters."""
        x = np.vstack([real, fake])
        target = np.concatenate([np.ones(len(real)), np.zeros(len(fake))])
        logit = self.discriminator.forward(x)[:, 0]
        loss = float(np.sum(np.logaddexp(0.0, logit) - target * logit) / len(real))
        _, grads = self.discriminator.backward(((_sigmoid(logit) - target) / len(real))[:, None])
        return loss, grads

    def generator_loss_and_grads(self, z: np.ndarray) -> tuple[float, list]:
        """G's non-saturating loss on noise z (n, latent_size) and the gradients of G's parameters."""
        fake = self.generator.forward(z)
        logit = self.discriminator.forward(fake)[:, 0]
        loss = float(np.mean(np.logaddexp(0.0, -logit)))            # -log sigmoid(D(G(z)))
        d_fake, _ = self.discriminator.backward(((_sigmoid(logit) - 1.0) / len(z))[:, None])
        _, grads = self.generator.backward(d_fake)
        return loss, grads

    def fit(self, X: np.ndarray) -> "GAN":
        """Alternate one discriminator step and one generator step for `train_steps` rounds. X: (n, d)."""
        cfg = self.config
        X = np.asarray(X, dtype=float)
        if X.ndim != 2:
            raise ValueError(f"X must be 2-d (rows, features), got shape {X.shape}")
        self.mean_ = X.mean(axis=0)
        self.std_ = np.where(X.std(axis=0) > 0, X.std(axis=0), 1.0)
        Z = (X - self.mean_) / self.std_
        self._init_nets(X.shape[1])
        rng = np.random.default_rng(cfg.seed + 1)
        self.d_loss_history, self.g_loss_history = [], []
        for _ in range(cfg.train_steps):
            real = Z[rng.integers(0, len(Z), size=cfg.batch_size)]
            fake = self.generator.forward(rng.normal(size=(cfg.batch_size, cfg.latent_size)))
            d_loss, d_grads = self.discriminator_loss_and_grads(real, fake)
            self.discriminator.adam_step(d_grads, cfg.learning_rate, beta1=0.5)
            g_loss, g_grads = self.generator_loss_and_grads(rng.normal(size=(cfg.batch_size, cfg.latent_size)))
            self.generator.adam_step(g_grads, cfg.learning_rate, beta1=0.5)
            self.d_loss_history.append(d_loss)
            self.g_loss_history.append(g_loss)
        return self

    def generate(self, n: int, seed: int = 0) -> np.ndarray:
        """Draw n new rows in the units of the training data. Returns (n, d)."""
        z = np.random.default_rng(seed).normal(size=(n, self.config.latent_size))
        return self.generator.forward(z) * self.std_ + self.mean_

    def predict(self, X: np.ndarray) -> np.ndarray:
        """The discriminator's probability that each row is real. X: (n, d) -> (n,)."""
        Z = (np.asarray(X, dtype=float) - self.mean_) / self.std_
        return _sigmoid(self.discriminator.forward(Z)[:, 0])
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Fit GAN on the correlated 2-d Gaussian from the README. Plot d_loss_history and g_loss_history and compare them with 1.386 and 0.693. Then call generate(1000) and compare the mean and covariance of the fakes with the real data, and check that predict on fakes is near 0.5.

Check on learning

  1. The generator never sees a real row. How does information about the real data reach it?
    A way to think about it

    Follow the gradient in the generator step. Ask what the discriminator's weights have been trained on and what its gradient with respect to its input describes.

  2. Early in training the discriminator rejects fakes with D(G(z))D(G(\mathbf{z})) near 0. Compare the slope of log⁡(1−D)\log(1 - D) and of −log⁡D-\log D at that point. Which gives the generator a more useful signal?
    A way to think about it

    Differentiate both with respect to DD and evaluate near D=0D = 0. One slope stays near 1, the other becomes very large.

  3. A generator that outputs the same single realistic row every time can fool the discriminator for a while. Why does the training objective not prevent this directly, and how would you detect it?
    A way to think about it

    The generator's loss only looks at whether each fake is accepted, not at how varied the batch is. Think about what statistics of the generated rows you could compare with the data.

  4. Both losses have settled near their equilibrium values. Does that prove the generator has learned the data distribution?
    A way to think about it

    Consider a weak discriminator that outputs 0.5 for everything. Work out the losses in that case.