Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
Origin
Abraham Wald, 1943

The Wald test checks a null value θ0\theta_0 by asking how many standard errors the maximum likelihood estimate θ^\hat\theta is from it. For one parameter its statistic is W=(θ^−θ0)2/Var⁡^(θ^)W = (\hat\theta - \theta_0)^2/\widehat{\operatorname{Var}}(\hat\theta), the square of the familiar "estimate over standard error" ratio; for rr parameters it is the quadratic form W=(θ^−θ0)⊤V^−1(θ^−θ0)W = (\hat\theta - \theta_0)^\top \hat V^{-1}(\hat\theta - \theta_0). 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 χr2\chi^2_r 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 x1,…,xnx_1, \dots, x_n are iid with density f(x;θ)f(x; \theta), θ∈Θ⊆Rk\theta \in \Theta \subseteq \mathbb R^k. The null hypothesis fixes rr coordinates, H0:θ(1)=θ0H_0: \theta_{(1)} = \theta_0 with θ(1)∈Rr\theta_{(1)} \in \mathbb R^r, and leaves the other k−rk - r coordinates free. The alternative is θ(1)≠θ0\theta_{(1)} \ne \theta_0. A general smooth restriction h(θ)=0h(\theta) = 0 works the same way with h(θ^)h(\hat\theta) and its delta method covariance HV^H⊤H\hat V H^\top.

Statistic. With θ^\hat\theta the unrestricted MLE and V^\hat V a consistent estimate of the covariance of its first rr coordinates,

W=(θ^(1)−θ0)⊤V^−1(θ^(1)−θ0).W = (\hat\theta_{(1)} - \theta_0)^\top \hat V^{-1} (\hat\theta_{(1)} - \theta_0).

The usual V^\hat V is the r×rr \times r block of In(θ^)−1I_n(\hat\theta)^{-1}, the inverse of the expected Fisher information In=nII_n = nI, or of the observed information −∇2ℓ(θ^)-\nabla^2 \ell(\hat\theta). For one parameter, W=z2W = z^2 with z=(θ^−θ0)/se^z = (\hat\theta - \theta_0)/\widehat{\mathrm{se}}.

Null distribution. Asymptotic. Under H0H_0 and the conditions of the asymptotic normality of the MLE, n(θ^−θ)→N(0,I(θ)−1)\sqrt n(\hat\theta - \theta) \to N(0, I(\theta)^{-1}), and nV^→n\hat V \to the matching block of I(θ)−1I(\theta)^{-1} in probability, so W→χr2W \to \chi^2_r in distribution. It is exact only when θ^\hat\theta is exactly normal with a known covariance, as for a normal mean with known σ\sigma.

Rejection rule and size. Reject at level α\alpha when W≥χr,1−α2W \ge \chi^2_{r, 1-\alpha}. For one parameter this is ∣z∣≥z1−α/2|z| \ge z_{1-\alpha/2}. The size tends to α\alpha, and for finite nn it can be well above α\alpha.

p-value. p=P(χr2≥W)=Q(r/2,W/2)p = P(\chi^2_r \ge W) = Q(r/2, W/2).

Sensitivity and power. Under local alternatives θ(1)=θ0+h/n\theta_{(1)} = \theta_0 + h/\sqrt n, WW tends to a noncentral χr2\chi^2_r with noncentrality h⊤(I−1)11−1hh^\top (I^{-1})_{11}^{-1} h, 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

  1. WALD-TEST(θ̂, θ₀, V̂) ▷ θ̂, θ₀ ∈ ℝ^r; V̂ an r × r estimate of Cov(θ̂), positive definite
  2. 1d ← θ̂ − θ₀
  3. 2solve V̂ y = d for y ▷ Gaussian elimination or Cholesky; never form V̂⁻¹
  4. 3W ← dᵀ y
  5. 4p ← Q(r/2, W/2) ▷ P(χ²_r ≥ W), the upper tail directly
  6. 5return (W, p)

The input comes from one fit: θ^\hat\theta from the MLE, and V^\hat V from the inverse information at θ^\hat\theta, 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 θ^\hat\theta Var⁡^(θ^)\widehat{\operatorname{Var}}(\hat\theta) WW
binomial, p=p0p = p_0 p^=k/n\hat p = k/n p^(1−p^)/n\hat p(1 - \hat p)/n n(p^−p0)2/(p^(1−p^))n(\hat p - p_0)^2/(\hat p(1 - \hat p))
binomial, log odds β=β0\beta = \beta_0 β^=log⁡(k/(n−k))\hat\beta = \log(k/(n - k)) 1/(np^(1−p^))1/(n\hat p(1 - \hat p)) (β^−β0)2np^(1−p^)(\hat\beta - \beta_0)^2 n\hat p(1 - \hat p)
Poisson, λ=λ0\lambda = \lambda_0 λ^=xˉ\hat\lambda = \bar x λ^/n\hat\lambda/n n(λ^−λ0)2/λ^n(\hat\lambda - \lambda_0)^2/\hat\lambda
normal, μ=μ0\mu = \mu_0, σ\sigma known xˉ\bar x σ2/n\sigma^2/n n(xˉ−μ0)2/σ2n(\bar x - \mu_0)^2/\sigma^2
normal, μ=μ0\mu = \mu_0, σ\sigma unknown xˉ\bar x σ^2/n\hat\sigma^2/n, σ^2=SS/n\hat\sigma^2 = SS/n n2(xˉ−μ0)2/SSn^2(\bar x - \mu_0)^2/SS

When p^∈{0,1}\hat p \in \{0, 1\} or λ^=0\hat\lambda = 0, the estimated variance is 0, and the implementation returns W=∞W = \infty and p=0p = 0. This is a known defect of the test: one sample with no successes "proves" that p≠p0p \ne p_0 for every p0p_0. 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 H0:p=0.5H_0: p = 0.5.

step value
p^\hat p, Var⁡^(p^)=0.75⋅0.25/20\widehat{\operatorname{Var}}(\hat p) = 0.75 \cdot 0.25/20 0.75, 0.009375
L1: d=0.75−0.5d = 0.75 - 0.5 0.25
L2: y=d/0.009375y = d/0.009375 26.6667
L3: W=d yW = d\,y 6.6667
L4: p=P(χ12≥6.6667)p = P(\chi^2_1 \ge 6.6667) 0.00982

The same data give Λ=5.2325\Lambda = 5.2325 (p=0.0222p = 0.0222) for the likelihood ratio test and S=5.0S = 5.0 (p=0.0253p = 0.0253) 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, β^=log⁡3=1.0986\hat\beta = \log 3 = 1.0986, Var⁡^=1/(20⋅0.75⋅0.25)=0.2667\widehat{\operatorname{Var}} = 1/(20 \cdot 0.75 \cdot 0.25) = 0.2667, and W=4.5261W = 4.5261 (p=0.0334p = 0.0334). 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, xˉ=502.7778\bar x = 502.7778 and σ^2=SS/9=8.3951\hat\sigma^2 = SS/9 = 8.3951. At the MLE the inverse information is diagonal, with entries σ^2/n\hat\sigma^2/n and 2σ^4/n2\hat\sigma^4/n. For H0:(μ,σ2)=(500,16)H_0: (\mu, \sigma^2) = (500, 16),

W=9(2.7778)28.3951+9(8.3951−16)22(8.3951)2=8.2721+3.6928=11.9649,W = \frac{9(2.7778)^2}{8.3951} + \frac{9(8.3951 - 16)^2}{2(8.3951)^2} = 8.2721 + 3.6928 = 11.9649,

with r=2r = 2 and p=0.00252p = 0.00252. The first term alone, 8.27218.2721 (p=0.0040p = 0.0040), is the Wald test of μ=500\mu = 500 with σ\sigma free. The exact t-test of the same null gives p=0.0266p = 0.0266, so here the Wald p-value is too small by a factor of more than 6.

The Hauck-Donner effect. Keep n=20n = 20 and H0:p=0.5H_0: p = 0.5, but test it on the log odds scale, H0:β=0H_0: \beta = 0, as a logistic regression with only an intercept does. As the number of successes kk grows, the evidence against H0H_0 grows, and the likelihood ratio statistic grows with it. The Wald statistic does not:

kk 15 16 17 18 19
Wald WW (log odds) 4.53 6.15 7.67 8.69 8.24
likelihood ratio Λ\Lambda 5.23 7.71 10.82 14.72 19.79

The Wald statistic is largest at k=18k = 18 and falls after it. As p^→1\hat p \to 1, β^2np^(1−p^)→0\hat\beta^2 n\hat p(1 - \hat p) \to 0, and at k=20k = 20 the MLE of β\beta does not exist.

Correctness

Line L2 solves V^y=d\hat V y = d, so y=V^−1dy = \hat V^{-1}d and line L3 returns d⊤V^−1dd^\top \hat V^{-1} d, which is ≥0\ge 0 when V^\hat V is positive definite. The table follows from the explicit MLEs and their inverse informations. Under H0H_0, asymptotic normality of the MLE gives n(θ^(1)−θ0)→N(0,Σ)\sqrt n(\hat\theta_{(1)} - \theta_0) \to N(0, \Sigma) with Σ\Sigma positive definite, and nV^→Σn\hat V \to \Sigma in probability; by Slutsky's theorem W→Z⊤ZW \to Z^\top Z with Z∼N(0,Ir)Z \sim N(0, I_r), which is χr2\chi^2_r. So the size of "reject when p≤αp \le \alpha" tends to α\alpha. 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 W=d⊤V^−1dW = d^\top \hat V^{-1} d with d=θ^−θ0d = \hat\theta - \theta_0, that W≥0W \ge 0 when V^\hat V is positive definite, that the closed forms of the table are this quadratic form, and that W→χr2W \to \chi^2_r under H0H_0 whenever the estimate is asymptotically normal and V^\hat V is consistent, so the size of the test tends to α\alpha. 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 V^\hat V is nonsingular, Gaussian elimination with partial pivoting in exact arithmetic returns the unique yy with V^y=d\hat V y = d. So line L3 returns W=d⊤V^−1dW = d^\top \hat V^{-1} d.

Proof. Each elimination step swaps two rows of the augmented matrix [V^∣d][\hat V \mid d] 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 cc, the pivot is the entry of largest absolute value in column cc at or below row cc. If it were 0, the first cc columns of the current matrix would have rank below cc, and V^\hat V would be singular; so for nonsingular V^\hat V every pivot is nonzero. After rr steps the matrix is upper triangular with nonzero diagonal, and back substitution gives the unique solution. □\square

With Fraction inputs every operation is exact, so the returned WW is exactly d⊤V^−1dd^\top \hat V^{-1} d; the tests check this against the inverse by cofactors. With floating point inputs, partial pivoting makes the solve backward stable: the computed yy solves (V^+E)y=d(\hat V + E)y = d with ∥E∥\|E\| a small multiple of the unit roundoff times ∥V^∥\|\hat V\|, for matrices of the sizes used here.

Lemma 2 (sign). If V^\hat V is symmetric positive definite, then W≥0W \ge 0, with equality only if d=0d = 0.

Proof. V^−1\hat V^{-1} is symmetric positive definite, since its eigenvalues are the reciprocals of those of V^\hat V. So d⊤V^−1d>0d^\top \hat V^{-1} d > 0 for d≠0d \ne 0. □\square

So a negative WW shows that V^\hat V 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 (θ^−θ0)2/Var⁡^(θ^)(\hat\theta - \theta_0)^2/\widehat{\operatorname{Var}}(\hat\theta) with the MLE and the inverse Fisher information evaluated at the MLE.

Proof. Binomial: ℓ(p)=klog⁡p+(n−k)log⁡(1−p)\ell(p) = k\log p + (n - k)\log(1 - p), the MLE is p^=k/n\hat p = k/n, and In(p)=n/(p(1−p))I_n(p) = n/(p(1 - p)), so Var⁡^=p^(1−p^)/n\widehat{\operatorname{Var}} = \hat p(1 - \hat p)/n. Log odds: with β=log⁡(p/(1−p))\beta = \log(p/(1 - p)), dp/dβ=p(1−p)dp/d\beta = p(1 - p), so In(β)=In(p)(dp/dβ)2=np(1−p)I_n(\beta) = I_n(p)(dp/d\beta)^2 = np(1 - p), and the MLE is β^=log⁡(p^/(1−p^))=log⁡(k/(n−k))\hat\beta = \log(\hat p/(1 - \hat p)) = \log(k/(n - k)) by invariance of the MLE. Poisson: ℓ(λ)=tlog⁡λ−nλ\ell(\lambda) = t\log\lambda - n\lambda, λ^=t/n\hat\lambda = t/n, In(λ)=n/λI_n(\lambda) = n/\lambda. Normal with σ\sigma known: μ^=xˉ\hat\mu = \bar x and In=n/σ2I_n = n/\sigma^2. Normal with σ2\sigma^2 unknown: the MLE is (xˉ,SS/n)(\bar x, SS/n), and the information matrix of (μ,σ2)(\mu, \sigma^2) is diag⁡(n/σ2,n/(2σ4))\operatorname{diag}(n/\sigma^2, n/(2\sigma^4)), whose inverse has (1,1)(1, 1) entry σ2/n\sigma^2/n. At the MLE this is SS/n2SS/n^2, so W=n2(xˉ−μ0)2/SSW = n^2(\bar x - \mu_0)^2/SS. □\square

Lemma 4 (the null distribution). Suppose that under H0H_0, n(θ^(1)−θ0)→N(0,Σ)\sqrt n(\hat\theta_{(1)} - \theta_0) \to N(0, \Sigma) in distribution with Σ\Sigma positive definite, and nV^→Σn\hat V \to \Sigma in probability. Then W→χr2W \to \chi^2_r in distribution, and PH0(Q(r/2,W/2)≤α)→αP_{H_0}(Q(r/2, W/2) \le \alpha) \to \alpha for every α∈(0,1)\alpha \in (0, 1).

Proof. Write Zn=n(θ^(1)−θ0)Z_n = \sqrt n(\hat\theta_{(1)} - \theta_0), so W=Zn⊤(nV^)−1ZnW = Z_n^\top (n\hat V)^{-1} Z_n. Matrix inversion is continuous at the positive definite Σ\Sigma, so (nV^)−1→Σ−1(n\hat V)^{-1} \to \Sigma^{-1} in probability, by the continuous mapping theorem. By Slutsky's theorem and continuous mapping, W→Z⊤Σ−1ZW \to Z^\top \Sigma^{-1} Z with Z∼N(0,Σ)Z \sim N(0, \Sigma). Let Σ1/2\Sigma^{1/2} be the symmetric square root and Y=Σ−1/2Z∼N(0,Ir)Y = \Sigma^{-1/2}Z \sim N(0, I_r). Then Z⊤Σ−1Z=Y⊤Y=∑j=1rYj2Z^\top \Sigma^{-1} Z = Y^\top Y = \sum_{j=1}^r Y_j^2, a sum of rr independent squared standard normals, which is χr2\chi^2_r by definition. The upper tail G(c)=Q(r/2,c/2)G(c) = Q(r/2, c/2) of χr2\chi^2_r is continuous and strictly decreasing, so {G(W)≤α}={W≥G−1(α)}\{G(W) \le \alpha\} = \{W \ge G^{-1}(\alpha)\}, and its probability tends to G(G−1(α))=αG(G^{-1}(\alpha)) = \alpha because the limit law is continuous. □\square

Under the conditions on the page on the asymptotic normality of the MLE, Σ\Sigma is the (1,1)(1, 1) block of I(θ)−1I(\theta)^{-1}, and nn times the corresponding block of In(θ^)−1I_n(\hat\theta)^{-1} converges to it in probability when II is continuous and θ^\hat\theta is consistent. For the normal mean with known σ\sigma, W=Z2W = Z^2 with Z∼N(0,1)Z \sim N(0, 1) exactly, so the size is exactly α\alpha for every nn.

Lemma 5 (the order for a normal mean). For iid normal data with σ\sigma unknown and u=n(xˉ−μ0)2/SS=T2/(n−1)u = n(\bar x - \mu_0)^2/SS = T^2/(n - 1), the Wald, likelihood ratio and score statistics are nunu, nlog⁡(1+u)n\log(1 + u) and nu/(1+u)nu/(1 + u), and nu≥nlog⁡(1+u)≥nu/(1+u)nu \ge n\log(1 + u) \ge nu/(1 + u).

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 σ2\sigma^2 is v0=(SS+n(xˉ−μ0)2)/nv_0 = (SS + n(\bar x - \mu_0)^2)/n, the score for μ\mu at (μ0,v0)(\mu_0, v_0) is n(xˉ−μ0)/v0n(\bar x - \mu_0)/v_0, the score for σ2\sigma^2 is 0 there, and the information is diagonal with (1,1)(1, 1) entry n/v0n/v_0; so S=n(xˉ−μ0)2/v0=nu/(1+u)S = n(\bar x - \mu_0)^2/v_0 = nu/(1 + u). For u≥0u \ge 0, log⁡(1+u)≤u\log(1 + u) \le u because log⁡(1+u)=∫0udt/(1+t)\log(1 + u) = \int_0^u dt/(1 + t) and the integrand is at most 1, and log⁡(1+u)≥u/(1+u)\log(1 + u) \ge u/(1 + u) because log⁡(1+u)=∫0udt/(1+t)\log(1 + u) = \int_0^u dt/(1 + t) and the integrand is at least 1/(1+u)1/(1 + u). □\square

Termination. Elimination makes rr passes, each over at most rr rows of r+1r + 1 entries, and back substitution makes rr more steps, so line L2 stops after O(r3)O(r^3) operations. The other lines take O(r)O(r) 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 V^\hat V, WALD-TEST returns W=(θ^−θ0)⊤V^−1(θ^−θ0)≥0W = (\hat\theta - \theta_0)^\top \hat V^{-1}(\hat\theta - \theta_0) \ge 0 and p=P(χr2≥W)p = P(\chi^2_r \ge W). If θ^\hat\theta is asymptotically normal and V^\hat V is consistent under H0H_0, rejecting when p≤αp \le \alpha has size tending to α\alpha.

Proof. Lemmas 1 to 4. ■\blacksquare

Complexity

On a real RAM, the closed forms need one pass over the data, Θ(n)\Theta(n) time and Θ(1)\Theta(1) extra space. The matrix form needs Θ(r3)\Theta(r^3) time and Θ(r2)\Theta(r^2) 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 H0H_0.

Numerical stability. Line L2 solves a linear system and does not invert V^\hat V. Solving with Cholesky or Gaussian elimination with partial pivoting is backward stable, while forming V^−1\hat V^{-1} first and then multiplying adds error for no gain. When V^\hat V is close to singular, for example with nearly collinear regressors, WW is sensitive to small errors in V^\hat V: its relative error is of order the condition number of V^\hat V times the unit roundoff. The implementation stops with an error when a pivot is exactly 0 and when W<0W < 0, which shows that V^\hat V 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 χr2\chi^2_r, and equivalent to the LR and score tests. Under H0H_0 and local alternatives, the three statistics differ by op(1)o_p(1).
  • Not invariant under reparametrization. WW for p=0.5p = 0.5 and for log⁡(p/(1−p))=0\log(p/(1 - p)) = 0 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, W≥Λ≥SW \ge \Lambda \ge S, so the Wald test rejects most often (Berndt and Savin 1977). For a normal mean, with u=T2/(n−1)u = T^2/(n - 1), the three are nunu, nlog⁡(1+u)n\log(1 + u) and nu/(1+u)nu/(1 + u).
  • Liberal in small samples. In the normal mean model the exact size of the nominal 5% Wald test is 0.1550.155 at n=5n = 5, 0.0960.096 at n=10n = 10, 0.0710.071 at n=20n = 20 and 0.0580.058 at n=50n = 50 (computed from the t distribution; the LRT has 0.0980.098, 0.0700.070, 0.0590.059, 0.0540.054 and the score test 0.0220.022, 0.0420.042, 0.0470.047, 0.0490.049).
  • Gives an interval directly. Inverting the test gives θ^±z1−α/2 se^\hat\theta \pm z_{1-\alpha/2}\,\widehat{\mathrm{se}}, the Wald interval.

Variants and improvements

  • Wald z and Wald interval. For one parameter, report z=(θ^−θ0)/se^z = (\hat\theta - \theta_0)/\widehat{\mathrm{se}} and the interval θ^±z1−α/2se^\hat\theta \pm z_{1-\alpha/2}\widehat{\mathrm{se}}. For a binomial proportion this interval has poor coverage: with n=20n = 20 the exact coverage of the nominal 95% interval is 0.9590.959 at p=0.5p = 0.5, 0.8950.895 at p=0.75p = 0.75 and 0.6390.639 at p=0.95p = 0.95. 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 In−1I_n^{-1} by A−1BA−1A^{-1}BA^{-1}, with AA the observed information and BB 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 H0:h(θ)=0H_0: h(\theta) = 0, use W=h(θ^)⊤(HV^H⊤)−1h(θ^)W = h(\hat\theta)^\top (H\hat V H^\top)^{-1} h(\hat\theta) with HH the Jacobian of hh. The value depends on how the restriction is written: θ1θ2=1\theta_1\theta_2 = 1 and θ1=1/θ2\theta_1 = 1/\theta_2 give different WW.
  • F form. In the normal linear model with unknown variance, W/rW/r with the unbiased variance estimate has an exact Fr,n−kF_{r, n-k} law; this is the regression F-test.
  • Choosing the scale. Compute WW on a scale where θ^\hat\theta 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 p^=0\hat p = 0 the plug-in variance is 0 and W=∞W = \infty for every p0p_0. Use the score test or an exact test.
  • Different answers for the same hypothesis. The parametrization and the form of a nonlinear restriction change WW. 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 2×22 \times 2 block of V^\hat V; 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.

stdist.pyI0RawGitHub
# 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 W≥Λ≥SW \ge \Lambda \ge S 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

  1. 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
  2. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 10.3.2 (other large-sample tests, with the Wald statistic)
  3. 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
  4. 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.

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