Algorithmcore
Likelihood ratio test
Also called LRT, generalized likelihood ratio test.
Compares the maximized likelihood under the null with that under the full model, and rejects when twice the log ratio is large. Wilks' theorem gives its null distribution.
- Time
- Θ(n + m) worst · best
- Space
- Θ(1) extra
- Where
- m = the number of cells of a multinomial; n = the number of observations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jerzy Neyman, Egon S. Pearson, 1928
The likelihood ratio test (LRT) compares two fits of the same model: the best fit under the null hypothesis and the best fit with the parameter free. Its statistic is , twice the gain in log-likelihood from freeing the parameter, and the test rejects when is large. By Wilks' theorem, has an approximate null distribution, where is the number of constraints, so the p-value is an upper chi-squared tail and is only asymptotic. For a simple null against a simple alternative the same ratio gives the most powerful test of the Neyman-Pearson lemma.
In plain words
You have a model with some settings you do not know, and a claim that fixes some of them. Fit the model twice. First let every setting take its best value for the data. Then hold the claimed settings fixed and let only the rest move. The first fit always explains the data at least as well. Measure how much better, on a log scale, and double it. If the claim is true, this gain is a matter of chance, and for large samples its typical size is known from a standard table that depends only on how many settings the claim fixed. If the gain is much larger than chance usually gives, reject the claim.
The problem
Model and hypotheses. The data are iid with density , . The log-likelihood is , as on the likelihood function page. The null hypothesis restricts to a subset of dimension , for example by fixing coordinates. The alternative is .
Statistic. With the maximum likelihood estimate over and the restricted MLE over ,
Null distribution. Asymptotic: under and the regularity conditions of Wilks' theorem, in distribution. Exact in a few models: for a normal mean with known , , which is exactly ; for a normal mean with unknown variance, with the Student t statistic, so the exact null law comes from .
Rejection rule and size. Reject at level when , the upper point of . The size tends to as . For finite it is only near , and it can be far off for small samples or discrete data.
p-value. , computed as an upper incomplete gamma function, .
Sensitivity and power. The test reacts to any departure from in the constrained directions. Under local alternatives , tends to a noncentral , where grows with the squared distance of from the null set in the metric of the Fisher information. For a scalar parameter the two-sided LRT has the same local power as the Wald test and the score test.
The algorithm
LIKELIHOOD-RATIO-TEST(x, ℓ, Θ, Θ₀, r) ▷ r = dim Θ − dim Θ₀ ≥ 1- 1
θ̂ ← a maximizer of ℓ(θ; x) over Θ - 2
θ̂₀ ← a maximizer of ℓ(θ; x) over Θ₀ - 3
Λ ← 2 (ℓ(θ̂; x) − ℓ(θ̂₀; x)) - 4
Λ ← max(Λ, 0) ▷ guards rounding and a weak optimizer - 5
p ← Q(r/2, Λ/2) ▷ P(χ²_r ≥ Λ), the upper tail directly - 6
return (Λ, p)
Lines L1 and L2 are where the work is. For most models they need a numerical optimizer, such as Newton's method or Fisher scoring. For the common models below the maximizers have closed forms, and line L3 becomes a sum of deviance terms , with :
| model, null | ||
|---|---|---|
| binomial, | 1 | |
| Poisson, | 1 | |
| normal, , known | 1 | |
| normal, , unknown | , | 1 |
| multinomial, cell probabilities | , the G-statistic |
In the deviance form the linear terms add up to 0 over the cells, so the table equals the usual . For the normal model with unknown variance, and , both with divisor (the MLE), and .
Example
A binomial count. In 20 trials there are 15 successes. Test against at .
| step | value |
|---|---|
| L1: | 0.75 |
| L2: | 0.5 |
| L3: | 1.081977 |
| L3: | 1.534264 |
| L3: | 5.232481 |
| L5: | 0.022169 |
Since , the test rejects at the 5% level. The test rejects exactly when or , so its exact size is , below the nominal . Its exact power is at , at and at .
A normal mean. The nine pack weights of the z-test page, , have and . For :
| case | p-value | exact p-value | |
|---|---|---|---|
| known | 4.3403 | 0.0372 | 0.0372 (exact, ) |
| unknown | 5.8668 | 0.0154 | 0.0266 (from , ) |
With unknown the chi-squared p-value is too small by a factor of almost 2 at . The t-test is the exact form of this LRT.
A multinomial. Counts in three cells, with : probabilities . The expected counts are , with , and . The Pearson statistic of the chi-squared goodness-of-fit test is , with . The two agree to first order, because the Pearson statistic is the score test of the same null.
Correctness
The statistic is nonnegative, because makes the unrestricted maximum at least the restricted one. It does not depend on the parametrization: a one-to-one change of parameter does not change the maximum values of the likelihood. The closed forms in the table follow from the explicit MLEs, and the deviance form follows from . The p-value is the upper tail of . Under and regularity, Wilks' theorem gives , so the size is asymptotically . This is the only guarantee of the general test. It is exact only where is exactly , as for the normal mean with known . The correctness proof below gives these steps, and also proves that the routine for a simple null against a simple alternative returns the Neyman-Pearson test.
Proof: The likelihood ratio test returns a nonnegative statistic with the stated closed forms, its p-value has size tending to alpha, and the finite routine returns the Neyman-Pearson testfull
We prove that LIKELIHOOD-RATIO-TEST returns , that does not depend on the parametrization, that the closed forms of the model table are correct, that the deviance series is exact, that the p-value has size tending to under the conditions of Wilks' theorem (and exactly for a normal mean with known ), and that the routine for a simple null against a simple alternative on a finite sample space returns a most powerful test of size . We do not prove Wilks' theorem here; it is proved on its own page.
Lemma 1 (nonnegative). If , maximizes over and maximizes over , then .
Proof. , so .
Line L4 does not change the value when the maximizers are exact. It only sets to 0 a negative value that comes from rounding or from an optimizer that stops early.
Lemma 2 (invariance). Let be a one-to-one map from onto , and write the model in the new parameter as , with null set . Then the LRT statistic in equals .
Proof. , because is a bijection from to ; the same holds for and . The statistic depends only on these two suprema.
Lemma 3 (the deviance form). For and , let with . Then with , and only at . For , .
Proof. by expanding. , , and , so is strictly convex with its minimum 0 at ; by continuity. For the series, . With for , the coefficient of in is for , which equals , and the coefficient of is 1, which cancels with .
When , the terms of the series decrease in size by a factor of at least . They alternate in sign when and are all positive when ; in both cases the terms after a given one add up to at most of its size, so stopping when a term is below of the sum leaves a relative error below that bound, plus rounding. No subtraction of nearly equal numbers occurs, because every term is computed from directly.
Lemma 4 (closed forms). The table of the algorithm section is correct:
- Binomial, successes in trials, : .
- Poisson, counts with sum , : .
- Normal, known, : .
- Normal, unknown, , with : , where and .
- Multinomial, counts with sum , : probabilities : .
Proof. (1) plus a constant, maximized at (at an endpoint if , with ). Then . The linear parts of the two terms are , so the sum of the terms is the same.
(2) plus a constant, maximized at . So .
(3) plus a constant, maximized at . With , .
(4) plus a constant. For fixed it is maximized at , with value . The full maximum is at , ; the restricted one at . So . Since , this is .
(5) plus a constant, maximized over the simplex at (Gibbs' inequality: ). So , and the linear parts add nothing.
Lemma 5 (p-value and size). Let .
- If exactly under , then for all .
- If in distribution under , then .
- For a normal mean with known , exactly under , for every .
Proof. The survival function is continuous and strictly decreasing on , from 1 to 0. So for . In case 1 this has probability . In case 2 the limit law has a continuous CDF, so for each fixed , and the same set has probability tending to . For case 3, under , as on the z-test page, and , which is by definition.
Case 2 holds under the conditions of Wilks' theorem. The routine does not check them, and for finite its size is only measured, not proved: the exact binomial sizes are computed in the tests by enumeration, for example 0.0414 at .
Lemma 6 (the finite Neyman-Pearson routine). Let be probability vectors on and . MOST-POWERFUL-TEST returns with , and maximizes over all with .
Proof. The routine sets where , which costs no size. It then takes the distinct values of on in decreasing order, including the value 0, and gives each class the share , where mass is the mass of the class, until the budget is 0. The total mass of all classes is 1 , so the budget reaches 0 at some class; let be its ratio. Every share is in , and the shares spend exactly , so . Also where , where , and is constant on the class . The points with get and contribute nothing to size or power. For optimality, take any as in the statement. For every , , because where the second factor is positive and where it is negative. Summing, . So the power of is at least that of .
This is the sufficiency part of the Neyman-Pearson lemma, applied to the vector the routine builds. The tests compare it with the best of all vertex tests of the linear program, in exact rational arithmetic.
Termination. The general routine calls each maximizer once and does a constant number of further operations, so it stops if the maximizers stop. Each closed form makes one pass over the data or the cells. The deviance series stops because its terms decrease geometrically when and the partial sums are bounded below by , the sum of the first two terms when and less than the first term when (the case returns 0 after one term). MOST-POWERFUL-TEST loops at most times over the distinct ratio values.
Theorem. LIKELIHOOD-RATIO-TEST returns and . The statistic is invariant under reparametrization, the closed forms agree with the general definition, and rejecting when has size tending to whenever under , and size exactly for the normal mean with known . MOST-POWERFUL-TEST returns a most powerful test of size .
Proof. Lemmas 1 to 6.
Complexity
On a real RAM, with closed-form maximizers, the statistic needs one pass over the data or the cells: time for the binomial, Poisson and normal forms, and for a multinomial with cells after counting. The p-value is one evaluation of the incomplete gamma function. The extra space is . In the general case, the cost is that of the two optimizations in lines L1 and L2, typically a number of iterations times for Newton steps in parameters.
Numerical stability. Three points matter.
- Cancellation near the null. Written as , the binomial statistic is a difference of two large numbers when is near . With and , the true is , and the naive formula returns , a negative number. The deviance term with is computed from the series when , which has no cancellation. This is catastrophic cancellation of the same kind as in variance computations.
- The general form. Line L3 subtracts two log-likelihoods that can each be of order . The difference keeps only the digits that the two values do not share. Line L4 clips the tiny negative values that rounding or an optimizer that stops early can produce. When accuracy matters, compute the difference in closed form, as the table does.
- The upper tail. Line L5 computes directly, by a continued fraction for large arguments. Computing returns 0 for p-values below about . For unknown, is computed with log1p.
Properties
- Invariant under reparametrization. The value of does not change when is replaced by for a one-to-one . The Wald test does not have this property.
- Nonnegative and nested. , and adding constraints to can only increase it.
- Asymptotically under the null. By Wilks' theorem, with the conditions stated there. The size is only near for finite .
- Asymptotically equivalent to the Wald and score tests. Under the null and local alternatives, the three statistics differ by . In finite samples they differ. For a normal mean with unknown variance, with , they are , and , so always.
- Optimal for simple hypotheses. For a simple null against a simple alternative, rejecting for large is most powerful, by the Neyman-Pearson lemma. For composite hypotheses the LRT has no exact optimality in general, but it is asymptotically optimal in several senses, for example in Bahadur efficiency.
- Needs both fits. The LRT uses the restricted and the unrestricted MLE. The Wald test needs only the unrestricted fit, and the score test only the restricted one.
Variants and improvements
- Simple null against simple alternative. On a finite sample space, the Neyman-Pearson test can be built directly: sort the points by , reject at the points with the largest ratios until the size is used, and randomize at the last point. The implementation provides it in exact rational arithmetic. Under , the ratio has expectation at most 1, so it is also an e-variable.
- Signed root. For a scalar parameter, is approximately and gives one-sided tests and likelihood-based confidence intervals.
- Profile likelihood intervals. Inverting the LRT gives the set , which is invariant under reparametrization and often better than the Wald interval. See test-interval duality.
- Bartlett correction. Dividing by an estimate of improves the chi-squared approximation from error to . Wilks' theorem shows the numbers for the normal mean.
- Parametric bootstrap. Simulate data from the fitted null model , recompute each time, and use the simulated distribution in place of . See parametric bootstrap. This also handles boundary cases.
- Deviance and G-test. In generalized linear models, is a difference of deviances. For counts, is the G-statistic.
- Split likelihood ratio. Fit the alternative on one half of the data and evaluate the ratio on the other half. The result is an e-variable for any composite null, with a valid level for every and no regularity conditions, at the cost of power (universal inference, Wasserman, Ramdas and Balakrishnan 2020).
When to use it
Use the LRT for nested parametric models when both fits are easy to compute: comparing a model with and without a group of terms, testing a variance component that is not on the boundary, or testing a parameter whose Wald statistic depends badly on the scale. Prefer it to the Wald test when the estimate is near the edge of the parameter space or the likelihood is skewed, as for small binomial or Poisson counts. Use the score test when the full model is hard to fit. For small samples, use an exact test where one exists, such as the binomial test or the t-test, or calibrate by a parametric bootstrap.
Pitfalls
- Parameters on the boundary. Testing a variance component equal to 0, or a mixture weight equal to 0, puts on the edge of . The null law is then a mixture such as , and the reference makes the test conservative. See Wilks' theorem.
- Parameters not identified under the null. For the number of mixture components or an unknown change point, the chi-squared reference is wrong, and the error grows with .
- Non-nested models. compares a model with a submodel. For two models where neither contains the other, the chi-squared reference does not apply. Use an information criterion such as the AIC, or a test made for non-nested models.
- Different data in the two fits. If missing values remove different rows from the two fits, the likelihoods are of different data and means nothing. Fit both models to the same rows.
- A local maximum. If the optimizer stops at a local maximum in line L1, is too small, and it can even be negative. Start the full fit from the null fit, which guarantees .
- Reading the asymptotic size as exact. The binomial test above has exact size 0.0414, and the normal LRT with unknown variance has size 0.098 at , not 0.05.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-test/. The authors are listed in prov/04CJ2P.jsonl.
"""The likelihood ratio test, in general form and for common models.
likelihood_ratio_test takes a log-likelihood and two maximizers and returns
(Lambda, p) with Lambda = 2 (l(theta_hat) - l(theta0_hat)) and p the upper
chi-squared tail with r degrees of freedom (Wilks' theorem, so p is only
asymptotic). The model functions compute Lambda in closed form, as a sum of
deviance terms x log(x / y) - x + y, which do not cancel when x is near y.
most_powerful_test builds the randomized Neyman-Pearson test of a simple
null against a simple alternative on a finite sample space.
The code is in this file and not in likelihood_ratio_test.py, because tools
treat a file whose name ends in _test.py as a test file.
"""
import math
from collections.abc import Callable, Sequence
from fractions import Fraction
from stdist import chi2_sf
def likelihood_ratio_test(loglik: Callable[[object], float],
fit_full: Callable[[], object],
fit_null: Callable[[], object],
r: int) -> tuple[float, float]:
"""General LRT: fit_full and fit_null return maximizers of loglik over Theta and Theta_0."""
if r < 1:
raise ValueError("r, the number of constraints, must be at least 1")
theta_hat = fit_full() # @line L1
theta0_hat = fit_null() # @line L2
lam = 2.0 * (loglik(theta_hat) - loglik(theta0_hat)) # @line L3
lam = max(lam, 0.0) # @line L4
p = chi2_sf(lam, r) # @line L5
return lam, p # @line L6
def deviance_term(x: float, y: float) -> float:
"""x log(x / y) - x + y for x >= 0 and y > 0, without cancellation near x = y."""
if y <= 0.0 or x < 0.0:
raise ValueError("need x >= 0 and y > 0")
if x == 0.0:
return y
d = (x - y) / y
if abs(d) < 0.1:
# y h(1 + d) with h(1 + d) = sum_{j >= 2} (-1)^j d^j / (j (j - 1)).
term, total, j = d * d, 0.0, 2
while True:
add = term / (j * (j - 1))
total += add
if abs(add) <= 1e-17 * total:
break
term *= -d
j += 1
return y * total
return x * math.log(x / y) - x + y
def binomial_lrt(k: int, n: int, p0: float) -> tuple[float, float]:
"""LRT of H_0: p = p0 from k successes in n trials; r = 1."""
if n < 1 or not 0 <= k <= n or not 0.0 < p0 < 1.0:
raise ValueError("need n >= 1, 0 <= k <= n and 0 < p0 < 1")
lam = 2.0 * (deviance_term(k, n * p0) + deviance_term(n - k, n * (1.0 - p0)))
return lam, chi2_sf(lam, 1)
def poisson_lrt(total: int, n: int, lam0: float) -> tuple[float, float]:
"""LRT of H_0: lambda = lam0 from n iid Poisson counts with sum total; r = 1."""
if n < 1 or total < 0 or lam0 <= 0.0:
raise ValueError("need n >= 1, total >= 0 and lam0 > 0")
lam = 2.0 * deviance_term(total, n * lam0)
return lam, chi2_sf(lam, 1)
def normal_mean_lrt(x: Sequence[float], mu0: float,
sigma: float | None = None) -> tuple[float, float]:
"""LRT of H_0: mu = mu0 for iid normal data; r = 1.
With sigma known, Lambda = n (xbar - mu0)^2 / sigma^2. With sigma unknown
(sigma=None), Lambda = n log(1 + n (xbar - mu0)^2 / SS), SS = sum (x - xbar)^2,
which equals n log(1 + T^2 / (n - 1)) for the t statistic T.
"""
n = len(x)
mean = math.fsum(x) / n if n else 0.0
if sigma is not None:
if n < 1 or sigma <= 0.0:
raise ValueError("need n >= 1 and sigma > 0")
lam = n * (mean - mu0) ** 2 / sigma ** 2
else:
if n < 2:
raise ValueError("need n >= 2 when sigma is unknown")
ss = math.fsum((v - mean) ** 2 for v in x)
if ss == 0.0:
raise ValueError("all observations are equal")
lam = n * math.log1p(n * (mean - mu0) ** 2 / ss)
return lam, chi2_sf(lam, 1)
def multinomial_lrt(counts: Sequence[int], probs: Sequence[float]) -> tuple[float, float]:
"""G-test of H_0: cell probabilities = probs; r = m - 1 for m cells."""
m, n = len(counts), sum(counts)
if m < 2 or n < 1 or len(probs) != m or any(c < 0 for c in counts):
raise ValueError("need at least 2 cells, nonnegative counts and one prob per cell")
if any(q <= 0.0 for q in probs) or abs(math.fsum(probs) - 1.0) > 1e-12:
raise ValueError("probs must be positive and sum to 1")
lam = 2.0 * math.fsum(deviance_term(c, n * q) for c, q in zip(counts, probs))
return lam, chi2_sf(lam, m - 1)
def most_powerful_test(f0: Sequence[Fraction], f1: Sequence[Fraction],
alpha: Fraction) -> list[Fraction]:
"""The Neyman-Pearson test phi on a finite sample space, with E_0 phi = alpha.
Points are taken in decreasing order of f1 / f0 (points with f0 = 0 first)
until the size budget alpha is spent; the last point is randomized.
Ties in the ratio share the remaining budget in proportion to f0.
"""
m = len(f0)
if len(f1) != m or not 0 <= alpha <= 1:
raise ValueError("need f0, f1 of equal length and 0 <= alpha <= 1")
phi = [Fraction(0)] * m
for i in range(m):
if f0[i] == 0 and f1[i] > 0:
phi[i] = Fraction(1)
ratio = {i: Fraction(f1[i]) / f0[i] for i in range(m) if f0[i] > 0}
budget = Fraction(alpha)
for k in sorted(set(ratio.values()), reverse=True):
level = [i for i in ratio if ratio[i] == k]
mass = sum(Fraction(f0[i]) for i in level)
share = min(Fraction(1), budget / mass)
for i in level:
phi[i] = share
budget -= share * mass
if budget == 0:
break
return phi
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
likelihood_ratio_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-test/. The authors are listed in prov/04CJ2P.jsonl.
"""Entry point named after the slug. The code lives in lrt_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from lrt_core import (binomial_lrt, deviance_term, likelihood_ratio_test, most_powerful_test,
multinomial_lrt, normal_mean_lrt, poisson_lrt)
__all__ = ["binomial_lrt", "deviance_term", "likelihood_ratio_test", "most_powerful_test",
"multinomial_lrt", "normal_mean_lrt", "poisson_lrt"]
test_likelihood_ratio_test.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-test/. The authors are listed in prov/04CJ2P.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from likelihood_ratio_test import (binomial_lrt, deviance_term, likelihood_ratio_test,
most_powerful_test, multinomial_lrt, normal_mean_lrt,
poisson_lrt)
from stdist import chi2_sf
def grid_argmax(f, lo: float, hi: float, steps: int = 200, rounds: int = 10) -> float:
"""Brute force: maximize a unimodal f on [lo, hi] by a grid, then shrink around the best point."""
for _ in range(rounds):
h = (hi - lo) / steps
best = max(range(steps + 1), key=lambda i: f(lo + i * h))
lo, hi = lo + max(best - 1, 0) * h, lo + min(best + 1, steps) * h
return 0.5 * (lo + hi)
def test_worked_example() -> None:
lam, p = binomial_lrt(15, 20, 0.5)
exact = 2.0 * (15 * math.log(1.5) + 5 * math.log(0.5))
assert abs(lam - exact) < 1e-12
assert abs(lam - 5.232481) < 1e-6
assert abs(p - 0.022169) < 1e-6
def test_binomial_against_brute_force_maximization() -> None:
rng = random.Random(11)
for _ in range(20):
n = rng.randint(5, 60)
k = rng.randint(1, n - 1)
p0 = rng.uniform(0.05, 0.95)
loglik = lambda p: k * math.log(p) + (n - k) * math.log(1.0 - p)
lam, p = likelihood_ratio_test(loglik, lambda: grid_argmax(loglik, 1e-9, 1 - 1e-9),
lambda: p0, 1)
assert abs(lam - binomial_lrt(k, n, p0)[0]) < 1e-8 * max(1.0, lam)
assert abs(p - binomial_lrt(k, n, p0)[1]) < 1e-8
def test_poisson_against_brute_force_maximization() -> None:
rng = random.Random(12)
for _ in range(20):
n = rng.randint(1, 30)
total = rng.randint(1, 100)
lam0 = rng.uniform(0.2, 6.0)
loglik = lambda t: total * math.log(t) - n * t
lam, _ = likelihood_ratio_test(loglik, lambda: grid_argmax(loglik, 1e-9, 200.0),
lambda: lam0, 1)
assert abs(lam - poisson_lrt(total, n, lam0)[0]) < 1e-8 * max(1.0, lam)
def test_normal_unknown_variance_against_brute_force() -> None:
rng = random.Random(13)
for _ in range(3):
n = rng.randint(3, 10)
x = [rng.gauss(1.0, 2.0) for _ in range(n)]
mu0 = rng.uniform(-1.0, 3.0)
def loglik(theta: tuple[float, float]) -> float:
mu, v = theta
return -0.5 * n * math.log(v) - 0.5 * sum((xi - mu) ** 2 for xi in x) / v
def profile_v(mu: float) -> float:
return grid_argmax(lambda v: loglik((mu, v)), 1e-6, 100.0, steps=50, rounds=12)
def fit_full() -> tuple[float, float]:
mu = grid_argmax(lambda m: loglik((m, profile_v(m))), -10.0, 10.0, steps=20, rounds=15)
return mu, profile_v(mu)
lam, _ = likelihood_ratio_test(loglik, fit_full, lambda: (mu0, profile_v(mu0)), 1)
closed, _ = normal_mean_lrt(x, mu0)
assert abs(lam - closed) < 1e-6 * max(1.0, closed)
mean = sum(x) / n
s2 = sum((v - mean) ** 2 for v in x) / (n - 1)
t = (mean - mu0) / math.sqrt(s2 / n)
assert abs(closed - n * math.log1p(t * t / (n - 1))) < 1e-10 * max(1.0, closed)
def test_trinity_agrees_for_normal_mean_with_known_variance() -> None:
rng = random.Random(14)
for _ in range(50):
n = rng.randint(1, 12)
x = [rng.randint(-20, 20) for _ in range(n)]
mu0, sigma = rng.randint(-5, 5), rng.randint(1, 6)
# Exact: 2 (l(xbar) - l(mu0)) = (sum (x - mu0)^2 - sum (x - xbar)^2) / sigma^2.
xbar = Fraction(sum(x), n)
lr = (sum((Fraction(v) - mu0) ** 2 for v in x) - sum((v - xbar) ** 2 for v in x)) / sigma ** 2
wald = (xbar - mu0) ** 2 / (Fraction(sigma ** 2) / n) # (theta_hat - theta_0)^2 / Var
u = sum(Fraction(v) - mu0 for v in x) / sigma ** 2 # score at mu0
score = u * u / (Fraction(n) / sigma ** 2) # U^2 / I_n
assert lr == wald == score
lam, _ = normal_mean_lrt(x, mu0, sigma)
assert abs(lam - float(lr)) < 1e-9 * max(1.0, float(lr))
def test_multinomial_g_statistic() -> None:
counts, probs = [18, 30, 52], [0.25, 0.25, 0.5]
lam, p = multinomial_lrt(counts, probs)
direct = 2.0 * sum(c * math.log(c / (100 * q)) for c, q in zip(counts, probs))
assert abs(lam - direct) < 1e-12
assert abs(p - chi2_sf(direct, 2)) < 1e-14
assert multinomial_lrt([0, 5, 5], [0.2, 0.4, 0.4])[0] == pytest.approx(
2.0 * 10 * math.log(1 / 0.8), rel=1e-12)
def test_deviance_term_is_stable_near_equality() -> None:
# x log(x / y) - x + y = y h(1 + d) with h(1 + d) ~ d^2 / 2; at d = 1e-9 the naive form cancels.
y, d = 50.0, 1e-9
assert deviance_term(y * (1 + d), y) == pytest.approx(y * d * d / 2, rel=1e-6)
for x, y in [(3.0, 2.9), (7.0, 7.5), (0.0, 1.5), (40.0, 4.0)]:
naive = (x * math.log(x / y) if x else 0.0) - x + y
assert deviance_term(x, y) == pytest.approx(naive, rel=1e-12, abs=1e-15)
assert deviance_term(5.0, 5.0) == 0.0
def test_exact_binomial_size_by_enumeration() -> None:
crit = 3.841458820694124
for n, expected in [(20, 0.041389), (100, 0.056888)]:
size = sum(Fraction(math.comb(n, k), 2 ** n)
for k in range(n + 1) if binomial_lrt(k, n, 0.5)[0] >= crit)
assert abs(float(size) - expected) < 1e-6
def test_monte_carlo_size_normal_unknown_variance() -> None:
rng = random.Random(15)
reps, n = 2000, 30
rejections = sum(normal_mean_lrt([rng.gauss(3.0, 2.0) for _ in range(n)], 3.0)[1] <= 0.05
for _ in range(reps))
# Exact size of this nominal 5% test at n = 30 is about 0.0545; the MC error is about 0.005.
assert abs(rejections / reps - 0.0545) < 0.02
def lp_vertex_optimum(f0: list[Fraction], f1: list[Fraction], alpha: Fraction) -> Fraction:
"""Brute force: the best power over all vertices of {0 <= phi <= 1, sum phi f0 <= alpha}.
A vertex is 0 or 1 at every point except at most one, which then spends the
rest of the size budget. The LP optimum is attained at a vertex.
"""
m, best = len(f0), Fraction(0)
for ones in itertools.product((0, 1), repeat=m):
size = sum(f for f, o in zip(f0, ones) if o)
if size > alpha:
continue
power = sum(f for f, o in zip(f1, ones) if o)
best = max(best, power)
for j in range(m):
if not ones[j] and f0[j] > 0:
frac = min(Fraction(1), (alpha - size) / f0[j])
best = max(best, power + frac * f1[j])
return best
def test_most_powerful_test_hand_example() -> None:
f0 = [Fraction(4, 10), Fraction(3, 10), Fraction(2, 10), Fraction(1, 10)]
f1 = [Fraction(1, 10), Fraction(2, 10), Fraction(3, 10), Fraction(4, 10)]
phi = most_powerful_test(f0, f1, Fraction(1, 4))
assert phi == [0, 0, Fraction(3, 4), 1]
assert sum(p * f for p, f in zip(phi, f1)) == Fraction(5, 8)
assert lp_vertex_optimum(f0, f1, Fraction(1, 4)) == Fraction(5, 8)
def test_most_powerful_test_against_all_vertex_tests() -> None:
rng = random.Random(16)
for _ in range(60):
m = rng.randint(2, 6)
w0 = [rng.randint(0, 6) for _ in range(m)]
w1 = [rng.randint(0, 6) for _ in range(m)]
if sum(w0) == 0 or sum(w1) == 0:
continue
f0 = [Fraction(w, sum(w0)) for w in w0]
f1 = [Fraction(w, sum(w1)) for w in w1]
alpha = Fraction(rng.randint(0, 20), 20)
phi = most_powerful_test(f0, f1, alpha)
assert all(0 <= p <= 1 for p in phi)
assert sum(p * f for p, f in zip(phi, f0)) <= alpha
power = sum(p * f for p, f in zip(phi, f1))
assert power == lp_vertex_optimum(f0, f1, alpha)
def test_simple_likelihood_ratio_is_an_e_variable_with_markov_bound() -> None:
n, half, q = 10, Fraction(1, 2), Fraction(4, 5)
prob = [Fraction(math.comb(n, k), 2 ** n) for k in range(n + 1)]
e = [(q / half) ** k * ((1 - q) / half) ** (n - k) for k in range(n + 1)]
assert sum(p * v for p, v in zip(prob, e)) == 1
for alpha in [Fraction(1, 2), Fraction(1, 10), Fraction(1, 20), Fraction(1, 100)]:
tail = sum(p for p, v in zip(prob, e) if v >= 1 / alpha)
assert tail <= alpha
assert sum(p for p, v in zip(prob, e) if v >= 20) == Fraction(11, 1024)
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
binomial_lrt(3, 2, 0.5)
with pytest.raises(ValueError):
normal_mean_lrt([1.0, 1.0, 1.0], 0.0)
with pytest.raises(ValueError):
multinomial_lrt([1, 2], [0.5, 0.6])
History
Jerzy Neyman and Egon Pearson introduced the likelihood ratio criterion in their 1928 papers in Biometrika, as a general principle to build tests of composite hypotheses. In 1933 they proved that for simple hypotheses the ratio gives the most powerful test. Samuel S. Wilks proved in 1938 that is asymptotically chi-squared, which made the test practical. Abraham Wald (1943) showed its large-sample optimality and its equivalence with the Wald test, and Rao (1948) added the score test, which completed the trio of classical large-sample tests. The G-statistic for counts goes back to the same period and became common in biology through the textbook of Sokal and Rohlf.
References
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 8.2.1 (likelihood ratio tests, with the normal and exponential examples) and Section 10.3.1 (the asymptotic distribution of the LRT)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Part II (large-sample theory), the chapters on likelihood ratio tests in quadratic mean differentiable families
- Neyman and Pearson 1928, the likelihood ratio criterion lambda for composite hypotheses
- S. S. Wilks, The large-sample distribution of the likelihood ratio for testing composite hypotheses, Annals of Mathematical Statistics 9(1) (1938), pages 60 to 62, the chi-squared limit of -2 log lambda
Where this leads
- Bayesian information criterion
- Deviance
- Empirical likelihood
- Fellegi-Sunter model
- GMM-UBM speaker verification
- Likelihood ratio membership attack
- Statistical model voice activity detection
- Linear mixed model
- PLDA scoring
- Punkt sentence tokenizer
- Sequential probability ratio test
- Speaker verification
- Voice activity detection
- Wilks' theorem
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 04CJ2P Edit this page History Report an error Markdown