Level 3 In-Depth AI · Math Foundations
Maximum Likelihood Estimation
Maximum likelihood picks the model parameters that make the observed data most probable. It is the principle behind nearly every training loss — squared error and cross-entropy both fall straight out of it — including the loss that trains large language models.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 3 concepts before this one
- Probability Basics
- Derivatives and Slopes
- Probability Distributions
- Maximum Likelihood Estimation
Read them roughly in this order. See it on the concept map →
Why it matters
Every model in this guide is trained by minimising a loss: mean squared error for Linear Regression, cross-entropy for Logistic Regression, image classifiers and language models. Where do these losses come from? Why squared error and not, say, the fourth power of the error? Why the logarithm in cross-entropy?
The answer, for almost all of them, is one principle: maximum likelihood. Write down a probability model of how the data could have been generated. Then choose the parameters under which the data you actually saw is most probable. Turn that into a quantity to minimise and you get the familiar losses, not by convention but by derivation.
Knowing this pays off in practice:
- You understand what assumptions a loss makes, and when to change it. Squared error quietly assumes Gaussian noise, which is badly wrong when your data has outliers.
- You can read papers, where losses are usually written as "negative log-likelihood".
- You see that pretraining a language model — the most expensive computation in AI — is maximum likelihood on trillions of tokens of text.
The intuition
A friend flips a coin 10 times and gets 7 heads. Is the coin fair? What is your best guess for its probability of heads, ?
You'd probably say 0.7. Maximum likelihood explains why that is the natural answer. Consider each possible value of as a hypothesis and ask: if the coin's true chance of heads were , how probable would it be to see exactly the flips we saw?
- If , seeing 7 heads and 3 tails is fairly unlikely.
- If , you'd expect about 9 heads, so 3 tails is quite unlikely.
- If , the data looks just as you'd expect.
The value of that makes the observed data most probable is the maximum-likelihood estimate. It is a detective's principle: of all the possible explanations, prefer the one under which what actually happened was least surprising.
Key idea Maximum likelihood estimation chooses parameters that make the observed data as probable as possible. In practice you minimise the negative log-likelihood, and that quantity is the training loss: Gaussian noise gives squared error, and categorical outputs give cross-entropy.
How it works
The likelihood function
Write for the parameters (here, just ) and for the data. The likelihood is the probability of the data, viewed as a function of the parameters:
It's the same formula as a probability, but we now hold the data fixed and vary . For independent flips, the probability of the whole sequence is the product of the individual probabilities (see Probability Basics). Each head contributes and each tail , so for 7 heads and 3 tails, in any particular order:
Evaluate it at a few candidates:
| 0.5 | 0.000977 | −6.931 |
| 0.7 | 0.002224 | −6.109 |
| 0.9 | 0.000478 | −7.645 |
The likelihood is largest at . Note that the likelihood values are tiny and don't add up to 1 across . A likelihood is not a probability distribution over . It is only used to compare parameter values with each other.
Why take the logarithm
In practice we work with the log-likelihood, , for three reasons.
- The peak doesn't move. The logarithm always increases, so whatever maximises also maximises .
- Products become sums. , so . Sums are far easier to differentiate, and a sum over training examples is exactly what mini-batch Gradient Descent needs.
- No underflow. The likelihood of 10,000 flips is around , far below the smallest number a computer can store, so it becomes 0. Its logarithm, about , is perfectly manageable.
(Here and throughout ML, means the natural logarithm, .)
Finding the maximum with a derivative
At a peak the slope is zero (see Derivatives and Slopes). Differentiate the log-likelihood, using and the The Chain Rule for :
Set it to zero: , so , giving . In general, for heads in flips the maximum-likelihood estimate is , the observed fraction. The hat on marks an estimate.
For neural networks there's no neat formula, so we find the maximum numerically with gradient descent. By convention, optimisers minimise, so we flip the sign and minimise the negative log-likelihood (NLL), usually averaged over the training examples:
This is the training loss. Every loss in the rest of this chapter is a special case.
Fitting a Gaussian
Suppose your data are 7 measurements: , and you assume they come from a Gaussian with unknown mean and standard deviation . Which bell curve fits best? Compute the log-likelihood of the data under each candidate:
Working through the derivatives shows that the maximum-likelihood estimates are exactly the familiar sample statistics: is the sample mean (6.29 here) and is the sample standard deviation dividing by (1.29 here). So "take the average" is maximum likelihood for a Gaussian.
Squared error is maximum likelihood with Gaussian noise
Now a regression model predicts , for example a straight line . Assume each true value equals the prediction plus Gaussian noise with a fixed : . Using the Gaussian density formula, the negative log of one example's probability is
The second term doesn't depend on , and is just a positive scale. So minimising the NLL over all examples is the same as minimising
the sum of squared errors. Mean squared error is maximum likelihood under Gaussian noise. That's also why squared error reacts so badly to outliers: a Gaussian considers a point 10 standard deviations away to be almost impossible, so the fit bends hard to accommodate it. Assume a heavier-tailed noise distribution (the Laplace distribution) and maximum likelihood gives you the mean absolute error instead, which is far more robust (see Loss Functions).
Cross-entropy is maximum likelihood for classification
A classifier outputs a probability for each class, usually via softmax. If the correct class for example is and the model gives it probability , the likelihood of that label is just . The negative log-likelihood, averaged, is
This is the cross-entropy loss (the Entropy, Cross-Entropy and KL Divergence chapter explains the name). It rewards putting high probability on the right answer: if the model gives the correct class probability 0.8, the loss for that example is ; if it gives 0.1, the loss is ; if it gives 0.001, the loss is 6.91. Confident mistakes are punished heavily.
For two classes with the probability of class 1 and true label , this becomes the binary cross-entropy used in Logistic Regression:
which is just the coin-flip log-likelihood from the start of the chapter, with a different for each example.
| What you assume about the target | Negative log-likelihood is | Used for |
|---|---|---|
| Gaussian noise around the prediction | mean squared error | regression |
| Laplace (heavy-tailed) noise | mean absolute error | robust regression |
| Bernoulli (yes/no) | binary cross-entropy | two-class classification |
| Categorical (one of ) | cross-entropy | multi-class classification, next-token prediction |
Language models
A language model assigns a probability to the next token given the previous ones. The probability of a whole training text is the product of those conditional probabilities (the chain rule of probability from Probability Basics). Its negative log is a sum of per-token cross-entropies. So pretraining GPT-style models is maximum likelihood estimation: adjust billions of parameters to make the training text as probable as possible. The loss curves in papers about Pretraining Large Language Models and Scaling Laws are curves of average negative log-likelihood per token.
Adding a prior: MAP estimation
Maximum likelihood trusts the data completely. With 3 flips that all came up heads, it says : the coin can never land tails. That's overconfident, and it's an example of Overfitting and the Bias–Variance Tradeoff.
Bayes' theorem suggests a fix: combine the likelihood with a prior belief about the parameters, and maximise the posterior instead. This is maximum a posteriori (MAP) estimation:
( means "the value of that makes this largest".) A beautiful connection appears for neural networks. If the prior says weights are probably small, a Gaussian centred on zero, then is proportional to . Minimising "NLL + " is exactly L2 Regularization: L1 and L2, also called weight decay. A Laplace prior gives L1 regularisation instead. Regularisation is a prior in disguise.
In code
import numpy as np
# Coin: 7 heads in 10 flips. Likelihood of each candidate p.
heads, flips = 7, 10
for p in [0.5, 0.7, 0.9]:
L = p**heads * (1 - p)**(flips - heads)
print(p, round(L, 6), round(np.log(L), 3))
# 0.5 0.000977 -6.931
# 0.7 0.002224 -6.109
# 0.9 0.000478 -7.645
grid = np.linspace(0.001, 0.999, 999)
loglik = heads * np.log(grid) + (flips - heads) * np.log(1 - grid)
print(grid[loglik.argmax()].round(3)) # 0.7 the maximum-likelihood estimate
# Why logs: the likelihood of 10,000 flips underflows to zero
print(0.7**7000 * 0.3**3000, 7000 * np.log(0.7) + 3000 * np.log(0.3))
# 0.0 -6108.643020548936
# Gaussian: the MLE of the mean and sd are the sample mean and (divide-by-n) sd
x = np.array([4.2, 5.1, 5.8, 6.3, 6.9, 7.4, 8.3])
def gauss_loglik(x, mu, sigma):
return np.sum(-0.5 * np.log(2 * np.pi * sigma**2) - (x - mu)**2 / (2 * sigma**2))
print(x.mean().round(3), x.std().round(3)) # 6.286 1.291
for mu, s in [(x.mean(), x.std()), (5.0, x.std()), (x.mean(), 3.0)]:
print(round(mu, 2), round(s, 2), round(gauss_loglik(x, mu, s), 3))
# 6.29 1.29 -11.721 <- the best
# 5.0 1.29 -15.192
# 6.29 3.0 -14.771
In PyTorch, the standard losses are negative log-likelihoods. Here we check that cross_entropy equals minus the log-softmax probability of the right class, then fit the coin by gradient descent on its NLL:
import torch
import torch.nn.functional as F
logits = torch.tensor([[2.0, 1.0, 0.1]]) # model scores for 3 classes
target = torch.tensor([0]) # the correct class is 0
nll = -torch.log_softmax(logits, dim=1)[0, 0]
print(nll, F.cross_entropy(logits, target)) # tensor(0.4170) tensor(0.4170) the same
# Fitting a coin by gradient descent on the negative log-likelihood
flips = torch.tensor([1., 1., 0., 1., 1., 1., 0., 1., 0., 1.]) # 7 heads
z = torch.zeros(1, requires_grad=True) # p = sigmoid(z) keeps p between 0 and 1
opt = torch.optim.SGD([z], lr=0.5)
for step in range(200):
loss = F.binary_cross_entropy_with_logits(z.expand(10), flips) # mean NLL
opt.zero_grad(); loss.backward(); opt.step()
print(torch.sigmoid(z).item()) # 0.699999988079071
Gradient descent finds the same answer as the formula , which is reassuring: training a neural network is this, at scale.
Common pitfalls
- Overconfidence with little data. Maximum likelihood gives probability 0 to anything not seen in training. A word that never appeared gets probability 0, and the log-likelihood of any text containing it becomes . Use smoothing, priors (MAP) or regularisation (see Naive Bayes for Laplace smoothing).
- The wrong noise model. Squared error assumes Gaussian noise with constant spread. With outliers, skewed targets or noise that grows with the value, it fits poorly. Choose the loss from the data, not by habit.
- Computing probabilities, then logs.
torch.log(torch.softmax(x))can produce-infwhen a probability underflows to 0. Uselog_softmaxorcross_entropyon raw logits, which compute the logarithm safely. - Confusing likelihood with probability of the parameters. does not mean "there is a 0.2% chance that ". For that you need a prior and Bayes' Theorem.
- Maximum likelihood can overfit. With enough parameters, a model can make the training data almost certain and still predict new data badly. Always measure NLL on held-out data (see Overfitting and the Bias–Variance Tradeoff).
Watch out A model trained by maximum likelihood learns to reproduce the training distribution, including its errors, biases and gaps. A language model maximising likelihood on web text becomes good at producing likely web text, not at being truthful. That is a key reason language models also need Instruction Tuning and Chat Models and RLHF and Preference Optimization, and why they can hallucinate.
Where it leads
- Entropy, Cross-Entropy and KL Divergence: cross-entropy, KL divergence and perplexity give another view of the same loss.
- Loss Functions: the full menu of losses, most of them negative log-likelihoods.
- Linear Regression and Logistic Regression: maximum likelihood with Gaussian and Bernoulli noise.
- Regularization: L1 and L2: L2 and L1 penalties as Gaussian and Laplace priors.
- Language Modeling and Next-Token Prediction and Pretraining Large Language Models: maximum likelihood on next tokens, at enormous scale.
- Variational autoencoders and Diffusion Models: generative models trained by maximising (a bound on) likelihood.
A bit of history
Fitting parameters by making data probable has roots in work by Daniel Bernoulli, Johann Heinrich Lambert and Joseph-Louis Lagrange in the 18th century, and Carl Friedrich Gauss showed in 1809 that least squares is what you get by assuming Gaussian errors. The general method, and the name "likelihood", come from Ronald Fisher, who developed them between 1912 and 1922 and proved many of their good properties, such as consistency: with enough data, the estimate converges to the truth. Fisher was careful to distinguish likelihood from probability. Since the 1980s, maximum likelihood has been the default way to train neural networks, and since 2018 it has been the objective behind the pretraining of every major language model.
Try it
- A die is rolled 60 times, giving a six 15 times. What is the maximum-likelihood estimate of the probability of a six? Write the log-likelihood and set its derivative to zero.
- Show by hand that if a model gives the correct class probability 1/2, 1/4 or 1/8, the cross-entropy loss is , or . What pattern do you see?
- In the PyTorch coin example, add an L2 penalty
0.1 * z**2to the loss. Where does the estimate end up now, and why? Try 3 flips that are all heads, with and without the penalty.Hint for 1: the log-likelihood is , which is maximised at .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Deep Learning: Foundations and Concepts
A rigorous modern textbook from the author of the classic Pattern Recognition and Machine Learning. Free to read online.
Stanford CS229: Machine Learning
The classic mathematically rigorous ML course. Lecture notes and recorded lectures are free online.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/maximum-likelihood.md