So far the chances have been given: a fair coin, a die, a weighted spinner. In practice it runs the other way round. You have the data, ten tosses or a million sentences, and you need the setting that produced it: the coin's p, or the billions of numbers inside a language model. Maximum likelihood is the rule almost every model is trained by: choose the setting under which the data you actually saw is least surprising. For a coin it gives the obvious answer, 7 heads in 10 means p = 0.7, but the same rule, applied to a network's predictions, is exactly what a training loop does. The loss a classifier or a language model minimizes, the negative log-likelihood, is this lesson's quantity with a minus sign. And the log is not decoration: without it, the probability of a long text rounds to 0 in any computer.
What you'll be able to do
Compute the likelihood of some data for a given setting: the product of each observation's probability
Take its log to turn the product into a sum, and find the setting that makes the data most likely
Search a grid of settings with np.argmax, plot the log-likelihood, and see why a product of many chances underflows while a sum of logs doesn't
Recognize training as maximum likelihood: minimizing the negative log-likelihood, the loss classifiers and language models use, in NumPy and with PyTorch's F.nll_loss
Quick check
Have a guess before you start. A coin lands heads 7 times in 10 tosses. Which value of p, the chance of heads, best explains that?
1
0.7
0.9
0.5
Show the answer
0.7
Of all the values of p, 0.7 gives this record the highest probability. Maximum likelihood makes the guess exact.
The math: the setting that makes the data least surprising
Purpose. Choose a model's setting from the data it should explain.
Likelihood. For a coin with chance p of heads, the record H H T has probability p × p × (1 − p): the tosses are independent, so their chances multiply (lesson 89). Read as a function of p, with the data fixed, this is the likelihood L(p). For the record of 10 tosses with 7 heads and 3 tails:
p
L(p) = p⁷(1 − p)³
0.5
0.000977
0.7
0.002224
0.9
0.000478
All three are small, because any one exact sequence of 10 tosses is unlikely. What matters is the comparison: p = 0.7 makes this record more than twice as likely as a fair coin does. Maximum likelihood picks the p with the largest L(p).
Quick check
From lesson 25: what is log(a × b)?
log(a + b)
log a × log b
a log b
log a + log b
Show the answer
log a + log b
Logs turn products into sums. That's the move that makes likelihoods workable.
Take the log. Because log turns products into sums, the log-likelihood is a sum: one log per observation. Since log only grows, the p that maximizes log L is the same p that maximizes L.
The picture. Step through the 10 tosses at p = 0.7, as boxes of numbers and as a drawing of log L for every p from 0 to 1 at once. Each toss adds its log at every p together, so the curve sinks a little with each one: a head pulls it down most on the left, where p is small, and a tail most on the right. The dot rides the curve at p = 0.7, holding the running total of the logs in the boxes. The ring marks the curve's top: the p that explains the tosses so far best.
Try it now
Then set chance p to 0.5 and press Use these numbers, then try 0.9. The curve stays the same and the dot slides down its side: both totals come out lower (−6.93 and −7.65), so 0.7 explains the record best.
Symbols and formula. For observations x₁ to xₙ and a setting θ (here θ = p):
In plain words: the likelihood multiplies each observation's chance under the setting; its log adds their logs; the best setting, θ̂ ("theta hat"), is the one with the largest total.
Why exactly 0.7? Module 5 answers it. For h heads and t tails, log L = h log p + t log(1 − p). Its slope is h/p − t/(1 − p) (lesson 73: the slope of log p is 1/p). Setting the slope to 0 gives p = h/(h + t) = 7/10: the picture's ring, where the curve is flat at its top. The maximum-likelihood estimate of a chance is just its share in the data, which is what lesson 88 did by counting.
Quick check
With p = 0.5, what is the likelihood of the record H H T?
0.125
0.5
0.25
1.5
Show the answer
0.125
0.5 × 0.5 × 0.5 = 0.125: every toss has chance 0.5 whatever it shows.
In your own words
The last ladder problem gave p = 1 from 5 heads in 5 tosses. Why might you not trust that estimate?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: search a grid of settings
Purpose. Find the best setting by computing the log-likelihood for many candidates and taking the largest.
It runs right here in your browser, with nothing to install.
np.linspace(0.01, 0.99, 99) lists the candidates 0.01, 0.02, up to 0.99. One line computes all 99 log-likelihoods at once, and np.argmax gives the position of the largest, whose p is 0.7: the formula's answer, found by search. Real models have millions of settings, too many for a grid, so they climb the log-likelihood by gradient steps instead (lesson 79), but the target is the same.
Code flow.np.argmax hides a small loop. Here it is written out on five candidates, 0.5 to 0.9: one line works out all five log-likelihoods, and the loop walks along them, keeping the position of the best so far. That's all np.argmax does. Step through and watch best change each time the loop meets a higher value.
A named mistake: multiplying many chances. A text of 1,100 words where each word had chance 0.5 has likelihood 0.5¹¹⁰⁰, about 10⁻³³¹. The smallest positive number a standard float can hold is about 10⁻³²⁴, so the product underflows to exactly 0.0, and every setting looks equally bad. The log-likelihood is 1,100 × log 0.5 = −762.5, an ordinary number. Always add logs; never multiply raw chances over a long sequence.
Worked example
Worked example: the best p for three coin records
Three coins were tossed different numbers of times. Find each one's maximum-likelihood p by grid search, and compare with the share of heads.
import numpy as np
ps = np.linspace(0.01, 0.99, 99)
heads = [7, 2, 45]
tosses = [10, 8, 50]
for i inrange(3):
h = heads[i]
t = tosses[i] - h
ll = h * np.log(ps) + t * np.log(1 - ps)
print(h, "of", tosses[i], "->", round(float(ps[np.argmax(ll)]), 2), round(h / tosses[i], 2))
In the lesson you can change this and run it.
Each grid search lands on the share of heads: 0.7, 0.25 and 0.9. The search didn't know the formula; it only compared log-likelihoods. That's the point of the method: for a coin the answer is obvious, but the same search, or gradient descent on the same quantity, works for settings with no formula at all, like the weights of a network.
0.5¹¹⁰⁰ is far below the smallest float, so it underflows to 0.0. The sum of its logs is an ordinary −762.5.
The curve in a plot. The 99 log-likelihoods from the first cell make a curve: the one the math part's picture ended on after the tenth toss. Draw it with the Matplotlib lines from lesson 19:
import numpy as np
import matplotlib.pyplot as plt
ps = np.linspace(0.01, 0.99, 99)
ll = 7 * np.log(ps) + 3 * np.log(1 - ps)
plt.plot(ps, ll)
plt.xlabel("p, the chance of heads")
plt.ylabel("log-likelihood of 7 heads, 3 tails")
plt.show()
The top is at 0.7, where the search landed. The two sides don't fall away alike, and the counts say why.
Quick check
Read the plot. Which end of the curve falls lower, and why?
The right end: a large p makes the 3 tails unlikely, and tails count more
Both ends stop at −1, the lowest a log of a chance can go
The left end: with 7 heads, a small p makes each head very unlikely
Neither: the curve is the same on both sides of p = 0.5
Show the answer
The left end: with 7 heads, a small p makes each head very unlikely
Each of the 7 heads adds log p, which plunges as p shrinks; the 3 tails add log(1 − p), which plunges only near p = 1. Seven falling terms beat three, so the left end drops further, and the top sits on the heads' side, at 0.7.
Drill
The best p by grid search
Write best_p(h, t) that searches the 99 candidates in ps and returns the p with the largest log-likelihood for h heads and t tails, rounded to 2 places. Then set best to the results for 6 heads and 4 tails, and for 1 head and 9 tails.
import numpy as np
ps = np.linspace(0.01, 0.99, 99)
defbest_p(h, t):
ll = h * np.log(ps) + t * np.log(1 - ps)
return0
best = [best_p(6, 4), best_p(1, 9)]
print(best)
In the lesson, your code is checked as you write it.
In your own words
The grid had 99 candidates. What goes wrong if the true best value isn't on the grid, and how would you fix it?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: training is maximum likelihood
Purpose. See that the loss a classifier or language model minimizes is a negative log-likelihood.
A language model gives a probability to each next word. Over a training text, the likelihood of its settings is the product of the probabilities it gave the words that actually came next, and the log-likelihood is their sum of logs. Training maximizes it. Optimizers are written to go downhill, so the sign is flipped: the negative log-likelihood (NLL), −Σ log P(right word), is minimized instead. Same top, seen from below. Divided by the number of words, it's the average loss printed during training.
The camp-log model of lesson 88 was already a maximum-likelihood model. After "the", its log had "fire" 3 times, "tent" once and "trail" once, so the model gives them chances 0.6, 0.2 and 0.2: the shares, exactly as 7/10 was the share of heads. Score those chances on the five times "the" came up, beside two other settings. targets holds the word that really came next each time (0 for fire, 1 for tent, 2 for trail), and p[targets] picks the chance the model gave it:
import numpy as np
targets = np.array([0, 1, 0, 2, 0])
for p in [np.array([0.6, 0.2, 0.2]), np.array([1, 1, 1]) / 3, np.array([0.8, 0.1, 0.1])]:
nll = -np.log(p[targets])
print(p.round(2).tolist(), round(float(nll.mean()), 4))
The shares give the lowest average NLL, 0.9503. Even chances give 1.0986, and leaning harder on "fire" gives 1.0549. Maximum likelihood and the smallest loss pick the same setting: the shares in the data.
Quick check
A training loop maximizes the log-likelihood of the data. What does it minimize instead, in practice?
The negative log-likelihood
The likelihood itself
The number of parameters
The probability of the right answer
Show the answer
The negative log-likelihood
Flipping the sign turns a top into a bottom, and optimizers are built to go downhill.
In PyTorch. The same loss in the real tool, two ways. First the formula itself: p[targets] picks each right answer's chance, -torch.log turns it into a surprise, and .mean() averages. Second, PyTorch's own loss, F.nll_loss. It takes log-chances, one row per prediction, and the position of each right answer. The camp-log model gives the same row every time it sees "the", so .repeat(5, 1) copies that row five times, one per use.
import torch
import torch.nn.functional as F
p = torch.tensor([0.6, 0.2, 0.2])
targets = torch.tensor([0, 1, 0, 2, 0])
print(round((-torch.log(p[targets])).mean().item(), 4))
logp = torch.log(p).repeat(5, 1)
print(logp.shape, round(F.nll_loss(logp, targets).item(), 4))
Both give 0.9503, the average the NumPy cell printed for the shares. A real classifier's last layer gives scores, not chances; F.cross_entropy turns them into log-chances and then does exactly what F.nll_loss does, as lesson 105 shows.
The NLL adds −log of each chance: 0.511 + 0.693 + 1.609 = 2.813. Averaged over the 3 answers, 0.938: the per-word loss.
A whole text. On four sentences from its own log, "the fire was warm", "the tent was dry", "the trail was long" and "the fire died", the camp-log model predicts 11 words, with chances like 0.6 for "fire" after "the" and 1/3 for "warm" after "was". Their NLL is 9.73, or 0.88 per word: the drill below works it out. And on a sentence with a word it never saw after "the", like "stove", its probability is 0 and the NLL is infinite: the reason real models never give any word exactly zero chance.
Drill
The camp-log model's loss
Each inner list holds the chances the camp-log model gave the words of one sentence. Set nll to the negative log-likelihood of all four sentences together and per_word to it divided by the number of words, both rounded to 4 places.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write