Overview
A model with a parameter assigns a probability to any data set. Turn that around: hold the data fixed and ask how probable they would have been under each possible parameter value. That function of the parameter is the likelihood. Maximum likelihood estimation picks the value at its peak, the one under which what you saw is least surprising. A sharp peak means the data pin the parameter down well, and a flat one means many values explain the data almost equally. The sharpness is measured by the Fisher information, and it gives the standard error of the estimate.
A short history
Ronald Fisher introduced the method in papers from 1912 to 1922, and his 1922 paper "On the mathematical foundations of theoretical statistics" named the likelihood and set out its properties. It answered the question of how to choose parameter values in a principled way for any model. Fisher showed the estimates are consistent and efficient in large samples, and the method became the default way to fit statistical models.
How it works
- Choose a model for the data: normal, Bernoulli, Poisson or exponential in this template.
- Write the likelihood: the product over all observations of the model's probability or density at that observation.
- Take the logarithm. The product becomes a sum, which is easier to differentiate and does not underflow, and the peak stays in the same place.
- Set the derivative with respect to each parameter to zero and solve. For these four models the answer is a simple formula, returned by fit.
- When no formula exists, minimize the negative log-likelihood numerically. fit_numeric does this with the Nelder-Mead simplex search, which needs no gradients.
- Get a standard error for each estimate from the curvature of the log-likelihood at its peak.
Watch out for
- The likelihood is not a probability distribution over the parameter. It need not integrate to 1, and reading it as the chance that the parameter has some value needs a prior.
- The maximum likelihood standard deviation divides by , not , so it is biased low. The difference matters for small samples.
- With little data the estimate can sit on a boundary. Three successes in three trials give and a standard error of zero, which is plainly too confident.
- The standard errors are large-sample approximations. They assume the model is correct and the sample is big enough for the log-likelihood to be nearly quadratic at its peak.
- Nelder-Mead can stop at a local peak or run out of iterations on hard problems. Compare fit_numeric with fit where a closed form exists.
Use cases
When to use it
Fitting any probabilistic model to data. Least squares, logistic regression and cross-entropy training of neural networks are all maximum likelihood under a particular model.
In industry
- Machine learning
- Logistic regression and neural classifiers are fitted by maximising the likelihood of the labels, which is the same as minimising cross-entropy.
- Reliability engineering
- Engineers fit Weibull or exponential lifetime models to failure times by maximum likelihood to predict warranty returns.
- Finance
- Risk teams fit volatility models such as GARCH to return series by maximising the likelihood with a numerical optimiser.
Choosing it: what must hold
- A parametric model: a named distribution family whose density or mass function you can write down.
- Observations that are independent given the parameters, or a model that states their dependence.
- Enough data for the large-sample properties to hold. Small samples can give biased or extreme estimates.
- A likelihood you can maximise, in closed form or with a numerical optimiser.
When to choose something else
| If | Use instead |
|---|---|
| The sample is small or you have real prior knowledge | Bayesian inference, with a prior and MAP or a full posterior |
| You cannot commit to a distribution family | Nonparametric summaries such as quantiles, or a bootstrap |
| The data contain gross outliers that a normal likelihood would follow | A heavy-tailed likelihood, or treat outliers first |
Math foundations
The likelihood
The probability of the whole data set under parameter , assuming the observations are independent. The data are fixed and is the variable.
The log-likelihood
The logarithm is increasing, so and peak at the same . Sums are easier to differentiate, and a product of thousands of small numbers would round to zero.
The estimate
The maximum likelihood estimate is the parameter at the peak. At an interior peak the slope of the log-likelihood is zero, which gives an equation to solve.
Normal model
Solving the two slope equations gives the sample mean and the average squared deviation from it. Note the divisor .
Bernoulli, Poisson and exponential models
The success fraction, the average count, and one over the average waiting time. In each case the estimate matches the model's mean to the sample mean.
Fisher information and standard error
The information is the expected curvature of the log density for one observation. More curvature means a sharper peak and a smaller standard error. For the Bernoulli model this gives .
Likelihood ratio statistic
How much worse a proposed value explains the data than the best value. It is zero at the estimate and grows as moves away.
Symbols
- the -th observation
- the number of observations
- the model parameter or parameters
- the maximum likelihood estimate
- the likelihood and the log-likelihood
- the mean and standard deviation of the normal model
- the Bernoulli success probability
- the number of successes
- the rate of the Poisson or exponential model
- the sample mean
- the Fisher information of one observation
- a proposed parameter value to compare with the estimate
Worked by hand
Ten Bernoulli trials give 7 successes. Write the log-likelihood, find its peak, and compare it with the value at . Natural logs: , , .
The estimate is 0.7 with a standard error of about 0.145. A fair coin explains the data only a little worse, with a likelihood ratio statistic of 1.65, so ten tosses cannot rule it out.
Visual example
Loading the example.
Try this
- Slide μ toward 2 and watch the stems grow and the log-likelihood rise.
- Press Jump to the estimate, then make σ too small: a few observations in the tails pull the total down sharply.
- Raise n to 60 and see the curve of ℓ(μ) become narrower.
Code sample
import numpy as np
from impl import LikelihoodMLE
from config import LikelihoodMLEConfig
data = np.random.default_rng(0).normal(5.0, 2.0, size=1000)
mle = LikelihoodMLE(LikelihoodMLEConfig(distribution="normal"))
est = mle.fit(data) # {"mean": about 5, "std": about 2}
mle.fit_numeric(data) # the same numbers, found by search
mle.log_likelihood(data, est) # the highest value any parameters can reach
mle.standard_errors(data) # {"mean": std / sqrt(n), "std": std / sqrt(2n)}Read the implementation (164 lines)
"""Likelihood and maximum likelihood estimation.
For normal, Bernoulli, Poisson and exponential models: the log-likelihood of data under given parameters, the
closed-form maximum likelihood estimate, the same estimate found numerically with a Nelder-Mead search (the
route to take when no closed form exists), and standard errors from the Fisher information.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import LikelihoodMLEConfig
except ImportError: # run from the template's own folder
from config import LikelihoodMLEConfig
_lgamma = np.vectorize(math.lgamma, otypes=[float])
def nelder_mead(func, x0, max_iter: int = 500, tolerance: float = 1e-12, step: float = 0.5):
"""Minimize func: array (d,) -> float with the Nelder-Mead simplex method. No gradients needed.
x0: starting point, array (d,).
step: size of the initial simplex around x0.
Returns (x_best array (d,), f_best, iterations used).
"""
x0 = np.atleast_1d(np.asarray(x0, dtype=float))
d = x0.size
simplex = np.vstack([x0] + [x0 + step * np.eye(d)[i] for i in range(d)])
values = np.array([func(p) for p in simplex])
iteration = 0
for iteration in range(1, max_iter + 1):
order = np.argsort(values)
simplex, values = simplex[order], values[order]
if abs(values[-1] - values[0]) < tolerance and np.abs(simplex[1:] - simplex[0]).max() < 1e-7:
break
centroid = simplex[:-1].mean(axis=0)
reflected = centroid + (centroid - simplex[-1])
f_reflected = func(reflected)
if f_reflected < values[0]:
expanded = centroid + 2.0 * (centroid - simplex[-1])
f_expanded = func(expanded)
simplex[-1], values[-1] = (expanded, f_expanded) if f_expanded < f_reflected else (reflected, f_reflected)
elif f_reflected < values[-2]:
simplex[-1], values[-1] = reflected, f_reflected
else:
contracted = centroid + 0.5 * (simplex[-1] - centroid)
f_contracted = func(contracted)
if f_contracted < values[-1]:
simplex[-1], values[-1] = contracted, f_contracted
else: # shrink everything toward the best point
simplex[1:] = simplex[0] + 0.5 * (simplex[1:] - simplex[0])
values[1:] = [func(p) for p in simplex[1:]]
best = int(np.argmin(values))
return simplex[best], float(values[best]), iteration
def _xlogy(x: float, y: float) -> float:
"""x * log(y) with 0 * log(0) = 0."""
if x == 0:
return 0.0
return -math.inf if y <= 0 else x * math.log(y)
class LikelihoodMLE:
"""Log-likelihood and maximum likelihood fit of one distribution.
Parameters are passed and returned as dicts:
normal {"mean", "std"}
bernoulli {"p"}
poisson {"rate"}
exponential {"rate"}
"""
def __init__(self, config: LikelihoodMLEConfig | None = None) -> None:
self.config = config or LikelihoodMLEConfig()
def _data(self, data) -> np.ndarray:
x = np.asarray(data, dtype=float).ravel()
if x.size == 0:
raise ValueError("data is empty")
d = self.config.distribution
if d == "bernoulli" and np.any((x != 0) & (x != 1)):
raise ValueError("Bernoulli data must be 0 or 1")
if d == "poisson" and (np.any(x < 0) or np.any(x != np.round(x))):
raise ValueError("Poisson data must be non-negative whole numbers")
if d == "exponential" and np.any(x < 0):
raise ValueError("exponential data must be non-negative")
return x
def log_likelihood(self, data, params: dict) -> float:
"""Sum over the data, array (n,), of log p(x_i | params)."""
x = self._data(data)
n, d = x.size, self.config.distribution
if d == "normal":
mean, std = params["mean"], params["std"]
if std <= 0:
return -math.inf
return float(-0.5 * n * math.log(2 * math.pi * std**2) - ((x - mean) ** 2).sum() / (2 * std**2))
if d == "bernoulli":
p = params["p"]
if not 0 <= p <= 1:
return -math.inf
return _xlogy(x.sum(), p) + _xlogy(n - x.sum(), 1 - p)
rate = params["rate"]
if rate <= 0:
return -math.inf
if d == "poisson":
return float(x.sum() * math.log(rate) - n * rate - _lgamma(x + 1).sum())
return float(n * math.log(rate) - rate * x.sum())
def fit(self, data) -> dict:
"""Closed-form maximum likelihood estimate."""
x = self._data(data)
d = self.config.distribution
if d == "normal":
return {"mean": float(x.mean()), "std": float(x.std())} # std divides by n: the MLE, not the unbiased one
if d == "bernoulli":
return {"p": float(x.mean())}
if d == "poisson":
return {"rate": float(x.mean())}
if x.mean() == 0:
raise ValueError("all observations are zero, the exponential rate is unbounded")
return {"rate": float(1.0 / x.mean())}
def _unpack(self, theta: np.ndarray) -> dict:
"""Map unconstrained optimizer coordinates to valid parameters."""
d = self.config.distribution
if d == "normal":
return {"mean": float(theta[0]), "std": float(math.exp(min(theta[1], 700.0)))}
if d == "bernoulli":
return {"p": float(1.0 / (1.0 + math.exp(-max(min(theta[0], 700.0), -700.0))))}
return {"rate": float(math.exp(min(theta[0], 700.0)))}
def fit_numeric(self, data) -> dict:
"""Maximum likelihood estimate found by minimizing the mean negative log-likelihood with Nelder-Mead.
The search runs in unconstrained coordinates (log std, logit p, log rate) so every trial point is valid.
"""
x = self._data(data)
start = np.array([float(np.median(x)), 0.0]) if self.config.distribution == "normal" else np.zeros(1)
def loss(theta: np.ndarray) -> float:
return -self.log_likelihood(x, self._unpack(theta)) / x.size
theta, _, _ = nelder_mead(loss, start, self.config.max_iter, self.config.tolerance)
return self._unpack(theta)
def standard_errors(self, data) -> dict:
"""Asymptotic standard error of each estimate: 1 / sqrt(n * Fisher information) at the MLE."""
x = self._data(data)
n, est, d = x.size, self.fit(x), self.config.distribution
if d == "normal":
return {"mean": est["std"] / math.sqrt(n), "std": est["std"] / math.sqrt(2 * n)}
if d == "bernoulli":
return {"p": math.sqrt(est["p"] * (1 - est["p"]) / n)}
if d == "poisson":
return {"rate": math.sqrt(est["rate"] / n)}
return {"rate": est["rate"] / math.sqrt(n)}
def likelihood_ratio(self, data, params: dict) -> float:
"""2 * (log L at the MLE - log L at params): 0 at the MLE, larger the worse `params` explains the data."""
return 2.0 * (self.log_likelihood(data, self.fit(data)) - self.log_likelihood(data, params))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create LikelihoodMLE with LikelihoodMLEConfig(distribution="bernoulli") and seven ones and three zeros. Call fit, fit_numeric, standard_errors and likelihood_ratio with {"p": 0.5} to reproduce the worked example. Then switch to the normal model on a sample you draw with numpy and compare the returned std with numpy's std using ddof=1.
Check on learning
- Why does taking the logarithm not change which parameter is best, and what would go wrong numerically without it for 10000 observations?
A way to think about it
A function that always increases keeps the order of its inputs. Then estimate the size of a product of 10000 numbers that are each below 1.
- The normal estimate of the variance divides by . Why is it too small on average?
A way to think about it
The deviations are measured from the sample mean, which is by construction the point closest to the data. Compare with deviations from the true mean.
- The exponential standard error is . What does it say about the relative precision of a rate estimate, and how many observations give 10% precision?
A way to think about it
Divide the standard error by the estimate. The rate itself cancels, leaving a function of only.
- fit_numeric searches over log std and logit p, not std and p directly. What problem does that solve?
A way to think about it
The search can step anywhere on the real line. Ask what the log-likelihood would do at a negative standard deviation or a probability of 1.2.
- Minimizing squared error in regression is maximum likelihood under a specific noise model. Which one, and what would change if the noise had heavy tails?
A way to think about it
Write the normal log density and look at the term that depends on the prediction. Then think about how much one extreme outlier pulls a squared penalty.