Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Generative adversarial networks (GANs)

After this lesson: I can read a toy GAN's training numbers to judge whether its fakes match the data.

60 min lesson2 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A forger and a detective

A generative adversarial network, or GAN, trains two neural networks against each other: one makes fakes and one spots them. Each gets better because the other does.

GANs made the first convincing photos of faces that belong to nobody. They are fast to sample from and hard to train, and this lesson shows both.

By the end of this lesson

Note

I can read a toy GAN's training numbers to judge whether its fakes match the data.

Key words

WordWhat it meansExample
Generatorthe network that turns noise into a fake
Discriminatorthe network that scores how real an input looks
Adversarial trainingtraining two networks against each other
Binary cross-entropya loss for a score between 0 and 1-log(0.9) = 0.105
Mode collapsea generator making too little variety

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Two networks play a game

The generator takes random noise and turns it into a fake. The discriminator takes an input and gives a score from 0, fake, to 1, real.

In adversarial training they take turns. The discriminator learns from real and fake examples. Then the generator changes so its fakes score higher. Neither ever sees the other's weights, only its scores.

One round of a GAN

flowchart LR
  N["Noise"] --> G["Generator"]
  G --> F["Fake"]
  F --> D["Discriminator"]
  R["Real data"] --> D
  D --> S["Score: 0 fake, 1 real"]
  S --> G

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Each network has its own loss

Both use binary cross-entropy, the minus log of the probability given to the right answer. The discriminator's loss is -log of its score on real plus -log of one minus its score on fake.

The generator's loss is -log of the score its fake got. When one loss falls, the other usually rises. When the discriminator cannot tell, both scores sit at 0.5.

Worked example: one real and one fake

ScoreValueLoss part
D(real)0.9-log 0.9 = 0.1054
D(fake)0.2-log (1 - 0.2) = 0.2231
Discriminator loss0.1054 + 0.2231 = 0.3285
Generator loss-log 0.2 = 1.609
Both at 0.5D loss 1.386, G loss 0.693

The cells students fill in are left blank in this preview.

Try it: the two losses

Code: python
import math

# The discriminator wants real near 1 and fake near 0.
# The generator wants its fake scored near 1.
for real, fake in [[0.9, 0.2], [0.6, 0.5], [0.5, 0.5]]:
    d_loss = -math.log(real) - math.log(1 - fake)
    g_loss = -math.log(fake)
    print("D(real)", real, "D(fake)", fake,
          "D loss", round(d_loss, 3), "G loss", round(g_loss, 3))
# Add the pair [0.99, 0.01]. Who is winning there?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A toy GAN on numbers from a bell

The lab's real data are numbers from a bell with mean 4 and spread 0.5. The generator is two weights: fake = a × noise + b, so b sets the mean and a the spread.

The discriminator sees each number and its square, which lets it notice a wrong spread as well as a wrong mean. It takes ten steps for every generator step.

Write the GAN script

Command
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'r = np.random.default_rng(0)' 'a, b = 1.0, 0.0' 'w = np.zeros(3)' 'def feats(x):' '    x = x / 4' '    return np.stack([x * x, x, np.ones_like(x)], axis=1)' 'def d(x):' '    return 1 / (1 + np.exp(-feats(x) @ w))' 'for step in range(3001):' '    for i in range(10):' '        real = r.normal(4, 0.5, 128)' '        fake = a * r.normal(0, 1, 128) + b' '        w += (feats(real).T @ (1 - d(real)) - feats(fake).T @ d(fake)) / 128' '    z = r.normal(0, 1, 128)' '    fake = a * z + b' '    if step % 500 == 0:' '        print(\"step\", step, \"fake mean\", round(fake.mean(), 2), \"spread\", round(abs(a), 2), \"D(real)\", round(d(real).mean(), 2), \"D(fake)\", round(d(fake).mean(), 2))' '    push = -(1 - d(fake)) * (2 * w[0] * fake / 16 + w[1] / 4)' '    a -= 0.02 * (push * z).mean()' '    b -= 0.02 * push.mean()' > steps/gan.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Train the toy GAN

Command
docker exec jupyter python3 steps/gan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What gan.py printed

StepFake mean (real 4)Fake spread (real 0.5)D(real), D(fake)
00.071.00.89, 0.22
5004.040.150.5, 0.5
10004.060.250.51, 0.5
15003.960.630.5, 0.49
25003.90.780.5, 0.51
30004.00.30.5, 0.5

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

GAN training swings, and can collapse

The spread went 0.15, 0.63, 0.23, 0.78: each network keeps undoing the other. At 0.15 most fakes were almost the same number. That is a small mode collapse, too little variety.

With data in several clumps, a collapsed generator may cover only one. So people judge a GAN by its samples, their variety as well as their look, never by one loss.

A common mistake

Warning

Many people think a falling generator loss means better fakes. In a GAN the two losses push against each other, so either can fall while the fakes get worse. Compare the samples with the data instead: here, their mean and spread.

GANs beside the other families

GANVAEDiffusion
Making one sampleOne pass, fastOne pass, fastMany steps, slow
TrainingUnstable, two networksStable, one lossStable, one loss
Typical weaknessMode collapseBlurry samplesCost of the steps

The cells students fill in are left blank in this preview.

Match each word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: GAN losses and collapse

Write four functions for judging a GAN.

bce(score, label) gives -math.log(score) when label is 1 and -math.log(1 - score) when it is 0. discriminator_loss(real_scores, fake_scores) gives the mean of bce over the real scores with label 1 plus the mean over the fake scores with label 0, rounded to 4 places. generator_loss(fake_scores) gives the mean of -math.log of each fake score, rounded to 4 places. modes_covered(samples, centres, radius) counts how many centres have at least one sample no further than radius from them. A count lower than the number of centres is a sign of mode collapse.

Code: python
import math


def bce(score, label):
    return 0.0


def discriminator_loss(real_scores, fake_scores):
    return 0.0


def generator_loss(fake_scores):
    return 0.0


def modes_covered(samples, centres, radius):
    return 0

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.