Module contents
Lesson 11 of 27Advanced 110 min

Optimal tests and the asymptotic trinity: Neyman-Pearson, likelihood ratio, Wald and score

Derive Neyman–Pearson and Karlin–Rubin optimal tests, compare likelihood-ratio, Wald and score tests, and recognize when Wilks fails or universal inference applies.

After this lesson you can

  • Use the Neyman–Pearson lemma and monotone likelihood ratios to identify most powerful tests.
  • Derive and compare generalized likelihood-ratio, Wald and score tests.
  • Apply Wilks’ theorem and identify boundary, mixture and nonregular failures.
  • Explain finite-sample validity and power tradeoffs of split likelihood-ratio inference.

Before you start

Motivation: which is the best test?

In the previous lesson a hypothesis test was a rule deciding from data whether to reject H0H_0. Given size α\alpha (maximum probability of a type I error), all tests at that level are equally cautious. But they are not equally useful: what distinguishes them is power, the chance of rejection when H0H_0 is false. Tests at the same level can have very different power.

A numerical example. You have n=10n = 10 observations Xi∼iidN(μ,1)X_i \iid \Normal(\mu, 1) and want to test H0:μ=0H_0: \mu = 0 versus H1:μ=1H_1: \mu = 1 at 5 %. Three reasonable candidates reject for large statistics: the mean, the median, or, as an extreme case, the first observation. The cell calibrates each critical value by simulation under H0H_0 and measures power under H1H_1.

[ ]Three tests at the same levelBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(0)
n, R, alfa = 10, 50_000, 0.05
X0 = rng.normal(0.0, 1.0, size=(R, n))     # datos bajo H0: mu = 0
X1 = rng.normal(1.0, 1.0, size=(R, n))     # datos bajo H1: mu = 1

estadisticos = {
    "media": lambda X: X.mean(axis=1),
    "mediana": lambda X: np.median(X, axis=1),
    "solo X1": lambda X: X[:, 0],
}
for nombre, T in estadisticos.items():
    c = np.quantile(T(X0), 1 - alfa)        # valor crítico: cuantil 0.95 bajo H0
    print(f"{nombre:8s} c = {c:6.3f}   tamaño = {(T(X0) > c).mean():.3f}   potencia = {(T(X1) > c).mean():.3f}")

print("potencia exacta del test de la media:", round(stats.norm.cdf(np.sqrt(n) - stats.norm.ppf(1 - alfa)), 4))

All three have size 0.05, with power 0.935, 0.855, and 0.258. The first-observation test discards nine of ten data points and pays for it. The median uses all observations but summarizes them less efficiently for normal data. Can any test beat the mean? Does an optimal test always exist? This lesson answers in three stages:

  1. Simple hypotheses (one distribution each under H0H_0 and H1H_1): the Neyman–Pearson lemma specifies the most powerful test exactly. Reject when the likelihood ratio is large.
  2. One-sided hypotheses in families with monotone likelihood ratio: the same test is optimal against all alternatives simultaneously (Karlin–Rubin). For two-sided alternatives such a test generally does not exist.
  3. General composite hypotheses: no exact optimum exists, but the generalized likelihood ratio with its asymptotic χ2\chi^2 distribution (Wilks’ theorem), and its two asymptotic siblings, Wald and score, form the trinity behind nearly every p-value printed by statistical software. We will see when Wilks fails and a test, universal inference, needing no regularity conditions.

Randomized tests: the language of optimality

To discuss optima, a more general definition helps. Instead of a rejection region RR, a test is a function ϕ:X→[0,1]\phi: \mathcal{X} \to [0, 1] giving the probability of rejection given data xx: if ϕ(x)=1\phi(x) = 1 reject; if ϕ(x)=0\phi(x) = 0 do not; if ϕ(x)=γ∈(0,1)\phi(x) = \gamma \in (0, 1) flip a coin with probability γ\gamma. Ordinary regions are the case ϕ=1R\phi = \ind_R.

Why allow a coin? With discrete data, region sizes form a finite set and without randomization the level-α\alpha optimum may not exist. Randomization makes the problem convex: mixtures of tests are tests, and the set of attainable (size, power) pairs is convex. In practice almost nobody flips the coin, but it makes the theorems clean.

The Neyman–Pearson lemma

Start with the simplest case: H0:X∼p0H_0: X \sim p_0 versus H1:X∼p1H_1: X \sim p_1, with known densities (or masses) p0p_0 and p1p_1. Think of sample space as points, each with cost p0(x)p_0(x) (added size if included in the rejection region) and value p1(x)p_1(x) (added power). You have a cost budget α\alpha and want maximum value. This is the fractional knapsack problem, with known greedy solution: include points in descending value/cost order p1(x)/p0(x)p_1(x)/p_0(x) until the budget runs out, taking the affordable fraction of the last.

InteractiveBuilding the most powerful region
Sample space (x1,x2)(x_1, x_2) in 24×24 cells. H1H_1: Xi∼iidN(0.8,1)X_i \iid \Normal(0.8, 1)
−2−20022x₁x₂
  • your rejection region
  • Neyman-Pearson, same size
  • randomized cell (fraction γ)
Power versus size: no region lies above the frontier
ignore the data: φ ≡ α
  • Neyman-Pearson frontier
  • your region
0.10
Size of your region, P0(R)P_0(R)8.76 %
Power of your region, P1(R)P_1(R)29.0 %
Neyman-Pearson at the same size41.2 %
Randomized boundary cell, γ\gamma0.65
At the same size, Neyman-Pearson detects H1H_1 12.1 % more often. No region exceeds it.
Two independent observations (x1,x2)(x_1, x_2), N(0,1)\Normal(0, 1) under H0H_0; sample space is discretized into 24×24 cells. Paint cells (click or drag) to build your rejection region: readouts give size P0(R)P_0(R) and power P1(R)P_1(R), and the blue outline is the Neyman–Pearson region at exactly the same size, with randomized boundary cell dashed. At right, the maximum-power frontier versus size: your orange point is never above it. Start with each pair's naive region, then press 'Fill by likelihood ratio'. Try 'Normal versus Laplace': did you expect the optimum region to include the center?

Four things the figure shows and the theorem formalizes:

  1. Only the order matters. Cell shading is likelihood ratio, and the optimal region of any size is a level set {p1/p0>k}\{p_1/p_0 > k\}. For a mean shift, p1/p0=exp⁡(0.8(x1+x2)−0.64)p_1/p_0 = \exp(0.8(x_1 + x_2) - 0.64) depends only on x1+x2x_1 + x_2, and the region is a diagonal half-plane. Looking only at x1x_1 gives a same-size vertical half-plane with lower power.
  2. Shape can surprise. Against a Laplace of the same variance, p1/p0∝∏iexp⁡(xi2/2−2∣xi∣)p_1/p_0 \propto \prod_i \exp(x_i^2/2 - \sqrt{2}\abs{x_i}), large at the center (Laplace has a sharp peak) and in tails, small near ∣xi∣≈2\abs{x_i} \approx \sqrt 2. The optimal region includes the center, which no “reject if data are extreme” intuition would suggest.
  3. The frontier is concave. Adding cells in decreasing ratio order means each adds less power per unit size than the last: the curve’s slope is exactly the last cell’s ratio. Concavity comes from the convex set of tests discussed above.
  4. The diagonal is the floor. Test ϕ≡α\phi \equiv \alpha, ignoring data and rejecting with probability α\alpha, has power α\alpha. The frontier never lies below it, so optimal power is at least size.

The result is the Neyman–Pearson lemma, from 1933. Its proof fits on one line, best first seen in discrete sample space, as in the figure.

Proof

We prove sufficiency, the heart of the lemma; existence and the continuous-density version are a guided exercise. Let ϕ\phi be any level-α\alpha test. At each xx,

(ϕ∗(x)−ϕ(x))(p1(x)−k p0(x))≥0.\big(\phi^*(x) - \phi(x)\big)\big(p_1(x) - k\,p_0(x)\big) \ge 0.

Indeed: if p1(x)>k p0(x)p_1(x) > k\,p_0(x), then ϕ∗(x)=1≥ϕ(x)\phi^*(x) = 1 \ge \phi(x) and both factors are nonnegative; if p1(x)<k p0(x)p_1(x) < k\,p_0(x), then ϕ∗(x)=0≤ϕ(x)\phi^*(x) = 0 \le \phi(x) and both are nonpositive; under equality the second factor is zero. Summing over xx (or integrating),

E1[ϕ∗]−E1[ϕ]  ≥  k(E0[ϕ∗]−E0[ϕ])=k(α−E0[ϕ])  ≥  0,\E_1[\phi^*] - \E_1[\phi] \;\ge\; k\big(\E_0[\phi^*] - \E_0[\phi]\big) = k\big(\alpha - \E_0[\phi]\big) \;\ge\; 0,

because k≥0k \ge 0 and E0[ϕ]≤α\E_0[\phi] \le \alpha. Power of ϕ∗\phi^* is at least that of ϕ\phi. For necessity, if ϕ\phi is also MP, the first inequality is equality, so the nonnegative integrand is zero almost surely: ϕ=ϕ∗\phi = \phi^* outside {p1=k p0}\{p_1 = k\,p_0\}.

∎

Two immediate corollaries. First, MP test power exceeds its size unless P0=P1P_0 = P_1: compare ϕ∗\phi^* with constant ϕ≡α\phi \equiv \alpha, which has level α\alpha and power α\alpha. This gives β≥α\beta \ge \alpha; equality would make ϕ≡α\phi \equiv \alpha also MP and, by necessity, of the lemma’s form, which with α∈(0,1)\alpha \in (0, 1) forces p1=k p0p_1 = k\,p_0 almost surely, i.e. k=1k = 1 and P0=P1P_0 = P_1. Second, the test depends on data only through p1(x)/p0(x)p_1(x)/p_0(x); if TT is a sufficient statistic, the factorization theorem makes the ratio, and hence optimal test, a function of TT.

Discrete data and randomization

With X∼Bin⁡(10,p)X \sim \Bin(10, p) and H0:p=0.5H_0: p = 0.5 versus H1:p=0.7H_1: p = 0.7, ratio p1(x)/p0(x)=(0.7/0.5)x(0.3/0.5)10−xp_1(x)/p_0(x) = (0.7/0.5)^x (0.3/0.5)^{10-x} increases with xx, so the optimal test rejects for large xx. But P0(X≥9)=0.0107P_0(X \ge 9) = 0.0107 and P0(X≥8)=0.0547P_0(X \ge 8) = 0.0547: no region {X≥c}\{X \ge c\} has size 0.05. The lemma says what to do: always reject if X≥9X \ge 9 and, if X=8X = 8, reject with probability γ=(0.05−0.0107)/P0(X=8)\gamma = (0.05 - 0.0107)/P_0(X = 8).

[ ]Discrete Neyman–Pearson with randomizationBrowser
import numpy as np
from scipy import stats

n, p0, p1, alfa = 10, 0.5, 0.7, 0.05
x = np.arange(n + 1)
f0, f1 = stats.binom.pmf(x, n, p0), stats.binom.pmf(x, n, p1)
print("razón p1/p0:", np.round(f1 / f0, 3))          # creciente en x

def neyman_pearson(f0, f1, alfa):
    """Test de Neyman-Pearson aleatorizado en un espacio finito: devuelve phi(x) en [0, 1]."""
    orden = np.argsort(-(f1 / f0), kind="stable")   # de mayor a menor razón
    phi, gastado = np.zeros_like(f0), 0.0
    for k in orden:
        if gastado + f0[k] <= alfa + 1e-15:
            phi[k], gastado = 1.0, gastado + f0[k]
        else:
            phi[k] = (alfa - gastado) / f0[k]          # la fracción que cabe: aleatorización
            break
    return phi

phi = neyman_pearson(f0, f1, alfa)
print("phi(x):", np.round(phi, 4))
print(f"aleatorizado:  tamaño = {phi @ f0:.4f}   potencia = {phi @ f1:.4f}")
for c in (8, 9):
    print(f"X >= {c}:        tamaño = {f0[c:].sum():.4f}   potencia = {f1[c:].sum():.4f}")

The randomized test has power 0.358; conservative {X≥9}\{X \ge 9\}, what non-randomizing software would do, reaches 0.149, less than half. {X≥8}\{X \ge 8\} has more power but exceeds 5 %. Thus exact tests on small counts are very conservative, and remedies such as mid-p count only half the mass at the observation. You will see this with Fisher’s exact test.

Monotone likelihood ratio and UMP tests

The normal-mean example had a fortunate property: the MP test against μ1\mu_1 was the same for every μ1>μ0\mu_1 > \mu_0. Thus it is MP against each alternative simultaneously, i.e. UMP for H1:μ>μ0H_1: \mu > \mu_0. The enabling property has a name.

The main source of examples is the one-parameter exponential family. If pθ(x)=h(x)exp⁡{η(θ)T(x)−A(θ)}p_\theta(x) = h(x)\exp\{\eta(\theta)T(x) - A(\theta)\} with increasing η\eta, then

pθ′′(x)pθ′(x)=exp⁡{(η(θ′′)−η(θ′))T(x)−(A(θ′′)−A(θ′))},\frac{p_{\theta''}(x)}{p_{\theta'}(x)} = \exp\big\{(\eta(\theta'') - \eta(\theta'))T(x) - (A(\theta'') - A(\theta'))\big\},

which increases in TT because η(θ′′)>η(θ′)\eta(\theta'') > \eta(\theta'). Thus normal with known variance (in ∑xi\sum x_i), Poisson (in ∑xi\sum x_i), binomial (in success count), and exponential with rate λ\lambda (in −∑xi-\sum x_i, because η(λ)=−λ\eta(\lambda) = -\lambda decreases; in mean 1/λ1/\lambda, in ∑xi\sum x_i) have MLR. Outside exponential families, uniform Unif⁡(0,θ)\Unif(0, \theta) has MLR in max⁡ixi\max_i x_i. Some families lack it: location Cauchy does not have MLR, and has no one-sided UMP test for its center.

Proof

Fix θ1>θ0\theta_1 > \theta_0. By MLR, pθ1/pθ0p_{\theta_1}/p_{\theta_0} is a nondecreasing function g(T)g(T). Take k=g(c)k = g(c). If g(T)>kg(T) > k, then T>cT > c (if T≤cT \le c, monotonicity gives g(T)≤g(c)g(T) \le g(c)); if g(T)<kg(T) < k, then T<cT < c. Thus {pθ1>k pθ0}⊆{T>c}\{p_{\theta_1} > k\,p_{\theta_0}\} \subseteq \{T > c\}, where ϕ∗=1\phi^* = 1, and {pθ1<k pθ0}⊆{T<c}\{p_{\theta_1} < k\,p_{\theta_0}\} \subseteq \{T < c\}, where ϕ∗=0\phi^* = 0: ϕ∗\phi^* has Neyman–Pearson form and size α\alpha at θ0\theta_0, so the lemma’s sufficiency makes it MP for θ0\theta_0 versus θ1\theta_1. The test does not depend on θ1\theta_1, so it is MP against every θ1>θ0\theta_1 > \theta_0.

It remains to show level α\alpha over the composite null θ≤θ0\theta \le \theta_0. For any θ′<θ′′\theta' < \theta'', the same argument shows ϕ∗\phi^* is MP for θ′\theta' versus θ′′\theta'' with its own size β(θ′)\beta(\theta'); by the lemma’s corollary, its power exceeds that of constant test ϕ≡β(θ′)\phi \equiv \beta(\theta'), i.e. β(θ′′)≥β(θ′)\beta(\theta'') \ge \beta(\theta'). Power is nondecreasing and sup⁡θ≤θ0β(θ)=β(θ0)=α\sup_{\theta \le \theta_0}\beta(\theta) = \beta(\theta_0) = \alpha. Finally any other level-α\alpha ϕ\phi for the composite null satisfies Eθ0[ϕ]≤α\E_{\theta_0}[\phi] \le \alpha, so its power at each θ1\theta_1 cannot exceed ϕ∗\phi^*.

∎

This is the uniformly most powerful test provided by monotone likelihood ratio: the one-sided zz test, Poisson rate test, and exact one-sided binomial test are UMP. But this luck ends for two-sided alternatives.

[ ]There is no two-sided UMP testBrowser
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

n, alfa = 25, 0.05
z1, z2 = stats.norm.ppf(1 - alfa), stats.norm.ppf(1 - alfa / 2)
mu = np.linspace(-1, 1, 401)
d = np.sqrt(n) * mu                          # media de Z = sqrt(n) * media muestral
pot_der = stats.norm.sf(z1 - d)              # rechaza si Z > z_{1-alfa}: UMP para mu > 0
pot_izq = stats.norm.cdf(-z1 - d)            # rechaza si Z < -z_{1-alfa}: UMP para mu < 0
pot_bil = stats.norm.sf(z2 - d) + stats.norm.cdf(-z2 - d)
for m in (-0.5, 0.3, 0.5):
    i = np.argmin(np.abs(mu - m))
    print(f"mu = {m:+.1f}:  unilateral derecha {pot_der[i]:.3f}   izquierda {pot_izq[i]:.3f}   bilateral {pot_bil[i]:.3f}")

plt.plot(mu, pot_der, label="unilateral derecha (UMP si mu > 0)")
plt.plot(mu, pot_izq, label="unilateral izquierda (UMP si mu < 0)")
plt.plot(mu, pot_bil, "k--", label="bilateral")
plt.axhline(alfa, color="gray", lw=0.8)
plt.xlabel("mu"); plt.ylabel("potencia"); plt.legend(); plt.show()

At μ=0.5\mu = 0.5 right-sided power is 0.804 and two-sided power 0.705; at μ=−0.5\mu = -0.5 the right-sided test is useless (nearly zero power). No test dominates all others for every μ≠0\mu \ne 0. Classical theory recovers optimality by restricting the class: the two-sided test is UMP among unbiased tests, those with power at least α\alpha throughout the alternative (Lehmann and Romano, chapter 4). Outside exponential families and highly symmetric problems even that generally fails, requiring a different strategy: abandon exact optimality and seek good large-nn tests.

The generalized likelihood ratio

Neyman–Pearson compares two likelihoods. For composite hypotheses, the natural idea is to compare the best likelihoods on each side.

This is the generalized likelihood-ratio test (LRT). It measures how much fit worsens under the constraint. The factor 2 and logarithm make the limiting distribution χ2\chi^2 without constants.

We are rarely so lucky. For logistic regression, Poisson with several rates, or gamma, the exact distribution of WW is intractable. For large nn, however, we have a universal result.

Wilks’ theorem

Wilks’ theorem (1938) allows calculation of p-values for almost any nested-model comparison: degrees of freedom are the number of constraints, the dimension difference between Θ\Theta and Θ0\Theta_0, and nothing else about the model matters.

Proof

A sketch of the essential ideas. Write θ=θ0+h/n\theta = \theta_0 + \vb{h}/\sqrt n. By second-order Taylor’s theorem, with Δn=n−1/2∇ℓ(θ0)\vb{\Delta}_n = n^{-1/2}\grad\ell(\theta_0) (rescaled score) and the law of large numbers applied to the Hessian,

ℓ(θ0+h/n)−ℓ(θ0)=h⊤Δn−12h⊤Ih+op(1),\ell(\theta_0 + \vb{h}/\sqrt n) - \ell(\theta_0) = \vb{h}\T\vb{\Delta}_n - \tfrac12\vb{h}\T\mat{I}\vb{h} + o_p(1),

uniformly over bounded h\vb{h}, where I=I(θ0)\mat{I} = \mat{I}(\theta_0) and Δn→dN(0,I)\vb{\Delta}_n \xrightarrow{d} \Normal(\vb{0}, \mat{I}) by the CLT. Since both MLEs are consistent at rate n\sqrt n, maxima of ℓ\ell occur at that scale, and maximizing the parabola suffices. Completing the square with Zn=I−1/2Δn→dN(0,Ip)\vb{Z}_n = \mat{I}^{-1/2}\vb{\Delta}_n \xrightarrow{d} \Normal(\vb{0}, \mat{I}_p):

h⊤Δn−12h⊤Ih=12∥Zn∥2−12∥Zn−I1/2h∥2.\vb{h}\T\vb{\Delta}_n - \tfrac12\vb{h}\T\mat{I}\vb{h} = \tfrac12\norm{\vb{Z}_n}^2 - \tfrac12\norm{\vb{Z}_n - \mat{I}^{1/2}\vb{h}}^2.

Without restriction, the maximum occurs at I1/2h=Zn\mat{I}^{1/2}\vb{h} = \vb{Z}_n. Under restriction, h\vb{h} ranges (to first order) over tangent subspace TT to Θ0\Theta_0 at θ0\theta_0, dimension p−rp - r, and I1/2h\mat{I}^{1/2}\vb{h} ranges over same-dimensional S=I1/2TS = \mat{I}^{1/2}T. Subtracting maxima,

W=min⁡s∈S∥Zn−s∥2+op(1)=∥(Ip−PS)Zn∥2+op(1),W = \min_{\vb{s} \in S}\norm{\vb{Z}_n - \vb{s}}^2 + o_p(1) = \norm{(\mat{I}_p - \mat{P}_S)\vb{Z}_n}^2 + o_p(1),

where PS\mat{P}_S is orthogonal projection onto SS. Ip−PS\mat{I}_p - \mat{P}_S is a rank-rr projection, and the squared norm of a standard normal projected onto an rr-dimensional subspace is χr2\chi^2_r (Cochran’s decomposition of χ²).

∎

The geometry deserves a sentence: in the Fisher-information metric, Mahalanobis distance, log-likelihood is locally a round paraboloid, and WW is squared distance from the MLE to the null hypothesis. The p−rp - r directions along Θ0\Theta_0 do not count because the constrained MLE moves along them too; only the rr perpendicular directions count.

Inverting the test gives intervals: the set of θ0\theta_0 not rejected by likelihood ratio, {θ0:2(ℓ(θ^)−ℓperfil(θ0))≤χr;1−α2}\{\theta_0: 2(\ell(\hat\theta) - \ell_{\text{perfil}}(\theta_0)) \le \chi^2_{r;1-\alpha}\}, is lesson 9’s profile likelihood interval, another face of test–interval duality.

How good is the approximation at moderate nn? The cell tests equality of three groups of 10 Poisson counts (p=3p = 3, r=2r = 2), comparing simulated WW with χ22\chi^2_2. Then it repeats this for a model violating regularity, uniform Unif⁡(0,θ)\Unif(0, \theta), whose support depends on the parameter.

[ ]Wilks in action and a nonregular modelBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
R, k, m, lam = 20_000, 3, 10, 2.0                  # 3 grupos de 10 recuentos, misma media bajo H0
Y = rng.poisson(lam, size=(R, k, m))
medias = Y.mean(axis=2)                             # EMV sin restricción: una tasa por grupo
comun = Y.mean(axis=(1, 2))                         # EMV bajo H0: una tasa común
with np.errstate(divide="ignore", invalid="ignore"):
    t = np.where(medias > 0, medias * np.log(medias / comun[:, None]), 0.0)
W = 2 * m * t.sum(axis=1)                           # 2[l(theta_hat) - l(theta_tilde)]
print("Poisson, r = 2:")
for q in (0.90, 0.95, 0.99):
    print(f"  cuantil {q}: simulado {np.quantile(W, q):6.3f}   chi2_2 {stats.chi2.ppf(q, 2):6.3f}"
          f"   tamaño real del test al {1 - q:.0%}: {np.mean(W > stats.chi2.ppf(q, 2)):.4f}")

# Unif(0, theta), H0: theta = 1 (un solo parámetro, pero el soporte depende de él)
n = 20
Xmax = rng.random((R, n)).max(axis=1)
W_u = 2 * n * np.log(1 / Xmax)                       # L(theta) = theta^-n si theta >= max: el EMV es el máximo
print("\nUniforme, r = 1:")
print(f"  media de W: {W_u.mean():.3f}   (chi2_1 tendría 1, chi2_2 tiene 2)")
print(f"  tamaño real con chi2_1 al 5 %: {np.mean(W_u > stats.chi2.ppf(0.95, 1)):.3f}"
      f"   con chi2_2: {np.mean(W_u > stats.chi2.ppf(0.95, 2)):.3f}")

With only ten counts per group, simulated Poisson quantiles are close to χ22\chi^2_2 and actual size close to nominal. Uniform instead gives mean WW of 2 rather than 1: here W=2nlog⁡(1/X(n))W = 2n\log(1/X_{(n)}) and, since P(X(n)≤e−t/n)=e−tP(X_{(n)} \le e^{-t/n}) = e^{-t}, WW is exactly χ22\chi^2_2, two degrees of freedom for one constraint. Using χ12\chi^2_1 gives actual size 15 % rather than 5 %. The uniform MLE converges at rate nn, not n\sqrt n, so Wilks’ entire proof starting from a parabola at scale n\sqrt n collapses.

The trinity: Wald, score and likelihood ratio

Wilks’ proof shows that near θ0\theta_0 all information is in a parabola. Three natural ways to measure how far H0H_0 is from data using it yield three tests. Separate θ=(ψ,λ)\theta = (\psi, \lambda), with ψ∈Rr\psi \in \R^r the parameter of interest, λ\lambda nuisance, and H0:ψ=ψ0H_0: \psi = \psi_0. Write In(θ)=n I(θ)\mat{I}_n(\theta) = n\,\mat{I}(\theta) for whole-sample information and Iψψ\mat{I}^{\psi\psi} for the ψψ\psi\psi block of the inverse information matrix, the asymptotic covariance of ψ^\hat\psi accounting for estimating λ\lambda.

The Wald test (1943) appears in every coefficient table: z=β^j/SE(β^j)z = \hat\beta_j/\mathrm{SE}(\hat\beta_j) is its signed square root, with r=1r = 1. The score test (Rao, 1948) is known in econometrics as the Lagrange multiplier test, for a reason we will see. Wald, score and likelihood ratio form the asymptotic trinity.

With one parameter the formulas become transparent:

WRV=2(ℓ(θ^)−ℓ(θ0)),WW=n I(θ^) (θ^−θ0)2,WS=U(θ0)2n I(θ0).W_{\text{RV}} = 2\big(\ell(\hat\theta) - \ell(\theta_0)\big), \qquad W_{\text{W}} = n\,I(\hat\theta)\,(\hat\theta - \theta_0)^2, \qquad W_{\text{S}} = \frac{U(\theta_0)^2}{n\,I(\theta_0)}.

Geometry on a curve

Divide all three by 2 and regard them as heights on the graph of ℓ\ell. Likelihood ratio is the actual curve drop from maximum to θ0\theta_0. Wald replaces the curve by a parabola with vertex at θ^\hat\theta and curvature there, nI(θ^)n I(\hat\theta), measuring its drop at θ0\theta_0: 12nI(θ^)(θ^−θ0)2\tfrac12 n I(\hat\theta)(\hat\theta - \theta_0)^2. Score does the reverse: at θ0\theta_0 build a parabola with slope U(θ0)U(\theta_0) and expected curvature nI(θ0)n I(\theta_0) there, and measure how much it rises to its maximum, U(θ0)2/(2nI(θ0))U(\theta_0)^2/(2nI(\theta_0)). This is the likelihood improvement predicted by one Newton (Fisher scoring) step from θ0\theta_0.

InteractiveThe trinity on a curve
Relative log-likelihood ℓ−ℓmax⁡\ell - \ell_{\max} versus λ\lambda, with n=10n = 10: each statistic is twice a height
MLEθ₀−1.92: 5% boundary (LR)
  • log-likelihood; height = LR/2
  • Wald parabola (curvature at MLE); height = W/2
  • score parabola (slope and curvature at θ₀); height = S/2
The three statistics against critical value χ1; 0.952=3.84\chi^2_{1;\,0.95} = 3.84 (vertical line)
Likelihood ratio
7.73 p = 0.005
Wald
5.00 p = 0.025
Score
10.00 p = 0.002
10
2.00
1.00
Likelihood ratio7.726
Wald5.000
Score10.000
Information nI(θ^)n I(\hat\theta) | nI(θ0)n I(\theta_0)5.00 | 10.00
Same verdict, different values: the curve is not a parabola.
The blue curve is relative log-likelihood ℓ−ℓmax⁡\ell - \ell_{\max} for a one-parameter model with nn observations and your chosen MLE. Drag the plot to move θ0\theta_0. Three thick vertical bars are half-statistics: blue actual drop (likelihood ratio); orange Wald parabola drop, centered on the MLE; teal score parabola rise, tangent at θ0\theta_0. Below are all three statistics versus critical value 3.84. Under normality they always coincide. With Poisson, n=10n = 10, λ^=2\hat\lambda = 2 and λ0=1\lambda_0 = 1, they differ; increase nn and they converge. Enable log parameterization: the axis changes, but two heights do not and one does.

The figure’s initial configuration is a complete example. With n=10n = 10 Poisson observations of mean xˉ=2\bar x = 2 and H0:λ=1H_0: \lambda = 1:

WRV=2n(xˉlog⁡xˉλ0−(xˉ−λ0))=7.73,WW=n(xˉ−λ0)2xˉ=5,WS=n(xˉ−λ0)2λ0=10.W_{\text{RV}} = 2n\Big(\bar x\log\frac{\bar x}{\lambda_0} - (\bar x - \lambda_0)\Big) = 7.73, \qquad W_{\text{W}} = \frac{n(\bar x - \lambda_0)^2}{\bar x} = 5, \qquad W_{\text{S}} = \frac{n(\bar x - \lambda_0)^2}{\lambda_0} = 10.

All three reject at 5 % (χ1;0.952=3.84\chi^2_{1;0.95} = 3.84), but p-values range from 0.0016 (score) to 0.025 (Wald). The discrepancy comes from skewness: Poisson log-likelihood falls more slowly rightward than leftward, and each test approximates it with a different parabola. One figure detail: the score parabola peaks exactly at the MLE, because for Poisson one Fisher scoring step from λ0\lambda_0 reaches λ0+U(λ0)/(nI(λ0))=xˉ\lambda_0 + U(\lambda_0)/(nI(\lambda_0)) = \bar x. On scale ψ=log⁡λ\psi = \log\lambda, the curve is more symmetric and Wald becomes nxˉ(log⁡xˉ−log⁡λ0)2=9.61n\bar x(\log\bar x - \log\lambda_0)^2 = 9.61, much closer to the others. Likelihood ratio and score do not change. This is no accident.

Proof

(1) One parameter, simple H0H_0. Taylor-expanding score around θ^\hat\theta gives U(θ0)=nI(θ0)(θ^−θ0)(1+op(1))U(\theta_0) = n I(\theta_0)(\hat\theta - \theta_0)(1 + o_p(1)), and consistency gives I(θ^)=I(θ0)+op(1)I(\hat\theta) = I(\theta_0) + o_p(1). Substitution makes WSW_{\text{S}} and WWW_{\text{W}} both nI(θ0)(θ^−θ0)2+op(1)nI(\theta_0)(\hat\theta - \theta_0)^2 + o_p(1), the same as Wilks’ proof gave for WRVW_{\text{RV}}. Nuisance parameters use the same block argument. (2) ℓ\ell at a point does not depend on its name, so neither do the maxima forming WRVW_{\text{RV}}. For score, the chain rule gives Uϕ=Uθ/g′(θ)U_\phi = U_\theta/g'(\theta) and Iϕ=Iθ/g′(θ)2I_\phi = I_\theta/g'(\theta)^2, leaving U2/IU^2/I unchanged. Wald instead measures (θ^−θ0)2(\hat\theta - \theta_0)^2 on the chosen scale using curvature at θ^\hat\theta, and (g(θ^)−g(θ0))2/g′(θ^)2(g(\hat\theta) - g(\theta_0))^2/g'(\hat\theta)^2 does not equal (θ^−θ0)2(\hat\theta - \theta_0)^2 unless gg is affine.

∎

What distinguishes each

Wald: one fit, but parameterization-dependent. It needs only the full model, so comes free in regression output and gives θ^±1.96 SE\hat\theta \pm 1.96\,\mathrm{SE} intervals. Lack of invariance is not cosmetic. For nonlinear constraint g(θ)=0g(\theta) = 0, statistic g(θ^)⊤[GV^G⊤]−1g(θ^)g(\hat\theta)\T[\mat{G}\hat{\mat{V}}\mat{G}\T]^{-1}g(\hat\theta), with G\mat{G} the Jacobian of gg and V^\hat{\mat V} estimated covariance (the delta method), changes if the same hypothesis is written θ1−θ2=0\theta_1 - \theta_2 = 0 or θ1/θ2−1=0\theta_1/\theta_2 - 1 = 0, and at finite nn can give very different p-values for the same hypothesis (Gregory and Veall, 1985).

Wald can also be nonmonotone: in logistic regression, when a fitted probability approaches 0 or 1, the standard error of β^\hat\beta grows faster than β^\hat\beta, and zz falls as evidence against H0H_0 increases. This is the Hauck–Donner effect (1977). The cell produces it with two groups of 50: control has 25 successes, treated increases from 40 to 49.

[ ]The Hauck–Donner effectBrowser
import numpy as np
from scipy import stats

m, s0 = 50, 25                                    # grupo de control: 25 éxitos de 50
def ll(s, n, p):                                  # log-verosimilitud binomial
    return s * np.log(p) + (n - s) * np.log(1 - p)

print("  k   p1     beta1    SE     Wald    score    RV")
for k in range(40, 50):
    p0, p1, pc = s0 / m, k / m, (s0 + k) / (2 * m)
    b1 = np.log(p1 / (1 - p1)) - np.log(p0 / (1 - p0))                 # EMV de la pendiente logística
    se = np.sqrt(1 / (m * p0 * (1 - p0)) + 1 / (m * p1 * (1 - p1)))     # inversa de la información en el EMV
    wald = (b1 / se) ** 2
    score = (p1 - p0) ** 2 / (pc * (1 - pc) * 2 / m)                    # = chi2 de Pearson de la tabla 2x2
    rv = 2 * (ll(s0, m, p0) + ll(k, m, p1) - ll(s0 + k, 2 * m, pc))
    print(f"{k:3d}  {p1:.2f}  {b1:6.3f}  {se:6.3f}  {wald:6.2f}  {score:6.2f}  {rv:6.2f}")

Likelihood ratio and score rise continuously with kk. Wald peaks at 17.4 for k=47k = 47, then falls: 49 successes out of 50 in treatment is stronger evidence than 47, but Wald says the opposite. With complete separation (k=50k = 50), β^1=∞\hat\beta_1 = \infty and Wald is undefined.

Score: null model only. Score needs only the restricted model fit, making it unbeatable when the full model is expensive or problematic: check whether 40 interactions are missing from a large model, regression residuals are autocorrelated, or an overdispersion parameter is zero, without fitting the alternative. It is also invariant. Its econometric name comes from constrained optimization: maximizing ℓ(θ)\ell(\theta) subject to g(θ)=0g(\theta) = 0 with Lagrangian ℓ(θ)−μ⊤g(θ)\ell(\theta) - \vb{\mu}\T g(\theta) gives first-order condition U(θ~)=G(θ~)⊤μ~\vb{U}(\tilde\theta) = \mat{G}(\tilde\theta)\T\tilde{\vb{\mu}}. Lagrange multipliers measure how strongly the constraint pulls on the optimum; testing μ=0\vb{\mu} = \vb{0} tests whether score at the restricted optimum is zero.

The best-known score test is one you have probably used without realizing it.

Proof

Take free parameters p1,…,pk−1p_1, \dots, p_{k-1}, with pk=1−∑j<kpjp_k = 1 - \sum_{j<k}p_j. Then ℓ=∑jXjlog⁡pj\ell = \sum_j X_j\log p_j, and with aj=Xj/pja_j = X_j/p_j the score is Uj=aj−akU_j = a_j - a_k for j<kj < k. Information is In=n(diag⁡(1/p1,…,1/pk−1)+1pk11⊤)\mat{I}_n = n\big(\diag(1/p_1, \dots, 1/p_{k-1}) + \tfrac{1}{p_k}\vb{1}\vb{1}\T\big), whose inverse by Sherman–Morrison is 1n(diag⁡(p)−pp⊤)\tfrac1n\big(\diag(\vb{p}) - \vb{p}\vb{p}\T\big) (with p\vb{p} of length k−1k - 1). Thus

n WS=∑j<kpjUj2−(∑j<kpjUj)2.n\,W_{\text{S}} = \sum_{j<k} p_j U_j^2 - \Big(\sum_{j<k}p_j U_j\Big)^2.

The second parenthesis is ∑j<kXj−(1−pk)ak=n−ak\sum_{j<k}X_j - (1 - p_k)a_k = n - a_k. In the first add j=kj = k, whose term is zero, and expand around nn: since ∑jpj(aj−n)=∑jXj−n=0\sum_j p_j(a_j - n) = \sum_j X_j - n = 0,

∑j=1kpj(aj−ak)2=∑j=1kpj(aj−n)2+(n−ak)2.\sum_{j=1}^k p_j(a_j - a_k)^2 = \sum_{j=1}^k p_j(a_j - n)^2 + (n - a_k)^2.

Subtracting, n WS=∑jpj(Xj/pj−n)2=∑j(Xj−npj)2/pjn\,W_{\text{S}} = \sum_j p_j(X_j/p_j - n)^2 = \sum_j (X_j - np_j)^2/p_j, all evaluated at p0\vb{p}^0.

∎

The likelihood-ratio test for this problem is the G-test, 2∑jXjlog⁡(Xj/(npj0))2\sum_j X_j\log\big(X_j/(np^0_j)\big); both are asymptotically χk−12\chi^2_{k-1}. The coding exercise implements Pearson via score and checks agreement with scipy.

Likelihood ratio: two fits and best behavior. It needs both models, but is invariant, always defined (including separation), and usually has actual size closest to nominal at small nn. A Bartlett correction divides WW by an estimate of E[W]/r\E[W]/r, improving χ2\chi^2 approximation error from order 1/n1/n to 1/n21/n^2.

Fits neededInvariantSmall nnTypical use
Waldfull onlynoworst; Hauck–Donnercoefficient tables, quick intervals
Scorerestricted onlyyesoften good, somewhat conservativespecification diagnostics, Pearson χ2\chi^2
Likelihood ratiobothyesgenerally bestnested-model comparison, profile intervals

The trinity from scratch

Now implement all three tests for coefficient β1\beta_1 in logistic regression logit⁡P(Y=1∣x)=β0+β1x\operatorname{logit}P(Y = 1 \given x) = \beta_0 + \beta_1 x, vectorized over thousands of simulated datasets under H0:β1=0H_0: \beta_1 = 0. The restricted model has a closed-form solution (logit⁡p~=β~0\operatorname{logit}\tilde p = \tilde\beta_0 with p~=yˉ\tilde p = \bar y), making score explicit:

Uβ1(θ~)=∑ixi(yi−yˉ),WS=(∑ixi(yi−yˉ))2yˉ(1−yˉ)∑i(xi−xˉ)2.U_{\beta_1}(\tilde\theta) = \sum_i x_i(y_i - \bar y), \qquad W_{\text{S}} = \frac{\big(\sum_i x_i(y_i - \bar y)\big)^2}{\bar y(1 - \bar y)\sum_i(x_i - \bar x)^2}.
[ ]The trinity from scratch: actual size at small nBrowser
import numpy as np
from scipy import stats
from scipy.special import expit

def ajusta_logistica(x, y, iters=25):
    """EMV de logit P(Y=1) = b0 + b1 x por Newton-Raphson, vectorizado: una réplica por fila."""
    b0, b1 = np.zeros(len(y)), np.zeros(len(y))
    for _ in range(iters):
        mu = expit(b0[:, None] + b1[:, None] * x)
        w = mu * (1 - mu)
        u0, u1 = (y - mu).sum(1), ((y - mu) * x).sum(1)                 # score
        i00, i01, i11 = w.sum(1), (w * x).sum(1), (w * x * x).sum(1)    # información (matriz 2x2)
        det = i00 * i11 - i01**2
        b0, b1 = b0 + (i11 * u0 - i01 * u1) / det, b1 + (i00 * u1 - i01 * u0) / det
    eta = b0[:, None] + b1[:, None] * x
    ll = (y * eta - np.logaddexp(0, eta)).sum(1)
    w = expit(eta) * (1 - expit(eta))
    i00, i01, i11 = w.sum(1), (w * x).sum(1), (w * x * x).sum(1)
    return b1, ll, i00 / (i00 * i11 - i01**2)                           # b1, l(theta_hat), [I^-1]_11

def trinidad(x, y):
    """Wald, score y razón de verosimilitudes para H0: b1 = 0 (x, y de forma (R, n))."""
    n = y.shape[1]
    b1, ll1, var_b1 = ajusta_logistica(x, y)
    p = y.mean(1)                                                       # EMV restringido
    ll0 = n * (p * np.log(p) + (1 - p) * np.log(1 - p))
    u1 = (x * (y - p[:, None])).sum(1)
    xc = x - x.mean(1, keepdims=True)
    return b1**2 / var_b1, u1**2 / (p * (1 - p) * (xc**2).sum(1)), 2 * (ll1 - ll0)

rng = np.random.default_rng(1)
c = stats.chi2.ppf(0.95, 1)
R = 6000
print(f"tamaño real al 5 % bajo H0 (b0 = -0.5, b1 = 0), {R} réplicas por fila")
for n in (15, 30, 100):
    x = rng.normal(size=(R, n))
    y = (rng.random((R, n)) < expit(-0.5)).astype(float)
    ok = (y.sum(1) > 0) & (y.sum(1) < n)                                # descarta muestras sin variación en y
    w, s, l = trinidad(x[ok], y[ok])
    print(f"n = {n:3d}:   Wald {np.mean(w > c):.3f}   score {np.mean(s > c):.3f}   RV {np.mean(l > c):.3f}")

With 6000 replicates, Monte Carlo error per size is about ±0.006\pm 0.006. At n=15n = 15, Wald rejects 0.6 % when it should reject 5 %: many small samples approach separation, β^1\hat\beta_1 is large and its standard error huge, collapsing the statistic (Hauck–Donner again). Likelihood ratio overshoots at 7.7 %, and score is nearest nominal at 5.4 %. At n=30n = 30 all three are between 3 % and 6 %, and at n=100n = 100 all reject about 5 %, as promised. Score winning here is not a law; what is general is Wald’s fragility. Comparison with statsmodels is in the libraries section.

When Wilks fails

Wilks’ assumptions are not decorative. Three common situations violate them.

Boundary parameters

Testing whether a variance, mixture weight or nonnegative coefficient is zero: in all three the null value is on the boundary of Θ\Theta, not its interior. The classic model is a one-factor random-effects model yij=μ+ui+eijy_{ij} = \mu + u_i + e_{ij} with aa groups, nn observations per group, ui∼N(0,τ2)u_i \sim \Normal(0, \tau^2) and eij∼N(0,σ2)e_{ij} \sim \Normal(0, \sigma^2), and H0:τ2=0H_0: \tau^2 = 0 (no between-group variation).

The mechanism is visible in one dimension. If θ≥0\theta \ge 0 and H0:θ=0H_0: \theta = 0, the unconstrained MLE would be approximately N(0,1/(nI))\Normal(0, 1/(nI)); write Z=nI θ^libreZ = \sqrt{nI}\,\hat\theta_{\text{libre}}. Under the constraint the MLE is max⁡(θ^libre,0)\max(\hat\theta_{\text{libre}}, 0): half the time the curve peaks at the boundary and W=0W = 0; otherwise W=Z2W = Z^2. Therefore

W→d12χ02+12χ12,W \xrightarrow{d} \tfrac12\chi^2_0 + \tfrac12\chi^2_1,

a mixture of a point mass at 0 and χ12\chi^2_1 (Chernoff, 1954; Self and Liang, 1987, for the general case). Its 95 % quantile is the 90 % quantile of χ12\chi^2_1, 2.712.71, not 3.843.84. In practice the correct p-value is half that from χ12\chi^2_1.

InteractiveWilks at the boundary
Distribution of W=2(ℓ1−ℓ0)W = 2(\ell_1 - \ell_0) in 20,000 replicates, a=10a = 10, n=5n = 5
← W = 0: 62 % of replicates
  • simulation (bar at 0: 62 % mass)
  • χ12\chi^2_1 (naive Wilks)
  • 12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1, continuous part
Tail P(W>c)P(W > c) on a log scale: the test size at critical value cc
2.713.84α = 0.05
  • simulation under H0H_0
  • P(χ12>c)P(\chi^2_1 > c)
  • 12P(χ12>c)\tfrac12 P(\chi^2_1 > c)
Number of groups aa
Observations per group nn
0.00
P(W=0)P(W = 0) simulated | exact62.3 % | 62.3 %
Actual size with χ12\chi^2_1 (c=3.84c = 3.84)1.34 %
Actual size with mixture (c=2.71c = 2.71)2.83 %
Using Wilks' χ12\chi^2_1, the nominal 5% test rejects only 1.3 % of the time: it is conservative. The mixture comes closer; mass at 0 above 50% is a finite-aa effect.
20 000 exact likelihood-ratio statistic replicates for H0:τ2=0H_0: \tau^2 = 0 in a balanced one-factor model, simulated from sums of squares. Left: histogram of positive WW values and separate bar for exact zeros, with χ12\chi^2_1 density and continuous part of mixture 12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1. Right: tail P(W>c)P(W > c) on a log scale: at c=3.84c = 3.84 read the actual size using χ12\chi^2_1, at c=2.71c = 2.71 that using the mixture. Increase group count aa and see mass at 0 approach 50 %. Then set τ2>0\tau^2 > 0: how much power is lost with the wrong critical value?

The figure shows two things. First, as expected, the Wilks critical value makes the test conservative: with a=10a = 10 groups of n=5n = 5, the purported 5 % test rejects about 1.3 % under H0H_0, and loses substantial power under moderate alternatives. Second, more subtly, with finitely many groups the mass at 0 is not 50 % but much higher (62 % with a=10a = 10 and n=5n = 5), because the MLE hits the boundary when SSB/a≤SSW/(a(n−1))\mathrm{SSB}/a \le \mathrm{SSW}/(a(n - 1)), an event of probability P(Fa−1, a(n−1)≤a/(a−1))>1/2P(F_{a-1,\,a(n-1)} \le a/(a - 1)) > 1/2. The mixture 12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1 is the limit as group count grows; with few groups it remains conservative (with a=10a = 10 and n=5n = 5, its 5 % test rejects about 2.8 %), and Crainiceanu and Ruppert (2004) give the exact distribution. With multiple boundary parameters, the limit is a mixture of χ2\chi^2 laws with different degrees of freedom (χˉ2\bar\chi^2), with weights depending on constraint-cone geometry.

Number of mixture components

Testing one normal against a two-normal mixture, π N(μ1,σ2)+(1−π) N(μ2,σ2)\pi\,\Normal(\mu_1, \sigma^2) + (1 - \pi)\,\Normal(\mu_2, \sigma^2), looks like nested models with 4−2=24 - 2 = 2 constraints. It is not. The null can be reached two ways: π=0\pi = 0 (then μ1\mu_1 is meaningless) or μ1=μ2\mu_1 = \mu_2 (then π\pi is meaningless). Under H0H_0 the parameter is unidentifiable, Fisher information is singular, and Wilks’ parabola does not exist. Hartigan (1985) showed that if means are unbounded, WW does not even converge in distribution: it grows without bound, though so slowly (at rate log⁡log⁡n\log\log n, as Bickel and Chernoff clarified in 1993) that it looks stable in simulation. This is the typical problem of a parameter existing only under the alternative (Davies, 1977), arising when choosing component count in a Gaussian mixture, state count of a hidden model, or a structural change point.

Nonregular models

You saw uniform: when support depends on the parameter, the MLE converges faster than n\sqrt n and has a different limiting distribution (χ22\chi^2_2 for one constraint). Other examples: regime-change parameters, thresholds, unit-root models (Dickey–Fuller distribution in time series), and generally any problem where log-likelihood is not locally quadratic.

There are two exits. The practical one calibrates WW by parametric bootstrap: simulate many datasets from the fitted null, recompute WW each time, and use its empirical distribution (McLachlan, 1987, for mixtures). It often works, but its validity is also asymptotic and not guaranteed in nonregular problems. The second is a test whose validity does not depend on asymptotics.

Universal inference

In 2020, Wasserman, Ramdas and Balakrishnan proposed a likelihood-ratio test so simple it is surprising it was not known earlier. Split data into independent halves D0D_0 and D1D_1. Use D1D_1 to compute any estimator θ^1\hat\theta_1 of the parameter, e.g. the full-model MLE. With D0D_0 compute null MLE θ^0=arg max⁡θ∈Θ0L0(θ)\hat\theta_0 = \argmax_{\theta \in \Theta_0} L_0(\theta), where L0L_0 is the likelihood of D0D_0. The statistic is

T=L0(θ^1)L0(θ^0),T = \frac{L_0(\hat\theta_1)}{L_0(\hat\theta_0)},

and the test rejects H0H_0 if T≥1/αT \ge 1/\alpha.

This is the universal split-sample test (split LRT). The proof uses three ingredients, reconstructed step by step in an exercise: conditioning on D1D_1 freezes θ^1\hat\theta_1; since θ^0\hat\theta_0 maximizes L0L_0 over Θ0\Theta_0 and θ∗∈Θ0\theta^* \in \Theta_0, the denominator is at least L0(θ∗)L_0(\theta^*); and expectation of density ratio pθ^1(D0)/pθ∗(D0)p_{\hat\theta_1}(D_0)/p_{\theta^*}(D_0) under pθ∗p_{\theta^*} is at most 1. Given E[T]≤1\E[T] \le 1, Markov’s inequality finishes: P(T≥1/α)≤α E[T]≤αP(T \ge 1/\alpha) \le \alpha\,\E[T] \le \alpha.

The price is power. In a regular problem, 2log⁡T2\log T is compared with 2log⁡(1/α)=5.992\log(1/\alpha) = 5.99 rather than χr;0.952\chi^2_{r;0.95} (3.84 if r=1r = 1), and only half the data enter each part. The figure measures this in the motivating case: one normal versus a mixture of two with common variance.

InteractiveUniversal inference versus classical LRT
A sample of n=200n = 200 with δ=0.00\delta = 0.00 and the three fits
  • one normal (MLE with all data)
  • mixture on all data: classical LRT
  • mixture on D1D_1 (upper marks)
  • D0D_0, where TT is evaluated (below)
Rejection rate at 5% versus δ\delta: at δ=0\delta = 0 it is actual size, then power
α = 0.05
  • classical LRT with χ22\chi^2_2
  • universal (split LRT)
  • squares: live replicates ± 1.96 Monte Carlo errors
0.00
Classical LRT reference
Classical LRT: WW and p value with χ22\chi^2_21.39 (p = 0.498)
Universal: log⁡T\log T (reject if ≥log⁡20=3.00\ge \log 20 = 3.00)−1.04
Here H0H_0 is true. The universal test almost never rejects: its size is guaranteed below 5%, but is often far below.
Samples of n=200n = 200 from 12N(−δ/2,1)+12N(δ/2,1)\tfrac12\Normal(-\delta/2, 1) + \tfrac12\Normal(\delta/2, 1); at δ=0\delta = 0 data are one normal and H0H_0 is true. Left: a sample with normal fit, EM mixture fitted on all data (classical LRT), and mixture fitted only on half D1D_1 (universal test evaluated on D0D_0); marks below the axis show the halves. Right: 5 % rejection rate versus δ\delta, from a previous simulation of 2000 replicates per point: at δ=0\delta = 0 actual size, afterward power. Press 'Simulate' to repeat 400 live replicates at chosen δ\delta and compare with curves. Change the classical LRT reference from χ22\chi^2_2 to χ32\chi^2_3: which is correct?

Under H0H_0, classical LRT with naive reference χ22\chi^2_2 rejects 5.8 % of the time, and with χ32\chi^2_3 2.9 %. Neither has theoretical justification; one being near 5 % at n=200n = 200 is coincidence that does not persist as nn or parameter space changes. The universal test’s actual size is 0.05 %, a hundred times below the limit: very conservative, like the Markov inequality supporting it. At separation δ=2.5\delta = 2.5, classical LRT detects the mixture 90 % and universal 18 % of the time; at δ=3.5\delta = 3.5, universal rises to 85 %. The tradeoff is guaranteed validity at all nn and models, at the cost of power.

Two practical refinements. Cross-fitting swaps D0D_0 and D1D_1 and averages the two statistics: the average also has expectation at most 1 under H0H_0, so the test remains valid and less dependent on the split. The same construction yields universal confidence sets, {θ:L0(θ)/L0(θ^1)>α}\{\theta: L_0(\theta)/L_0(\hat\theta_1) > \alpha\}, valid where Wilks promises nothing. A nonnegative statistic with expectation at most 1 under H0H_0 is an e-value; in sequential experiments you will see that they can be multiplied over time and yield valid tests even when data are inspected daily.

[ ]Universal test for mixtures: a scikit-learn exampleBrowser
import numpy as np
from scipy import stats
from sklearn.mixture import GaussianMixture

def ll_normal(D, m, v):
    return -0.5 * len(D) * np.log(2 * np.pi * v) - 0.5 * ((D - m) ** 2).sum() / v

def split_lrt(x, ajusta_alt, loglik_alt, rng, alfa=0.05):
    """Split LRT: ajusta la alternativa con D1 y la evalúa en D0 frente al EMV nulo de D0."""
    idx = rng.permutation(len(x))
    D0, D1 = x[idx[: len(x) // 2]], x[idx[len(x) // 2:]]
    theta1 = ajusta_alt(D1)                                   # cualquier estimador que solo vea D1
    logT = loglik_alt(D0, theta1) - ll_normal(D0, D0.mean(), D0.var())   # el EMV nulo es exacto
    return logT, logT >= np.log(1 / alfa)

ajusta_gm = lambda D: GaussianMixture(2, covariance_type="tied", n_init=3, random_state=0).fit(D[:, None])
loglik_gm = lambda D, gm: gm.score_samples(D[:, None]).sum()

rng = np.random.default_rng(0)
for delta in (0.0, 3.0):
    x = rng.normal(size=200) + np.where(rng.random(200) < 0.5, -delta / 2, delta / 2)
    logT, rechaza = split_lrt(x, ajusta_gm, loglik_gm, rng)
    W = 2 * (loglik_gm(x, ajusta_gm(x)) - ll_normal(x, x.mean(), x.var()))
    print(f"delta = {delta}:  log T = {logT:6.2f} (umbral {np.log(20):.2f}; rechaza: {rechaza})"
          f"   W clásico = {W:5.2f}, p con chi2_2 = {stats.chi2.sf(W, 2):.3f}")

With covariance_type="tied" the scikit-learn mixture has common variance, as in the figure. The universal test does not require the alternative fit to be the exact MLE (EM can get stuck in a local maximum and validity survives); the null MLE must be exact, and here has closed form. To measure type I error with many replicates, GaussianMixture is too slow; the next cell implements vectorized EM, one replicate per row.

[ ]Universal test for mixtures: type I error by simulationBrowser
import numpy as np
from scipy import stats

def ll_mezcla(X, p, m1, m2, v):
    a = np.log(p)[:, None] - 0.5 * (X - m1[:, None]) ** 2 / v[:, None]
    b = np.log1p(-p)[:, None] - 0.5 * (X - m2[:, None]) ** 2 / v[:, None]
    return np.logaddexp(a, b).sum(1) - 0.5 * X.shape[1] * np.log(2 * np.pi * v)

def em_comun(X, iters=150):
    """EM de una mezcla de dos normales con varianza común, vectorizado (una réplica por fila).
    Tres arranques por cuantiles, como el interactivo; devuelve el de mayor verosimilitud."""
    q = np.quantile(X, [0.10, 0.25, 0.40, 0.60, 0.75, 0.90], axis=1)
    mejor = None
    for i, j in [(1, 4), (0, 5), (2, 3)]:
        p, m1, m2, v = np.full(len(X), 0.5), q[i], q[j], X.var(1)
        for _ in range(iters):
            a = np.log(p)[:, None] - 0.5 * (X - m1[:, None]) ** 2 / v[:, None]
            b = np.log1p(-p)[:, None] - 0.5 * (X - m2[:, None]) ** 2 / v[:, None]
            r = 1 / (1 + np.exp(b - a))                               # paso E: responsabilidades
            s = r.sum(1)
            p = np.clip(s / X.shape[1], 1e-6, 1 - 1e-6)               # paso M
            m1, m2 = (r * X).sum(1) / s, ((1 - r) * X).sum(1) / (X.shape[1] - s)
            v = (r * (X - m1[:, None]) ** 2 + (1 - r) * (X - m2[:, None]) ** 2).mean(1)
        ll = ll_mezcla(X, p, m1, m2, v)
        if mejor is None:
            mejor = [ll, p, m1, m2, v]
        else:
            k = ll > mejor[0]
            mejor = [np.where(k, nuevo, viejo) for nuevo, viejo in zip([ll, p, m1, m2, v], mejor)]
    return mejor[1:]

def ll_normal_emv(X):
    return -0.5 * X.shape[1] * (np.log(2 * np.pi * X.var(1)) + 1)

rng = np.random.default_rng(2)
R, n = 600, 200
X = rng.normal(size=(R, n))                                       # H0 cierta: una sola normal
D0, D1 = X[:, : n // 2], X[:, n // 2:]
logT = ll_mezcla(D0, *em_comun(D1)) - ll_normal_emv(D0)
print(f"split LRT:   error de tipo I = {np.mean(logT >= np.log(20)):.4f}   media de T = {np.exp(logT).mean():.3f} (teoría: <= 1)")
W = 2 * (ll_mezcla(X, *em_comun(X)) - ll_normal_emv(X))
for df in (2, 3):
    print(f"LRT clásico con chi2_{df}: error de tipo I = {np.mean(W > stats.chi2.ppf(0.95, df)):.3f}")

Empirical mean of TT is far below 1, as the theorem guarantees (0.29), and the universal test never rejects in 600 replicates. Classical LRT rejects 4.2 % with χ22\chi^2_2 and 2.2 % with χ32\chi^2_3; with 600 replicates Monte Carlo error is nearly ±1.7\pm 1.7 points, compatible with the figure (5.8 % and 2.9 %, with 2000 replicates). Whichever reference is chosen, no theorem guarantees its size.

Using libraries

statsmodels implements the trinity for fitted models. Names vary across model classes, so know where to look:

TestWhereNotes
Waldres.wald_test("x1 = 0, x2 = 0", scalar=True), res.t_test(...)any maximum-likelihood model; uses res covariance (robust too, if requested)
Likelihood ratiores_ols.compare_lr_test(res_restringido) in OLS; in GLM and discrete models, manually with 2 * (res1.llf - res0.llf)both models must be fitted on the same rows
Scoreres_glm0.score_test(exog_extra=...) in GLM; res.score_test in discrete modelscalled on the restricted model
Pearson χ2\chi^2 and G-testscipy.stats.chisquare, scipy.stats.power_divergence(..., lambda_="log-likelihood")multinomial score and likelihood ratio
[ ]The trinity in statsmodels versus our implementationBrowser
import numpy as np
import statsmodels.api as sm
from scipy import stats
from scipy.special import expit

rng = np.random.default_rng(7)
n = 40
x, z = rng.normal(size=n), rng.normal(size=n)
y = (rng.random(n) < expit(-0.3 + 0.7 * x)).astype(float)
X = sm.add_constant(np.column_stack([x, z]))

# H0: b_x = 0 (r = 1). Implementación propia (de la celda anterior) frente a statsmodels
w, s, l = trinidad(x[None, :], y[None, :])
completo1 = sm.Logit(y, X[:, :2]).fit(disp=0)
nulo = sm.Logit(y, X[:, :1]).fit(disp=0)
glm_nulo = sm.GLM(y, X[:, :1], family=sm.families.Binomial()).fit()
print("H0: b_x = 0          propia      statsmodels")
print(f"  Wald             {w[0]:9.5f}   {float(completo1.wald_test('x1 = 0', scalar=True).statistic):9.5f}")
print(f"  score            {s[0]:9.5f}   {float(glm_nulo.score_test(exog_extra=X[:, 1:2])[0][0]):9.5f}")
print(f"  RV               {l[0]:9.5f}   {2 * (completo1.llf - nulo.llf):9.5f}")

# H0: b_x = b_z = 0 (r = 2), los tres con statsmodels
completo = sm.Logit(y, X).fit(disp=0)
rv = 2 * (completo.llf - nulo.llf)
wald = completo.wald_test("x1 = 0, x2 = 0", scalar=True)
score = glm_nulo.score_test(exog_extra=X[:, 1:])
print(f"\nH0: b_x = b_z = 0:  RV {rv:.3f} (p = {stats.chi2.sf(rv, 2):.4f})   Wald {float(wald.statistic):.3f} (p = {float(wald.pvalue):.4f})"
      f"   score {float(score[0][0]):.3f} (p = {float(score[1][0]):.4f})")

# en mínimos cuadrados, compare_lr_test y el test F exacto
yc = 1.0 + 0.4 * x + rng.normal(size=n)
ols1, ols0 = sm.OLS(yc, X).fit(), sm.OLS(yc, X[:, :1]).fit()
lr_stat, lr_p, df = ols1.compare_lr_test(ols0)
f_stat, f_p, _ = ols1.compare_f_test(ols0)
print(f"\nOLS: RV = {lr_stat:.3f} (p chi2_{int(df)} = {lr_p:.4f})   F = {f_stat:.3f} (p exacto = {f_p:.4f})")

# Pearson (score) y G-test (RV) para una multinomial
obs, p0 = np.array([18, 30, 22, 10]), np.array([0.25, 0.35, 0.25, 0.15])
print("Pearson:", stats.chisquare(obs, 80 * p0))
print("G-test: ", stats.power_divergence(obs, 80 * p0, lambda_="log-likelihood"))

All three figures from our implementation agree with statsmodels to optimization precision. Two library details can bite. score_test is called on the null fit and receives missing columns, not on the full fit. In least squares with normal errors the exact test is F; compare_lr_test uses Wilks’ χ2\chi^2 approximation, somewhat anticonservative at small nn: likelihood ratio is a monotone function of F, but calibrated with an approximate reference.

Common mistakes

Exercises

NumericA Wilks p-value
You compare two nested models; the larger has 3 more free parameters, and regularity holds. You obtain 2log⁡Λ−1=2(ℓ(θ^)−ℓ(θ~))=9.22\log\Lambda^{-1} = 2(\ell(\hat\theta) - \ell(\tilde\theta)) = 9.2. What is the asymptotic p-value?
NumericNeyman–Pearson's coin
With X∼Bin⁡(10,p)X \sim \Bin(10, p), the 5 % MP test of H0:p=0.5H_0: p = 0.5 versus H1:p=0.7H_1: p = 0.7 always rejects at X≥9X \ge 9 and, at X=8X = 8, rejects with probability γ\gamma. What is γ\gamma?
NumericMaximum power
With n=9n = 9 observations N(μ,1)\Normal(\mu, 1), what is the maximum power of a level-0.05 test of H0:μ=0H_0: \mu = 0 versus H1:μ=1H_1: \mu = 1?
NumericPoisson likelihood ratio
You observe n=10n = 10 Poisson counts with sample mean xˉ=2\bar x = 2. Calculate likelihood-ratio statistic 2(ℓ(λ^)−ℓ(λ0))2(\ell(\hat\lambda) - \ell(\lambda_0)) for H0:λ=1H_0: \lambda = 1.
NumericWilks gets degrees of freedom wrong
With n=10n = 10 observations from Unif⁡(0,θ)\Unif(0, \theta) and H0:θ=1H_0: \theta = 1, observed maximum is X(10)=0.8X_{(10)} = 0.8. The likelihood-ratio statistic is W=2nlog⁡(1/X(n))W = 2n\log(1/X_{(n)}). Calculate its exact p-value.
NumericThe p-value at a boundary
You test H0:τ2=0H_0: \tau^2 = 0 (random-effect variance) with many groups and obtain W=3.0W = 3.0. Under the Self–Liang limit, what is the correct asymptotic p-value?
QuizChoose the test
Three situations. (1) The full model is very expensive to fit (hundreds of possible interactions), but the restricted one is cheap. (2) A logistic coefficient is 9.3 with standard error 41, suggesting near separation. (3) Your report must give the same p-value whether a parameter is expressed as rate λ\lambda or as log⁡λ\log\lambda. Which test suits each?
QuizWhat optimality guarantees
Which statements are true?

More than one answer may be correct.

QuizA negative likelihood ratio
You fit Poisson regression on 1000 rows. You add a covariate with 120 missing values and software fits the larger model on 880 rows. You obtain 2(ℓgrande−ℓpequen˜o)=−3122(\ell_{\text{grande}} - \ell_{\text{pequeño}}) = -312. What happened?
ProofNeyman–Pearson for continuous densities
Prove: Let p0p_0 and p1p_1 be densities on Rd\R^d with P0(p1(X)=k p0(X))=0P_0(p_1(X) = k\,p_0(X)) = 0 for every k≥0k \ge 0, and α∈(0,1)\alpha \in (0, 1). There exists k≥0k \ge 0 such that ϕ∗=1[p1>k p0]\phi^* = \ind[p_1 > k\,p_0] has size α\alpha, and ϕ∗\phi^* is most powerful among level-α\alpha tests.
0
Write Λ(x)=p1(x)/p0(x)\Lambda(x) = p_1(x)/p_0(x) where p0(x)>0p_0(x) > 0 (and Λ=∞\Lambda = \infty where p0=0<p1p_0 = 0 < p_1), and G(t)=P0(Λ(X)>t)G(t) = P_0(\Lambda(X) > t) for t≥0t \ge 0.

Step 1 of 4. How do you choose kk?

ProofWhy split LRT is valid
Prove: Let D0D_0 and D1D_1 be independent, iid from pθ∗p_{\theta^*} with θ∗∈Θ0\theta^* \in \Theta_0; θ^1\hat\theta_1 a function only of D1D_1; θ^0=arg max⁡θ∈Θ0L0(θ)\hat\theta_0 = \argmax_{\theta \in \Theta_0} L_0(\theta) with L0(θ)=pθ(D0)L_0(\theta) = p_\theta(D_0); and T=L0(θ^1)/L0(θ^0)T = L_0(\hat\theta_1)/L_0(\hat\theta_0). Then Pθ∗(T≥1/α)≤αP_{\theta^*}(T \ge 1/\alpha) \le \alpha.
0
All expectations are under θ∗\theta^*.

Step 1 of 4. What is the first step?

CodePearson's χ² as a score test
Implement the score test of H0:p=p0H_0: \vb{p} = \vb{p}^0 for a multinomial with kk categories via score, not Pearson's formula. score_e_informacion(x, p0) must return score U∈Rk−1\vb{U} \in \R^{k-1} and information In∈R(k−1)×(k−1)\mat{I}_n \in \R^{(k-1)\times(k-1)} at p0\vb{p}^0, using free parameters p1,…,pk−1p_1, \dots, p_{k-1}. estadistico_score(x, p0) must return statistic U⊤In−1U\vb{U}\T\mat{I}_n^{-1}\vb{U} and its p-value using χk−12\chi^2_{k-1} (solve with np.linalg.solve, without inversion).
import numpy as np
from scipy import stats

def score_e_informacion(x, p0):
  """Score U (longitud k-1) e información de Fisher I (k-1 x k-1) de la multinomial en p0."""
  x, p0 = np.asarray(x, dtype=float), np.asarray(p0, dtype=float)
  k = len(x)
  # tu código: U_j = x_j/p_j - x_k/p_k ; I = n (diag(1/p_j) + 1/p_k * 1 1^T)
  U = np.zeros(k - 1)
  I = np.eye(k - 1)
  return U, I

def estadistico_score(x, p0):
  """Estadístico score y valor p asintótico."""
  U, I = score_e_informacion(x, p0)
  S = 0.0
  return S, 1.0
Shift+Enter to run

Summary

Key idea
For simple hypotheses the best test rejects when the likelihood ratio is large; for composite hypotheses generalized likelihood ratio and its Wald and score approximations are three readings of one local parabola, equivalent at large nn but different in cost, invariance and small-sample behavior.
  • Neyman–Pearson. The most powerful test of p0p_0 versus p1p_1 adds points to the rejection region in p1/p0p_1/p_0 order until α\alpha is spent, randomizing at the boundary for discrete data. The proof integrates pointwise inequality (ϕ∗−ϕ)(p1−kp0)≥0(\phi^* - \phi)(p_1 - kp_0) \ge 0.
  • Karlin–Rubin. With monotone likelihood ratio (e.g. one-parameter exponential family), the one-sided sufficient-statistic test is UMP. For two-sided alternatives no UMP exists; the two-sided test is UMP only among unbiased tests.
  • Wilks. Under regularity and an interior null, 2(ℓ(θ^)−ℓ(θ~))→χr22(\ell(\hat\theta) - \ell(\tilde\theta)) \to \chi^2_r, with rr constraints: squared Mahalanobis distance from the MLE to the null model.
  • The trinity. Wald fits only the full model, is not invariant, and suffers Hauck–Donner; score fits only the null, is invariant, and includes Pearson’s χ2\chi^2; likelihood ratio fits both, is invariant, and is usually most reliable. All three are asymptotically equivalent.
  • Wilks failures. Boundary null (12χ02+12χ12\tfrac12\chi^2_0 + \tfrac12\chi^2_1: halve the p-value), parameters unidentifiable under H0H_0 (mixture component count), and nonregular models (parameter-dependent support).
  • Universal inference. Fit the alternative on one half and evaluate on the other against the null MLE, giving a statistic with E[T]≤1\E[T] \le 1 under H0H_0; by Markov, rejecting at T≥1/αT \ge 1/\alpha has level α\alpha for all nn without regularity, at the cost of power.