A model that can make new examples
A generative model learns how data is spread so it can make new examples that look like it. A discriminative model only learns to tell kinds of data apart.
A spam filter is discriminative: it says spam or not. A tool that writes a new email, draws a picture or speaks a sentence is generative. This module builds the main kinds by hand.
By the end of this lesson
Note
I can explain how a generative model differs from a discriminative one by sampling from a distribution I fitted.
Key words
| Word | What it means |
|---|---|
| Discriminative model | a model that predicts a label from an input |
| Generative model | a model of how the data itself is spread |
| Distribution | how likely each possible value is |
| Sample | one new value drawn at random from a distribution |
| Likelihood | how probable the real data is under a model |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsA discriminative model learns a boundary
A discriminative model answers one question: given this input, which label? It learns where one kind of data ends and the next begins, and nothing more.
It never learns what a typical email looks like. Ask it to write one and it has nothing to say. That is fine for a filter, and it is why filters are cheaper to train.
The same emails, two kinds of model
| Discriminative | Generative | |
|---|---|---|
| Learns | Where spam ends and real mail starts | How words in emails are spread |
| Answers | Is this email spam? | How likely is this email? What would a new one say? |
| Can make a new email | No | Yes, by sampling |
| Example from earlier modules | The word-count classifier | The next-character model |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsA generative model learns a distribution
The simplest generative model is a table of shares. Count what happened, divide by the total, and you have a distribution.
To make something new, you draw a sample: pick at random, but in proportion to the shares. Popular values come up often and rare ones seldom. The code below does this for a canteen.
Try it: sample new canteen orders
import random
# What 100 students chose in the canteen last week.
meals = ["pasta", "curry", "salad", "soup"]
counts = [40, 30, 20, 10]
# The model: the share of each meal. That is the whole distribution.
total = sum(counts)
shares = []
for c in counts:
shares.append(c / total)
print("shares:", shares)
# Generate ten new orders by sampling from the shares.
draw = random.Random(14)
orders = draw.choices(meals, weights=shares, k=10)
print("ten new orders:", orders)
# Change counts so that soup is the favourite, then press Run again.
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsFit a bell curve, then sample from it
Numbers like bus delays need a shape, not a table. A bell curve, the normal distribution, has two settings: its mean and its spread, the standard deviation.
Fitting it means working both out from the data. Generating means drawing new delays from the curve. The lab does both for 1,000 made-up delays.
Fit a bell curve to bus delays
docker exec jupyter python3 -c "import numpy as np; d = np.random.default_rng(1).normal(6, 2, 1000); m, s = d.mean(), d.std(); print(round(m, 2), round(s, 2), np.random.default_rng(2).normal(m, s, 5).round(1).tolist())"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
What the lab printed
| Value | What it is |
|---|---|
| 5.89 | The mean delay in minutes, fitted from the data |
| 1.97 | The spread, fitted from the data |
| 6.3, 4.9, 5.1, 1.1, 9.4 | Five new delays sampled from the fitted curve |
The cells students fill in are left blank in this preview.
Likelihood says how well a model fits
Suppose buses are either about 3 minutes late in the morning or about 12 in the evening. One bell curve sits in the middle and samples delays that never happen.
The likelihood measures the fit: how probable the real data is under the model. We average its log over the data. Higher is better, so two bells beat one.
One bell on two clumps of delays
docker exec jupyter python3 -c "import numpy as np; r = np.random.default_rng(3); d = np.concatenate([r.normal(3, 1, 500), r.normal(12, 1, 500)]); m, s = d.mean(), d.std(); new = np.random.default_rng(4).normal(m, s, 1000); gap = lambda x: int(((x > 6) & (x < 9)).sum()); print(round(m, 2), round(s, 2), gap(d), gap(new))"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Score one bell against two
docker exec jupyter python3 -c "import numpy as np; from scipy.stats import norm; r = np.random.default_rng(3); d = np.concatenate([r.normal(3, 1, 500), r.normal(12, 1, 500)]); a, b = d[d < 7.5], d[d >= 7.5]; one = norm.logpdf(d, d.mean(), d.std()).mean(); two = np.log(0.5 * norm.pdf(d, a.mean(), a.std()) + 0.5 * norm.pdf(d, b.mean(), b.std())).mean(); print(round(one, 3), round(two, 3))"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a generative model stores its examples and hands one back. It learns a distribution and draws new values from it: 9.4 minutes was never in the data. A model fitted too closely can copy, which lesson 4 shows.
Check
Have a go
Check
3 questionsFour ways to build a generative model
| Family | How it makes a sample | Lesson |
|---|---|---|
| Autoregressive | One piece at a time, each from the pieces before | Module 90, next token |
| Variational autoencoder | Decode a random point from a small code space | Lesson 2 |
| Generative adversarial network | A generator turns noise into a fake that fools a judge | Lesson 3 |
| Diffusion model | Start from noise and remove it step by step | Lesson 4 |
The cells students fill in are left blank in this preview.
Match each family to its idea
Have a go
Loading…
Your answers are marked here and are not kept. An account keeps your marks.
Assignment: fit and sample a distribution
Write three functions for the simplest generative model, a table of shares.
probabilities(counts) takes a list of counts and gives a list of shares, each count divided by the total. sample_one(probs, u) takes the shares and a number u from 0 up to 1, and gives the index of the first value whose running total of shares is greater than u. This is how a random draw picks in proportion. log_likelihood(probs, data) takes the shares and a list of indexes seen, and gives the sum of math.log of the share of each, rounded to 3 places.
import math
def probabilities(counts):
return counts
def sample_one(probs, u):
return 0
def log_likelihood(probs, data):
return 0.0
Make a free account to save your work and track your progress.
Exit quiz
Have a go