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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- C. R. Rao, 1948
The score test asks whether the log-likelihood is still climbing at the null value. If is true, the slope of the log-likelihood, the score , should be near 0 at the best fit under ; a large slope says that the data pull the parameter away from the null. The statistic is , the squared score in the metric of the Fisher information, where is the MLE under . 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 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 are iid with density , . The null hypothesis fixes coordinates, , and leaves nuisance coordinates free, or more generally imposes smooth restrictions .
Statistic. Let be the MLE under , the score of the sample and the expected Fisher information. Then
The score for the nuisance coordinates is 0 at , because maximizes over them; only the tested coordinates contribute, through the matching block of . For one parameter and a simple null, .
Null distribution. Asymptotic. Under , by the central limit theorem, since the score is a sum of iid terms with mean 0 and variance . So . 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 .
Rejection rule and size. Reject at level when . For one parameter one can also use the signed root against , which gives one-sided tests. The size tends to .
p-value. .
Sensitivity and power. Under local alternatives , tends to the same noncentral as the Wald test and the likelihood ratio test. For a one-sided alternative in a one-parameter family, the test based on is locally most powerful: it has the largest slope of the power function at among tests of size . Far from the null, the score test can lose power, because the information at may not describe the data well there.
The algorithm
SCORE-TEST(x, U, I, Θ₀, r) ▷ U(θ): score vector; I(θ): Fisher information of the sample- 1
θ̃₀ ← a maximizer of ℓ(θ; x) over Θ₀ ▷ the only fit - 2
u ← U(θ̃₀) ▷ 0 in the nuisance coordinates - 3
J ← I(θ̃₀) - 4
solve J y = u for y ▷ never form J⁻¹ - 5
S ← uᵀ y - 6
p ← Q(r/2, S/2) ▷ P(χ²_r ≥ S), the upper tail directly - 7
return (S, p)
For the common models the steps reduce to closed forms, all of them at the null value:
| model, null | |||
|---|---|---|---|
| binomial, | |||
| Poisson, | , | ||
| normal, , known | |||
| normal, , unknown | |||
| multinomial, probabilities | , |
In the fourth row, is the MLE of under , and in terms of the t statistic . 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 subject to with a Lagrange multiplier . At the restricted maximum, , where is the Jacobian of . The multiplier 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 is large, in the metric of its asymptotic covariance, is the Lagrange multiplier test of Aitchison and Silvey (1958) and Silvey (1959). Because , its statistic is the same number . Econometrics uses the name "LM test"; statistics uses "score test".
Example
A binomial count. In 20 trials there are 15 successes, and .
| step | value |
|---|---|
| L1: (simple null, nothing to fit) | 0.5 |
| L2: | 20 |
| L3: | 80 |
| L4: | 0.25 |
| L5: | 5.0 |
| L6: | 0.02535 |
This is the square of the z statistic of the one-proportion z-test. The Wald test gives and the likelihood ratio test . Inverting the score test, the values that it does not reject at 5% form the interval , which is the Wilson score interval.
A normal mean with unknown variance. For the nine pack weights of the z-test page and , line L1 fits with held at 500: . The score for is , the score for is 0, the information for is , and , with . The other two give () and (), and the exact t-test gives . Here , as always in this model.
Counts in cells. For the counts and : probabilities , the score test is Pearson's statistic with and . The likelihood ratio (G) statistic of the same data is .
Correctness
Line L4 solves , so line L5 returns , which is when is positive definite. The closed forms follow from the scores and informations of each model; for a multinomial the quadratic form equals Pearson's exactly, which the tests check in rational arithmetic. Under a simple null, the score is a sum of iid vectors with mean 0 and covariance , so and ; 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 , and the limit is again . The size of the test therefore tends to ; 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 with the score and the Fisher information at the restricted MLE, that the closed forms are correct, that the multinomial score statistic is exactly Pearson's , that does not depend on the parametrization when is the expected information, that inverting the binomial score test gives the Wilson interval, and that under . 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 is nonsingular, lines L4 and L5 return . If is symmetric positive definite, .
Proof. Gaussian elimination with partial pivoting uses only row swaps and row operations that keep the solution set; every pivot is nonzero when is nonsingular, since a zero pivot column would make the leading columns dependent; back substitution then gives the unique . If is positive definite, so is , and .
Lemma 2 (closed forms). The first four rows of the table are correct.
Proof. Binomial: , so , and . Then . Poisson: , , , and . Normal with known: and . Normal with unknown: under the log-likelihood is maximized at , where the score for is 0. The score for is , and the information matrix of is , so . With , and , which gives .
Lemma 3 (the multinomial score statistic is Pearson's ). Let be multinomial counts with total , and : probabilities . Parametrize by with . Then the score test statistic is .
Proof. , so for . The information is with , since and . By the Sherman-Morrison formula, , where and we used . Write , so and . Then
using and . Also , so . Subtracting, , which is .
Lemma 4 (invariance). Let with one-to-one and differentiable with nonsingular Jacobian . With expected information, the score statistic in at equals the one in at .
Proof. By the chain rule the score in is , and the expected information in is , because the information is the covariance of the score. So . With nuisance parameters, must map the null set onto the null set; then the restricted MLEs correspond, and the same computation applies at .
The observed information in has the extra term , 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 out of , the set with is the open interval between the roots of , which are .
Proof. is , that is . This quadratic in has positive leading coefficient, so the set is the open interval between its roots, which the quadratic formula gives as stated after dividing by . Both roots are in because the quadratic is at and at , and it is negative at when .
Lemma 6 (null distribution, simple null). If is simple and is finite and positive definite, with and , then under .
Proof. is a sum of iid vectors with mean 0 and covariance . By the multivariate central limit theorem, . Since , by continuous mapping, and with , which is .
The mean 0 and covariance 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 known, exactly with , so the size is exactly for every .
Lemma 7 (null distribution with nuisance parameters). Write with tested and free, and let be the MLE of with . Assume the conditions of the asymptotic normality of the MLE for the model with fixed, so that is consistent and converges in probability to uniformly near the true value. Then under .
Proof. Write at the true and split into blocks. A first-order expansion of around gives , and the same expansion of gives
By the central limit theorem the right side tends to . This covariance is , by the formula for the inverse of a block matrix. The score for is 0 at , so , and in probability by consistency and continuity. As in Lemma 6, the limit is .
Lemma 8 (size). If under , then .
Proof. The upper tail of is continuous and strictly decreasing, so , and its probability tends to because the limit law has a continuous distribution function.
Termination. Line L1 is one call of the null fit. The solve makes operations, the quadratic form , 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 at the restricted MLE and . The closed forms equal this statistic, the multinomial one is Pearson's , the statistic is invariant under reparametrization with expected information, and rejecting when has size tending to under the stated conditions.
Proof. Lemmas 1 to 8.
Complexity
On a real RAM, the closed forms need one pass over the data: time, or after counting for a multinomial with cells, and extra space. The general form costs one fit under , plus to sum the score, for an observed or empirical information, and 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 . In the closed forms there is no cancellation of large terms: 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 . 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 is the expected information. Under , the score and the information change by the Jacobian of 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 the score test is finite, while the Wald statistic is infinite. It uses the variance under , which does not depend on the data.
- Asymptotically , and equivalent to the Wald and LR tests under and local alternatives.
- Conservative in the normal mean model. With , . The exact size of the nominal 5% score test is at , at , at and at (computed from the t distribution). For the binomial the sizes go both ways: at , , and at , (exact enumeration).
- Locally most powerful. For a one-sided alternative in a one-parameter family, rejecting for large maximizes the derivative of the power at among tests of size .
Variants and improvements
- Signed score statistic. For one parameter, 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 by the observed information , or by the outer product of the per-observation scores (the 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 , 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 limit fails.
- Loss of power far from the null. The test uses the curvature at . 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 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6H761T Edit this page History Report an error Markdown