Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 Λ=2(ℓ(θ^)−ℓ(θ^0))\Lambda = 2(\ell(\hat\theta) - \ell(\hat\theta_0)), twice the gain in log-likelihood from freeing the parameter, and the test rejects when Λ\Lambda is large. By Wilks' theorem, Λ\Lambda has an approximate χr2\chi^2_r null distribution, where rr 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 x=(x1,…,xn)x = (x_1, \dots, x_n) are iid with density f(x;θ)f(x; \theta), θ∈Θ⊆Rk\theta \in \Theta \subseteq \mathbb R^k. The log-likelihood is ℓ(θ)=∑ilog⁡f(xi;θ)\ell(\theta) = \sum_i \log f(x_i; \theta), as on the likelihood function page. The null hypothesis H0:θ∈Θ0H_0: \theta \in \Theta_0 restricts θ\theta to a subset of dimension k−rk - r, for example by fixing rr coordinates. The alternative is H1:θ∈Θ∖Θ0H_1: \theta \in \Theta \setminus \Theta_0.

Statistic. With θ^\hat\theta the maximum likelihood estimate over Θ\Theta and θ^0\hat\theta_0 the restricted MLE over Θ0\Theta_0,

Λ=2(ℓ(θ^)−ℓ(θ^0))=−2log⁡sup⁡θ∈Θ0L(θ;x)sup⁡θ∈ΘL(θ;x) ≥ 0.\Lambda = 2\left(\ell(\hat\theta) - \ell(\hat\theta_0)\right) = -2\log\frac{\sup_{\theta \in \Theta_0} L(\theta; x)}{\sup_{\theta \in \Theta} L(\theta; x)} \ \ge\ 0.

Null distribution. Asymptotic: under H0H_0 and the regularity conditions of Wilks' theorem, Λ→χr2\Lambda \to \chi^2_r in distribution. Exact in a few models: for a normal mean with known σ\sigma, Λ=n(xˉ−μ0)2/σ2\Lambda = n(\bar x - \mu_0)^2/\sigma^2, which is exactly χ12\chi^2_1; for a normal mean with unknown variance, Λ=nlog⁡(1+T2/(n−1))\Lambda = n\log(1 + T^2/(n - 1)) with TT the Student t statistic, so the exact null law comes from tn−1t_{n-1}.

Rejection rule and size. Reject at level α\alpha when Λ≥χr,1−α2\Lambda \ge \chi^2_{r, 1-\alpha}, the upper α\alpha point of χr2\chi^2_r. The size tends to α\alpha as n→∞n \to \infty. For finite nn it is only near α\alpha, and it can be far off for small samples or discrete data.

p-value. p=P(χr2≥Λ)p = P(\chi^2_r \ge \Lambda), computed as an upper incomplete gamma function, p=Q(r/2,Λ/2)p = Q(r/2, \Lambda/2).

Sensitivity and power. The test reacts to any departure from Θ0\Theta_0 in the rr constrained directions. Under local alternatives θn=θ0+h/n\theta_n = \theta_0 + h/\sqrt n, Λ\Lambda tends to a noncentral χr2(δ)\chi^2_r(\delta), where δ\delta grows with the squared distance of hh 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

  1. LIKELIHOOD-RATIO-TEST(x, ℓ, Θ, Θ₀, r) ▷ r = dim Θ − dim Θ₀ ≥ 1
  2. 1θ̂ ← a maximizer of ℓ(θ; x) over Θ
  3. 2θ̂₀ ← a maximizer of ℓ(θ; x) over Θ₀
  4. 3Λ ← 2 (ℓ(θ̂; x) − ℓ(θ̂₀; x))
  5. 4Λ ← max(Λ, 0) ▷ guards rounding and a weak optimizer
  6. 5p ← Q(r/2, Λ/2) ▷ P(χ²_r ≥ Λ), the upper tail directly
  7. 6return (Λ, 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 D(a,b)=alog⁡(a/b)−a+b≥0D(a, b) = a\log(a/b) - a + b \ge 0, with 0log⁡0=00\log 0 = 0:

model, null Λ\Lambda rr
binomial, p=p0p = p_0 2(D(k,np0)+D(n−k,n(1−p0)))2\left(D(k, np_0) + D(n - k, n(1 - p_0))\right) 1
Poisson, λ=λ0\lambda = \lambda_0 2D(∑xi,nλ0)2D(\textstyle\sum x_i, n\lambda_0) 1
normal, μ=μ0\mu = \mu_0, σ\sigma known n(xˉ−μ0)2/σ2n(\bar x - \mu_0)^2/\sigma^2 1
normal, μ=μ0\mu = \mu_0, σ\sigma unknown nlog⁡(1+n(xˉ−μ0)2/SS)n\log\left(1 + n(\bar x - \mu_0)^2/SS\right), SS=∑(xi−xˉ)2SS = \sum(x_i - \bar x)^2 1
multinomial, cell probabilities qjq_j 2∑jD(Oj,nqj)2\sum_j D(O_j, nq_j), the G-statistic m−1m - 1

In the deviance form the linear terms −a+b-a + b add up to 0 over the cells, so the table equals the usual 2∑Olog⁡(O/E)2\sum O\log(O/E). For the normal model with unknown variance, σ^2=SS/n\hat\sigma^2 = SS/n and σ^02=SS/n+(xˉ−μ0)2\hat\sigma_0^2 = SS/n + (\bar x - \mu_0)^2, both with divisor nn (the MLE), and Λ=nlog⁡(σ^02/σ^2)\Lambda = n\log(\hat\sigma_0^2/\hat\sigma^2).

Example

A binomial count. In 20 trials there are 15 successes. Test H0:p=0.5H_0: p = 0.5 against p≠0.5p \ne 0.5 at α=0.05\alpha = 0.05.

step value
L1: p^=15/20\hat p = 15/20 0.75
L2: p^0\hat p_0 0.5
L3: D(15,10)=15log⁡1.5−5D(15, 10) = 15\log 1.5 - 5 1.081977
L3: D(5,10)=5log⁡0.5+5D(5, 10) = 5\log 0.5 + 5 1.534264
L3: Λ=2(1.081977+1.534264)\Lambda = 2(1.081977 + 1.534264) 5.232481
L5: p=P(χ12≥5.232481)p = P(\chi^2_1 \ge 5.232481) 0.022169

Since 5.2325≥3.84155.2325 \ge 3.8415, the test rejects at the 5% level. The test rejects exactly when K≤5K \le 5 or K≥15K \ge 15, so its exact size is 2∑k≤5(20k)2−20=0.04142\sum_{k \le 5}\binom{20}{k}2^{-20} = 0.0414, below the nominal 0.050.05. Its exact power is 0.12720.1272 at p=0.6p = 0.6, 0.41640.4164 at p=0.7p = 0.7 and 0.80420.8042 at p=0.8p = 0.8.

A normal mean. The nine pack weights of the z-test page, 502,498,505,503,501,507,499,504,506502, 498, 505, 503, 501, 507, 499, 504, 506, have xˉ=502.7778\bar x = 502.7778 and SS=75.5556SS = 75.5556. For H0:μ=500H_0: \mu = 500:

case Λ\Lambda χ12\chi^2_1 p-value exact p-value
σ=4\sigma = 4 known 4.3403 0.0372 0.0372 (exact, Λ=z2\Lambda = z^2)
σ\sigma unknown 5.8668 0.0154 0.0266 (from t8t_8, T=2.7116T = 2.7116)

With σ\sigma unknown the chi-squared p-value is too small by a factor of almost 2 at n=9n = 9. The t-test is the exact form of this LRT.

A multinomial. Counts 18,30,5218, 30, 52 in three cells, with H0H_0: probabilities 0.25,0.25,0.50.25, 0.25, 0.5. The expected counts are 25,25,5025, 25, 50, Λ=G=3.1921\Lambda = G = 3.1921 with r=2r = 2, and p=0.2027p = 0.2027. The Pearson statistic of the chi-squared goodness-of-fit test is 3.043.04, with p=0.2187p = 0.2187. The two agree to first order, because the Pearson statistic is the score test of the same null.

Correctness

The statistic is nonnegative, because Θ0⊆Θ\Theta_0 \subseteq \Theta 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 ∑j(Oj−nqj)=0\sum_j (O_j - nq_j) = 0. The p-value Q(r/2,Λ/2)Q(r/2, \Lambda/2) is the upper tail of χr2\chi^2_r. Under H0H_0 and regularity, Wilks' theorem gives P(p≤α)→αP(p \le \alpha) \to \alpha, so the size is asymptotically α\alpha. This is the only guarantee of the general test. It is exact only where Λ\Lambda is exactly χr2\chi^2_r, as for the normal mean with known σ\sigma. 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 Λ=2(ℓ(θ^)−ℓ(θ^0))≥0\Lambda = 2(\ell(\hat\theta) - \ell(\hat\theta_0)) \ge 0, that Λ\Lambda 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 α\alpha under the conditions of Wilks' theorem (and exactly α\alpha for a normal mean with known σ\sigma), and that the routine for a simple null against a simple alternative on a finite sample space returns a most powerful test of size α\alpha. We do not prove Wilks' theorem here; it is proved on its own page.

Lemma 1 (nonnegative). If Θ0⊆Θ\Theta_0 \subseteq \Theta, θ^\hat\theta maximizes ℓ\ell over Θ\Theta and θ^0\hat\theta_0 maximizes ℓ\ell over Θ0\Theta_0, then Λ≥0\Lambda \ge 0.

Proof. θ^0∈Θ0⊆Θ\hat\theta_0 \in \Theta_0 \subseteq \Theta, so ℓ(θ^0)≤sup⁡Θℓ=ℓ(θ^)\ell(\hat\theta_0) \le \sup_\Theta \ell = \ell(\hat\theta). □\square

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 gg be a one-to-one map from Θ\Theta onto Ψ\Psi, and write the model in the new parameter as ℓ~(ψ)=ℓ(g−1(ψ))\tilde\ell(\psi) = \ell(g^{-1}(\psi)), with null set Ψ0=g(Θ0)\Psi_0 = g(\Theta_0). Then the LRT statistic in ψ\psi equals Λ\Lambda.

Proof. sup⁡ψ∈Ψℓ~(ψ)=sup⁡θ∈Θℓ(θ)\sup_{\psi \in \Psi} \tilde\ell(\psi) = \sup_{\theta \in \Theta} \ell(\theta), because gg is a bijection from Θ\Theta to Ψ\Psi; the same holds for Ψ0\Psi_0 and Θ0\Theta_0. The statistic depends only on these two suprema. □\square

Lemma 3 (the deviance form). For a≥0a \ge 0 and b>0b > 0, let D(a,b)=alog⁡(a/b)−a+bD(a, b) = a\log(a/b) - a + b with 0log⁡0=00\log 0 = 0. Then D(a,b)=b h(a/b)D(a, b) = b\,h(a/b) with h(t)=tlog⁡t−t+1≥0h(t) = t\log t - t + 1 \ge 0, and h(t)=0h(t) = 0 only at t=1t = 1. For ∣d∣<1|d| < 1, h(1+d)=∑j≥2(−1)jdj/(j(j−1))h(1 + d) = \sum_{j \ge 2} (-1)^j d^j/(j(j - 1)).

Proof. b h(a/b)=alog⁡(a/b)−a+bb\,h(a/b) = a\log(a/b) - a + b by expanding. h(1)=0h(1) = 0, h′(t)=log⁡th'(t) = \log t, and h′′(t)=1/t>0h''(t) = 1/t > 0, so hh is strictly convex with its minimum 0 at t=1t = 1; h(0)=1h(0) = 1 by continuity. For the series, h(1+d)=(1+d)log⁡(1+d)−dh(1 + d) = (1 + d)\log(1 + d) - d. With log⁡(1+d)=∑j≥1(−1)j+1dj/j\log(1 + d) = \sum_{j \ge 1} (-1)^{j+1}d^j/j for ∣d∣<1|d| < 1, the coefficient of djd^j in (1+d)log⁡(1+d)(1 + d)\log(1 + d) is (−1)j+1/j+(−1)j/(j−1)(-1)^{j+1}/j + (-1)^j/(j - 1) for j≥2j \ge 2, which equals (−1)j/(j(j−1))(-1)^j/(j(j - 1)), and the coefficient of dd is 1, which cancels with −d-d. □\square

When ∣d∣<0.1|d| < 0.1, the terms of the series decrease in size by a factor of at least 0.10.1. They alternate in sign when d>0d > 0 and are all positive when d<0d < 0; in both cases the terms after a given one add up to at most 1/91/9 of its size, so stopping when a term is below 10−1710^{-17} 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 dd directly.

Lemma 4 (closed forms). The table of the algorithm section is correct:

  1. Binomial, K=kK = k successes in nn trials, H0:p=p0H_0: p = p_0: Λ=2(D(k,np0)+D(n−k,n(1−p0)))\Lambda = 2(D(k, np_0) + D(n - k, n(1 - p_0))).
  2. Poisson, nn counts with sum tt, H0:λ=λ0H_0: \lambda = \lambda_0: Λ=2D(t,nλ0)\Lambda = 2D(t, n\lambda_0).
  3. Normal, σ\sigma known, H0:μ=μ0H_0: \mu = \mu_0: Λ=n(xˉ−μ0)2/σ2\Lambda = n(\bar x - \mu_0)^2/\sigma^2.
  4. Normal, σ\sigma unknown, H0:μ=μ0H_0: \mu = \mu_0, with SS=∑(xi−xˉ)2>0SS = \sum (x_i - \bar x)^2 > 0: Λ=nlog⁡(1+n(xˉ−μ0)2/SS)=nlog⁡(1+T2/(n−1))\Lambda = n\log(1 + n(\bar x - \mu_0)^2/SS) = n\log(1 + T^2/(n - 1)), where T=n(xˉ−μ0)/ST = \sqrt n(\bar x - \mu_0)/S and S2=SS/(n−1)S^2 = SS/(n - 1).
  5. Multinomial, counts O1,…,OmO_1, \dots, O_m with sum nn, H0H_0: probabilities qj>0q_j > 0: Λ=2∑jD(Oj,nqj)\Lambda = 2\sum_j D(O_j, nq_j).

Proof. (1) ℓ(p)=klog⁡p+(n−k)log⁡(1−p)\ell(p) = k\log p + (n - k)\log(1 - p) plus a constant, maximized at p^=k/n\hat p = k/n (at an endpoint if k∈{0,n}k \in \{0, n\}, with 0log⁡0=00\log 0 = 0). Then Λ=2[klog⁡(k/(np0))+(n−k)log⁡((n−k)/(n(1−p0)))]\Lambda = 2[k\log(k/(np_0)) + (n - k)\log((n - k)/(n(1 - p_0)))]. The linear parts of the two DD terms are −k+np0−(n−k)+n(1−p0)=0-k + np_0 - (n - k) + n(1 - p_0) = 0, so the sum of the DD terms is the same.

(2) ℓ(λ)=tlog⁡λ−nλ\ell(\lambda) = t\log\lambda - n\lambda plus a constant, maximized at λ^=t/n\hat\lambda = t/n. So Λ=2[tlog⁡(t/(nλ0))−t+nλ0]=2D(t,nλ0)\Lambda = 2[t\log(t/(n\lambda_0)) - t + n\lambda_0] = 2D(t, n\lambda_0).

(3) ℓ(μ)=−∑(xi−μ)2/(2σ2)\ell(\mu) = -\sum (x_i - \mu)^2/(2\sigma^2) plus a constant, maximized at xˉ\bar x. With ∑(xi−μ0)2=SS+n(xˉ−μ0)2\sum (x_i - \mu_0)^2 = SS + n(\bar x - \mu_0)^2, Λ=n(xˉ−μ0)2/σ2\Lambda = n(\bar x - \mu_0)^2/\sigma^2.

(4) ℓ(μ,v)=−n2log⁡v−∑(xi−μ)2/(2v)\ell(\mu, v) = -\tfrac n2\log v - \sum(x_i - \mu)^2/(2v) plus a constant. For fixed μ\mu it is maximized at v(μ)=∑(xi−μ)2/nv(\mu) = \sum(x_i - \mu)^2/n, with value −n2log⁡v(μ)−n2-\tfrac n2\log v(\mu) - \tfrac n2. The full maximum is at μ=xˉ\mu = \bar x, v=SS/nv = SS/n; the restricted one at v0=(SS+n(xˉ−μ0)2)/nv_0 = (SS + n(\bar x - \mu_0)^2)/n. So Λ=nlog⁡(v0/(SS/n))=nlog⁡(1+n(xˉ−μ0)2/SS)\Lambda = n\log(v_0/(SS/n)) = n\log(1 + n(\bar x - \mu_0)^2/SS). Since T2=n(xˉ−μ0)2(n−1)/SST^2 = n(\bar x - \mu_0)^2(n - 1)/SS, this is nlog⁡(1+T2/(n−1))n\log(1 + T^2/(n - 1)).

(5) ℓ(q)=∑jOjlog⁡qj\ell(q) = \sum_j O_j\log q_j plus a constant, maximized over the simplex at q^j=Oj/n\hat q_j = O_j/n (Gibbs' inequality: ∑jOjlog⁡(q^j/qj)=n KL(q^ ∥ q)≥0\sum_j O_j\log(\hat q_j/q_j) = n\,\mathrm{KL}(\hat q\,\|\,q) \ge 0). So Λ=2∑jOjlog⁡(Oj/(nqj))\Lambda = 2\sum_j O_j\log(O_j/(nq_j)), and the linear parts ∑j(−Oj+nqj)=−n+n=0\sum_j(-O_j + nq_j) = -n + n = 0 add nothing. □\square

Lemma 5 (p-value and size). Let p=Q(r/2,Λ/2)=P(χr2≥Λ)p = Q(r/2, \Lambda/2) = P(\chi^2_r \ge \Lambda).

  1. If Λ∼χr2\Lambda \sim \chi^2_r exactly under H0H_0, then PH0(p≤α)=αP_{H_0}(p \le \alpha) = \alpha for all α∈[0,1]\alpha \in [0, 1].
  2. If Λ→χr2\Lambda \to \chi^2_r in distribution under H0H_0, then PH0(p≤α)→αP_{H_0}(p \le \alpha) \to \alpha.
  3. For a normal mean with known σ\sigma, Λ∼χ12\Lambda \sim \chi^2_1 exactly under H0H_0, for every n≥1n \ge 1.

Proof. The survival function G(c)=P(χr2≥c)G(c) = P(\chi^2_r \ge c) is continuous and strictly decreasing on [0,∞)[0, \infty), from 1 to 0. So {p≤α}={Λ≥G−1(α)}\{p \le \alpha\} = \{\Lambda \ge G^{-1}(\alpha)\} for 0<α<10 < \alpha < 1. In case 1 this has probability G(G−1(α))=αG(G^{-1}(\alpha)) = \alpha. In case 2 the limit law has a continuous CDF, so P(Λ≥c)→G(c)P(\Lambda \ge c) \to G(c) for each fixed cc, and the same set has probability tending to α\alpha. For case 3, Z=n(Xˉ−μ0)/σ∼N(0,1)Z = \sqrt n(\bar X - \mu_0)/\sigma \sim N(0, 1) under H0H_0, as on the z-test page, and Λ=Z2\Lambda = Z^2, which is χ12\chi^2_1 by definition. □\square

Case 2 holds under the conditions of Wilks' theorem. The routine does not check them, and for finite nn its size is only measured, not proved: the exact binomial sizes are computed in the tests by enumeration, for example 0.0414 at n=20n = 20.

Lemma 6 (the finite Neyman-Pearson routine). Let f0,f1f_0, f_1 be probability vectors on {1,…,m}\{1, \dots, m\} and 0≤α≤10 \le \alpha \le 1. MOST-POWERFUL-TEST returns ϕ∈[0,1]m\phi \in [0, 1]^m with ∑iϕif0(i)=α\sum_i \phi_i f_0(i) = \alpha, and ϕ\phi maximizes ∑iϕif1(i)\sum_i \phi_i f_1(i) over all ψ∈[0,1]m\psi \in [0, 1]^m with ∑iψif0(i)≤α\sum_i \psi_i f_0(i) \le \alpha.

Proof. The routine sets ϕi=1\phi_i = 1 where f0(i)=0<f1(i)f_0(i) = 0 < f_1(i), which costs no size. It then takes the distinct values kk of f1/f0f_1/f_0 on {f0>0}\{f_0 > 0\} in decreasing order, including the value 0, and gives each class the share min⁡(1,budget/mass)\min(1, \text{budget}/\text{mass}), where mass is the f0f_0 mass of the class, until the budget is 0. The total f0f_0 mass of all classes is 1 ≥α\ge \alpha, so the budget reaches 0 at some class; let k∗≥0k^* \ge 0 be its ratio. Every share is in [0,1][0, 1], and the shares spend exactly α\alpha, so ∑iϕif0(i)=α\sum_i \phi_i f_0(i) = \alpha. Also ϕi=1\phi_i = 1 where f1(i)>k∗f0(i)f_1(i) > k^* f_0(i), ϕi=0\phi_i = 0 where f1(i)<k∗f0(i)f_1(i) < k^* f_0(i), and ϕ\phi is constant on the class f1=k∗f0f_1 = k^* f_0. The points with f0=0=f1f_0 = 0 = f_1 get ϕi=0\phi_i = 0 and contribute nothing to size or power. For optimality, take any ψ\psi as in the statement. For every ii, (ϕi−ψi)(f1(i)−k∗f0(i))≥0(\phi_i - \psi_i)(f_1(i) - k^* f_0(i)) \ge 0, because ϕi=1≥ψi\phi_i = 1 \ge \psi_i where the second factor is positive and ϕi=0≤ψi\phi_i = 0 \le \psi_i where it is negative. Summing, ∑(ϕi−ψi)f1(i)≥k∗∑(ϕi−ψi)f0(i)=k∗(α−∑ψif0(i))≥0\sum(\phi_i - \psi_i) f_1(i) \ge k^* \sum(\phi_i - \psi_i) f_0(i) = k^*(\alpha - \sum \psi_i f_0(i)) \ge 0. So the power of ϕ\phi is at least that of ψ\psi. □\square

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 ∣d∣<0.1|d| < 0.1 and the partial sums are bounded below by d2/2−∣d∣3/6>0d^2/2 - |d|^3/6 > 0, the sum of the first two terms when d>0d > 0 and less than the first term when d<0d < 0 (the case d=0d = 0 returns 0 after one term). MOST-POWERFUL-TEST loops at most mm times over the distinct ratio values.

Theorem. LIKELIHOOD-RATIO-TEST returns Λ=2(ℓ(θ^)−ℓ(θ^0))≥0\Lambda = 2(\ell(\hat\theta) - \ell(\hat\theta_0)) \ge 0 and p=P(χr2≥Λ)p = P(\chi^2_r \ge \Lambda). The statistic is invariant under reparametrization, the closed forms agree with the general definition, and rejecting when p≤αp \le \alpha has size tending to α\alpha whenever Λ→χr2\Lambda \to \chi^2_r under H0H_0, and size exactly α\alpha for the normal mean with known σ\sigma. MOST-POWERFUL-TEST returns a most powerful test of size α\alpha.

Proof. Lemmas 1 to 6. ■\blacksquare

Complexity

On a real RAM, with closed-form maximizers, the statistic needs one pass over the data or the cells: Θ(n)\Theta(n) time for the binomial, Poisson and normal forms, and Θ(m)\Theta(m) for a multinomial with mm cells after counting. The p-value is one evaluation of the incomplete gamma function. The extra space is Θ(1)\Theta(1). In the general case, the cost is that of the two optimizations in lines L1 and L2, typically a number of iterations times Θ(nk2+k3)\Theta(nk^2 + k^3) for Newton steps in kk parameters.

Numerical stability. Three points matter.

  • Cancellation near the null. Written as 2[klog⁡(k/(np0))+(n−k)log⁡((n−k)/(n(1−p0)))]2[k\log(k/(np_0)) + (n - k)\log((n - k)/(n(1 - p_0)))], the binomial statistic is a difference of two large numbers when p^\hat p is near p0p_0. With n=109n = 10^9 and k=500 000 001k = 500\,000\,001, the true Λ\Lambda is 4×10−94 \times 10^{-9}, and the naive formula returns −1.07×10−7-1.07 \times 10^{-7}, a negative number. The deviance term D(a,b)=b h(a/b)D(a, b) = b\,h(a/b) with h(t)=tlog⁡t−t+1h(t) = t\log t - t + 1 is computed from the series h(1+d)=∑j≥2(−1)jdj/(j(j−1))h(1 + d) = \sum_{j \ge 2} (-1)^j d^j/(j(j - 1)) when ∣d∣<0.1|d| < 0.1, 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 nn. 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 Q(r/2,Λ/2)Q(r/2, \Lambda/2) directly, by a continued fraction for large arguments. Computing 1−P(r/2,Λ/2)1 - P(r/2, \Lambda/2) returns 0 for p-values below about 10−1610^{-16}. For σ\sigma unknown, log⁡(1+u)\log(1 + u) is computed with log1p.

Properties

  • Invariant under reparametrization. The value of Λ\Lambda does not change when θ\theta is replaced by g(θ)g(\theta) for a one-to-one gg. The Wald test does not have this property.
  • Nonnegative and nested. Λ≥0\Lambda \ge 0, and adding constraints to Θ0\Theta_0 can only increase it.
  • Asymptotically χr2\chi^2_r under the null. By Wilks' theorem, with the conditions stated there. The size is only near α\alpha for finite nn.
  • Asymptotically equivalent to the Wald and score tests. Under the null and local alternatives, the three statistics differ by op(1)o_p(1). In finite samples they differ. For a normal mean with unknown variance, with u=T2/(n−1)u = T^2/(n - 1), they are W=nuW = nu, Λ=nlog⁡(1+u)\Lambda = n\log(1 + u) and S=nu/(1+u)S = nu/(1 + u), so W≥Λ≥SW \ge \Lambda \ge S always.
  • Optimal for simple hypotheses. For a simple null against a simple alternative, rejecting for large L(θ1;x)/L(θ0;x)L(\theta_1; x)/L(\theta_0; x) 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 f1/f0f_1/f_0, reject at the points with the largest ratios until the size α\alpha is used, and randomize at the last point. The implementation provides it in exact rational arithmetic. Under H0H_0, the ratio f1(X)/f0(X)f_1(X)/f_0(X) has expectation at most 1, so it is also an e-variable.
  • Signed root. For a scalar parameter, r=sign⁡(θ^−θ0)Λr = \operatorname{sign}(\hat\theta - \theta_0)\sqrt\Lambda is approximately N(0,1)N(0, 1) and gives one-sided tests and likelihood-based confidence intervals.
  • Profile likelihood intervals. Inverting the LRT gives the set {θ0:Λ(θ0)<χ1,1−α2}\{\theta_0 : \Lambda(\theta_0) < \chi^2_{1, 1-\alpha}\}, which is invariant under reparametrization and often better than the Wald interval. See test-interval duality.
  • Bartlett correction. Dividing Λ\Lambda by an estimate of E0Λ/rE_0\Lambda/r improves the chi-squared approximation from error O(n−1)O(n^{-1}) to O(n−2)O(n^{-2}). Wilks' theorem shows the numbers for the normal mean.
  • Parametric bootstrap. Simulate data from the fitted null model θ^0\hat\theta_0, recompute Λ\Lambda each time, and use the simulated distribution in place of χr2\chi^2_r. See parametric bootstrap. This also handles boundary cases.
  • Deviance and G-test. In generalized linear models, Λ\Lambda is a difference of deviances. For counts, Λ\Lambda 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 nn 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 Λ\Lambda by a parametric bootstrap.

Pitfalls

  • Parameters on the boundary. Testing a variance component equal to 0, or a mixture weight equal to 0, puts θ0\theta_0 on the edge of Θ\Theta. The null law is then a mixture such as 12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1, and the χ12\chi^2_1 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 nn.
  • Non-nested models. Λ\Lambda 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 Λ\Lambda means nothing. Fit both models to the same rows.
  • A local maximum. If the optimizer stops at a local maximum in line L1, Λ\Lambda is too small, and it can even be negative. Start the full fit from the null fit, which guarantees ℓ(θ^)≥ℓ(θ^0)\ell(\hat\theta) \ge \ell(\hat\theta_0).
  • 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 n=5n = 5, 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.

lrt_core.pyI0RawGitHub
# 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 λ\lambda 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 −2log⁡λ-2\log\lambda 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

  1. 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)
  2. 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
  3. Neyman and Pearson 1928, the likelihood ratio criterion lambda for composite hypotheses
  4. 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

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example