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
| Word | What it means | Example |
|---|---|---|
| Generator | the network that turns noise into a fake | |
| Discriminator | the network that scores how real an input looks | |
| Adversarial training | training two networks against each other | |
| Binary cross-entropy | a loss for a score between 0 and 1 | -log(0.9) = 0.105 |
| Mode collapse | a generator making too little variety |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsTwo 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 --> GCheck
Have a go
Check
3 questionsEach 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
| Score | Value | Loss part |
|---|---|---|
| D(real) | 0.9 | -log 0.9 = 0.1054 |
| D(fake) | 0.2 | -log (1 - 0.2) = 0.2231 |
| Discriminator loss | 0.1054 + 0.2231 = 0.3285 | |
| Generator loss | -log 0.2 = 1.609 | |
| Both at 0.5 | D loss 1.386, G loss 0.693 |
The cells students fill in are left blank in this preview.
Try it: the two losses
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 questionsA 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
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
docker exec jupyter python3 steps/gan.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What gan.py printed
| Step | Fake mean (real 4) | Fake spread (real 0.5) | D(real), D(fake) |
|---|---|---|---|
| 0 | 0.07 | 1.0 | 0.89, 0.22 |
| 500 | 4.04 | 0.15 | 0.5, 0.5 |
| 1000 | 4.06 | 0.25 | 0.51, 0.5 |
| 1500 | 3.96 | 0.63 | 0.5, 0.49 |
| 2500 | 3.9 | 0.78 | 0.5, 0.51 |
| 3000 | 4.0 | 0.3 | 0.5, 0.5 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsGAN 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
| GAN | VAE | Diffusion | |
|---|---|---|---|
| Making one sample | One pass, fast | One pass, fast | Many steps, slow |
| Training | Unstable, two networks | Stable, one loss | Stable, one loss |
| Typical weakness | Mode collapse | Blurry samples | Cost 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.
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