Likelihood functions
似然函数
Compare parameters for fixed observations, calculate log-likelihood ratios, and keep support and parameter transformations straight.
likelihoodKeep the observations still; move the parameter
You observe the binary sequence 1,1,0,1. Suppose each observation is an independent trial with the same success probability . Would or assign more probability to this particular sequence? The two answers are and . Their ratio is 1.3824. The data favor the first parameter in this likelihood comparison. If these are two discrete hypotheses with equal positive prior probabilities, the ratio also equals their posterior odds. Under a continuous prior, individual parameter points have probability zero; density ratios in a fixed coordinate system must be distinguished from odds for discrete hypotheses.
A likelihood function holds the observed data fixed and varies the model parameter. It uses the same numerical expression as a probability model, with a different question attached. The distribution asks which observations can appear under a chosen parameter; the likelihood asks how that already observed record compares under different parameters. MML, Section 8.3.1 develops this distinction through a conditional prediction model.
A function of parameters is not automatically a distribution over them
Let be the observed data and a possible parameter. Write
For discrete data, is a probability mass function; for continuous data it is a density with respect to a specified common data measure. The latter is not the probability of an exact continuous observation, which is typically zero. For example, one observation under a uniform density on gives likelihood 2. A density, and therefore a continuous-data likelihood, can exceed one. MIT’s Lecture 2 defines the discrete and continuous cases explicitly.
Normalization is over possible data, separately for every parameter. There is no requirement that the likelihood integrate or sum to one over . In the opening example,
Normalizing that expression over would produce a posterior for a uniform prior in this particular coordinate system. It is an added modeling choice. In general, a prior density gives
provided the denominator is finite and positive. This is the step that turns a likelihood and a prior into a parameter distribution; MML, Sections 8.3.2 and 8.4.2 separates it from parameter estimation.
When observations are independent conditional on , their joint likelihood factors. The familiar repeated-factor form additionally assumes the same observation distribution:
Independent but differently distributed observations can still be multiplied using their respective densities. For dependent observations, the chain rule instead gives . Copying one measurement twice does not create two independent contributions. The product-to-sum derivation is given in MML, equations 8.16–8.17.
For a Bernoulli sequence containing successes in trials, this becomes . If the observed object is only the count, the probability includes the number of compatible sequences:
For fixed , the coefficient is independent of , so both experiments give the same likelihood ratios between parameter values. Their raw likelihoods and log-likelihoods differ. In the opening example the multiplier is four. This follows by enumerating the four positions of the single failure, and agrees with the binomial construction in MML, Example 6.9.
Parameter-independent positive factors cancel in a likelihood ratio, so they can be omitted for that specific comparison. Factors depending on the parameter cannot. Consider nonnegative observations from a uniform distribution with unknown endpoint , using a density that includes its upper endpoint. With ,
The indicator is zero when the proposed interval cannot contain the data. Dropping it would make impossible parameters appear attractive. At , the included-endpoint version reaches its maximum at . If the chosen density excludes the endpoint, the condition becomes and the same supremum is approached but never attained. These density versions define the same sampling distribution for each fixed parameter, yet pointwise likelihood optimization is sensitive to their boundary convention. MIT Lecture 2, pages 7–9 discusses exactly this qualification. If all observations are zero, is outside the parameter space and the density is unbounded as decreases to zero. Solving a derivative equation would miss these cases.
Calculate evidence ratios without multiplying tiny numbers
This complete Python example evaluates Bernoulli log-likelihoods for either an ordered sequence summarized by counts or a binomial count, and uniform log-likelihoods with an explicit boundary convention. It does not search for an estimate. An impossible observation gives negative infinity, the logarithm of zero; malformed arguments raise an error.
import math
def bernoulli_loglik(h, n, p, *, counted=False):
if type(h) is not int or type(n) is not int or not 0 <= h <= n <= 1_000_000:
raise ValueError("integer counts with 0 <= h <= n <= 1000000 required")
if not math.isfinite(p) or not 0 <= p <= 1:
raise ValueError("a finite probability in [0,1] required")
if p == 0:
value = 0.0 if h == 0 else -math.inf
elif p == 1:
value = 0.0 if h == n else -math.inf
else:
value = h*math.log(p) + (n-h)*math.log1p(-p)
if counted:
value += math.lgamma(n+1)-math.lgamma(h+1)-math.lgamma(n-h+1)
return value
def uniform_loglik(data, theta, *, closed=True):
x = tuple(float(v) for v in data)
if not x or any(not math.isfinite(v) or v < 0 for v in x):
raise ValueError("nonempty finite nonnegative data required")
if not math.isfinite(theta) or theta <= 0:
raise ValueError("a finite positive upper endpoint required")
maximum = max(x)
if maximum > theta or (not closed and maximum == theta):
return -math.inf
return -len(x)*math.log(theta)
a = bernoulli_loglik(3, 4, 0.6)
b = bernoulli_loglik(3, 4, 0.5)
assert math.isclose(math.exp(a-b), 1.3824)
assert math.isclose(bernoulli_loglik(3, 4, 0.6, counted=True)-a, math.log(4))
assert bernoulli_loglik(0, 4, 0) == 0
assert bernoulli_loglik(1, 4, 0) == -math.inf
assert bernoulli_loglik(0, 0, 1) == 0
assert uniform_loglik((0.2, 0.8), 0.7) == -math.inf
assert math.isfinite(uniform_loglik((0.2, 0.8), 0.8))
assert uniform_loglik((0.2, 0.8), 0.8, closed=False) == -math.inf
print(round(math.exp(a-b), 4), round(uniform_loglik((0.2, 0.8), 1.0), 4))
It prints 1.3824 0.0. The empty Bernoulli sample has likelihood one and log-likelihood zero at every valid parameter. Boundary branches avoid evaluating expressions such as . The uniform function instead requires at least one observation because it uses a maximum.
Counting a binary sequence initially takes time. Once are available, each Bernoulli parameter evaluation takes arithmetic and space, treating library calls as fixed cost. The one-million-trial ceiling is a teaching implementation limit. The uniform evaluator takes time and space as written; storing only the count and maximum would allow streaming in constant extra space. Log Gamma avoids explicitly constructing a large binomial coefficient, but subtracting its terms still introduces rounding error. Very large log-ratios can overflow when exponentiated; keep the result as a log-ratio when necessary.
Check which quantity is changing
A one-to-one parameter change simply relabels the likelihood:
There is no Jacobian factor because no probability mass over parameters is being transformed. For Bernoulli , use on the interior. Evaluating the likelihood at or at its corresponding must give the same value.
A prior or posterior density over those parameters does transform with a Jacobian. For example, the uniform prior on becomes a density on , evaluated at . Thus “normalize the likelihood” depends on which parameter is declared uniform. Probability-preserving density transformations are used by Stan’s parameter transforms when sampling in unconstrained coordinates; that operation must not be confused with relabeling a likelihood.
Changing the observed data’s units is a third operation. Densities then acquire the data-transformation Jacobian. If the transform is one-to-one and independent of the parameter, this factor cancels from parameter likelihood ratios for the same observation. Raw density values from different units or different observed objects are not directly comparable scores.
A high likelihood also cannot establish that the model family is correct. Misspecified dependence, ignored censoring, or selecting only successful records changes the observation model. For censored data, the contribution may be an interval or tail probability rather than the density at a fabricated exact value. Good arithmetic must follow a description of how the record was produced.
Experiments and exercises
- For the sequence 1,1,0,1, compare with . Then retain only the number of successes. Does the ratio change? Answer: it is in both cases. The count likelihoods are four times the sequence likelihoods, and the factor cancels.
- A single observed success gives . Is determined by the likelihood alone? Answer: no. A uniform prior yields density and probability , but a Beta(1,2) prior yields posterior Beta(2,2), with probability . Both use the same likelihood.
- With uniform-model observations , compare endpoints , , and . Answer: under the included-endpoint density, their likelihoods are , , and . With the excluded endpoint, the value at is zero and values just above it approach 1.5625. State the convention before claiming an attained maximum.
- Transform a Bernoulli parameter to log-odds. Should you multiply its likelihood by ? Answer: no; evaluate the original likelihood at the corresponding . That factor is required when transforming a density on into a density on log-odds, such as a prior or posterior, because .
What this function supports next
Maximum likelihood estimation asks where this function is largest and under what conditions the estimate behaves well. Likelihood-ratio tests ask whether competing parameter restrictions fit differently enough to reject one under a specified sampling model. Bayesian inference combines the same likelihood with a prior, while posterior prediction integrates over the resulting uncertainty. These methods share a likelihood without making it a posterior, a significance level, or a guarantee of predictive accuracy.
Make a prediction, then check
How does a Bernoulli likelihood change when p is replaced by log-odds η?
Learning objectives
- Compare parameters with fixed data and distinguish likelihood, data density and posterior.
- Derive log-likelihoods for independent observations and explain equal parameter ratios for sequences and counts.
- Retain parameter-dependent support and distinguish likelihood reparameterization from probability-density transformation.
Prerequisites & connections
- Conditional probability
- Independence and conditional independence
- Bernoulli and binomial distributions
References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - Statistics for Applications — Lecture 2: Maximum Likelihood Estimators
Dmitry Panchenko; MIT OpenCourseWare · 2006 - Stan Reference Manual — Program Blocks: Constraining inverse transform
Stan Development Team
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Read MML, MIT and Stan sources; checked likelihood/posterior distinctions, independence, parameter-dependent support and Jacobians for parameter densities.
- Checked the Uniform endpoint convention, all-zero data and empty sample separately; did not treat a zero derivative as a universal solution rule.
- Enumerated every binary sequence of lengths 1–7 with rational arithmetic to verify count probabilities and likelihood ratios; checked different prior posteriors, boundaries, log-odds relabeling and bilingual correspondence.
- Independent cross-review restricted the opening odds example to discrete hypotheses with positive prior probability and distinguished continuous-point density ratios; also checked the logit derivative and Uniform data-unit transformation.
- The parent executed all 25 independent probability checks; bilingual code, display equations, main anchors, sources and exercises were additionally compared.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, PDF pages 272–275 (printed 266–269), Section 8.3 equations 8.14–8.20: fixed data/variable parameter, conditional independent factorization, log sum and posterior; PDF 280 (printed 274), equation 8.22; PDF 212 (printed 206), Example 6.9 binomial coefficient. Actual local PDF text read; loose most-likely-parameter wording replaced by explicit likelihood/posterior distinction.
- Statistics for Applications — Lecture 2: Maximum Likelihood Estimators · PDF pages 5–6 (printed 11–12): mass versus density, fixed observations and Bernoulli likelihood; PDF pages 7–9 (printed 13–15): Uniform [0,theta] indicator, excluded-endpoint convention and non-attained maximum. Entire relevant fetched PDF text read.
- Stan Reference Manual — Program Blocks: Constraining inverse transform · Program block: parameters / Constraining inverse transform, lines 282–288: sampling density in unconstrained coordinates and log Jacobian of inverse transform. Used specifically for prior/posterior density transform; likelihood relabeling identity is derived separately.
Related topics