Lesson 13 · Thinking in probabilities
Maximum likelihood and MAP
The problem
Of the shop's last ten deliveries, three were late:
on time, late, on time, on time, late, on time, on time, on time, late, on time
What is the chance that the next one is late? Most people say 0.3, three in ten. That's a good answer. But why is it the right one, and what rule gave it?
This lesson names that rule. It's called maximum likelihood, and it's the idea behind almost every loss in this course. The squared error of linear regression and the cross-entropy of logistic regression both come out of it. Then we fix its one weakness, small data, by adding what we believed before we looked.
From here on, (theta) stands for a model's parameters in general. In the late-rate example, the only parameter is .
One delivery: the Bernoulli distribution
Each delivery has two outcomes: late () or on time (). A model of one delivery needs one number, the chance that it's late. Then
This is the Bernoulli distribution. It's the simplest distribution there is: a categorical distribution with two outcomes, or a coin that lands heads with chance .
The two lines fit into one formula:
Read it back: if , the second factor is , leaving . If , the first factor is , leaving . The formula looks odd, but it only picks the right one of the two numbers.
The likelihood
Pick a value for , say 0.5. How probable were these exact ten deliveries? Each late one had chance 0.5, and so did each on-time one. Assume one delivery's outcome doesn't affect another's: they are independent. Then you can multiply:
That's tiny, but any particular sequence of ten is unlikely. What matters is how it compares with other values of . Slide and watch the product.
Late rate p = 0.50: each late delivery gets 0.50, each on-time one 0.50
Likelihood = 0.50³ × 0.50⁷ = 0.00098
Drag the handle on the p axis. 3 of 10 were late.
Things to notice:
- Raising makes the three late bars taller and the seven on-time bars shorter. The product balances the two.
- At , each on-time delivery gets only 0.1, and the product is almost 0.
- The curve has one peak.
Predict first
Where does the curve peak?
Worked example
The product at three values of p
: .
The probability of the data, read as a function of the parameter, is the likelihood. We write it . The data stay fixed; the parameter moves. For the deliveries,
The sign means "multiply all of these", as means "add". Choosing the parameter value with the highest likelihood is maximum likelihood estimation (MLE). The value it picks is written ("theta hat"), here .
The likelihood is not the probability that is 0.3. It's the probability of the data, if were 0.3. The curve doesn't even have area 1. The last part of this lesson asks how probable each value of is, and that needs one more ingredient.
DigressionWhere maximum likelihood comes fromFisher named it in 1922. The idea is older. · 1 min
The statistician Ronald Fisher named the method in a 1922 paper, "On the mathematical foundations of theoretical statistics". The same paper gave modern meanings to words like parameter and statistic. He had used the procedure since 1912 without that name.
Versions of the idea are older still. Historians trace it back to 18th-century work by Daniel Bernoulli and Lagrange on combining measurements. Fisher's contribution was to make it a general method and to study when it works.
Logs, and the formula
Products of many small numbers are awkward. With 1,000 deliveries, the likelihood is around , near the limit of what a computer can store. So we take the log. It turns the product into a sum. The log only goes up when its input goes up, so the peak stays at the same :
Each term is a log-probability, one per delivery. This is the log-likelihood.
At the peak, the slope is zero. Take the derivative and set it to 0:
With late deliveries out of , the same steps give . The "obvious" answer is the maximum-likelihood one.
Losses in this book are things to make small, so we usually flip the sign. The negative log-likelihood (NLL) is
Minimising it is the same as maximising the likelihood. Read it back: each example adds its surprise, of the probability the model gave it. A model that finds the data unsurprising has a small NLL. Dividing by gives the average surprise per example, which changes the size but not the best .
More data, sharper peak
Three late out of 10 and 300 late out of 1,000 have the same best . But they are not equally convincing. To compare them on one axis, divide each likelihood curve by its peak value.
3 late of 10: the peak is at p = 0.30 every time
Values of p within a tenth of the peak: 0.07 to 0.63
The bold line is the one you picked; the others are dashed.
Things to notice:
- All three curves peak at 0.3.
- With 10 deliveries, anything from about 0.07 to 0.63 is still fairly plausible. With 1,000, only 0.27 to 0.33 is.
- Ten times the data makes the curve about three times narrower: the width shrinks like .
The MLE is a single number, and it says nothing about this width. Ten deliveries and a thousand give the same .
DigressionWhy we always work with log-likelihoodsA product of 1,000 probabilities rounds to exactly zero. · 1 min
Each delivery's probability is at most 1, so every extra delivery shrinks the product. A 32-bit float can't store a positive number below about . Anything smaller rounds to exactly 0. This is called underflow.
The likelihood of 1,000 deliveries at is about . In 32-bit floats it's 0, and so is the likelihood at every other , so there is no peak to find. The log-likelihood is about , an ordinary number. The PyTorch primer's Numbers and stability lesson shows the same failure in code.
Cross-entropy is a negative log-likelihood
Now give each delivery its own late rate. Logistic regression does this: delivery gets from its features. Treat each label as a Bernoulli outcome with its own . The negative log-likelihood is
That's times the cross-entropy loss, term for term. So training logistic regression with cross-entropy is maximum likelihood. The weights it finds are the ones that make the observed labels most probable.
This is why cross-entropy was the natural choice for probabilities. It wasn't picked from a list of possible losses. It's what "make the data probable" says, written out for yes/no labels.
Squared error is a negative log-likelihood
Delivery times aren't yes/no. In the Linear regression lesson, the model was a line, minutes = km . The real times scatter around it.
Here is a model of that scatter. Each time is the line's prediction plus some noise. The noise comes from a normal distribution with mean 0 and spread .
So each delivery's time has its own bell curve, centred on the line. The likelihood scores how high each delivery sits on its bell. A density is not a probability, but its height plays the same role here: higher means more likely.
Line: minutes = 2.00 × km + 16.0
MSE = 11.83 · log-likelihood = −30.91
The thick tick on each bell is that delivery's density. The best line has MSE 3.64.
Things to notice:
- A delivery far from the line sits out in its bell's tail, where the density is near 0. That costs a lot of log-likelihood.
- Moving the line to lower the MSE always raises the log-likelihood. The dot in the lower plot only ever slides along the same straight line.
- "Snap to the least-squares line" gives the highest log-likelihood, , at the lowest MSE, 3.64.
The maths
The normal density's log at a time , for a bell centred at with spread , is
Add this up over deliveries and flip the sign:
Read it back: the first part doesn't depend on the line at all. The second is the mean squared error times a positive number. So the line with the smallest MSE has the smallest NLL. Least squares is maximum likelihood, if the noise is normal.
With and 10 deliveries, that's . For the best line, , matching the figure.
The assumption matters. Squared error suits noise that is bell-shaped. If a few deliveries go wildly wrong (a driver gets lost), the normal model fits badly. That's why squared error swings towards outliers.
A noise model with heavier tails gives a different loss. The mean absolute error is the NLL of one such model.
Maximum likelihood in PyTorch
The torch.distributions objects from the PyTorch primer have a .log_prob method, which is all maximum likelihood needs. First, score three values of and search a grid:
late = torch.tensor(LAST_TEN, dtype=torch.float64) # (10,): 1 = late
def log_likelihood(p: torch.Tensor) -> torch.Tensor:
"""log P(data | p): the sum of each delivery's log-probability under Bernoulli(p)."""
return Bernoulli(probs=p).log_prob(late).sum()
for p in [0.1, 0.3, 0.5]:
ll = log_likelihood(torch.tensor(p, dtype=torch.float64))
print(f"p = {p}: log-likelihood {ll.item():.3f}, likelihood {ll.exp().item():.5f}")
grid = torch.linspace(0.01, 0.99, 99, dtype=torch.float64) # candidate values of p
scores = torch.stack([log_likelihood(p) for p in grid]) # (99,)
print(grid[scores.argmax()].item()) # 0.3: the peak of the likelihood curve
print(late.mean().item()) # 0.3: the formula, k / np = 0.1: log-likelihood -7.645, likelihood 0.00048
p = 0.3: log-likelihood -6.109, likelihood 0.00222
p = 0.5: log-likelihood -6.931, likelihood 0.00098
0.3
0.3Bernoulli(probs=p).log_prob(late)gives one log-probability per delivery..sum()makes it the log-likelihood.- The grid search and the formula (
late.mean()) agree.
Most models have no formula, so the general tool is gradient descent on the NLL:
def fit_bernoulli(data: torch.Tensor, steps: int = 200, lr: float = 0.5) -> float:
"""Maximum likelihood by gradient descent on the negative log-likelihood (mean per delivery)."""
z = torch.zeros((), dtype=torch.float64, requires_grad=True) # logit of p; p = sigmoid(z) = 0.5
optimizer = torch.optim.SGD([z], lr=lr)
for _ in range(steps):
optimizer.zero_grad()
nll = -Bernoulli(logits=z).log_prob(data).mean() # average surprise per delivery
nll.backward()
optimizer.step()
return torch.sigmoid(z).item()
p_hat = fit_bernoulli(late)
print(round(p_hat, 4)) # 0.30.3- The parameter is the logit , not . Any real gives a valid , so gradient steps can never push below 0 or above 1.
Bernoulli(logits=z)accepts it directly. - Minimising the NLL is maximising the likelihood: "gradient ascent on the log-likelihood" and "gradient descent on the NLL" are the same steps.
The check that cross-entropy is the Bernoulli NLL:
z = torch.tensor(0.4, dtype=torch.float64) # any logit: here p = sigmoid(0.4) = 0.599
nll = -Bernoulli(logits=z).log_prob(late).sum()
bce = F.binary_cross_entropy_with_logits(z.expand(10), late, reduction="sum")
print(nll.item(), bce.item()) # the same number: cross-entropy is the Bernoulli negative log-likelihood7.930152523999526 7.930152523999526F.binary_cross_entropy_with_logits with reduction="sum" and the Bernoulli NLL give the same number, for any logit.
The normal-noise line, fitted by gradient descent on the NLL, and compared with least squares:
km, minutes = ten_deliveries() # (10,), (10,)
sigma = 2.0 # assumed spread of the noise around the line, in minutes
def normal_nll(w: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""−log P(times | line), if each time is the line's prediction plus Normal(0, sigma²) noise."""
return -Normal(loc=w * km + b, scale=sigma).log_prob(minutes).sum()
w = torch.zeros((), dtype=torch.float64, requires_grad=True)
b = torch.zeros((), dtype=torch.float64, requires_grad=True)
optimizer = torch.optim.SGD([w, b], lr=0.1)
for _ in range(5000):
optimizer.zero_grad()
loss = normal_nll(w, b) / len(km) # mean negative log-likelihood
loss.backward()
optimizer.step()
X = torch.stack([km, torch.ones_like(km)], dim=1) # (10, 2): distance and a column of ones
least_squares = torch.linalg.lstsq(X, minutes.unsqueeze(1)).solution.squeeze(1) # (2,)
print(w.item(), b.item()) # 3.913 10.850: maximum likelihood ...
print(least_squares.tolist()) # [3.913, 10.850]: ... is least squares
with torch.inference_mode():
mse = F.mse_loss(w * km + b, minutes)
constant = 0.5 * len(km) * math.log(2 * math.pi * sigma**2)
print(normal_nll(w, b).item(), (constant + len(km) * mse / (2 * sigma**2)).item()) # equal3.913179682257515 10.850073842016084
[3.9131796822555382, 10.850073842022827]
20.67680321059315 20.676803210593146Normal(loc=w * km + b, scale=sigma)holds ten bells, one per delivery (a batch of distributions)..log_prob(minutes)scores each delivery under its own bell.- The weights match
torch.linalg.lstsq, the least-squares solution from the Linear regression lesson, to 10 decimal places. - The last line checks the formula: NLL = constant + .
Maximum likelihood can fit the bell's spread too. Here it fits one normal to the ten times themselves:
times = minutes # fit one normal to the ten times themselves
mu = torch.zeros((), dtype=torch.float64, requires_grad=True)
log_sigma = torch.tensor(2.0, dtype=torch.float64, requires_grad=True) # sigma = exp(log_sigma) > 0; start at 7.4
optimizer = torch.optim.Adam([mu, log_sigma], lr=0.1)
for _ in range(3000):
optimizer.zero_grad()
loss = -Normal(loc=mu, scale=log_sigma.exp()).log_prob(times).mean()
loss.backward()
optimizer.step()
print(mu.item(), log_sigma.exp().item()) # 21.22 6.15: by gradient descent
print(times.mean().item(), times.std(correction=0).item()) # 21.22 6.15: the formulas (std with no correction)21.220000000000002 6.15317804065509
21.22 6.1531780406550896The best mean is the sample mean. The best spread is the standard deviation computed by dividing by (correction=0), not . The parameter is , so can never go negative, the same trick as the logit.
Pretend deliveries: prior and posterior
Maximum likelihood trusts the data completely. With lots of data that's fine. With a little, it's reckless.
Suppose the shop opens a second branch, and its first delivery is late. The MLE of its late rate is : every delivery will be late. Nobody believes that. Before seeing anything, you already knew a late rate of 1 is absurd.
A simple way to write that down is to pretend you have already seen some deliveries. Say 2 pretend late ones and 2 pretend on-time ones. A cautious prior is "probably around a half, but I've only seen 4". Their likelihood curve, , is a gentle hump centred on 0.5. That curve is your belief before the data.
What you believe about a parameter before seeing the data, written as a distribution over its values, is the prior. Here the prior gives every a weight, highest at 0.5, zero at 0 and 1.
Now combine it with the data by Bayes' rule. The cause is the value of ; the evidence is the data:
The sign means "is proportional to". The bottom, , is the same for every , so it only rescales the curve to have area 1.
The result is the posterior: what you believe after seeing the data. With pretend deliveries it has a neat form. The counts add up: 3 real + 2 pretend late, 7 real + 2 pretend on time.
Prior (dashed): 2.0 pretend late, 2.0 pretend on time
Likelihood (dotted): 3 late of 10 · MLE = 0.300
Posterior (solid): MAP = (3 + 2.0) ÷ (10 + 4) = 0.357
At strength 0 there is no prior, and the posterior is the likelihood.
Things to notice:
- The posterior always sits between the prior and the likelihood.
- Raise the prior's strength and the posterior moves towards the prior's guess. At strength 40, four times the real data, the prior wins.
- At strength 0 there is no prior. The posterior is the likelihood, and its peak is the MLE.
The peak of the posterior is the MAP estimate, for "maximum a posteriori". With pretend late and pretend on-time deliveries, and late out of real ones, the same derivative steps as before give
Worked example
MAP with a prior of 2 late in 4
Real data: late out of . The MLE is .
Predict first
3 of 10 deliveries were late. Before seeing them, you add one pretend late delivery and one pretend on-time one. What's the MAP estimate of the late rate?
Few deliveries vs many
The prior matters most when the data are few. Watch both estimates as deliveries arrive one at a time.
0 deliveries seen, 0 late
MLE (dotted) = no data yet · MAP (solid) = (0 + 2) ÷ (0 + 4) = 0.50
The prior is 2 pretend late and 2 pretend on time. The grey line is the 30% rate the deliveries were drawn with.
Things to notice:
- After the first delivery (on time), the MLE says 0: never late. The MAP estimate says 0.4.
- Over the first ten deliveries the MLE jumps around between 0 and 0.5. The MAP estimate moves less.
- By 100 deliveries the two agree to within 0.01. The 4 pretend deliveries are swamped by 100 real ones.
That's the trade. A prior steadies the estimate when data are scarce, and fades away when data are plentiful. A bad prior does harm only while the data are few.
DeeperThe pretend deliveries are a Beta priorThe hump-shaped prior has a name, and RL uses it. · 1 min
The prior curve , scaled to area 1, belongs to a family called the Beta distribution. It's usually written : its two numbers count the pretend deliveries plus one each. Its convenient property is the one you saw: a Beta prior times a Bernoulli likelihood gives another Beta, with the counts added.
The Reinforcement learning course meets the Beta distribution properly, for deciding which of several options to try next. PyTorch has it as torch.distributions.Beta.
A prior on weights is a penalty
The same idea works for a model's weights. Before seeing any deliveries, you might believe that each weight is probably small: near 0, rarely huge. Write that as a normal prior on each weight, centred on 0 with spread (tau).
The MAP estimate maximises log-likelihood plus log-prior. Flip the sign, and the loss to minimise is
With normal noise, the NLL is the MSE times a constant. So MAP for linear regression is "squared error plus a penalty on the squared weights". That is L2 regularisation, also called ridge regression. A strong belief that weights are small (a small ) means a big penalty.
So regularisation isn't a hack bolted onto the loss. It's a prior. It does the same job as the pretend deliveries: it keeps a model with few data points from chasing noise.
DeeperNormal prior + normal noise = ridge regressionThe penalty strength is the noise variance over the prior variance. · 2 min
Take linear regression with normal noise of spread , and a normal prior of spread on each weight. Leave the intercept without a prior. Up to constants, the negative log of the posterior is
Multiply through by , which doesn't move the minimum:
That's the ridge loss from the regularisation lesson, , with . Read it back:
- Noisier data (bigger ) means a bigger penalty: trust the prior more.
- More data (bigger ) means a smaller penalty: the prior fades, as with the pretend deliveries.
- A vaguer prior (bigger ) means a smaller penalty. As grows without limit, MAP becomes maximum likelihood.
A prior shaped like a sharp peak at 0 with heavy tails (the Laplace distribution) gives the L1 penalty instead.
MAP in PyTorch
MAP adds the log-prior to the log-likelihood. For the pretend deliveries, the log-prior is their log-likelihood, :
a, b_on_time = 2.0, 2.0 # the prior: 2 pretend late deliveries and 2 pretend on-time ones
def log_posterior(z: torch.Tensor) -> torch.Tensor:
"""log prior + log-likelihood (up to a constant), as a function of the logit z."""
# log p = logsigmoid(z) and log(1 - p) = logsigmoid(-z), computed without rounding p first
log_prior = a * F.logsigmoid(z) + b_on_time * F.logsigmoid(-z) # the pretend deliveries' log-likelihood
return log_prior + Bernoulli(logits=z).log_prob(late).sum()
z = torch.zeros((), dtype=torch.float64, requires_grad=True)
optimizer = torch.optim.SGD([z], lr=0.05)
for _ in range(500):
optimizer.zero_grad()
(-log_posterior(z)).backward()
optimizer.step()
k, n = late.sum().item(), len(late)
print(round(torch.sigmoid(z).item(), 4)) # 0.3571 by gradient ascent
print((k + a) / (n + a + b_on_time)) # 0.3571 = 5/14, against the MLE's 0.30.3571
0.35714285714285715Gradient descent on the negative log-posterior lands on , the same as the formula. F.logsigmoid(z) gives and F.logsigmoid(-z) gives , straight from the logit . Neither rounds down to when gets close to 0 or 1.
Putting it together
Here is the lesson in one pass:
- Model the data: each delivery is late with chance , a Bernoulli outcome.
- Likelihood: the probability of the observed data, as a function of . For 3 late of 10, .
- Maximum likelihood: pick the peak. Here . In practice, minimise the negative log-likelihood, often by gradient descent.
- Familiar losses: for yes/no labels, the NLL is cross-entropy. For numbers with normal noise, it's the MSE plus a constant.
- Prior: pretend deliveries, 2 late and 2 on time. Posterior = prior × likelihood: the counts add up.
- MAP: the posterior's peak, . With few data it's steadier than the MLE; with many, the two agree.
- Weights: a normal prior on the weights adds an L2 penalty to the loss.
Common misconceptions
"The likelihood is the probability that the parameter is right." It's the probability of the data, given the parameter. Its curve over doesn't have area 1. To talk about how probable each is, you need a prior, and then you get the posterior.
"Maximum likelihood is a different method from minimising a loss." They're the same thing when the loss is a negative log-likelihood. Cross-entropy and MSE both are, for the Bernoulli and normal models.
"A bigger likelihood value means a better model, whatever the data." Likelihoods shrink with every extra example, so you can only compare them on the same data. A likelihood of 0.00222 is good for 10 deliveries and impossible for 1,000.
"MAP adds pretend data to the dataset." It changes the estimate as if you had, but nothing is added to the table. The pretend counts only describe the prior. With there is no prior, and MAP is the MLE.
"A prior is cheating, because it's not from the data." Every estimate assumes something. The MLE assumes nothing beyond the model, and on one delivery it says "always late". The prior is stated openly, and its effect fades as data arrive.
Recap
- A Bernoulli distribution describes one yes/no outcome: 1 with chance , 0 with chance .
- The likelihood is the probability of the observed data under the parameters . For independent examples it's a product, so we work with its log.
- Maximum likelihood picks the parameters with the highest likelihood. For late out of , .
- The negative log-likelihood is the loss version. Cross-entropy is the Bernoulli NLL; MSE is the normal NLL, up to a constant.
- A prior is your belief before the data. The posterior is prior × likelihood, rescaled. With pretend counts, the counts add.
- The MAP estimate is the posterior's peak, . It's steadier than the MLE on small data, and the two agree on large data.
- A normal prior on weights is L2 regularisation.
- PyTorch names in this lesson:
torch.distributionsBernoulliandNormalwith.log_prob,torch.sigmoid,F.logsigmoid,torch.inference_mode,F.binary_cross_entropy_with_logits,torch.linalg.lstsqandtorch.optim.SGDandAdam.