Algorithmcore
Wald test
Also called Wald chi-squared test.
Tests a parameter by the squared distance of its estimate from the null value, scaled by the estimated variance. It needs only the unrestricted fit.
- Time
- Θ(n + r^3) worst · best
- Space
- Θ(r^2) extra
- Where
- n = the number of observations; r = the number of parameters tested
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Abraham Wald, 1943
The Wald test checks a null value by asking how many standard errors the maximum likelihood estimate is from it. For one parameter its statistic is , the square of the familiar "estimate over standard error" ratio; for parameters it is the quadratic form . It needs only the unrestricted fit, which is why regression software prints a Wald z or chi-squared value next to every coefficient. Its null distribution is only in the limit, it is not invariant under a change of parameter, and in some models it can fall as the evidence grows.
In plain words
Fit the model once, with every setting free, and get an estimate and its standard error. Ask how far the estimate is from the claimed value, counted in standard errors. Square that count. If the claim is true and the sample is large, this squared count behaves like a square of a standard normal number, so values above about 3.84 happen only 5% of the time. If several settings are tested together, the same idea uses the joint spread of the estimates. The test is cheap, because it never fits the model under the claim. The price is that the answer depends on the scale in which the setting is written.
The problem
Model and hypotheses. The data are iid with density , . The null hypothesis fixes coordinates, with , and leaves the other coordinates free. The alternative is . A general smooth restriction works the same way with and its delta method covariance .
Statistic. With the unrestricted MLE and a consistent estimate of the covariance of its first coordinates,
The usual is the block of , the inverse of the expected Fisher information , or of the observed information . For one parameter, with .
Null distribution. Asymptotic. Under and the conditions of the asymptotic normality of the MLE, , and the matching block of in probability, so in distribution. It is exact only when is exactly normal with a known covariance, as for a normal mean with known .
Rejection rule and size. Reject at level when . For one parameter this is . The size tends to , and for finite it can be well above .
p-value. .
Sensitivity and power. Under local alternatives , tends to a noncentral with noncentrality , the same limit as the likelihood ratio test and the score test. Far from the null the three differ, and the Wald test can lose power badly (the Hauck-Donner effect below).
The algorithm
WALD-TEST(θ̂, θ₀, V̂) ▷ θ̂, θ₀ ∈ ℝ^r; V̂ an r × r estimate of Cov(θ̂), positive definite- 1
d ← θ̂ − θ₀ - 2
solve V̂ y = d for y ▷ Gaussian elimination or Cholesky; never form V̂⁻¹ - 3
W ← dᵀ y - 4
p ← Q(r/2, W/2) ▷ P(χ²_r ≥ W), the upper tail directly - 5
return (W, p)
The input comes from one fit: from the MLE, and from the inverse information at , or from a sandwich estimate when the model may be wrong. For the common one-parameter models the steps reduce to closed forms:
| model, null | |||
|---|---|---|---|
| binomial, | |||
| binomial, log odds | |||
| Poisson, | |||
| normal, , known | |||
| normal, , unknown | , |
When or , the estimated variance is 0, and the implementation returns and . This is a known defect of the test: one sample with no successes "proves" that for every . On the log odds scale the MLE does not exist at all in that case, and the implementation raises an error.
Example
A binomial count. In 20 trials there are 15 successes, and .
| step | value |
|---|---|
| , | 0.75, 0.009375 |
| L1: | 0.25 |
| L2: | 26.6667 |
| L3: | 6.6667 |
| L4: | 0.00982 |
The same data give () for the likelihood ratio test and () for the score test. All three reject at 5%, but the Wald p-value is less than half of the others. On the log odds scale, , , and (). The data and the null are the same, but the Wald statistic changed from 6.67 to 4.53 because the parameter was written differently.
Two parameters. For the nine pack weights of the z-test page, and . At the MLE the inverse information is diagonal, with entries and . For ,
with and . The first term alone, (), is the Wald test of with free. The exact t-test of the same null gives , so here the Wald p-value is too small by a factor of more than 6.
The Hauck-Donner effect. Keep and , but test it on the log odds scale, , as a logistic regression with only an intercept does. As the number of successes grows, the evidence against grows, and the likelihood ratio statistic grows with it. The Wald statistic does not:
| 15 | 16 | 17 | 18 | 19 | |
|---|---|---|---|---|---|
| Wald (log odds) | 4.53 | 6.15 | 7.67 | 8.69 | 8.24 |
| likelihood ratio | 5.23 | 7.71 | 10.82 | 14.72 | 19.79 |
The Wald statistic is largest at and falls after it. As , , and at the MLE of does not exist.
Correctness
Line L2 solves , so and line L3 returns , which is when is positive definite. The table follows from the explicit MLEs and their inverse informations. Under , asymptotic normality of the MLE gives with positive definite, and in probability; by Slutsky's theorem with , which is . So the size of "reject when " tends to . This is proved. The finite-sample sizes below are only measured, by exact enumeration. The correctness proof gives each step.
Proof: The Wald test returns the quadratic form of the estimate error, the closed forms are correct, and its size tends to alpha under the regularity conditions of MLE asymptoticsfull
We prove that WALD-TEST returns with , that when is positive definite, that the closed forms of the table are this quadratic form, and that under whenever the estimate is asymptotically normal and is consistent, so the size of the test tends to . The asymptotic normality of the MLE is proved on its own page and is used here as a hypothesis. Finite-sample sizes are not proved; they are computed by enumeration in the tests.
Lemma 1 (the solve). If is nonsingular, Gaussian elimination with partial pivoting in exact arithmetic returns the unique with . So line L3 returns .
Proof. Each elimination step swaps two rows of the augmented matrix or subtracts a multiple of one row from a later row. Both operations are invertible and keep the solution set of the system. At step , the pivot is the entry of largest absolute value in column at or below row . If it were 0, the first columns of the current matrix would have rank below , and would be singular; so for nonsingular every pivot is nonzero. After steps the matrix is upper triangular with nonzero diagonal, and back substitution gives the unique solution.
With Fraction inputs every operation is exact, so the returned is exactly ; the tests check this against the inverse by cofactors. With floating point inputs, partial pivoting makes the solve backward stable: the computed solves with a small multiple of the unit roundoff times , for matrices of the sizes used here.
Lemma 2 (sign). If is symmetric positive definite, then , with equality only if .
Proof. is symmetric positive definite, since its eigenvalues are the reciprocals of those of . So for .
So a negative shows that is not positive definite, and the implementation raises an error in that case.
Lemma 3 (closed forms). The one-parameter formulas of the table equal with the MLE and the inverse Fisher information evaluated at the MLE.
Proof. Binomial: , the MLE is , and , so . Log odds: with , , so , and the MLE is by invariance of the MLE. Poisson: , , . Normal with known: and . Normal with unknown: the MLE is , and the information matrix of is , whose inverse has entry . At the MLE this is , so .
Lemma 4 (the null distribution). Suppose that under , in distribution with positive definite, and in probability. Then in distribution, and for every .
Proof. Write , so . Matrix inversion is continuous at the positive definite , so in probability, by the continuous mapping theorem. By Slutsky's theorem and continuous mapping, with . Let be the symmetric square root and . Then , a sum of independent squared standard normals, which is by definition. The upper tail of is continuous and strictly decreasing, so , and its probability tends to because the limit law is continuous.
Under the conditions on the page on the asymptotic normality of the MLE, is the block of , and times the corresponding block of converges to it in probability when is continuous and is consistent. For the normal mean with known , with exactly, so the size is exactly for every .
Lemma 5 (the order for a normal mean). For iid normal data with unknown and , the Wald, likelihood ratio and score statistics are , and , and .
Proof. The Wald value is Lemma 3. The likelihood ratio value is proved on the likelihood ratio test page. For the score, the restricted MLE of is , the score for at is , the score for is 0 there, and the information is diagonal with entry ; so . For , because and the integrand is at most 1, and because and the integrand is at least .
Termination. Elimination makes passes, each over at most rows of entries, and back substitution makes more steps, so line L2 stops after operations. The other lines take operations, plus one evaluation of the incomplete gamma function, which stops after a bounded number of iterations. The closed forms make one pass over the data.
Theorem. For a positive definite , WALD-TEST returns and . If is asymptotically normal and is consistent under , rejecting when has size tending to .
Proof. Lemmas 1 to 4.
Complexity
On a real RAM, the closed forms need one pass over the data, time and extra space. The matrix form needs time and space for the solve in line L2, after a fit that is not part of the test. In practice the cost of the Wald test is the one unrestricted fit; the likelihood ratio test needs that fit and a second one under .
Numerical stability. Line L2 solves a linear system and does not invert . Solving with Cholesky or Gaussian elimination with partial pivoting is backward stable, while forming first and then multiplying adds error for no gain. When is close to singular, for example with nearly collinear regressors, is sensitive to small errors in : its relative error is of order the condition number of times the unit roundoff. The implementation stops with an error when a pivot is exactly 0 and when , which shows that is not positive definite. Line L4 computes the upper tail directly, so tiny p-values do not round to 0.
Properties
- One fit. Only the unrestricted MLE is needed. This makes it the default for many coefficients at once: each coefficient gets its own Wald z from the same fit.
- Asymptotically , and equivalent to the LR and score tests. Under and local alternatives, the three statistics differ by .
- Not invariant under reparametrization. for and for differ, as the example shows. The likelihood ratio and score tests do not have this defect (the score test is invariant when the information is expected).
- Ordered in the normal linear model. For linear restrictions on the mean of a normal linear model with unknown variance, , so the Wald test rejects most often (Berndt and Savin 1977). For a normal mean, with , the three are , and .
- Liberal in small samples. In the normal mean model the exact size of the nominal 5% Wald test is at , at , at and at (computed from the t distribution; the LRT has , , , and the score test , , , ).
- Gives an interval directly. Inverting the test gives , the Wald interval.
Variants and improvements
- Wald z and Wald interval. For one parameter, report and the interval . For a binomial proportion this interval has poor coverage: with the exact coverage of the nominal 95% interval is at , at and at . The Wilson score interval, which inverts the score test, is much better.
- Observed or expected information. Both give the same limit. The observed information is often more accurate in finite samples, and the two agree in exponential families with the natural parameter.
- Sandwich covariance. Replace by , with the observed information and the outer product of the per-observation scores. The test is then valid when the model is wrong but the estimating equation is right. See heteroscedasticity-consistent standard errors and cluster-robust standard errors.
- Nonlinear restrictions. For , use with the Jacobian of . The value depends on how the restriction is written: and give different .
- F form. In the normal linear model with unknown variance, with the unbiased variance estimate has an exact law; this is the regression F-test.
- Choosing the scale. Compute on a scale where is closer to normal, such as the log of a rate or the log odds near the middle, and transform the interval back.
When to use it
Use the Wald test when only the unrestricted model is fitted or easy to fit, and the sample is large compared with the number of parameters: reading coefficient tables, testing a few coefficients of a large regression, or building quick intervals. Prefer the likelihood ratio test when both fits are cheap, when the estimate is near the edge of the parameter space, or when the parameter has no natural scale. Prefer the score test when the full model is expensive or fails to converge, as when screening many candidate terms. For small samples use an exact test.
Pitfalls
- The Hauck-Donner effect. For a logistic coefficient, the Wald statistic first rises and then falls as the estimate grows, because the standard error grows faster than the estimate (the last example). In logistic regression with separated or nearly separated data, a large and real effect can have a small Wald z. Use the likelihood ratio test there.
- Zero variance estimates. With the plug-in variance is 0 and for every . Use the score test or an exact test.
- Different answers for the same hypothesis. The parametrization and the form of a nonlinear restriction change . Report the scale used.
- Reading the Wald p-value as exact. It is liberal in small samples, as the size table shows.
- Ignoring the covariance. Testing two coefficients jointly needs the full block of ; two separate z-tests are not the same test.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
wald_core.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wald-test/. The authors are listed in prov/QP1T8S.jsonl.
"""The Wald test, in matrix form and for common models.
wald_test takes an estimate theta_hat of r parameters, the null values theta_0
and an estimate V of the covariance matrix of theta_hat, and returns
(W, p) with W = d^T V^(-1) d, d = theta_hat - theta_0, and p the upper
chi-squared tail with r degrees of freedom. The p-value is only asymptotic.
The linear system V y = d is solved by Gaussian elimination with partial
pivoting, in the arithmetic of the inputs, so Fraction inputs give an exact W.
The code is in this file and not in wald_test.py, because tools treat a file
whose name ends in _test.py as a test file.
"""
import math
from collections.abc import Sequence
from stdist import chi2_sf
def solve(a: Sequence[Sequence], b: Sequence) -> list:
"""Solve a y = b by Gaussian elimination with partial pivoting."""
n = len(a)
if n == 0 or any(len(row) != n for row in a) or len(b) != n:
raise ValueError("need a square nonempty matrix and a vector of the same size")
m = [list(row) + [b[i]] for i, row in enumerate(a)]
for col in range(n):
piv = max(range(col, n), key=lambda i: abs(m[i][col]))
if m[piv][col] == 0:
raise ValueError("the covariance matrix is singular")
m[col], m[piv] = m[piv], m[col]
for i in range(col + 1, n):
f = m[i][col] / m[col][col]
if f:
for j in range(col, n + 1):
m[i][j] -= f * m[col][j]
y = [0] * n
for i in range(n - 1, -1, -1):
s = m[i][n] - sum(m[i][j] * y[j] for j in range(i + 1, n))
y[i] = s / m[i][i]
return y
def wald_test(theta_hat: Sequence, theta0: Sequence, cov: Sequence[Sequence]):
"""Wald test of H_0: theta = theta0 for r = len(theta0) parameters; returns (W, p)."""
r = len(theta0)
if r < 1 or len(theta_hat) != r:
raise ValueError("theta_hat and theta0 must have the same length r >= 1")
d = [theta_hat[i] - theta0[i] for i in range(r)] # @line L1
y = solve(cov, d) # @line L2
w = sum(d[i] * y[i] for i in range(r)) # @line L3
if w < 0:
raise ValueError("the covariance matrix is not positive definite")
p = chi2_sf(float(w), r) # @line L4
return w, p # @line L5
def binomial_wald(k: int, n: int, p0: float) -> tuple[float, float]:
"""W = (p_hat - p0)^2 / (p_hat (1 - p_hat) / n); infinite when p_hat is 0 or 1."""
if n < 1 or not 0 <= k <= n or not 0.0 < p0 < 1.0:
raise ValueError("need n >= 1, 0 <= k <= n and 0 < p0 < 1")
if k in (0, n):
return math.inf, 0.0
ph = k / n
w = n * (ph - p0) ** 2 / (ph * (1.0 - ph))
return w, chi2_sf(w, 1)
def logit_binomial_wald(k: int, n: int, p0: float) -> tuple[float, float]:
"""Wald test of the log odds: W = (logit p_hat - logit p0)^2 n p_hat (1 - p_hat)."""
if n < 1 or not 0 <= k <= n or not 0.0 < p0 < 1.0:
raise ValueError("need n >= 1, 0 <= k <= n and 0 < p0 < 1")
if k in (0, n):
raise ValueError("the MLE of the log odds does not exist when k is 0 or n")
ph = k / n
beta = math.log(k / (n - k))
beta0 = math.log(p0 / (1.0 - p0))
w = (beta - beta0) ** 2 * n * ph * (1.0 - ph)
return w, chi2_sf(w, 1)
def poisson_wald(total: int, n: int, lam0: float) -> tuple[float, float]:
"""W = n (lam_hat - lam0)^2 / lam_hat with lam_hat = total / n; infinite when total = 0."""
if n < 1 or total < 0 or lam0 <= 0.0:
raise ValueError("need n >= 1, total >= 0 and lam0 > 0")
if total == 0:
return math.inf, 0.0
lh = total / n
w = n * (lh - lam0) ** 2 / lh
return w, chi2_sf(w, 1)
def normal_mean_wald(x: Sequence[float], mu0: float,
sigma: float | None = None) -> tuple[float, float]:
"""W = n (xbar - mu0)^2 / sigma^2, with sigma^2 = SS / n (the MLE) when sigma is None."""
n = len(x)
if n < 1 or (sigma is None and n < 2):
raise ValueError("need n >= 1, and n >= 2 when sigma is unknown")
mean = math.fsum(x) / n
if sigma is None:
var = math.fsum((v - mean) ** 2 for v in x) / n
if var == 0.0:
raise ValueError("all observations are equal")
else:
if sigma <= 0.0:
raise ValueError("sigma must be positive")
var = sigma * sigma
w = n * (mean - mu0) ** 2 / var
return w, chi2_sf(w, 1)
test_wald_test.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wald-test/. The authors are listed in prov/QP1T8S.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from stdist import chi2_sf
from wald_test import (binomial_wald, logit_binomial_wald, normal_mean_wald, poisson_wald,
solve, wald_test)
def observed_information(loglik, theta: list[float]) -> list[list[float]]:
"""Brute force: minus the Hessian of loglik at theta, by central differences with
steps relative to each coordinate and one Richardson extrapolation step."""
k = len(theta)
def hessian(scale: float) -> list[list[float]]:
out = [[0.0] * k for _ in range(k)]
for i in range(k):
for j in range(k):
hi, hj = scale * abs(theta[i]), scale * abs(theta[j])
def at(si: int, sj: int) -> float:
t = list(theta)
t[i] += si * hi
t[j] += sj * hj
return loglik(t)
out[i][j] = (at(1, 1) - at(1, -1) - at(-1, 1) + at(-1, -1)) / (4 * hi * hj)
return out
coarse, fine = hessian(2e-3), hessian(1e-3)
return [[-(4 * fine[i][j] - coarse[i][j]) / 3 for j in range(k)] for i in range(k)]
def inverse_by_cofactors(a: list[list[Fraction]]) -> list[list[Fraction]]:
"""Brute force: the inverse by the adjugate, with determinants by permutation sums."""
n = len(a)
def det(m: list[list[Fraction]]) -> Fraction:
total = Fraction(0)
for perm in itertools.permutations(range(len(m))):
sign = 1
for i in range(len(perm)):
for j in range(i + 1, len(perm)):
if perm[i] > perm[j]:
sign = -sign
prod = Fraction(sign)
for i, pi in enumerate(perm):
prod *= m[i][pi]
total += prod
return total
d = det(a)
minor = lambda i, j: [row[:j] + row[j + 1:] for r, row in enumerate(a) if r != i]
return [[(-1) ** (i + j) * det(minor(j, i)) / d for j in range(n)] for i in range(n)]
def test_worked_example() -> None:
w, p = binomial_wald(15, 20, 0.5)
assert w == pytest.approx(20 / 3, rel=1e-14)
assert p == pytest.approx(0.009823, abs=1e-6)
w2, p2 = wald_test([0.75], [0.5], [[0.75 * 0.25 / 20]])
assert w2 == pytest.approx(w, rel=1e-14) and p2 == pytest.approx(p, rel=1e-12)
def test_solver_is_exact_against_cofactor_inverse() -> None:
rng = random.Random(21)
for _ in range(30):
r = rng.randint(1, 4)
b = [[Fraction(rng.randint(-5, 5)) for _ in range(r)] for _ in range(r)]
cov = [[sum(b[i][t] * b[j][t] for t in range(r)) + (1 if i == j else 0)
for j in range(r)] for i in range(r)] # B B^T + I is positive definite
est = [Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(r)]
null = [Fraction(rng.randint(-3, 3)) for _ in range(r)]
w, p = wald_test(est, null, cov)
inv = inverse_by_cofactors(cov)
d = [e - z for e, z in zip(est, null)]
assert w == sum(d[i] * inv[i][j] * d[j] for i in range(r) for j in range(r))
assert p == pytest.approx(chi2_sf(float(w), r), rel=1e-15)
def test_binomial_and_poisson_against_numerical_observed_information() -> None:
rng = random.Random(22)
for _ in range(20):
n = rng.randint(5, 80)
k = rng.randint(1, n - 1)
p0 = rng.uniform(0.05, 0.95)
ll = lambda t: k * math.log(t[0]) + (n - k) * math.log(1.0 - t[0])
info = observed_information(ll, [k / n])
w, _ = wald_test([k / n], [p0], [[1.0 / info[0][0]]])
assert w == pytest.approx(binomial_wald(k, n, p0)[0], rel=1e-5)
total, lam0 = rng.randint(1, 100), rng.uniform(0.2, 6.0)
llp = lambda t: total * math.log(t[0]) - n * t[0]
info = observed_information(llp, [total / n])
w, _ = wald_test([total / n], [lam0], [[1.0 / info[0][0]]])
assert w == pytest.approx(poisson_wald(total, n, lam0)[0], rel=1e-5)
def test_normal_two_parameters_against_numerical_observed_information() -> None:
rng = random.Random(23)
for _ in range(10):
n = rng.randint(3, 30)
x = [rng.gauss(2.0, 1.5) for _ in range(n)]
mean = sum(x) / n
v = sum((t - mean) ** 2 for t in x) / n
ll = lambda t: -0.5 * n * math.log(t[1]) - sum((xi - t[0]) ** 2 for xi in x) / (2 * t[1])
info = observed_information(ll, [mean, v])
det = info[0][0] * info[1][1] - info[0][1] * info[1][0]
cov = [[info[1][1] / det, -info[0][1] / det], [-info[1][0] / det, info[0][0] / det]]
mu0 = rng.uniform(0.0, 4.0)
w1, _ = wald_test([mean], [mu0], [[cov[0][0]]])
assert w1 == pytest.approx(normal_mean_wald(x, mu0)[0], rel=1e-5)
v0 = rng.uniform(0.5, 4.0)
w2, p2 = wald_test([mean, v], [mu0, v0], cov)
closed = n * (mean - mu0) ** 2 / v + n * (v - v0) ** 2 / (2 * v * v)
assert w2 == pytest.approx(closed, rel=1e-5)
assert p2 == pytest.approx(chi2_sf(closed, 2), rel=1e-4, abs=1e-12)
def test_trinity_agrees_for_normal_mean_with_known_variance() -> None:
rng = random.Random(24)
for _ in range(50):
n = rng.randint(1, 12)
x = [rng.randint(-20, 20) for _ in range(n)]
mu0, sigma = rng.randint(-5, 5), rng.randint(1, 6)
xbar = Fraction(sum(x), n)
wald, _ = wald_test([xbar], [Fraction(mu0)], [[Fraction(sigma * sigma, n)]])
lr = (sum((Fraction(v) - mu0) ** 2 for v in x) - sum((v - xbar) ** 2 for v in x)) / sigma ** 2
u = sum(Fraction(v) - mu0 for v in x) / sigma ** 2
score = u * u / (Fraction(n) / sigma ** 2)
assert wald == lr == score
assert normal_mean_wald(x, mu0, sigma)[0] == pytest.approx(float(wald), rel=1e-12, abs=1e-15)
def test_trinity_order_for_normal_mean_with_unknown_variance() -> None:
x = [502, 498, 505, 503, 501, 507, 499, 504, 506]
w, p = normal_mean_wald(x, 500)
assert w == pytest.approx(8.2721, abs=1e-4) and p == pytest.approx(0.00403, abs=1e-5)
rng = random.Random(25)
for _ in range(100):
n = rng.randint(2, 20)
x = [rng.gauss(0.0, 1.0) for _ in range(n)]
mean = sum(x) / n
ss = sum((t - mean) ** 2 for t in x)
u = n * mean ** 2 / ss # T^2 / (n - 1) for mu0 = 0
w = normal_mean_wald(x, 0.0)[0]
assert w == pytest.approx(n * u, rel=1e-10)
assert w >= n * math.log1p(u) >= n * u / (1 + u) # W >= LR >= score
def test_not_invariant_under_reparametrization() -> None:
assert binomial_wald(15, 20, 0.5)[0] == pytest.approx(6.6667, abs=1e-4)
assert logit_binomial_wald(15, 20, 0.5)[0] == pytest.approx(4.5261, abs=1e-4)
def test_hauck_donner_effect_on_the_logit_scale() -> None:
w = {k: logit_binomial_wald(k, 20, 0.5)[0] for k in range(11, 20)}
assert w[18] == pytest.approx(8.69, abs=1e-2)
assert w[19] < w[18] # the statistic falls as the evidence grows
assert all(w[k] < w[k + 1] for k in range(11, 18))
p_scale = [binomial_wald(k, 20, 0.5)[0] for k in range(10, 20)]
assert all(a < b for a, b in zip(p_scale, p_scale[1:]))
with pytest.raises(ValueError):
logit_binomial_wald(20, 20, 0.5)
def test_exact_binomial_size_by_enumeration() -> None:
crit = 3.841458820694124
for n, p0, expected in [(10, Fraction(1, 2), 0.1094), (20, Fraction(1, 2), 0.0414),
(20, Fraction(1, 10), 0.1240), (30, Fraction(1, 20), 0.2179)]:
size = sum(math.comb(n, k) * p0 ** k * (1 - p0) ** (n - k)
for k in range(n + 1) if binomial_wald(k, n, float(p0))[0] >= crit)
assert abs(float(size) - expected) < 1e-4
def test_monte_carlo_size_poisson() -> None:
rng = random.Random(26)
reps, n, lam0 = 3000, 50, 2.0
hits = 0
for _ in range(reps):
total = 0
for _ in range(n): # Poisson(lam0) by counting unit-rate arrivals
t = rng.expovariate(lam0)
while t < 1.0:
total += 1
t += rng.expovariate(lam0)
hits += poisson_wald(total, n, lam0)[1] <= 0.05
assert abs(hits / reps - 0.05) < 0.02
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
wald_test([1.0, 2.0], [0.0], [[1.0]])
with pytest.raises(ValueError):
solve([[1.0, 2.0], [2.0, 4.0]], [1.0, 1.0])
with pytest.raises(ValueError):
normal_mean_wald([3.0, 3.0], 0.0)
assert binomial_wald(0, 10, 0.3) == (math.inf, 0.0)
wald_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wald-test/. The authors are listed in prov/QP1T8S.jsonl.
"""Entry point named after the slug. The code lives in wald_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from wald_core import (binomial_wald, logit_binomial_wald, normal_mean_wald, poisson_wald,
solve, wald_test)
__all__ = ["binomial_wald", "logit_binomial_wald", "normal_mean_wald", "poisson_wald",
"solve", "wald_test"]
History
Abraham Wald introduced the test in a long paper in the Transactions of the American Mathematical Society in 1943, where he proved that the statistic built from the unrestricted MLE has a chi-squared limit and that tests based on it have the best average power over certain families of alternatives, among tests based on large samples. The likelihood ratio statistic of Neyman and Pearson (1928) and Wilks (1938) and the score statistic of Rao (1948) complete what is now called the trinity of classical tests. Hauck and Donner (1977) showed the loss of power in logit models, and Berndt and Savin (1977) proved the ordering in normal linear models. The general use of robust sandwich covariances in Wald tests comes from the work of Huber (1967) and White (1980).
References
- Abraham Wald, Tests of statistical hypotheses concerning several parameters when the number of observations is large, Transactions of the American Mathematical Society 54(3) (1943), pages 426 to 482, the statistic built from the unrestricted maximum likelihood estimate and its asymptotic chi-squared law
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 10.3.2 (other large-sample tests, with the Wald statistic)
- Walter W. Hauck and Allan Donner, Wald's test as applied to hypotheses in logit analysis, Journal of the American Statistical Association 72(360) (1977), pages 851 to 853, the Wald statistic of a logistic coefficient falls to 0 as the coefficient grows
- E. R. Berndt and N. E. Savin, Conflict among criteria for testing hypotheses in the multivariate linear regression model, Econometrica 45(5) (1977), pages 1263 to 1277, the inequality W >= LR >= LM in the normal linear model
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QP1T8S Edit this page History Report an error Markdown