◆ AI All-in-One

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
↗ Plan a path here

Read first

Probability DistributionsDerivatives and Slopes

This leads to

—
The full path from zero — 3 concepts before this one
  1. Probability Basics
  2. Derivatives and Slopes
  3. Probability Distributions
  4. 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, pp?

You'd probably say 0.7. Maximum likelihood explains why that is the natural answer. Consider each possible value of pp as a hypothesis and ask: if the coin's true chance of heads were pp, how probable would it be to see exactly the flips we saw?

  • If p=0.5p = 0.5, seeing 7 heads and 3 tails is fairly unlikely.
  • If p=0.9p = 0.9, you'd expect about 9 heads, so 3 tails is quite unlikely.
  • If p=0.7p = 0.7, the data looks just as you'd expect.

The value of pp 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 θ\theta for the parameters (here, just pp) and DD for the data. The likelihood is the probability of the data, viewed as a function of the parameters:

L(θ)=P(D∣θ)L(\theta) = P(D \mid \theta)

It's the same formula as a probability, but we now hold the data fixed and vary θ\theta. For independent flips, the probability of the whole sequence is the product of the individual probabilities (see Probability Basics). Each head contributes pp and each tail 1−p1 - p, so for 7 heads and 3 tails, in any particular order:

L(p)=p7(1−p)3L(p) = p^7 (1 - p)^3

Evaluate it at a few candidates:

pp L(p)=p7(1−p)3L(p) = p^7 (1-p)^3 log⁡L(p)\log L(p)
0.5 0.000977 −6.931
0.7 0.002224 −6.109
0.9 0.000478 −7.645

The likelihood is largest at p=0.7p = 0.7. Note that the likelihood values are tiny and don't add up to 1 across pp. A likelihood is not a probability distribution over θ\theta. It is only used to compare parameter values with each other.

Likelihood L(p) = p⁷ (1 − p)³ probability of the 10 flips seen 0 0.5 1 candidate p (chance of heads) 0.00098 max 0.00222 at p = 0.7 0.00048 Log-likelihood log L(p) same peak, but a sum instead of a product 0 0.5 1 candidate p (chance of heads) −6.93 −6.11 −7.65
Fig. 1 Left: the likelihood L(p) = p⁷(1 − p)³ for 7 heads in 10 flips, peaking at p = 0.7. Right: its logarithm, which has its peak at exactly the same place but turns the product into a sum.

Why take the logarithm

In practice we work with the log-likelihood, log⁡L(θ)\log L(\theta), for three reasons.

  1. The peak doesn't move. The logarithm always increases, so whatever maximises LL also maximises log⁡L\log L.
  2. Products become sums. log⁡(ab)=log⁡a+log⁡b\log(ab) = \log a + \log b, so log⁡L(p)=7log⁡p+3log⁡(1−p)\log L(p) = 7 \log p + 3 \log(1 - p). Sums are far easier to differentiate, and a sum over training examples is exactly what mini-batch Gradient Descent needs.
  3. No underflow. The likelihood of 10,000 flips is around 10−265310^{-2653}, far below the smallest number a computer can store, so it becomes 0. Its logarithm, about −6,109-6{,}109, is perfectly manageable.

(Here and throughout ML, log⁡\log means the natural logarithm, ln⁡\ln.)

Finding the maximum with a derivative

At a peak the slope is zero (see Derivatives and Slopes). Differentiate the log-likelihood, using ddplog⁡p=1p\frac{d}{dp}\log p = \frac{1}{p} and the The Chain Rule for log⁡(1−p)\log(1-p):

ddp[7log⁡p+3log⁡(1−p)]=7p−31−p\frac{d}{dp}\big[7 \log p + 3 \log(1 - p)\big] = \frac{7}{p} - \frac{3}{1 - p}

Set it to zero: 7p=31−p\frac{7}{p} = \frac{3}{1 - p}, so 7(1−p)=3p7(1 - p) = 3p, giving p=0.7p = 0.7. In general, for hh heads in nn flips the maximum-likelihood estimate is p^=h/n\hat{p} = h / n, the observed fraction. The hat on p^\hat{p} 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 NN training examples:

NLL(θ)=−1N∑i=1Nlog⁡P(examplei∣θ)\text{NLL}(\theta) = -\frac{1}{N} \sum_{i=1}^{N} \log P(\text{example}_i \mid \theta)

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: 4.2,5.1,5.8,6.3,6.9,7.4,8.34.2, 5.1, 5.8, 6.3, 6.9, 7.4, 8.3, and you assume they come from a Gaussian with unknown mean μ\mu and standard deviation σ\sigma. Which bell curve fits best? Compute the log-likelihood of the data under each candidate:

0 2 4 6 8 10 12 Which bell curve makes the 7 data points most probable? blue dots: the data; each curve is a candidate Gaussian log-likelihood μ = 5.0, σ = 1.29 −15.19 μ = 6.29, σ = 3.0 −14.77 μ = 6.29, σ = 1.29 −11.72 ← best Best: μ = sample mean, σ = sample sd
Fig. 2 Seven data points and three candidate Gaussians. One centred too far left (log-likelihood −15.19), one too wide (−14.77), and one centred on the sample mean with the sample standard deviation (−11.72), which makes the data most probable.

Working through the derivatives shows that the maximum-likelihood estimates are exactly the familiar sample statistics: μ^\hat{\mu} is the sample mean (6.29 here) and σ^\hat{\sigma} is the sample standard deviation dividing by nn (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 y^i=f(xi;θ)\hat{y}_i = f(x_i; \theta), for example a straight line wxi+bwx_i + b. Assume each true value equals the prediction plus Gaussian noise with a fixed σ\sigma: yi∼N(y^i,σ2)y_i \sim \mathcal{N}(\hat{y}_i, \sigma^2). Using the Gaussian density formula, the negative log of one example's probability is

−log⁡p(yi∣xi,θ)=(yi−y^i)22σ2+12log⁡(2πσ2)-\log p(y_i \mid x_i, \theta) = \frac{(y_i - \hat{y}_i)^2}{2\sigma^2} + \frac{1}{2}\log(2\pi\sigma^2)

The second term doesn't depend on θ\theta, and 2σ22\sigma^2 is just a positive scale. So minimising the NLL over all examples is the same as minimising

∑i(yi−y^i)2\sum_{i} (y_i - \hat{y}_i)^2

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 ii is cic_i and the model gives it probability p^i,ci\hat{p}_{i,c_i}, the likelihood of that label is just p^i,ci\hat{p}_{i,c_i}. The negative log-likelihood, averaged, is

L=−1N∑i=1Nlog⁡p^i, ciL = -\frac{1}{N} \sum_{i=1}^{N} \log \hat{p}_{i,\,c_i}

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 −log⁡0.8=0.22-\log 0.8 = 0.22; if it gives 0.1, the loss is −log⁡0.1=2.30-\log 0.1 = 2.30; if it gives 0.001, the loss is 6.91. Confident mistakes are punished heavily.

For two classes with p^\hat{p} the probability of class 1 and true label y∈{0,1}y \in \{0, 1\}, this becomes the binary cross-entropy used in Logistic Regression:

−[ ylog⁡p^+(1−y)log⁡(1−p^) ]-\big[\, y \log \hat{p} + (1 - y) \log (1 - \hat{p}) \,\big]

which is just the coin-flip log-likelihood from the start of the chapter, with a different p^\hat{p} 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 kk) 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 p^=1\hat{p} = 1: 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:

θ^MAP=arg⁡max⁡θ[log⁡P(D∣θ)+log⁡P(θ)]\hat{\theta}_{\text{MAP}} = \arg\max_\theta \big[ \log P(D \mid \theta) + \log P(\theta) \big]

(arg⁡max⁡\arg\max means "the value of θ\theta 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 −log⁡P(θ)-\log P(\theta) is proportional to ∑jθj2\sum_j \theta_j^2. Minimising "NLL + λ∑jθj2\lambda \sum_j \theta_j^2" 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 h/nh / n, 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 −∞-\infty. 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 -inf when a probability underflows to 0. Use log_softmax or cross_entropy on raw logits, which compute the logarithm safely.
  • Confusing likelihood with probability of the parameters. L(0.7)=0.0022L(0.7) = 0.0022 does not mean "there is a 0.2% chance that p=0.7p = 0.7". 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

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

  1. 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.
  2. Show by hand that if a model gives the correct class probability 1/2, 1/4 or 1/8, the cross-entropy loss is log⁡2\log 2, 2log⁡22\log 2 or 3log⁡23\log 2. What pattern do you see?
  3. In the PyTorch coin example, add an L2 penalty 0.1 * z**2 to 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 15log⁡p+45log⁡(1−p)15 \log p + 45 \log(1 - p), which is maximised at p=15/60=0.25p = 15/60 = 0.25.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A die is rolled 60 times and shows a six 15 times. What is the maximum-likelihood estimate of the probability of a six?

  2. Why do we maximise the log-likelihood rather than the likelihood itself?

  3. You train a regression model with mean squared error. Which assumption are you implicitly making?

  4. A classifier gives the correct class probability 0.001 on one example. How does its cross-entropy loss on that example compare to giving it 0.8?

  5. You add a penalty λ Σ θ² to the negative log-likelihood. In maximum-likelihood terms, what have you done?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Deep Learning: Foundations and Concepts

Christopher & Hugh Bishop · 2024 · Advanced · Free

A rigorous modern textbook from the author of the classic Pattern Recognition and Machine Learning. Free to read online.

Course

Stanford CS229: Machine Learning

Stanford University · Advanced · Free

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