Algorithm Search⌘K

Algorithmcore

Score test

Also called Rao score test, Lagrange multiplier test.

Tests a null by the size of the score at the restricted estimate, scaled by the Fisher information. It needs only the fit under the null.

Time
Θ(n + m + k^3) worst · best
Space
Θ(k^2) extra
Where
k = the number of parameters; m = the number of cells of a multinomial; n = the number of observations
Properties
deterministicnot exactofflineiterative
Origin
C. R. Rao, 1948

The score test asks whether the log-likelihood is still climbing at the null value. If H0H_0 is true, the slope of the log-likelihood, the score Un(θ)U_n(\theta), should be near 0 at the best fit under H0H_0; a large slope says that the data pull the parameter away from the null. The statistic is S=Un(θ~0)⊤In(θ~0)−1Un(θ~0)S = U_n(\tilde\theta_0)^\top I_n(\tilde\theta_0)^{-1} U_n(\tilde\theta_0), the squared score in the metric of the Fisher information, where θ~0\tilde\theta_0 is the MLE under H0H_0. It needs only the fit under the null, so it is the cheap test when the full model is hard to fit. Its null distribution is χr2\chi^2_r only in the limit. Many classical tests are score tests: the one-proportion z-test, Pearson's chi-squared test, the log-rank test and the Breusch-Pagan test.

In plain words

Fit the model under the claim, holding the claimed settings fixed. Then ask: if you were allowed to move those settings a little, how steeply would the fit improve? A steep slope means the claim sits on the side of a hill, away from where the data want to be. Measure the slope in units of its natural spread, square it, and compare with a standard table that depends on the number of fixed settings. You never fit the bigger model. That is the main reason to use this test: it lets you check many possible extensions of a simple model, each at the cost of one slope.

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, and leaves k−rk - r nuisance coordinates free, or more generally imposes rr smooth restrictions h(θ)=0h(\theta) = 0.

Statistic. Let θ~0\tilde\theta_0 be the MLE under H0H_0, Un(θ)=∇ℓ(θ)U_n(\theta) = \nabla\ell(\theta) the score of the sample and In(θ)=nI(θ)I_n(\theta) = nI(\theta) the expected Fisher information. Then

S=Un(θ~0)⊤In(θ~0)−1Un(θ~0).S = U_n(\tilde\theta_0)^\top I_n(\tilde\theta_0)^{-1} U_n(\tilde\theta_0).

The score for the nuisance coordinates is 0 at θ~0\tilde\theta_0, because θ~0\tilde\theta_0 maximizes over them; only the rr tested coordinates contribute, through the matching block of In−1I_n^{-1}. For one parameter and a simple null, S=Un(θ0)2/In(θ0)S = U_n(\theta_0)^2/I_n(\theta_0).

Null distribution. Asymptotic. Under H0H_0, Un(θ)/n→N(0,I(θ))U_n(\theta)/\sqrt n \to N(0, I(\theta)) by the central limit theorem, since the score is a sum of iid terms with mean 0 and variance I(θ)I(\theta). So S→χr2S \to \chi^2_r. For a simple null this needs only the moment conditions of the score; with nuisance parameters it needs the conditions of the asymptotic normality of the MLE for θ~0\tilde\theta_0.

Rejection rule and size. Reject at level α\alpha when S≥χr,1−α2S \ge \chi^2_{r, 1-\alpha}. For one parameter one can also use the signed root Un/InU_n/\sqrt{I_n} against N(0,1)N(0, 1), which gives one-sided tests. The size tends to α\alpha.

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

Sensitivity and power. Under local alternatives θ(1)=θ0+h/n\theta_{(1)} = \theta_0 + h/\sqrt n, SS tends to the same noncentral χr2\chi^2_r as the Wald test and the likelihood ratio test. For a one-sided alternative in a one-parameter family, the test based on Un(θ0)U_n(\theta_0) is locally most powerful: it has the largest slope of the power function at θ0\theta_0 among tests of size α\alpha. Far from the null, the score test can lose power, because the information at θ0\theta_0 may not describe the data well there.

The algorithm

  1. SCORE-TEST(x, U, I, Θ₀, r) ▷ U(θ): score vector; I(θ): Fisher information of the sample
  2. 1θ̃₀ ← a maximizer of ℓ(θ; x) over Θ₀ ▷ the only fit
  3. 2u ← U(θ̃₀) ▷ 0 in the nuisance coordinates
  4. 3J ← I(θ̃₀)
  5. 4solve J y = u for y ▷ never form J⁻¹
  6. 5S ← uᵀ y
  7. 6p ← Q(r/2, S/2) ▷ P(χ²_r ≥ S), the upper tail directly
  8. 7return (S, p)

For the common models the steps reduce to closed forms, all of them at the null value:

model, null Un(θ0)U_n(\theta_0) In(θ0)I_n(\theta_0) SS
binomial, p=p0p = p_0 (k−np0)/(p0(1−p0))(k - np_0)/(p_0(1 - p_0)) n/(p0(1−p0))n/(p_0(1 - p_0)) (k−np0)2/(np0(1−p0))(k - np_0)^2/(np_0(1 - p_0))
Poisson, λ=λ0\lambda = \lambda_0 (t−nλ0)/λ0(t - n\lambda_0)/\lambda_0, t=∑xit = \sum x_i n/λ0n/\lambda_0 (t−nλ0)2/(nλ0)(t - n\lambda_0)^2/(n\lambda_0)
normal, μ=μ0\mu = \mu_0, σ\sigma known n(xˉ−μ0)/σ2n(\bar x - \mu_0)/\sigma^2 n/σ2n/\sigma^2 n(xˉ−μ0)2/σ2n(\bar x - \mu_0)^2/\sigma^2
normal, μ=μ0\mu = \mu_0, σ\sigma unknown n(xˉ−μ0)/σ~02n(\bar x - \mu_0)/\tilde\sigma_0^2 n/σ~02n/\tilde\sigma_0^2 n2(xˉ−μ0)2/∑(xi−μ0)2n^2(\bar x - \mu_0)^2/\sum(x_i - \mu_0)^2
multinomial, probabilities qjq_j Oj/qj−Om/qmO_j/q_j - O_m/q_m, j<mj < m n(diag⁡(1/qj)+11⊤/qm)n(\operatorname{diag}(1/q_j) + \mathbf 1\mathbf 1^\top/q_m) ∑j(Oj−nqj)2/(nqj)\sum_j (O_j - nq_j)^2/(nq_j)

In the fourth row, σ~02=∑(xi−μ0)2/n\tilde\sigma_0^2 = \sum(x_i - \mu_0)^2/n is the MLE of σ2\sigma^2 under H0H_0, and S=nT2/(n−1+T2)S = nT^2/(n - 1 + T^2) in terms of the t statistic TT. In the last row, the score test is exactly Pearson's chi-squared statistic, as the correctness proof shows.

Why it is also called the Lagrange multiplier test. Maximize ℓ(θ)\ell(\theta) subject to h(θ)=0h(\theta) = 0 with a Lagrange multiplier λ\lambda. At the restricted maximum, ∇ℓ(θ~0)=H(θ~0)⊤λ~\nabla\ell(\tilde\theta_0) = H(\tilde\theta_0)^\top\tilde\lambda, where HH is the Jacobian of hh. The multiplier λ~\tilde\lambda is the price of the constraint: the rate at which the maximum log-likelihood would rise if the constraint were relaxed. A test that rejects when λ~\tilde\lambda is large, in the metric of its asymptotic covariance, is the Lagrange multiplier test of Aitchison and Silvey (1958) and Silvey (1959). Because Un(θ~0)=H⊤λ~U_n(\tilde\theta_0) = H^\top\tilde\lambda, its statistic is the same number SS. Econometrics uses the name "LM test"; statistics uses "score test".

Example

A binomial count. In 20 trials there are 15 successes, and H0:p=0.5H_0: p = 0.5.

step value
L1: θ~0=p0\tilde\theta_0 = p_0 (simple null, nothing to fit) 0.5
L2: u=(15−10)/0.25u = (15 - 10)/0.25 20
L3: J=20/0.25J = 20/0.25 80
L4: y=20/80y = 20/80 0.25
L5: S=u yS = u\,y 5.0
L6: p=P(χ12≥5)p = P(\chi^2_1 \ge 5) 0.02535

This is the square of the z statistic (15−10)/20⋅0.25=2.2361(15 - 10)/\sqrt{20 \cdot 0.25} = 2.2361 of the one-proportion z-test. The Wald test gives W=6.67W = 6.67 and the likelihood ratio test Λ=5.23\Lambda = 5.23. Inverting the score test, the values p0p_0 that it does not reject at 5% form the interval (0.5313,0.8881)(0.5313, 0.8881), which is the Wilson score interval.

A normal mean with unknown variance. For the nine pack weights of the z-test page and H0:μ=500H_0: \mu = 500, line L1 fits σ2\sigma^2 with μ\mu held at 500: σ~02=∑(xi−500)2/9=145/9=16.1111\tilde\sigma_0^2 = \sum(x_i - 500)^2/9 = 145/9 = 16.1111. The score for μ\mu is 9⋅2.7778/16.1111=1.55179 \cdot 2.7778/16.1111 = 1.5517, the score for σ2\sigma^2 is 0, the information for μ\mu is 9/16.1111=0.55869/16.1111 = 0.5586, and S=1.55172/0.5586=4.3103S = 1.5517^2/0.5586 = 4.3103, with p=0.0379p = 0.0379. The other two give W=8.2721W = 8.2721 (p=0.0040p = 0.0040) and Λ=5.8668\Lambda = 5.8668 (p=0.0154p = 0.0154), and the exact t-test gives p=0.0266p = 0.0266. Here W≥Λ≥SW \ge \Lambda \ge S, as always in this model.

Counts in cells. For the counts 18,30,5218, 30, 52 and H0H_0: probabilities 0.25,0.25,0.50.25, 0.25, 0.5, the score test is Pearson's statistic X2=49/25+25/25+4/50=3.04X^2 = 49/25 + 25/25 + 4/50 = 3.04 with r=2r = 2 and p=0.2187p = 0.2187. The likelihood ratio (G) statistic of the same data is 3.19213.1921.

Correctness

Line L4 solves Jy=uJy = u, so line L5 returns u⊤J−1uu^\top J^{-1}u, which is ≥0\ge 0 when JJ is positive definite. The closed forms follow from the scores and informations of each model; for a multinomial the quadratic form equals Pearson's X2X^2 exactly, which the tests check in rational arithmetic. Under a simple null, the score is a sum of nn iid vectors with mean 0 and covariance I(θ0)I(\theta_0), so Un/n→N(0,I)U_n/\sqrt n \to N(0, I) and S→χr2S \to \chi^2_r; with nuisance parameters, the restricted MLE adds a correction that turns the covariance of the tested part of the score into the inverse of the matching block of I−1I^{-1}, and the limit is again χr2\chi^2_r. The size of the test therefore tends to α\alpha; this is proved. Finite-sample sizes are only measured, here by exact enumeration. The correctness proof gives each step.

Proof: The score test returns the quadratic form of the score, equals Pearson's statistic for a multinomial, is invariant under reparametrization, and has size tending to alphafull

We prove that SCORE-TEST returns S=u⊤J−1uS = u^\top J^{-1} u with uu the score and JJ the Fisher information at the restricted MLE, that the closed forms are correct, that the multinomial score statistic is exactly Pearson's X2X^2, that SS does not depend on the parametrization when JJ is the expected information, that inverting the binomial score test gives the Wilson interval, and that S→χr2S \to \chi^2_r under H0H_0. For a simple null the limit is proved from the central limit theorem alone. With nuisance parameters it is proved under the regularity conditions of the page on the asymptotic normality of the MLE, which we use as hypotheses. Finite-sample sizes are not proved; the tests compute them by enumeration.

Lemma 1 (the solve and the sign). If JJ is nonsingular, lines L4 and L5 return S=u⊤J−1uS = u^\top J^{-1}u. If JJ is symmetric positive definite, S≥0S \ge 0.

Proof. Gaussian elimination with partial pivoting uses only row swaps and row operations that keep the solution set; every pivot is nonzero when JJ is nonsingular, since a zero pivot column would make the leading columns dependent; back substitution then gives the unique y=J−1uy = J^{-1}u. If JJ is positive definite, so is J−1J^{-1}, and u⊤J−1u≥0u^\top J^{-1}u \ge 0. □\square

Lemma 2 (closed forms). The first four rows of the table are correct.

Proof. Binomial: ℓ(p)=klog⁡p+(n−k)log⁡(1−p)\ell(p) = k\log p + (n - k)\log(1 - p), so Un(p)=k/p−(n−k)/(1−p)=(k−np)/(p(1−p))U_n(p) = k/p - (n - k)/(1 - p) = (k - np)/(p(1 - p)), and In(p)=n/(p(1−p))I_n(p) = n/(p(1 - p)). Then S=Un2/In=(k−np0)2/(np0(1−p0))S = U_n^2/I_n = (k - np_0)^2/(np_0(1 - p_0)). Poisson: ℓ(λ)=tlog⁡λ−nλ\ell(\lambda) = t\log\lambda - n\lambda, Un=t/λ−n=(t−nλ)/λU_n = t/\lambda - n = (t - n\lambda)/\lambda, In=n/λI_n = n/\lambda, and S=(t−nλ0)2/(nλ0)S = (t - n\lambda_0)^2/(n\lambda_0). Normal with σ\sigma known: Un(μ)=n(xˉ−μ)/σ2U_n(\mu) = n(\bar x - \mu)/\sigma^2 and In=n/σ2I_n = n/\sigma^2. Normal with σ2\sigma^2 unknown: under H0H_0 the log-likelihood −n2log⁡v−∑(xi−μ0)2/(2v)-\tfrac n2\log v - \sum(x_i - \mu_0)^2/(2v) is maximized at v~0=∑(xi−μ0)2/n\tilde v_0 = \sum(x_i - \mu_0)^2/n, where the score for vv is 0. The score for μ\mu is n(xˉ−μ0)/v~0n(\bar x - \mu_0)/\tilde v_0, and the information matrix of (μ,v)(\mu, v) is diag⁡(n/v,n/(2v2))\operatorname{diag}(n/v, n/(2v^2)), so S=n(xˉ−μ0)2/v~0=n2(xˉ−μ0)2/∑(xi−μ0)2S = n(\bar x - \mu_0)^2/\tilde v_0 = n^2(\bar x - \mu_0)^2/\sum(x_i - \mu_0)^2. With SS=∑(xi−xˉ)2SS = \sum(x_i - \bar x)^2, ∑(xi−μ0)2=SS+n(xˉ−μ0)2\sum(x_i - \mu_0)^2 = SS + n(\bar x - \mu_0)^2 and T2=n(n−1)(xˉ−μ0)2/SST^2 = n(n - 1)(\bar x - \mu_0)^2/SS, which gives S=nT2/(n−1+T2)S = nT^2/(n - 1 + T^2). □\square

Lemma 3 (the multinomial score statistic is Pearson's X2X^2). Let O1,…,OmO_1, \dots, O_m be multinomial counts with total nn, and H0H_0: probabilities q1,…,qm>0q_1, \dots, q_m > 0. Parametrize by q1,…,qm−1q_1, \dots, q_{m-1} with qm=1−∑j<mqjq_m = 1 - \sum_{j<m} q_j. Then the score test statistic is ∑j=1m(Oj−nqj)2/(nqj)\sum_{j=1}^m (O_j - nq_j)^2/(nq_j).

Proof. ℓ=∑jOjlog⁡qj\ell = \sum_j O_j\log q_j, so Uj=Oj/qj−Om/qmU_j = O_j/q_j - O_m/q_m for j<mj < m. The information is J=n(D+11⊤/qm)J = n(D + \mathbf 1\mathbf 1^\top/q_m) with D=diag⁡(1/q1,…,1/qm−1)D = \operatorname{diag}(1/q_1, \dots, 1/q_{m-1}), since E[Oj]=nqjE[O_j] = nq_j and −∂2ℓ/∂qi∂qj=Oiδij/qi2+Om/qm2-\partial^2\ell/\partial q_i\partial q_j = O_i\delta_{ij}/q_i^2 + O_m/q_m^2. By the Sherman-Morrison formula, J−1=1n(D−1−D−111⊤D−1/(qm+1⊤D−11))=1n(diag⁡(q)−qq⊤)J^{-1} = \tfrac1n\left(D^{-1} - D^{-1}\mathbf 1\mathbf 1^\top D^{-1}/(q_m + \mathbf 1^\top D^{-1}\mathbf 1)\right) = \tfrac1n(\operatorname{diag}(q) - qq^\top), where q=(q1,…,qm−1)q = (q_1, \dots, q_{m-1}) and we used qm+∑j<mqj=1q_m + \sum_{j<m} q_j = 1. Write aj=Oj−nqja_j = O_j - nq_j, so ∑j=1maj=0\sum_{j=1}^m a_j = 0 and Uj=aj/qj−am/qmU_j = a_j/q_j - a_m/q_m. Then

u⊤diag⁡(q) u=∑j<mqj(ajqj−amqm)2=∑j<maj2qj+2am2qm+am2(1−qm)qm2,u^\top\operatorname{diag}(q)\,u = \sum_{j<m} q_j\left(\frac{a_j}{q_j} - \frac{a_m}{q_m}\right)^2 = \sum_{j<m}\frac{a_j^2}{q_j} + \frac{2a_m^2}{q_m} + \frac{a_m^2(1 - q_m)}{q_m^2},

using ∑j<maj=−am\sum_{j<m} a_j = -a_m and ∑j<mqj=1−qm\sum_{j<m} q_j = 1 - q_m. Also q⊤u=∑j<m(aj−qjam/qm)=−am−am(1−qm)/qm=−am/qmq^\top u = \sum_{j<m}(a_j - q_ja_m/q_m) = -a_m - a_m(1 - q_m)/q_m = -a_m/q_m, so u⊤qq⊤u=am2/qm2u^\top qq^\top u = a_m^2/q_m^2. Subtracting, nS=∑j<maj2/qj+am2/qmnS = \sum_{j<m} a_j^2/q_j + a_m^2/q_m, which is ∑j=1maj2/qj\sum_{j=1}^m a_j^2/q_j. □\square

Lemma 4 (invariance). Let θ=g(ψ)\theta = g(\psi) with gg one-to-one and differentiable with nonsingular Jacobian G=∂θ/∂ψG = \partial\theta/\partial\psi. With expected information, the score statistic in ψ\psi at ψ0=g−1(θ0)\psi_0 = g^{-1}(\theta_0) equals the one in θ\theta at θ0\theta_0.

Proof. By the chain rule the score in ψ\psi is G⊤U(θ)G^\top U(\theta), and the expected information in ψ\psi is G⊤I(θ)GG^\top I(\theta)G, because the information is the covariance of the score. So (G⊤U)⊤(G⊤IG)−1(G⊤U)=U⊤GG−1I−1G−⊤G⊤U=U⊤I−1U(G^\top U)^\top(G^\top IG)^{-1}(G^\top U) = U^\top G G^{-1}I^{-1}G^{-\top}G^\top U = U^\top I^{-1}U. With nuisance parameters, gg must map the null set onto the null set; then the restricted MLEs correspond, and the same computation applies at θ~0=g(ψ~0)\tilde\theta_0 = g(\tilde\psi_0). □\square

The observed information in ψ\psi has the extra term −∑iUi(θ) ∂2θi/∂ψ2-\sum_i U_i(\theta)\,\partial^2\theta_i/\partial\psi^2, which is not 0 unless the score is 0, so with the observed information the statistic is not invariant.

Lemma 5 (the Wilson interval). For a binomial count kk out of nn, the set {p0∈(0,1):S(p0)<z2}\{p_0 \in (0, 1) : S(p_0) < z^2\} with z=z1−α/2z = z_{1-\alpha/2} is the open interval between the roots of (k−np)2=z2np(1−p)(k - np)^2 = z^2np(1 - p), which are (p^+z22n±zp^(1−p^)/n+z2/(4n2))/(1+z2/n)\left(\hat p + \tfrac{z^2}{2n} \pm z\sqrt{\hat p(1 - \hat p)/n + z^2/(4n^2)}\right)/(1 + z^2/n).

Proof. S(p)<z2S(p) < z^2 is (k−np)2<z2np(1−p)(k - np)^2 < z^2np(1 - p), that is (n2+z2n)p2−(2kn+z2n)p+k2<0(n^2 + z^2n)p^2 - (2kn + z^2n)p + k^2 < 0. This quadratic in pp has positive leading coefficient, so the set is the open interval between its roots, which the quadratic formula gives as stated after dividing by n2(1+z2/n)n^2(1 + z^2/n). Both roots are in [0,1][0, 1] because the quadratic is k2≥0k^2 \ge 0 at p=0p = 0 and (n−k)2≥0(n - k)^2 \ge 0 at p=1p = 1, and it is negative at p=p^p = \hat p when 0<k<n0 < k < n. □\square

Lemma 6 (null distribution, simple null). If H0:θ=θ0H_0: \theta = \theta_0 is simple and I(θ0)I(\theta_0) is finite and positive definite, with Eθ0[u(θ0;X)]=0E_{\theta_0}[u(\theta_0; X)] = 0 and Cov⁡θ0[u(θ0;X)]=I(θ0)\operatorname{Cov}_{\theta_0}[u(\theta_0; X)] = I(\theta_0), then S→χk2S \to \chi^2_k under H0H_0.

Proof. Un(θ0)=∑iu(θ0;Xi)U_n(\theta_0) = \sum_i u(\theta_0; X_i) is a sum of nn iid vectors with mean 0 and covariance I=I(θ0)I = I(\theta_0). By the multivariate central limit theorem, Un/n→Z∼N(0,I)U_n/\sqrt n \to Z \sim N(0, I). Since In=nII_n = nI, S=(Un/n)⊤I−1(Un/n)→Z⊤I−1ZS = (U_n/\sqrt n)^\top I^{-1}(U_n/\sqrt n) \to Z^\top I^{-1}Z by continuous mapping, and Z⊤I−1Z=Y⊤YZ^\top I^{-1}Z = Y^\top Y with Y=I−1/2Z∼N(0,Ik)Y = I^{-1/2}Z \sim N(0, I_k), which is χk2\chi^2_k. □\square

The mean 0 and covariance II of the score hold under the condition that differentiation under the integral sign is allowed, as on the score function page. For the normal mean with σ\sigma known, S=Z2S = Z^2 exactly with Z∼N(0,1)Z \sim N(0, 1), so the size is exactly α\alpha for every nn.

Lemma 7 (null distribution with nuisance parameters). Write θ=(α,β)\theta = (\alpha, \beta) with α∈Rr\alpha \in \mathbb R^r tested and β\beta free, and let β~\tilde\beta be the MLE of β\beta with α=α0\alpha = \alpha_0. Assume the conditions of the asymptotic normality of the MLE for the model with α\alpha fixed, so that β~\tilde\beta is consistent and 1n∇2ℓ\frac1n\nabla^2\ell converges in probability to −I-I uniformly near the true value. Then S→χr2S \to \chi^2_r under H0H_0.

Proof. Write U=(Uα,Uβ)U = (U_\alpha, U_\beta) at the true θ=(α0,β)\theta = (\alpha_0, \beta) and split II into blocks. A first-order expansion of Uβ(α0,β~)=0U_\beta(\alpha_0, \tilde\beta) = 0 around β\beta gives n(β~−β)=Iββ−1Uβ/n+op(1)\sqrt n(\tilde\beta - \beta) = I_{\beta\beta}^{-1}U_\beta/\sqrt n + o_p(1), and the same expansion of UαU_\alpha gives

Uα(α0,β~)n=Uα−IαβIββ−1Uβn+op(1).\frac{U_\alpha(\alpha_0, \tilde\beta)}{\sqrt n} = \frac{U_\alpha - I_{\alpha\beta}I_{\beta\beta}^{-1}U_\beta}{\sqrt n} + o_p(1).

By the central limit theorem the right side tends to N(0,Iαα−IαβIββ−1Iβα)N(0, I_{\alpha\alpha} - I_{\alpha\beta}I_{\beta\beta}^{-1}I_{\beta\alpha}). This covariance is ((I−1)αα)−1((I^{-1})_{\alpha\alpha})^{-1}, by the formula for the inverse of a block matrix. The score for β\beta is 0 at θ~0\tilde\theta_0, so S=Uα⊤(In(θ~0)−1)ααUα=(Uα/n)⊤(I(θ~0)−1)αα(Uα/n)S = U_\alpha^\top (I_n(\tilde\theta_0)^{-1})_{\alpha\alpha} U_\alpha = (U_\alpha/\sqrt n)^\top (I(\tilde\theta_0)^{-1})_{\alpha\alpha}(U_\alpha/\sqrt n), and I(θ~0)→II(\tilde\theta_0) \to I in probability by consistency and continuity. As in Lemma 6, the limit is χr2\chi^2_r. □\square

Lemma 8 (size). If S→χr2S \to \chi^2_r under H0H_0, then PH0(Q(r/2,S/2)≤α)→αP_{H_0}(Q(r/2, S/2) \le \alpha) \to \alpha.

Proof. 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(S)≤α}={S≥G−1(α)}\{G(S) \le \alpha\} = \{S \ge G^{-1}(\alpha)\}, and its probability tends to α\alpha because the limit law has a continuous distribution function. □\square

Termination. Line L1 is one call of the null fit. The solve makes O(k3)O(k^3) operations, the quadratic form O(k)O(k), and the tail one evaluation of the incomplete gamma function, which stops after a bounded number of iterations. The closed forms make one pass over the data or the cells.

Theorem. For a positive definite information, SCORE-TEST returns S=u⊤J−1u≥0S = u^\top J^{-1}u \ge 0 at the restricted MLE and p=P(χr2≥S)p = P(\chi^2_r \ge S). The closed forms equal this statistic, the multinomial one is Pearson's X2X^2, the statistic is invariant under reparametrization with expected information, and rejecting when p≤αp \le \alpha has size tending to α\alpha under the stated conditions.

Proof. Lemmas 1 to 8. ■\blacksquare

Complexity

On a real RAM, the closed forms need one pass over the data: Θ(n)\Theta(n) time, or Θ(m)\Theta(m) after counting for a multinomial with mm cells, and Θ(1)\Theta(1) extra space. The general form costs one fit under H0H_0, plus Θ(nk)\Theta(nk) to sum the score, Θ(nk2)\Theta(nk^2) for an observed or empirical information, and Θ(k3)\Theta(k^3) for the solve in line L4. The likelihood ratio test needs two fits and the Wald test one fit of the full model; the score test needs only the fit of the smaller model, which often has a closed form when the full one does not.

Numerical stability. Line L4 solves a system and does not invert JJ. In the closed forms there is no cancellation of large terms: k−np0k - np_0 is a difference of the data and a constant, computed once, and squared. When the score is computed from a sum of per-observation scores that nearly cancel, use compensated summation or math.fsum. Line L6 computes the upper tail directly.

Properties

  • Only the null fit. The score test fits only Θ0\Theta_0. To screen many candidate extensions of a model, such as many extra regressors one at a time, the score test needs one fit in total, while the Wald and likelihood ratio tests need one new fit per candidate.
  • Invariant under reparametrization when InI_n is the expected information. Under θ=g(ψ)\theta = g(\psi), the score and the information change by the Jacobian of gg and its square, and the quadratic form does not change. With the observed information this is not true in general.
  • Exists at the edge. At p^=0\hat p = 0 the score test is finite, while the Wald statistic is infinite. It uses the variance under H0H_0, which does not depend on the data.
  • Asymptotically χr2\chi^2_r, and equivalent to the Wald and LR tests under H0H_0 and local alternatives.
  • Conservative in the normal mean model. With u=T2/(n−1)u = T^2/(n - 1), S=nu/(1+u)≤nlog⁡(1+u)=Λ≤nu=WS = nu/(1 + u) \le n\log(1 + u) = \Lambda \le nu = W. The exact size of the nominal 5% score test is 0.0220.022 at n=5n = 5, 0.0420.042 at n=10n = 10, 0.0470.047 at n=20n = 20 and 0.0490.049 at n=50n = 50 (computed from the t distribution). For the binomial the sizes go both ways: 0.02150.0215 at n=10n = 10, p0=0.5p_0 = 0.5, and 0.06080.0608 at n=30n = 30, p0=0.05p_0 = 0.05 (exact enumeration).
  • Locally most powerful. For a one-sided alternative in a one-parameter family, rejecting for large Un(θ0)U_n(\theta_0) maximizes the derivative of the power at θ0\theta_0 among tests of size α\alpha.

Variants and improvements

  • Signed score statistic. For one parameter, Z=Un(θ0)/In(θ0)Z = U_n(\theta_0)/\sqrt{I_n(\theta_0)} gives one-sided tests. For the binomial it is the one-proportion z-test.
  • Score intervals. Inverting the score test gives the Wilson score interval for a proportion, which has much better coverage than the Wald interval.
  • Observed information or outer product. Replacing InI_n by the observed information −∇2ℓ(θ~0)-\nabla^2\ell(\tilde\theta_0), or by the outer product of the per-observation scores (the nR2nR^2 form common in econometrics), gives statistics with the same limit. They differ in finite samples, and the outer product form often has poor size.
  • Robust score test. With a sandwich estimate of the covariance of the score, the test stays valid when the variance model is wrong, as in generalized estimating equations.
  • Famous special cases. Pearson's chi-squared goodness-of-fit test and the chi-squared test of independence; the log-rank test, which is the score test of the Cox model for a group indicator; the Breusch-Pagan test for heteroscedasticity; and the LM test of Engle (1982) for ARCH effects in time series.

When to use it

Use the score test when the null model is easy to fit and the full model is not: testing whether a simple model needs an extra term, a nonzero variance component, an interaction or a more general error structure. It is the natural choice for screening many candidate extensions, since all of them share the one null fit. Use it for a proportion near 0 or 1, where the Wald test fails. When both models are easy to fit, the likelihood ratio test is usually more accurate. For small samples, use an exact test when one exists.

Pitfalls

  • Expected or observed information. They give different numbers in finite samples, and only the expected information makes the test invariant. State which one is used.
  • Nuisance parameters must be refitted. The score must be evaluated at the restricted MLE θ~0\tilde\theta_0, not at the full MLE and not at guessed nuisance values. With other plug-in values the variance of the score is wrong and the χr2\chi^2_r limit fails.
  • Loss of power far from the null. The test uses the curvature at θ0\theta_0. For some models the score at the null can be small even when the alternative is far away, so the power can be low or even fall as the effect grows.
  • Boundary nulls. For a variance component equal to 0, the one-sided nature of the alternative must be taken into account, as for the likelihood ratio test.
  • Reading the asymptotic size as exact. The size can be well below or above α\alpha for small samples and discrete data, as the size values above show.

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.

score_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/score-test/. The authors are listed in prov/6H761T.jsonl.
"""The score test (Rao score test, Lagrange multiplier test), general and for common models.

score_test fits the model under H_0 only, evaluates the score U and the
Fisher information J at the restricted estimate, and returns (S, p) with
S = U^T J^(-1) U and p the upper chi-squared tail with r degrees of
freedom (asymptotic). The linear system J y = U is solved by Gaussian
elimination with partial pivoting in the arithmetic of the inputs, so
Fraction inputs give an exact S. The model functions give S in closed form;
for a multinomial it is Pearson's X^2.
The code is in this file and not in score_test.py, because tools treat a
file whose name ends in _test.py as a test file.
"""

import math
from collections.abc import Callable, Sequence

from 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 information 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 score_test(score: Callable[[object], Sequence], info: Callable[[object], Sequence[Sequence]],
               fit_null: Callable[[], object], r: int):
    """General score test: score(theta) and info(theta) are the full score vector and the
    Fisher information of the sample; fit_null returns the MLE under H_0. Returns (S, p)."""
    if r < 1:
        raise ValueError("r, the number of constraints, must be at least 1")
    theta0 = fit_null()  # @line L1
    u = list(score(theta0))  # @line L2
    j = info(theta0)  # @line L3
    y = solve(j, u)  # @line L4
    s = sum(u[i] * y[i] for i in range(len(u)))  # @line L5
    if s < 0:
        raise ValueError("the information matrix is not positive definite")
    p = chi2_sf(float(s), r)  # @line L6
    return s, p  # @line L7


def binomial_score(k: int, n: int, p0: float) -> tuple[float, float]:
    """S = (k - n p0)^2 / (n p0 (1 - p0)), the square of the one-proportion z statistic."""
    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")
    s = (k - n * p0) ** 2 / (n * p0 * (1.0 - p0))
    return s, chi2_sf(s, 1)


def poisson_score(total: int, n: int, lam0: float) -> tuple[float, float]:
    """S = (total - n lam0)^2 / (n lam0) for n iid Poisson counts with sum total."""
    if n < 1 or total < 0 or lam0 <= 0.0:
        raise ValueError("need n >= 1, total >= 0 and lam0 > 0")
    s = (total - n * lam0) ** 2 / (n * lam0)
    return s, chi2_sf(s, 1)


def normal_mean_score(x: Sequence[float], mu0: float,
                      sigma: float | None = None) -> tuple[float, float]:
    """Score test of mu = mu0. With sigma unknown, S = n^2 (xbar - mu0)^2 / sum (x - mu0)^2,
    which is n T^2 / (n - 1 + T^2) for the t statistic T."""
    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:
        ss0 = math.fsum((v - mu0) ** 2 for v in x)
        if ss0 == 0.0:
            raise ValueError("all observations equal mu0")
        s = n * n * (mean - mu0) ** 2 / ss0
    else:
        if sigma <= 0.0:
            raise ValueError("sigma must be positive")
        s = n * (mean - mu0) ** 2 / sigma ** 2
    return s, chi2_sf(s, 1)


def multinomial_score(counts: Sequence[int], probs: Sequence[float]) -> tuple[float, float]:
    """Score test of cell probabilities = probs; S is Pearson's X^2, with m - 1 degrees of freedom."""
    m, n = len(counts), sum(counts)
    if m < 2 or n < 1 or len(probs) != m or any(c < 0 for c in counts):
        raise ValueError("need at least 2 cells, nonnegative counts and one prob per cell")
    if any(q <= 0.0 for q in probs) or abs(math.fsum(probs) - 1.0) > 1e-12:
        raise ValueError("probs must be positive and sum to 1")
    s = math.fsum((c - n * q) ** 2 / (n * q) for c, q in zip(counts, probs))
    return s, chi2_sf(s, m - 1)
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
score_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/score-test/. The authors are listed in prov/6H761T.jsonl.
"""Entry point named after the slug. The code lives in score_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from score_core import (binomial_score, multinomial_score, normal_mean_score, poisson_score,
                        score_test, solve)

__all__ = ["binomial_score", "multinomial_score", "normal_mean_score", "poisson_score",
           "score_test", "solve"]
test_score_test.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/score-test/. The authors are listed in prov/6H761T.jsonl.

import math
import random
from fractions import Fraction

import pytest

from score_test import (binomial_score, multinomial_score, normal_mean_score, poisson_score,
                        score_test, solve)
from stdist import chi2_sf, norm_ppf


def numeric_score(loglik, theta: list[float]) -> list[float]:
    """Brute force: the gradient of loglik by central differences with Richardson extrapolation."""
    out = []
    for i in range(len(theta)):
        def diff(h: float) -> float:
            up, dn = list(theta), list(theta)
            up[i] += h
            dn[i] -= h
            return (loglik(up) - loglik(dn)) / (2 * h)
        h = 1e-3 * max(abs(theta[i]), 1e-3)
        out.append((4 * diff(h / 2) - diff(h)) / 3)
    return out


def expected_information(one_loglik, theta: float, support) -> float:
    """Brute force: Var of the one-observation score, by summing over the support."""
    total = 0.0
    for x, prob in support:
        u = numeric_score(lambda t: one_loglik(x, t[0]), [theta])[0]
        total += prob * u * u
    return total


def test_worked_example() -> None:
    s, p = binomial_score(15, 20, 0.5)
    assert s == pytest.approx(5.0, rel=1e-14)
    assert p == pytest.approx(0.025347, abs=1e-6)
    z = (15 - 10) / math.sqrt(20 * 0.25)
    assert s == pytest.approx(z * z, rel=1e-14)  # the one-proportion z-test squared


def test_binomial_and_poisson_against_numerical_score_and_information() -> None:
    rng = random.Random(31)
    for _ in range(15):
        n = rng.randint(5, 60)
        k = rng.randint(0, n)
        p0 = rng.uniform(0.05, 0.95)
        ll = lambda t: k * math.log(t[0]) + (n - k) * math.log(1.0 - t[0])
        one = lambda x, p: x * math.log(p) + (1 - x) * math.log(1.0 - p)
        info = n * expected_information(one, p0, [(0, 1 - p0), (1, p0)])
        s, _ = score_test(lambda t: numeric_score(ll, t), lambda t: [[info]], lambda: [p0], 1)
        assert s == pytest.approx(binomial_score(k, n, p0)[0], rel=1e-6, abs=1e-9)
    for _ in range(10):
        n, total, lam0 = rng.randint(1, 20), rng.randint(0, 80), rng.uniform(0.5, 5.0)
        ll = lambda t: total * math.log(t[0]) - n * t[0]
        one = lambda x, lam: x * math.log(lam) - lam
        support = [(x, math.exp(-lam0 + x * math.log(lam0) - math.lgamma(x + 1))) for x in range(80)]
        info = n * expected_information(one, lam0, support)
        s, _ = score_test(lambda t: numeric_score(ll, t), lambda t: [[info]], lambda: [lam0], 1)
        assert s == pytest.approx(poisson_score(total, n, lam0)[0], rel=1e-6, abs=1e-9)


def test_normal_unknown_variance_against_numerical_score() -> None:
    rng = random.Random(32)
    for _ in range(20):
        n = rng.randint(2, 25)
        x = [rng.gauss(1.0, 2.0) for _ in range(n)]
        mu0 = rng.uniform(-1.0, 3.0)
        ll = lambda t: -0.5 * n * math.log(t[1]) - sum((v - t[0]) ** 2 for v in x) / (2 * t[1])
        fit_null = lambda: [mu0, sum((v - mu0) ** 2 for v in x) / n]
        info = lambda t: [[n / t[1], 0.0], [0.0, n / (2 * t[1] ** 2)]]
        s, _ = score_test(lambda t: numeric_score(ll, t), info, fit_null, 1)
        closed = normal_mean_score(x, mu0)[0]
        assert s == pytest.approx(closed, rel=1e-6, abs=1e-9)
        mean = sum(x) / n
        t2 = (mean - mu0) ** 2 / (sum((v - mean) ** 2 for v in x) / (n - 1) / n)
        assert closed == pytest.approx(n * t2 / (n - 1 + t2), rel=1e-10)


def test_multinomial_score_is_pearson_exactly() -> None:
    rng = random.Random(33)
    for _ in range(40):
        m = rng.randint(2, 5)
        w = [rng.randint(1, 6) for _ in range(m)]
        q = [Fraction(v, sum(w)) for v in w]
        counts = [rng.randint(0, 15) for _ in range(m)]
        n = sum(counts)
        if n == 0:
            continue
        # Free parameters q_1..q_(m-1); q_m = 1 - sum. Score and information at q.
        u = [Fraction(counts[j]) / q[j] - Fraction(counts[-1]) / q[-1] for j in range(m - 1)]
        info = [[n * ((1 / q[i] if i == j else 0) + 1 / q[-1]) for j in range(m - 1)]
                for i in range(m - 1)]
        s, p = score_test(lambda t: u, lambda t: info, lambda: q, m - 1)
        pearson = sum((c - n * qj) ** 2 / (n * qj) for c, qj in zip(counts, q))
        assert s == pearson
        got, pg = multinomial_score(counts, [float(v) for v in q])
        assert got == pytest.approx(float(pearson), rel=1e-12, abs=1e-14)
        assert pg == pytest.approx(p, rel=1e-10)


def test_trinity_agrees_for_normal_mean_with_known_variance() -> None:
    rng = random.Random(34)
    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)
        u = sum(Fraction(v) - mu0 for v in x) / sigma ** 2
        s, _ = score_test(lambda t: [u], lambda t: [[Fraction(n, sigma ** 2)]], lambda: [mu0], 1)
        xbar = Fraction(sum(x), n)
        lr = (sum((Fraction(v) - mu0) ** 2 for v in x) - sum((v - xbar) ** 2 for v in x)) / sigma ** 2
        wald = (xbar - mu0) ** 2 * n / sigma ** 2
        assert s == lr == wald
        assert normal_mean_score(x, mu0, sigma)[0] == pytest.approx(float(s), rel=1e-12, abs=1e-15)


def test_invariant_under_reparametrization() -> None:
    # The score test of p = p0 and of logit p = logit p0 give the same S with expected information.
    for k, n, p0 in [(15, 20, 0.5), (3, 40, 0.2), (0, 10, 0.3)]:
        b0 = math.log(p0 / (1 - p0))
        ll = lambda t: k * t[0] - n * math.log1p(math.exp(t[0]))  # log-likelihood in beta
        info = n * p0 * (1 - p0)
        s, _ = score_test(lambda t: numeric_score(ll, t), lambda t: [[info]], lambda: [b0], 1)
        assert s == pytest.approx(binomial_score(k, n, p0)[0], rel=1e-6)


def test_inverting_gives_the_wilson_interval() -> None:
    z = norm_ppf(0.975)
    for k, n in [(15, 20), (0, 10), (7, 9), (50, 120)]:
        ph = k / n
        centre = (ph + z * z / (2 * n)) / (1 + z * z / n)
        half = z / (1 + z * z / n) * math.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n))
        for end in (centre - half, centre + half):
            if 0.0 < end < 1.0:
                assert binomial_score(k, n, end)[0] == pytest.approx(z * z, rel=1e-9)
        assert binomial_score(k, n, min(max(centre, 1e-9), 1 - 1e-9))[0] < z * z


def test_exact_binomial_size_by_enumeration() -> None:
    crit = 3.841458820694124
    for n, p0, expected in [(10, Fraction(1, 2), 0.0215), (20, Fraction(1, 10), 0.0432),
                            (50, Fraction(1, 10), 0.0297), (30, Fraction(1, 20), 0.0608)]:
        size = sum(math.comb(n, k) * p0 ** k * (1 - p0) ** (n - k)
                   for k in range(n + 1) if binomial_score(k, n, float(p0))[0] >= crit)
        assert abs(float(size) - expected) < 1e-4


def test_monte_carlo_size_normal_unknown_variance() -> None:
    rng = random.Random(35)
    reps, n = 3000, 30
    hits = sum(normal_mean_score([rng.gauss(0.0, 3.0) for _ in range(n)], 0.0)[1] <= 0.05
               for _ in range(reps))
    assert abs(hits / reps - 0.05) < 0.02


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        score_test(lambda t: [1.0], lambda t: [[1.0]], lambda: [0.0], 0)
    with pytest.raises(ValueError):
        solve([[0.0]], [1.0])
    with pytest.raises(ValueError):
        multinomial_score([1, 2], [0.5, 0.6])
    assert chi2_sf(0.0, 1) == 1.0

History

C. R. Rao proposed the test in 1948 in the Proceedings of the Cambridge Philosophical Society, as a large-sample test that uses only quantities at the null value: the score and the information. Aitchison and Silvey (1958) studied the maximum likelihood estimate under restrictions and the asymptotic law of its Lagrange multipliers, and Silvey (1959) built the test on the multipliers and named it the Lagrangian multiplier test; it is the same statistic as Rao's. Econometricians adopted the name "LM test" in the 1970s and 1980s, with work by Breusch and Pagan and by Engle, and used it for specification tests of regression models. Pearson's chi-squared statistic of 1900 and the log-rank test of the 1960s turned out to be score tests of their models.

References

  1. C. R. Rao, Large sample tests of statistical hypotheses concerning several parameters with applications to problems of estimation, Proceedings of the Cambridge Philosophical Society 44(1) (1948), pages 50 to 57, the score statistic for simple and composite hypotheses
  2. J. Aitchison and S. D. Silvey, Maximum-likelihood estimation of parameters subject to restraints, Annals of Mathematical Statistics 29(3) (1958), pages 813 to 828, the Lagrange multipliers of the restricted MLE and their asymptotic distribution
  3. S. D. Silvey, The Lagrangian multiplier test, Annals of Mathematical Statistics 30 (1959), pages 389 to 407, the test based on the Lagrange multipliers and its equivalence with the score test
  4. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 10.3.2 (other large-sample tests, with the score statistic)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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