Lesson 7 of 118 min
Maximum likelihood
Pick the setting that makes the data you saw the likeliest; minus the log of that likelihood is the loss a model is trained on.
After this lesson you can fit a model by making the observed data most probable.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Fit a bell to the masses
Run the cells in order. norm.fit finds the centre and standard deviation of the normal distribution that gives these measured masses the highest likelihood. Both numbers are in kilos.
import numpy as np
import pandas as pd
from scipy.stats import norm
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
df = pd.read_csv(url).dropna(subset=["body_mass_g", "flipper_length_mm"])
mass = df.body_mass_g.to_numpy() / 1000
centre, width = norm.fit(mass)
print(f"Centre {centre:.2f} kg, width {width:.2f} kg")Centre 4.20 kg, width 0.80 kg
Change the bell's width
A fixed bell width changes how much a squared miss costs. When every penguin uses the same width, the same line wins at any positive width. Once the line uses flipper length, its remaining misses have a spread of just 0.39 kg.
x = (df.flipper_length_mm.to_numpy() - 200) / 10
slope, intercept = np.polyfit(x, mass, 1)
predicted = slope * x + intercept
print(f"Slope {slope:.3f} kg/cm, centre at 20 cm {intercept:.3f} kg")
for width in (0.2, 1.0):
losses = [-norm.logpdf(mass, predicted + d, width).mean()
for d in (-0.1, 0, 0.1)]
print(f"Width {width}: {[round(float(loss), 3) for loss in losses]}")
print(f"Spread of the line's misses: {(mass - predicted).std():.2f} kg")Slope 0.497 kg/cm, centre at 20 cm 4.156 kg Width 0.2: [1.366, 1.241, 1.366] Width 1.0: [1.001, 0.996, 1.001] Spread of the line's misses: 0.39 kg
Let PyTorch score the bell
GaussianNLLLoss takes a predicted centre, the measured mass and the bell's variance. Square its width before passing it in. full=True includes the constant needed to match the whole negative log-likelihood. It uses natural logs, so the result is in nats.
import torch
guess = torch.tensor(predicted)
actual = torch.tensor(mass)
variance = torch.full_like(guess, 0.39**2)
loss = torch.nn.GaussianNLLLoss(full=True)(guess, actual, variance)
print(f"Average loss: {loss.item():.4f} nats")Average loss: 0.4854 nats
Use absolute misses for a tent-shaped bell
A Laplace distribution falls away from its centre with the size of the miss. At a fixed scale, its negative log-likelihood is the mean absolute error divided by the scale, plus a constant. Compare two guesses for the whole pile.
from scipy.stats import laplace
for guess in (mass.mean(), np.median(mass)):
mae = np.abs(mass - guess).mean()
nll = -laplace.logpdf(mass, loc=guess, scale=1).mean()
print(f"{guess:.3f} kg: absolute miss {mae:.4f}, loss {nll:.4f}")4.202 kg: absolute miss 0.6764, loss 1.3695 4.050 kg: absolute miss 0.6664, loss 1.3595
Fit a rate to three ratings
Three thumbs-up in three tries put the best fit at 100%. With so few ratings, the next one can move it a lot. Each order with the same counts has the same likelihood. Counting all those orders multiplies every rate's likelihood by the same number, so the peak stays put.
from math import comb
rates = np.linspace(0, 1, 101)
likelihood = rates**7 * (1 - rates)**3
print(f"Seven in ten, one order: {rates[likelihood.argmax()]:.2f}")
print(f"Seven in ten, any order: {rates[(comb(10, 7) * likelihood).argmax()]:.2f}")
likelihood = rates**3
print(f"Three in three: {rates[likelihood.argmax()]:.2f}")Seven in ten, one order: 0.70 Seven in ten, any order: 0.70 Three in three: 1.00
Run on Python 3.13.3, NumPy 2.5.5, pandas 3.1.1, SciPy 1.18.1 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Random variables and distributions
The penguins' masses are drawn as bars of share per kilo. The bar from 3.5 to 4 kilos is half a kilo wide, and 0.55 high. What share of the penguins weigh 3.5 to 4 kilos?
2 of 3
Five ratings: four thumbs-up and one thumbs-down. Of the like-rates 0.5, 0.8 and 1, which makes these five ratings the likeliest?
3 of 3
Three ratings get the chances 0.5, 0.25 and 0.5. Multiplied, that's one sixteenth. What is its log, counting halvings?
The ideas in this lesson
- Maximum likelihood
- Score each setting by how likely it makes the data you saw, then pick the setting with the top score.
- Logarithm
- The log counts how many times you halve 1 to reach a number, so multiplying numbers adds their logs.
- Negative log-likelihood
- Minus the log of how likely a model makes the data: a loss, and with bell-shaped misses it's the squared error.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Which like-rate?
Here's a question. People rate a chatbot's answers. Each answer gets a thumbs-up or a thumbs-down. The like-rate is how often people like an answer. You only see a few ratings. Which like-rate fits them best?
Your guess
Here are ten ratings: seven thumbs-up, and three thumbs-down. Which like-rate makes these ten ratings the likeliest?
Zero point five? Zero point seven? Or one?
The chance of the ratings
Start with a like-rate of zero point five. Then each thumbs-up has a chance of zero point five, and so does each thumbs-down. One rating tells you nothing about the next one, so their chances multiply. Zero point five, ten times over: about one in a thousand. It's small, because it's the chance of exactly these ten ratings, in this order.
The likelihood
Now try zero point seven. Each thumbs-up has a chance of zero point seven, and each thumbs-down gets what's left: zero point three. Multiply them: about two in a thousand. More than twice as likely.
That number is the like-rate's likelihood: the chance of what you saw, if that like-rate were true.
It's not the chance that zero point seven is right. It's a score, for comparing like-rates.
Maximum likelihood
So score every like-rate, from zero to one. The curve climbs to a top at zero point seven, the share you saw, and falls again. Picking the like-rate at the top... is called maximum likelihood. If you said zero point seven, that's why it's right.
And one?
And a like-rate of one?
Every thumbs-up gets its biggest chance. But at one, a thumbs-down can't happen. Its chance is zero, and a single zero makes the whole product zero. The best like-rate has to fit all ten ratings at once.
Too small for a computer
A real chatbot gets thousands of ratings. Take ten thousand, and seven thousand of them are thumbs-up. Multiply ten thousand chances, and the answer has more than two thousand zeros after the point. A computer only keeps about three hundred. So it writes zero, at every like-rate. The curve goes flat. There's no top to find.
The log counts halvings
The fix is the logarithm: the log, for short. The log of a chance counts how many times you halve one to reach it. It gets a minus, because you went down. A half is one halving: its log is minus one. A quarter: minus two. An eighth: minus three. A chance in between has a log in between. Zero point seven has a log of about minus a half. Zero point three, about minus one and three quarters.
Multiplying adds logs
Now the useful part. A half times a quarter is an eighth. So what happens to their logs?
Minus one and minus two add up to minus three.
Multiplying chances... adds their logs.
So, the ten ratings at zero point seven. Each thumbs-up adds about minus a half.
Each thumbs-down adds about minus one and three quarters. Added up, that's about minus eight point eight.
The log-likelihood
Now ten thousand ratings: add ten thousand logs.
At zero point seven, it's about minus eight thousand eight hundred. At zero point five, minus ten thousand.
A computer holds numbers like those with no trouble. And a bigger chance always has a bigger log. So the top stays at zero point seven. This sum of logs is called the log-likelihood.
Minus is a loss
Put a minus in front.
Then divide by the number of ratings, to get the average for one rating. Now lower is better, like any loss. The lowest point is still at a like-rate of zero point seven, where the loss is zero point eight eight. Minus the log-likelihood... is called the negative log-likelihood.
A bell over the masses
Now a number, not a thumbs-up: a penguin's mass. A model guesses one mass for every penguin. It puts a bell around its guess, as wide as the spread of the masses. For a number, the likelihood uses the bell's height at each mass. High near the guess. Low far out.
Slide the bell along. Minus the log-likelihood is lowest at four point two kilos. So the masses are likeliest at their average.
And the average is also the one guess that makes the squared misses smallest.
The bell and the squared misses pick the same place. Why?
The log of a bell is a square
Take the bell's log. At a miss of one standard deviation, it drops zero point seven two. At two, it drops about two point nine. At three, about six point five. That's zero point seven two times one... times four... times nine. The square of the miss. So minus the log-likelihood is the squared misses, times a fixed number, plus a fixed number. The squares came from the bell.
The line too
The same goes for the line from the Calculus course. It guesses each penguin's mass from its flipper. Put a bell around the line's guess for each penguin, and the same squares come out. So the likeliest line is the line with the smallest squared misses.
In code
Now in real code. NumPy works out the likelihood of a hundred and one like-rates in a few lines. Then it finds the top: zero point seven. The product of ten thousand halves prints zero. The sum of their logs: minus ten thousand.
Now the loop that trained the penguin line in the Calculus course.
One line changes. The loss is now minus the log of a bell's height at each mass. The bell is zero point three nine kilos wide: the spread of the line's misses.
Where will the line land?
The line lands where it did in the Calculus course. That's the line with the smallest squared misses. So the squared error was never a random choice.
If the misses are shaped like a bell, maximum likelihood gives you the squares.
The likeliest setting
So maximum likelihood picks the setting with the highest likelihood. With many ratings, add their logs instead of multiplying their chances. And minus the log-likelihood is a loss. With a bell, it gives the mean squared error.
Make the data likeliest
The best setting makes your data the likeliest. Now try it on this lesson's page, and take the quiz. Change the ratings until the top sits in the middle.
You use this lesson in Lab 3: Score a language model's guesses, after Cross-entropy and KL divergence.
Facts last checked on .
