Sign in

Likelihood and MLE

Likelihood and maximum likelihood estimation

Choosing the parameter values that make the observed data most probable, in closed form or by numerical search, with standard errors.

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

  1. Choose a model for the data: normal, Bernoulli, Poisson or exponential in this template.
  2. Write the likelihood: the product over all observations of the model's probability or density at that observation.
  3. 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.
  4. 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.
  5. When no formula exists, minimize the negative log-likelihood numerically. fit_numeric does this with the Nelder-Mead simplex search, which needs no gradients.
  6. 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 nn, not n−1n - 1, 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 p^=1\hat{p} = 1 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

IfUse instead
The sample is small or you have real prior knowledgeBayesian inference, with a prior and MAP or a full posterior
You cannot commit to a distribution familyNonparametric summaries such as quantiles, or a bootstrap
The data contain gross outliers that a normal likelihood would followA heavy-tailed likelihood, or treat outliers first

Math foundations

  1. The likelihood

    L(θ)=∏i=1np(xi∣θ)L(\theta) = \prod_{i=1}^{n} p(x_i \mid \theta)

    The probability of the whole data set under parameter θ\theta, assuming the observations are independent. The data are fixed and θ\theta is the variable.

  2. The log-likelihood

    ℓ(θ)=log⁡L(θ)=∑i=1nlog⁡p(xi∣θ)\ell(\theta) = \log L(\theta) = \sum_{i=1}^{n} \log p(x_i \mid \theta)

    The logarithm is increasing, so ℓ\ell and LL peak at the same θ\theta. Sums are easier to differentiate, and a product of thousands of small numbers would round to zero.

  3. The estimate

    θ^=arg⁡max⁡θ ℓ(θ),∂ℓ∂θ∣θ=θ^=0\hat{\theta} = \arg\max_{\theta}\ \ell(\theta), \qquad \left.\frac{\partial \ell}{\partial \theta}\right|_{\theta = \hat{\theta}} = 0

    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.

  4. Normal model

    μ^=1n∑i=1nxi,σ^2=1n∑i=1n(xi−μ^)2\hat{\mu} = \frac{1}{n}\sum_{i=1}^{n} x_i, \qquad \hat{\sigma}^{2} = \frac{1}{n}\sum_{i=1}^{n} (x_i - \hat{\mu})^{2}

    Solving the two slope equations gives the sample mean and the average squared deviation from it. Note the divisor nn.

  5. Bernoulli, Poisson and exponential models

    p^=sn,λ^Poisson=xˉ,λ^exp=1xˉ\hat{p} = \frac{s}{n}, \qquad \hat{\lambda}_{\text{Poisson}} = \bar{x}, \qquad \hat{\lambda}_{\text{exp}} = \frac{1}{\bar{x}}

    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.

  6. Fisher information and standard error

    I(θ)=− E ⁣[∂2∂θ2log⁡p(x∣θ)],se⁡(θ^)≈1n I(θ^)I(\theta) = -\,\mathbb{E}\!\left[\frac{\partial^{2}}{\partial \theta^{2}} \log p(x \mid \theta)\right], \qquad \operatorname{se}(\hat{\theta}) \approx \frac{1}{\sqrt{n\,I(\hat{\theta})}}

    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 p^(1−p^)/n\sqrt{\hat{p}(1-\hat{p})/n}.

  7. Likelihood ratio statistic

    Λ=2 [ℓ(θ^)−ℓ(θ0)]\Lambda = 2\,\big[\ell(\hat{\theta}) - \ell(\theta_0)\big]

    How much worse a proposed value θ0\theta_0 explains the data than the best value. It is zero at the estimate and grows as θ0\theta_0 moves away.

Symbols

xix_i
the ii-th observation
nn
the number of observations
θ\theta
the model parameter or parameters
θ^\hat{\theta}
the maximum likelihood estimate
L, ℓL,\ \ell
the likelihood and the log-likelihood
μ, σ\mu,\ \sigma
the mean and standard deviation of the normal model
pp
the Bernoulli success probability
ss
the number of successes
λ\lambda
the rate of the Poisson or exponential model
xˉ\bar{x}
the sample mean
I(θ)I(\theta)
the Fisher information of one observation
θ0\theta_0
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 p=0.5p = 0.5. Natural logs: ln⁡0.7=−0.3567\ln 0.7 = -0.3567, ln⁡0.3=−1.2040\ln 0.3 = -1.2040, ln⁡0.5=−0.6931\ln 0.5 = -0.6931.

ℓ(p)=7ln⁡p+3ln⁡(1−p)\ell(p) = 7 \ln p + 3 \ln (1 - p)
dℓdp=7p−31−p=0 ⟹ p^=710=0.7\frac{d\ell}{dp} = \frac{7}{p} - \frac{3}{1 - p} = 0 \ \Longrightarrow\ \hat{p} = \frac{7}{10} = 0.7
ℓ(0.7)=7×(−0.3567)+3×(−1.2040)=−6.109\ell(0.7) = 7 \times (-0.3567) + 3 \times (-1.2040) = -6.109
se⁡(p^)=0.7×0.310=0.021≈0.145\operatorname{se}(\hat{p}) = \sqrt{\frac{0.7 \times 0.3}{10}} = \sqrt{0.021} \approx 0.145
Λ=2 [−6.109−10×(−0.6931)]=2×0.823=1.646\Lambda = 2\,\big[-6.109 - 10 \times (-0.6931)\big] = 2 \times 0.823 = 1.646

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

  1. 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.

  2. The normal estimate of the variance divides by nn. 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.

  3. The exponential standard error is λ^/n\hat{\lambda} / \sqrt{n}. 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 nn only.

  4. 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.

  5. 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.