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
- 05Hypothesis testType I and type II errorsp-valueAsymptotic normality of the MLEFisher information matrixScore functionExponential familyProfile likelihood intervalNormal sampling theory: chi-squared, Student t and F distributions
- 04Markov's inequalityMahalanobis distanceExponential, gamma and chi-squared distributions
- 03Multivariable Taylor theorem
Motivation: which is the best test?
In the previous lesson a hypothesis test was a rule deciding from data whether to reject . Given size (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 is false. Tests at the same level can have very different power.
A numerical example. You have observations and want to test versus 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 and measures power under .
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:
- Simple hypotheses (one distribution each under and ): the Neyman–Pearson lemma specifies the most powerful test exactly. Reject when the likelihood ratio is large.
- 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.
- General composite hypotheses: no exact optimum exists, but the generalized likelihood ratio with its asymptotic 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 , a test is a function giving the probability of rejection given data : if reject; if do not; if flip a coin with probability . Ordinary regions are the case .
Why allow a coin? With discrete data, region sizes form a finite set and without randomization the level- 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: versus , with known densities (or masses) and . Think of sample space as points, each with cost (added size if included in the rejection region) and value (added power). You have a cost budget and want maximum value. This is the fractional knapsack problem, with known greedy solution: include points in descending value/cost order until the budget runs out, taking the affordable fraction of the last.
Four things the figure shows and the theorem formalizes:
- Only the order matters. Cell shading is likelihood ratio, and the optimal region of any size is a level set . For a mean shift, depends only on , and the region is a diagonal half-plane. Looking only at gives a same-size vertical half-plane with lower power.
- Shape can surprise. Against a Laplace of the same variance, , large at the center (Laplace has a sharp peak) and in tails, small near . The optimal region includes the center, which no “reject if data are extreme” intuition would suggest.
- 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.
- The diagonal is the floor. Test , ignoring data and rejecting with probability , has power . 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 be any level- test. At each ,
Indeed: if , then and both factors are nonnegative; if , then and both are nonpositive; under equality the second factor is zero. Summing over (or integrating),
because and . Power of is at least that of . For necessity, if is also MP, the first inequality is equality, so the nonnegative integrand is zero almost surely: outside .
∎Two immediate corollaries. First, MP test power exceeds its size unless : compare with constant , which has level and power . This gives ; equality would make also MP and, by necessity, of the lemma’s form, which with forces almost surely, i.e. and . Second, the test depends on data only through ; if is a sufficient statistic, the factorization theorem makes the ratio, and hence optimal test, a function of .
Discrete data and randomization
With and versus , ratio increases with , so the optimal test rejects for large . But and : no region has size 0.05. The lemma says what to do: always reject if and, if , reject with probability .
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 , what non-randomizing software would do, reaches 0.149, less than half. 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 was the same for every . Thus it is MP against each alternative simultaneously, i.e. UMP for . The enabling property has a name.
The main source of examples is the one-parameter exponential family. If with increasing , then
which increases in because . Thus normal with known variance (in ), Poisson (in ), binomial (in success count), and exponential with rate (in , because decreases; in mean , in ) have MLR. Outside exponential families, uniform has MLR in . Some families lack it: location Cauchy does not have MLR, and has no one-sided UMP test for its center.
Proof
Fix . By MLR, is a nondecreasing function . Take . If , then (if , monotonicity gives ); if , then . Thus , where , and , where : has Neyman–Pearson form and size at , so the lemma’s sufficiency makes it MP for versus . The test does not depend on , so it is MP against every .
It remains to show level over the composite null . For any , the same argument shows is MP for versus with its own size ; by the lemma’s corollary, its power exceeds that of constant test , i.e. . Power is nondecreasing and . Finally any other level- for the composite null satisfies , so its power at each cannot exceed .
∎This is the uniformly most powerful test provided by monotone likelihood ratio: the one-sided test, Poisson rate test, and exact one-sided binomial test are UMP. But this luck ends for two-sided alternatives.
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 right-sided power is 0.804 and two-sided power 0.705; at the right-sided test is useless (nearly zero power). No test dominates all others for every . Classical theory recovers optimality by restricting the class: the two-sided test is UMP among unbiased tests, those with power at least 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- 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 without constants.
We are rarely so lucky. For logistic regression, Poisson with several rates, or gamma, the exact distribution of is intractable. For large , 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 and , and nothing else about the model matters.
Proof
A sketch of the essential ideas. Write . By second-order Taylor’s theorem, with (rescaled score) and the law of large numbers applied to the Hessian,
uniformly over bounded , where and by the CLT. Since both MLEs are consistent at rate , maxima of occur at that scale, and maximizing the parabola suffices. Completing the square with :
Without restriction, the maximum occurs at . Under restriction, ranges (to first order) over tangent subspace to at , dimension , and ranges over same-dimensional . Subtracting maxima,
where is orthogonal projection onto . is a rank- projection, and the squared norm of a standard normal projected onto an -dimensional subspace is (Cochran’s decomposition of χ²).
∎The geometry deserves a sentence: in the Fisher-information metric, Mahalanobis distance, log-likelihood is locally a round paraboloid, and is squared distance from the MLE to the null hypothesis. The directions along do not count because the constrained MLE moves along them too; only the perpendicular directions count.
Inverting the test gives intervals: the set of not rejected by likelihood ratio, , is lesson 9’s profile likelihood interval, another face of test–interval duality.
How good is the approximation at moderate ? The cell tests equality of three groups of 10 Poisson counts (, ), comparing simulated with . Then it repeats this for a model violating regularity, uniform , whose support depends on the parameter.
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 and actual size close to nominal. Uniform instead gives mean of 2 rather than 1: here and, since , is exactly , two degrees of freedom for one constraint. Using gives actual size 15 % rather than 5 %. The uniform MLE converges at rate , not , so Wilks’ entire proof starting from a parabola at scale collapses.
The trinity: Wald, score and likelihood ratio
Wilks’ proof shows that near all information is in a parabola. Three natural ways to measure how far is from data using it yield three tests. Separate , with the parameter of interest, nuisance, and . Write for whole-sample information and for the block of the inverse information matrix, the asymptotic covariance of accounting for estimating .
The Wald test (1943) appears in every coefficient table: is its signed square root, with . 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:
Geometry on a curve
Divide all three by 2 and regard them as heights on the graph of . Likelihood ratio is the actual curve drop from maximum to . Wald replaces the curve by a parabola with vertex at and curvature there, , measuring its drop at : . Score does the reverse: at build a parabola with slope and expected curvature there, and measure how much it rises to its maximum, . This is the likelihood improvement predicted by one Newton (Fisher scoring) step from .
The figure’s initial configuration is a complete example. With Poisson observations of mean and :
All three reject at 5 % (), 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 reaches . On scale , the curve is more symmetric and Wald becomes , much closer to the others. Likelihood ratio and score do not change. This is no accident.
Proof
(1) One parameter, simple . Taylor-expanding score around gives , and consistency gives . Substitution makes and both , the same as Wilks’ proof gave for . Nuisance parameters use the same block argument. (2) at a point does not depend on its name, so neither do the maxima forming . For score, the chain rule gives and , leaving unchanged. Wald instead measures on the chosen scale using curvature at , and does not equal unless 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 intervals. Lack of invariance is not cosmetic. For nonlinear constraint , statistic , with the Jacobian of and estimated covariance (the delta method), changes if the same hypothesis is written or , and at finite 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 grows faster than , and falls as evidence against 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.
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 . Wald peaks at 17.4 for , then falls: 49 successes out of 50 in treatment is stronger evidence than 47, but Wald says the opposite. With complete separation (), 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 subject to with Lagrangian gives first-order condition . Lagrange multipliers measure how strongly the constraint pulls on the optimum; testing 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 , with . Then , and with the score is for . Information is , whose inverse by Sherman–Morrison is (with of length ). Thus
The second parenthesis is . In the first add , whose term is zero, and expand around : since ,
Subtracting, , all evaluated at .
∎The likelihood-ratio test for this problem is the G-test, ; both are asymptotically . 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 . A Bartlett correction divides by an estimate of , improving approximation error from order to .
| Fits needed | Invariant | Small | Typical use | |
|---|---|---|---|---|
| Wald | full only | no | worst; Hauck–Donner | coefficient tables, quick intervals |
| Score | restricted only | yes | often good, somewhat conservative | specification diagnostics, Pearson |
| Likelihood ratio | both | yes | generally best | nested-model comparison, profile intervals |
The trinity from scratch
Now implement all three tests for coefficient in logistic regression , vectorized over thousands of simulated datasets under . The restricted model has a closed-form solution ( with ), making score explicit:
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 . At , Wald rejects 0.6 % when it should reject 5 %: many small samples approach separation, 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 all three are between 3 % and 6 %, and at 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 , not its interior. The classic model is a one-factor random-effects model with groups, observations per group, and , and (no between-group variation).
The mechanism is visible in one dimension. If and , the unconstrained MLE would be approximately ; write . Under the constraint the MLE is : half the time the curve peaks at the boundary and ; otherwise . Therefore
a mixture of a point mass at 0 and (Chernoff, 1954; Self and Liang, 1987, for the general case). Its 95 % quantile is the 90 % quantile of , , not . In practice the correct p-value is half that from .
The figure shows two things. First, as expected, the Wilks critical value makes the test conservative: with groups of , the purported 5 % test rejects about 1.3 % under , 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 and ), because the MLE hits the boundary when , an event of probability . The mixture is the limit as group count grows; with few groups it remains conservative (with and , 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 laws with different degrees of freedom (), with weights depending on constraint-cone geometry.
Number of mixture components
Testing one normal against a two-normal mixture, , looks like nested models with constraints. It is not. The null can be reached two ways: (then is meaningless) or (then is meaningless). Under the parameter is unidentifiable, Fisher information is singular, and Wilks’ parabola does not exist. Hartigan (1985) showed that if means are unbounded, does not even converge in distribution: it grows without bound, though so slowly (at rate , 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 and has a different limiting distribution ( 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 by parametric bootstrap: simulate many datasets from the fitted null, recompute 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 and . Use to compute any estimator of the parameter, e.g. the full-model MLE. With compute null MLE , where is the likelihood of . The statistic is
and the test rejects if .
This is the universal split-sample test (split LRT). The proof uses three ingredients, reconstructed step by step in an exercise: conditioning on freezes ; since maximizes over and , the denominator is at least ; and expectation of density ratio under is at most 1. Given , Markov’s inequality finishes: .
The price is power. In a regular problem, is compared with rather than (3.84 if ), 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.
Under , classical LRT with naive reference rejects 5.8 % of the time, and with 2.9 %. Neither has theoretical justification; one being near 5 % at is coincidence that does not persist as 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 , classical LRT detects the mixture 90 % and universal 18 % of the time; at , universal rises to 85 %. The tradeoff is guaranteed validity at all and models, at the cost of power.
Two practical refinements. Cross-fitting swaps and and averages the two statistics: the average also has expectation at most 1 under , so the test remains valid and less dependent on the split. The same construction yields universal confidence sets, , valid where Wilks promises nothing. A nonnegative statistic with expectation at most 1 under 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.
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.
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 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 and 2.2 % with ; with 600 replicates Monte Carlo error is nearly 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:
| Test | Where | Notes |
|---|---|---|
| Wald | res.wald_test("x1 = 0, x2 = 0", scalar=True), res.t_test(...) | any maximum-likelihood model; uses res covariance (robust too, if requested) |
| Likelihood ratio | res_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 |
| Score | res_glm0.score_test(exog_extra=...) in GLM; res.score_test in discrete models | called on the restricted model |
| Pearson and G-test | scipy.stats.chisquare, scipy.stats.power_divergence(..., lambda_="log-likelihood") | multinomial score and likelihood ratio |
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’ approximation, somewhat anticonservative at small : likelihood ratio is a monotone function of F, but calibrated with an approximate reference.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How do you choose ?
Step 1 of 4. What is the first step?
score_e_informacion(x, p0) must return score and information at , using free parameters . estadistico_score(x, p0) must return statistic and its p-value using (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.0Summary
- Neyman–Pearson. The most powerful test of versus adds points to the rejection region in order until is spent, randomizing at the boundary for discrete data. The proof integrates pointwise inequality .
- 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, , with 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 ; likelihood ratio fits both, is invariant, and is usually most reliable. All three are asymptotically equivalent.
- Wilks failures. Boundary null (: halve the p-value), parameters unidentifiable under (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 under ; by Markov, rejecting at has level for all without regularity, at the cost of power.