A coin lands heads, heads, tails. Is it fair? Nobody can know for sure from three flips, but some biases explain the result better than others. A coin that lands heads times in is not strange, and a coin that is heads only of the time would rarely give this result. Is there a rule that picks the best bias, and does the same rule also fit a bell curve to data, a line to points, or a language model to text?
There is, and it is called maximum likelihood. Earlier lessons planted three seeds. P1.D2 multiplied densities at observed values, P1.D3 said that the negative log of a probability is a loss function, and P1.D5 wrote the probability of i.i.d. data as a product. This lesson combines them: choose the parameters that make the data you saw as probable as possible.
Data, a model family and the likelihood
Three ingredients are needed.
- Data: observed values , assumed i.i.d. (P1.D5).
- A model family: a distribution with a formula and some unknown parameters . For a coin, is the probability of heads. For a Gaussian (P1.D3), .
- A question: which is best?
The formula can be read in two ways. With fixed and free, it is a distribution that says how likely each outcome is. With the data fixed and free, it is a function that says how well each parameter value explains what was seen. That second reading is the likelihood:
The product comes from independence (P1.D5). Notation. Many books write or for the likelihood. This course already uses and for a loss (one example and the average), so the likelihood is written , the log-likelihood and the negative log-likelihood .
| Probability | Likelihood | |
|---|---|---|
| parameters | fixed | vary |
| data | vary over outcomes | fixed (observed) |
| adds up to over | the outcomes | nothing in general |
P1.D2 already computed two likelihoods. A fair die that shows gives . Waiting times and under the exponential density with give . For continuous data this product is a product of densities, so it is not itself a probability, but it can still be compared between parameter values for the same data. Try : the product is , lower than , so explains these two waits better than . The best rate turns out to be , with likelihood (a Go-deeper box below derives it).
The coin has the same structure. After H, H, T, each candidate bias gives the data the probability :
The likelihood rises and then falls, with its top near . The next section shows that is exactly the best.
The coin: from a picture to a formula
Suppose of flips are heads. For any order of flips, the likelihood of the whole sequence is a product of factors and factors :
(If only the count of heads is recorded, the binomial formula of P1.D3 adds a factor . It does not depend on , so it does not move the peak.) Use the widget to see the shape before doing any algebra.
What to try:
- H, H, T. The peak is at . The likelihood there is , and at the fair-coin value it is .
- More data. Switch between in and in : the peak stays at but the bump gets much narrower. At the likelihood is of the peak with flips and of the peak with flips. More data rules out more biases.
- Three heads in three. The peak is at the edge, . Keep that in mind: it is the first warning sign of this lesson.
- The area. For H, H, T the area under the curve is , not .
That last point is worth a pause. For a fixed , the likelihoods of all possible sequences add up to (they are probabilities of outcomes). For fixed data, the likelihood over all adds up to something else. The likelihood is not a probability distribution over , and “the likelihood of is ” does not mean “ has probability ”. It means: if the bias were , the data would have had probability .
Finding the peak with calculus
Take the log first (the next section explains why that is allowed):
At a maximum the derivative is zero (P1.C1, P1.C2):
Multiply through by : , so and
The hat means “estimate”. This is a maximum, not a minimum, because the second derivative is negative (the curve bends downward everywhere). For H, H, T, . The estimate is the fraction of heads, which is what intuition says. Maximum likelihood is a principle that gives the obvious answer here and a useful answer where intuition fails.
Why the log?
Almost nobody maximizes the likelihood itself. They maximize its logarithm, the log-likelihood
for three reasons, the first two from P1.A2 and P1.A3.
- The maximizer does not change. The log is an increasing function, so a bigger likelihood always has a bigger log. Whichever wins on one wins on the other. For the coin, have likelihoods and log-likelihoods : the same ranking.
- A product becomes a sum. Sums are far easier to differentiate than products: the derivative of a sum is the sum of the derivatives, one small piece per example. The coin derivative above would have been a mess without it.
- Products underflow. A computer stores a float with a smallest positive value of about . Multiply probabilities of and the true product, , is rounded to
0.0. The sum of the logs is , an ordinary number. (When probabilities have to be added inside a log, as in a mixture, the stable trick is log-sum-exp, P1.G2.)
The log-likelihood of probabilities is never positive, since when . For densities, which can exceed (P1.D2), a log-likelihood can be positive. Its size also changes if the data are measured in different units, so compare log-likelihoods only for the same data.
The recipe, and the negative log-likelihood
Everything in this lesson follows one recipe.
- Choose a model family .
- Write the likelihood and take its log.
- Find the that maximizes it: set the gradient to zero (P1.C5) if you can solve that, or climb numerically if you cannot.
- Check that it is a maximum, not a minimum or a saddle.
The answer is the maximum-likelihood estimate (MLE):
The negative log-likelihood is . Optimization software minimizes, so a loss is written as an NLL, and minimizing it is the same as maximizing the likelihood. Because the NLL of examples grows with , training usually uses the average NLL, . This is the number a framework reports as “the loss”: by default PyTorch’s cross-entropy losses average over the examples. Dividing by is a positive constant, so it does not change the argmax. A loss written as in this course is such an average.
One more fact is used all the time. If is the MLE of , then is the MLE of for a one-to-one function (such as the square root of the variance): the MLE of a standard deviation is the square root of the MLE of the variance.
A Gaussian: slide it over the data
Now a model with two parameters. The data are real numbers and the family is the Gaussian (P1.D3). Each data point gets a bar: the height of the curve above it. The likelihood is the product of the bars, and the log-likelihood is the sum of the logs of the bars. Slide the curve until that sum is as large as it can be.
What to try, with the six points :
- Slide μ. Start with . The log-likelihood is a downward parabola in with its top exactly at the sample mean . At it is .
- Slide σ. Keep . Too narrow () and the points far from the centre get almost no density: the log-likelihood is and the likelihood is . Too wide () and every bar is low: . The top is at , where the log-likelihood is .
- The two buttons. “Best μ (keep σ)” always lands on , whatever σ is. “Best σ (keep μ)” changes with μ: if the centre is off, the best spread is larger, because the curve must cover the distance to the points.
- The outlier. Replacing by moves the best centre from to and the best from to . One point drags both estimates, because the Gaussian likelihood penalizes distance squared.
- Two clusters. The best Gaussian is centred at , between the clusters, with the huge spread . Maximum likelihood finds the best member of the family you chose, even when the family is a bad description. (A model with two humps, centred at and with spread and half the weight each, does far better: log-likelihood against , P3.C2.)
- All equal. The six values are all . Centre the curve at and shrink : the log-likelihood keeps growing, so there is no best . The next section explains why, and the slider stops at .
The derivation
Write the log-likelihood of the Gaussian by taking the log of each factor and adding:
The partial derivatives (P1.C4) are set to zero one at a time. For :
The factor cancels, so the best centre is the sample mean for every (the pink line in the widget). For , put back in and differentiate:
For these two equations the critical point is the global maximum, as the widget’s picture suggests (a rigorous check uses the second derivatives). For the six points, , so and . At that point the bars are , , , , and , with logs , , , , and , which add to . (In general , and the average NLL here is .)
This is the variance. Maximum likelihood divides the sum of squares by , not by . P1.D4 showed that dividing by (Bessel’s correction) gives an unbiased estimate of . The version is biased low: averaged over many data sets of size , it equals , which is of the truth for (a simulation in the code section gives for a true variance of ). The estimator is still consistent (it homes in on as grows), and the two versions agree for large . Maximum likelihood does not promise unbiasedness. NumPy’s np.var divides by , so it is the MLE; np.var(x, ddof=1) divides by .
Several dimensions. For vectors, maximum likelihood with the multivariate Gaussian of P1.D7 gives the sample mean vector and the covariance matrix with the factor, (the proof uses matrix calculus, P1.C11). For the five students of P1.D7 it gives covariance and variances instead of the covariance and variances , and the correlation is still .
A categorical variable: counts over
A die, a spam filter that sorts email into three folders, or one step of a language model: the outcome is one of classes with probabilities that add to (the categorical distribution of P1.D3). If class occurred times in observations, the likelihood is and the log-likelihood is . The maximum, with , is
The best probabilities are the observed frequencies. Ten rolls of a die that show give and a log-likelihood of , higher than the of the fair die for the same data. The coin is the case . A Go-deeper box proves the result without calculus.
Go deeper Poisson counts and exponential waiting times
Two more one-line derivations, both of the same recipe. For counts from a Poisson distribution (P1.D3), , so and gives : the rate is the average count. For counts it is .
For waiting times from the exponential density , , and gives . For the waits and the mean is , so and the likelihood is , a little above the of in the first section.
Go deeper Why counts over N is the maximum for a categorical variable
Let be the observed frequencies, with every (a class with contributes nothing to the log-likelihood, so every sum below runs over the classes with , and over those classes still gives a result of at most ). For any probabilities that add to , write for the gain over . Then
The inequality uses for every , with equality only at . So no beats , and only ties. The quantity is , minus the KL divergence of P1.E4. Maximum likelihood for a categorical variable is minimizing the KL divergence from the observed frequencies to the model, and KL is never negative.
From likelihood to loss functions
In supervised learning each example is a pair , and the model says how likely each target is given the input. With i.i.d. pairs the likelihood is . The inputs’ own distribution does not depend on and drops out of the argmax. So
Every standard loss is this sum for a particular choice of . P1.D3 previewed three of them. Here they are derived.
Gaussian noise gives mean squared error
Suppose the target is a prediction plus noise, with and noise with a fixed . Then and one example’s negative log density is
With , and this is , the number from P1.D3. Summing over examples:
The second term does not depend on , and is a positive constant, so minimizing the NLL is minimizing the sum of squared errors, which is minimizing the mean squared error (P3.A2). With fixed, the chosen does not even change the best predictions. If is also fitted, the Gaussian result above applies: is the mean squared error of the best fit.
For three examples with and , the per-example losses are . The total is and the average is with . (Setting to a constant for every example gives the Gaussian fit of the previous section: the best is the mean. If the noise were Laplace instead, with density proportional to , the same steps give the absolute error.)
Bernoulli outputs give binary cross-entropy
For a yes-or-no label the model outputs , the probability that (a sigmoid output, P1.A5). The probability of the observed label is , so the NLL of one example is
This is binary cross-entropy. For labels and predictions the model gives the truth the probabilities . The likelihood of the labels is , the NLL is , and the average is : the number from P1.D3. The three losses are , and , which add to . (A confident wrong answer costs much more: if the model says and the label is , the truth gets and the loss is .) Fitting the parameters is P3.A7.
Categorical outputs give cross-entropy
For one of classes the model outputs probabilities (softmax, P3.A8). The probability of the observed class is , so the loss is
where is the one-hot label (the sum has a single nonzero term). This is cross-entropy. For with the true class first it is . Only the probability given to the true class matters.
Language models. A text is a sequence of tokens. The probability of the whole text is a product over positions of the next-token probabilities, , which is the chain rule of P1.D5. The NLL of a text is the sum of the per-token cross-entropies, and pretraining a language model is maximum likelihood: the reported loss is the average NLL per token (P10.A1). Its exponential is the perplexity (P1.E5): an average NLL of per token means the model is, on average, as unsure as if it were choosing among equally likely tokens.
| output and model (loss name, lesson) | NLL of one example |
|---|---|
| real number, Gaussian with fixed (squared error, P3.A2) | + constant |
| yes or no, Bernoulli (binary cross-entropy, P3.A7) | |
| one of classes, categorical (cross-entropy, P3.A8) | |
| next token, categorical over the vocabulary (P10.A1) |
When there is no formula
The coin and the Gaussian can be solved with a pencil. Logistic regression cannot: setting the gradient of the NLL to zero has no closed-form solution. The same holds for every neural network. The remedy is gradient descent on the average NLL (P1.F3): compute the gradient, step downhill, repeat. For binary cross-entropy the gradient with respect to the pre-sigmoid score has the pleasant form (for and it is , so the step increases the score), and for softmax cross-entropy it is the vector . The code section runs gradient descent on the coin’s NLL and arrives at .
What maximum likelihood can get wrong
Maximum likelihood is the default, not the whole story. Each of these points has a precise condition.
- Small data and the edge of the range. After heads in flips, : the model says tails is impossible. A fourth flip that lands tails would have likelihood and an infinite loss, . A coin that is only heads would still give three heads half the time (). A prior belief fixes this, which is MAP estimation (P1.D11): maximize . Adding one imagined head and one imagined tail gives here, and a prior that prefers small weights acts like the L2 penalty (P3.A6). The same problem appears whenever a class or word is never seen in the data (smoothing in naive Bayes, P3.B2).
- A bias in small samples. The variance is too small on average. For it is (a single point has no spread), and the likelihood is then unbounded, as in the “All equal” widget set.
- A wrong family. Maximum likelihood gives the best parameters inside the family. It does not say the family is right. The two-cluster data get a perfectly good Gaussian fit, and a poor description. Check the fit (histograms, held-out data, P3.A4).
- Sensitivity to the likelihood’s shape. A Gaussian puts a squared penalty on distance, so a single outlier drags the fit, as the widget showed. Heavier-tailed noise models give robust losses.
- The model must be identifiable. If two parameter values give exactly the same distribution, several tie. For only the sum matters, and swapping two hidden units of a neural network (with their weights) gives the same function. The MLE is then not unique, which is harmless for predictions and awkward for interpreting parameters.
- No closed form, many peaks. Beyond simple models the NLL must be minimized numerically, and for neural networks (P1.F2) the landscape has many valleys.
- Dependent data. The product assumes independence. Time series or duplicated data break it. The likelihood is still right if written with the chain rule, , which is how language models avoid the assumption.
- The likelihood is not the probability of the parameters. The MLE is the parameter that makes the data most probable. It is not the most probable parameter given the data. They agree when the prior is flat (see P1.D11).
Go deeper Consistency, asymptotic normality and the spread of an estimate
Under regularity conditions (the data really come from some in the family, different parameters give different distributions, the likelihood is smooth, and is not on the edge of the allowed range), the MLE has two good properties as grows. It is consistent: in probability. And it is asymptotically normal: for one parameter, approaches a Gaussian with variance , where is the Fisher information, . It measures how sharply the log-likelihood curves at the peak.
For the coin, , so the spread of is about . That is the standard error of an average of results from P1.D8, since is such an average. For heads in it is . This matches the width of the bump in the coin widget: the likelihood falls to half its peak over a width of about standard deviations, . These are statements about large and a correct model. They do not apply to a wrong family or to a few data points.
Go deeper Maximum likelihood is minimizing a KL divergence
Let be the true distribution that generated the data. As grows, the average NLL approaches an expectation (the law of large numbers, P1.D8):
The middle expression is the cross-entropy of relative to (P1.E3), and is the entropy (P1.E2), which does not involve . So minimizing the average NLL is minimizing (P1.E4), the divergence from the data’s distribution to the model’s. For a finite data set the statement is exact with the observed frequencies in place of , as the categorical box showed. This is why the classification loss is called cross-entropy.
Go deeper A likelihood with no maximum: the Gaussian mixture
Fit a mixture of two Gaussians (P3.C2) to the six points: half the weight on a Gaussian centred on the first point with spread , half on a Gaussian with and . The density at is at least , which grows without bound as , while the other points are still covered by the second Gaussian. The log-likelihood is for , and it keeps rising like . So the likelihood has no maximum: it can be made as large as you like by putting a spike on one data point. The practical fixes are to limit how small a variance may become, or to add a prior (P1.D11). The single Gaussian in the widget’s “All equal” set shows the same effect in its simplest form.
Try it: maximum likelihood in code
The first cell finds the coin and Gaussian estimates by brute force on a grid and compares them with the formulas, shows the product underflowing while the sum of logs works, and checks that binary cross-entropy is the NLL divided by . The second cell fits the coin by gradient descent on the average NLL, simulates the bias of the variance, and shows the mixture likelihood growing without limit. Predict first: will the grid search for land on or on the value ?
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first block prints for the coin (the grid has no , and the likelihoods at are ). The grid and the formulas agree on and with log-likelihood , while ddof=1 gives . The product of a thousand s prints 0.0 and the sum of logs is . The binary cross-entropy is , and the likelihood has the log . Challenge: change [1, 1, 0] to [1, 1, 1] and find which wins (the largest value on the grid, , because the true peak is at the edge).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The gradient-descent run moves from through and to , and the average NLL falls from to its minimum , which is . The variance simulation prints about for the estimates and about for the estimates (the exact values depend on the random numbers). The mixture’s log-likelihood climbs from to and would keep climbing. Challenge: change the gradient-descent step size to . The estimate then bounces between about and and never settles, because the step is too large for the curvature (P1.F3).
Intuition, math and code at a glance
Intuition
The likelihood asks, for each possible setting of the parameters, “how surprised would this model be by the data I actually saw?” A good setting is rarely surprised. Maximum likelihood picks the least surprised model. Taking logs turns a product of probabilities into a sum of surprises, (P1.E1), so the loss is the total surprise.
Math
The likelihood, log-likelihood and estimate:
Closed forms:
- coin:
- Gaussian: and
- categorical:
Losses from :
- Gaussian:
- Bernoulli:
- categorical:
Code
Compute a Gaussian’s maximum-likelihood fit and its log-likelihood with NumPy.
import numpy as np
x = np.array([2, 3, 3.5, 4.5, 5, 6.0])
mu, sigma = x.mean(), x.std() # np.std divides by N: the MLE
ll = np.sum(-np.log(sigma * np.sqrt(2 * np.pi)) - (x - mu) ** 2 / (2 * sigma ** 2))
print(mu, sigma, ll) # 4.0, 1.3229, -10.1925Common mistakes
Check your understanding
A coin lands heads times in flips. What is the maximum-likelihood estimate of the probability of heads?
Setting the derivative of to zero gives . The value is the fair-coin guess that ignores the data. The value adds one imagined head and one imagined tail, a smoothing that belongs to MAP estimation, not to maximum likelihood. The value is the fraction of tails.
Why do we maximize the log-likelihood instead of the likelihood?
The log is increasing, so the maximizer is the same, and products of many small numbers become sums of moderate numbers. A different maximizer would mean a different estimate, which is not what the log does. The log of a likelihood is not a distribution over the parameters. The log of a probability is at most , so it never makes a likelihood larger than .
After heads in flips, maximum likelihood gives . What goes wrong?
At the likelihood of the three heads is , its largest possible value, and the model gives tails probability , so any later tail gets likelihood and loss . The likelihood at is not . The problem is overconfidence from too little data, not a technical bias. The likelihood is perfectly well defined at .
A model predicts and the targets are with Gaussian noise of a fixed . Maximizing the likelihood of the data over the model’s parameters is the same as minimizing which quantity?
The negative log of the Gaussian density is plus a constant, so the total is a positive multiple of the sum of squared errors plus a constant. Absolute errors come from Laplace noise. Counting mistakes is the zero-one loss, which has no such link. A product of errors can be zero or negative and does not appear in the NLL.
A classifier gives the true class the probabilities , and on three examples. What is the average negative log-likelihood (the cross-entropy loss)?
The three losses are , and , and their average is . The value is the negative log of the average probability, which takes the log in the wrong place. The value is the total NLL, the negative log of the product , before dividing by . The value is the average probability, not a loss.
Exercises
- A coin gives heads in flips. Write and , find , and compare the likelihood at with the likelihood at .
Show answer
and . Setting gives . The likelihood at is and at it is , a ratio of . The log-likelihoods are and . - Find the maximum-likelihood Gaussian for the data , and compare with the standard deviation.
Show answer
. The squared distances are , adding to . So and . The version is . - Waiting times are and . Find the maximum-likelihood rate of an exponential model, and the likelihood there.
Show answer
, and . - A call center counts calls in four hours. What is the maximum-likelihood Poisson rate per hour?
Show answer
The sample mean, . - Of emails, are ordinary, are spam and are other. What does maximum likelihood say about the three class probabilities?
Show answer
The observed frequencies, . - A model gives probability to each of independent examples. What is the log-likelihood, the average NLL, and why can the product not be stored?
Show answer
and the average NLL is . The product is about , far below the smallest positive float, about , so it would be stored as . - For , find the total NLL of a Gaussian with , and the per-example loss of an error of when .
Show answer
The errors are and , so the sum of is and the total is . With and an error of : . - A language model gives three tokens the probabilities and . Find the average NLL per token and the perplexity.
Show answer
The NLLs are , adding to . The average is and the perplexity is . - A coin gives heads in flips. What does maximum likelihood estimate, what does add-one smoothing estimate, and why is the second safer?
Show answer
. Adding one imagined head and one imagined tail gives . The first says tails is impossible (a tail later has likelihood and infinite loss), and the second never gives a probability of exactly or . P1.D11 shows that this is MAP estimation with a particular prior. - Compare heads in flips with in : the standard error of the estimate, and the likelihood at as a fraction of the peak.
Show answer
The standard errors are and . At the likelihood is of the peak for flips and for flips. More data narrows the bump and rules out more biases. - Show that for a Gaussian with known and unknown , maximizing the likelihood is the same as minimizing .
Show answer
The only part of the log-likelihood that depends on is , and is positive. Maximizing the negative of a positive multiple of a sum is minimizing the sum. Setting its derivative to zero gives . - Why is the likelihood not a valid probability distribution over , and what is needed to get one?
Show answer
For fixed data, nothing forces it to add up (or integrate) to over : for H, H, T the integral is . A distribution over needs a prior and Bayes’ theorem (P1.D6), whose posterior is proportional to likelihood times prior.
Next: P1.D11 adds a prior to the likelihood (MAP estimation) and shows how it repairs the small-data problem and acts like regularization. P1.E3 and P1.E4 look at cross-entropy and the KL divergence on their own, P1.F3 uses gradient descent to minimize an NLL that has no formula, and P3.A2, P3.A7 and P3.A8 build regression and classification on the losses derived here.