ML fundamentals13 / 22

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 pp 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 (theta) stands for a model's parameters in general. In the late-rate example, the only parameter is pp.

One delivery: the Bernoulli distribution

Each delivery has two outcomes: late (y=1y = 1) or on time (y=0y = 0). A model of one delivery needs one number, the chance pp that it's late. Then

P(y=1)=p,P(y=0)=1−p.P(y = 1) = p, \qquad P(y = 0) = 1 - p .

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 pp.

The two lines fit into one formula:

P(y)=p y(1−p)1−y.P(y) = p^{\,y} (1 - p)^{1 - y} .

Read it back: if y=1y = 1, the second factor is (1−p)0=1(1-p)^0 = 1, leaving pp. If y=0y = 0, the first factor is p0=1p^0 = 1, leaving 1−p1 - p. The formula looks odd, but it only picks the right one of the two numbers.

The likelihood

Pick a value for pp, 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:

0.53×0.57=0.510≈0.00098.0.5^{3} \times 0.5^{7} = 0.5^{10} \approx 0.00098 .

That's tiny, but any particular sequence of ten is unlikely. What matters is how it compares with other values of pp. Slide pp and watch the product.

1234567891000.51the last ten deliveries (× late, ○ on time)its probability○×○○×○○○×○00.20.40.60.810.0000.0010.002late rate plikelihood

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.

Top: each delivery's probability when the late rate is p (× late, ○ on time). Bottom: their product, plotted against p. Drag the handle on the p axis.

Things to notice:

  • Raising pp makes the three late bars taller and the seven on-time bars shorter. The product balances the two.
  • At p=0.9p = 0.9, 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

  1. p=0.1p = 0.1: 0.13×0.97=0.001×0.478=0.000480.1^3 \times 0.9^7 = 0.001 \times 0.478 = 0.00048.

The probability of the data, read as a function of the parameter, is the likelihood. We write it L(θ)L(\theta). The data stay fixed; the parameter moves. For the deliveries,

L(p)=∏i=110p yi(1−p)1−yi=p3(1−p)7.L(p) = \prod_{i=1}^{10} p^{\,y_i} (1 - p)^{1 - y_i} = p^{3} (1 - p)^{7} .

The ∏\prod sign means "multiply all of these", as ∑\sum means "add". Choosing the parameter value with the highest likelihood is maximum likelihood estimation (MLE). The value it picks is written θ^\hat\theta ("theta hat"), here p^=0.3\hat p = 0.3.

The likelihood is not the probability that pp is 0.3. It's the probability of the data, if pp were 0.3. The curve doesn't even have area 1. The last part of this lesson asks how probable each value of pp 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 10−26510^{-265}, 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 pp:

log⁡L(p)=3log⁡p+7log⁡(1−p).\log L(p) = 3 \log p + 7 \log (1 - p) .

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:

ddplog⁡L=3p−71−p=03(1−p)=7p(multiply both sides by p(1−p))p=310.\begin{aligned} \frac{d}{dp} \log L &= \frac{3}{p} - \frac{7}{1 - p} = 0 \\ 3 (1 - p) &= 7p \qquad \text{(multiply both sides by } p(1-p)\text{)} \\ p &= \tfrac{3}{10} . \end{aligned}

With kk late deliveries out of nn, the same steps give p^=k/n\hat p = k / n. 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

NLL(θ)=−∑i=1nlog⁡P(yi∣θ).\text{NLL}(\theta) = -\sum_{i=1}^{n} \log P(y_i \mid \theta) .

Minimising it is the same as maximising the likelihood. Read it back: each example adds its surprise, −log⁡-\log of the probability the model gave it. A model that finds the data unsurprising has a small NLL. Dividing by nn gives the average surprise per example, which changes the size but not the best θ\theta.

More data, sharper peak

Three late out of 10 and 300 late out of 1,000 have the same best pp. But they are not equally convincing. To compare them on one axis, divide each likelihood curve by its peak value.

00.20.40.60.8100.51late rate plikelihood ÷ its peak

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.

Likelihood curves for 30% late, each divided by its peak. The bar at height 0.1 marks the values of p that keep at least a tenth of the peak likelihood.

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 1/n1/\sqrt{n}.

The MLE is a single number, and it says nothing about this width. Ten deliveries and a thousand give the same p^\hat p.

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 10−4510^{-45}. Anything smaller rounds to exactly 0. This is called underflow.

The likelihood of 1,000 deliveries at p=0.3p = 0.3 is about 10−26510^{-265}. In 32-bit floats it's 0, and so is the likelihood at every other pp, so there is no peak to find. The log-likelihood is about −611-611, 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 ii gets pi=σ(w⋅xi+b)p_i = \sigma(\mathbf{w} \cdot \mathbf{x}_i + b) from its features. Treat each label as a Bernoulli outcome with its own pip_i. The negative log-likelihood is

NLL=−∑i=1n[ yilog⁡pi+(1−yi)log⁡(1−pi)].\text{NLL} = -\sum_{i=1}^{n} \Big[\, y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big] .

That's nn 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 = w×w \times km +b+ b. 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 σ\sigma.

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.

01234567010203040distance (km)minutes
0102030405060050100mean squared error−log-likelihood

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.

Ten deliveries and a line. Each delivery has a bell curve of times around the line (spread σ = 2 minutes); the thick tick shows how high the delivery sits on it. Below: every line's mean squared error and negative log-likelihood fall on one straight line.

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, −20.68-20.68, at the lowest MSE, 3.64.

The maths

The normal density's log at a time yy, for a bell centred at y^\hat y with spread σ\sigma, is

log⁡N(y∣y^,σ2)=−12log⁡(2πσ2)−(y−y^)22σ2.\log \mathcal{N}(y \mid \hat y, \sigma^2) = -\tfrac{1}{2} \log (2\pi\sigma^2) - \frac{(y - \hat y)^2}{2\sigma^2} .

Add this up over nn deliveries and flip the sign:

NLL=n2log⁡(2πσ2)⏟same for every line+n2σ2⋅MSE.\text{NLL} = \underbrace{\tfrac{n}{2} \log (2\pi\sigma^2)}_{\text{same for every line}} + \frac{n}{2\sigma^2} \cdot \text{MSE} .

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 σ=2\sigma = 2 and 10 deliveries, that's NLL=16.12+1.25×MSE\text{NLL} = 16.12 + 1.25 \times \text{MSE}. For the best line, 16.12+1.25×3.64=20.6816.12 + 1.25 \times 3.64 = 20.68, 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 pp and search a grid:

The late-rate likelihood
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 / n
p = 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.3
  • Bernoulli(probs=p).log_prob(late) gives one log-probability per delivery. .sum() makes it the log-likelihood.
  • The grid search and the formula k/nk/n (late.mean()) agree.

Most models have no formula, so the general tool is gradient descent on the NLL:

Maximum likelihood by gradient descent
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.3
0.3
  • The parameter is the logit zz, not pp. Any real zz gives a valid p=σ(z)p = \sigma(z), so gradient steps can never push pp 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:

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-likelihood
7.930152523999526 7.930152523999526

F.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:

Normal noise gives 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())  # equal
3.913179682257515 10.850073842016084
[3.9131796822555382, 10.850073842022827]
20.67680321059315 20.676803210593146
  • Normal(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 + n⋅MSE/(2σ2)n \cdot \text{MSE} / (2\sigma^2).

Maximum likelihood can fit the bell's spread too. Here it fits one normal to the ten times themselves:

Fitting a normal's mean and spread
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.1531780406550896

The best mean is the sample mean. The best spread is the standard deviation computed by dividing by nn (correction=0), not n−1n - 1. The parameter is log⁡σ\log \sigma, so σ=elog⁡σ\sigma = e^{\log \sigma} 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 1/1=11/1 = 1: 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, p2(1−p)2p^{2}(1 - p)^{2}, 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 pp 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 pp; the evidence is the data:

P(p∣data)=P(data∣p) P(p)P(data)  ∝  p3(1−p)7⏟likelihood×p2(1−p)2⏟prior=p5(1−p)9.P(p \mid \text{data}) = \frac{P(\text{data} \mid p)\, P(p)}{P(\text{data})} \;\propto\; \underbrace{p^{3}(1 - p)^{7}}_{\text{likelihood}} \times \underbrace{p^{2}(1 - p)^{2}}_{\text{prior}} = p^{5}(1 - p)^{9} .

The sign ∝\propto means "is proportional to". The bottom, P(data)P(\text{data}), is the same for every pp, 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.

00.20.40.60.8101234late rate pbelief (area 1)

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.

The prior (dashed), the likelihood of 3 late of 10 (dotted) and the posterior (solid), each scaled to area 1. The thin vertical lines mark the MLE and the MAP estimate.

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 aa pretend late and bb pretend on-time deliveries, and kk late out of nn real ones, the same derivative steps as before give

p^MAP=k+an+a+b.\hat p_{\text{MAP}} = \frac{k + a}{n + a + b} .

Worked example

MAP with a prior of 2 late in 4

  1. Real data: k=3k = 3 late out of n=10n = 10. The MLE is 3/10=0.303/10 = 0.30.

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.

02040608010000.20.40.60.81deliveries seenestimated late rate
Deliveries 0 of 100
00.20.40.60.81024late rate pbelief

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.

The same deliveries arriving one at a time: the MLE (dotted) and the MAP estimate with 2 pretend deliveries of each kind (solid). Below: the posterior and the likelihood after the current delivery. The deliveries were drawn with a 30% late rate.

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 pa(1−p)bp^{a}(1 - p)^{b}, scaled to area 1, belongs to a family called the Beta distribution. It's usually written Beta(a+1, b+1)\text{Beta}(a + 1,\, b + 1): 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 (tau).

The MAP estimate maximises log-likelihood plus log-prior. Flip the sign, and the loss to minimise is

NLL(w)⏟fit the data+12τ2∑jwj2⏟from the prior.\underbrace{\text{NLL}(\mathbf{w})}_{\text{fit the data}} + \underbrace{\frac{1}{2\tau^2} \sum_j w_j^2}_{\text{from the prior}} .

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 τ\tau) 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 σ\sigma, and a normal prior of spread τ\tau on each weight. Leave the intercept without a prior. Up to constants, the negative log of the posterior is

12σ2∑i=1n(yi−y^i)2+12τ2∑jwj2.\frac{1}{2\sigma^2} \sum_{i=1}^{n} (y_i - \hat y_i)^2 + \frac{1}{2\tau^2} \sum_j w_j^2 .

Multiply through by 2σ2/n2\sigma^2 / n, which doesn't move the minimum:

MSE+σ2nτ2∑jwj2.\text{MSE} + \frac{\sigma^2}{n \tau^2} \sum_j w_j^2 .

That's the ridge loss from the regularisation lesson, MSE+λ2∑jwj2\text{MSE} + \tfrac{\lambda}{2}\sum_j w_j^2, with λ=2σ2/(nτ2)\lambda = 2\sigma^2/(n\tau^2). Read it back:

  • Noisier data (bigger σ\sigma) means a bigger penalty: trust the prior more.
  • More data (bigger nn) means a smaller penalty: the prior fades, as with the pretend deliveries.
  • A vaguer prior (bigger τ\tau) means a smaller penalty. As τ\tau 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, alog⁡p+blog⁡(1−p)a \log p + b \log(1 - p):

MAP with pretend deliveries
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.3
0.3571
0.35714285714285715

Gradient descent on the negative log-posterior lands on 5/145/14, the same as the formula. F.logsigmoid(z) gives log⁡p\log p and F.logsigmoid(-z) gives log⁡(1−p)\log(1 - p), straight from the logit zz. Neither rounds down to log⁡0\log 0 when pp gets close to 0 or 1.

Putting it together

Here is the lesson in one pass:

  1. Model the data: each delivery is late with chance pp, a Bernoulli outcome.
  2. Likelihood: the probability of the observed data, as a function of pp. For 3 late of 10, L(p)=p3(1−p)7L(p) = p^3(1 - p)^7.
  3. Maximum likelihood: pick the peak. Here p^=3/10\hat p = 3/10. In practice, minimise the negative log-likelihood, often by gradient descent.
  4. Familiar losses: for yes/no labels, the NLL is cross-entropy. For numbers with normal noise, it's the MSE plus a constant.
  5. Prior: pretend deliveries, 2 late and 2 on time. Posterior = prior × likelihood: the counts add up.
  6. MAP: the posterior's peak, 5/14≈0.3575/14 \approx 0.357. With few data it's steadier than the MLE; with many, the two agree.
  7. 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 pp doesn't have area 1. To talk about how probable each pp 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 a=b=0a = b = 0 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 pp, 0 with chance 1−p1 - p.
  • The likelihood L(θ)L(\theta) is the probability of the observed data under the parameters θ\theta. For independent examples it's a product, so we work with its log.
  • Maximum likelihood picks the parameters with the highest likelihood. For kk late out of nn, p^=k/n\hat p = k / n.
  • 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, (k+a)/(n+a+b)(k + a)/(n + a + b). 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.distributions Bernoulli and Normal with .log_prob, torch.sigmoid, F.logsigmoid, torch.inference_mode, F.binary_cross_entropy_with_logits, torch.linalg.lstsq and torch.optim.SGD and Adam.