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 and discriminative models

After this lesson: I can explain how a generative model differs from a discriminative one by sampling from a distribution I fitted.

60 min lesson3 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 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

WordWhat it means
Discriminative modela model that predicts a label from an input
Generative modela model of how the data itself is spread
Distributionhow likely each possible value is
Sampleone new value drawn at random from a distribution
Likelihoodhow 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 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 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

DiscriminativeGenerative
LearnsWhere spam ends and real mail startsHow words in emails are spread
AnswersIs this email spam?How likely is this email? What would a new one say?
Can make a new emailNoYes, by sampling
Example from earlier modulesThe word-count classifierThe next-character model

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

A 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

Code: python
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 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

Fit 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

Command
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

ValueWhat it is
5.89The mean delay in minutes, fitted from the data
1.97The spread, fitted from the data
6.3, 4.9, 5.1, 1.1, 9.4Five 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

Command
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

Command
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 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

Four ways to build a generative model

FamilyHow it makes a sampleLesson
AutoregressiveOne piece at a time, each from the pieces beforeModule 90, next token
Variational autoencoderDecode a random point from a small code spaceLesson 2
Generative adversarial networkA generator turns noise into a fake that fools a judgeLesson 3
Diffusion modelStart from noise and remove it step by stepLesson 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.

Code: python
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

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.