Algorithmintro
F-test for nested linear models
Also called overall F-test, partial F-test, extra sum of squares test.
Compares a linear model with a nested smaller one by the drop in residual sum of squares per extra parameter over the residual variance. Exact F law under normal errors. One QR, O(n p^2).
- Time
- Θ(n p^2) worst · best
- Space
- Θ(n p) extra
- Counts
- flops 2n p^2 - 2p^3/3 + O(n p) worst
- Where
- n = the number of observations; p = the number of columns of the full design matrix, with p < n
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald A. Fisher, George W. Snedecor, 1925
The F-test for nested linear models decides whether some coefficients of a linear model are 0, or more generally whether a smaller model, whose column space lies inside that of a larger one, fits as well as the larger model. It compares the drop in the residual sum of squares per removed parameter with the residual variance of the larger model. Under normal errors with equal variance and the null hypothesis, the ratio has the F distribution with and degrees of freedom exactly. The overall F-test (all slopes 0) and the partial F-test (one group of predictors) are special cases, and with one restriction the test is the two-sided t-test of one coefficient. This page owns the test; the fit itself is on the ordinary least squares page.
In plain words
You fitted a straight-line rule with several inputs and want to know if some of the inputs help at all. Fit the rule twice: once with them and once without them. Without them, the fit can only be worse, so the leftover error grows a little even if the inputs are useless. The question is whether it grows more than chance would make it grow. The test divides the growth per dropped input by the leftover error per remaining degree of freedom of the big model. If the dropped inputs are useless and the errors are bell-shaped with equal spread, this ratio has a known law, the F law, so a large ratio is evidence that they help. One QR factorization of the big model gives both fits at once.
The problem
Model. , where is a fixed matrix of rank (its columns include the intercept column if there is one), is the coefficient vector, and with unknown. Order the columns so that the first form the null design , , and let and .
Hypotheses. : the last coefficients are 0, so ; : they are not all 0. The general linear hypothesis , with a matrix of rank , reduces to this form by a change of basis (see Variants).
Statistic. With and ,
Null distribution. Exact: under , for every and every . Reject at level when , the upper point (lower quantile) of . The test is one-sided in : a large is evidence against , and a small one is not.
Special cases. The overall F-test has (intercept only), , and then , so with the coefficient of determination. The partial F-test drops one group of predictors. With one dropped column, for the t statistic of that coefficient, and the F-test and the two-sided t-test agree. One-way ANOVA is the overall F-test on group indicator columns.
The algorithm
REGRESSION-F-TEST(X[1..n, 1..p], y[1..n], p₀) ▷ the first p₀ columns span the null model- 1
for j ← 1 to p do ▷ Householder QR of X, applied to y - 2
a ← X[j..n, j]; α ← −sign(a₁)·‖a‖; v ← a − α·e₁ ▷ ‖a‖ = 0 means rank < p - 3
apply I − 2vvᵀ/(vᵀv) to columns j..p of X, rows j..n - 4
apply the same reflection to y[j..n] ▷ after the loop y holds c = Qᵀy - 5
RSS₁ ← c[p+1]² + ... + c[n]² - 6
ΔSS ← c[p₀+1]² + ... + c[p]² ▷ = RSS₀ − RSS₁ - 7
q ← p − p₀; ν ← n − p - 8
F ← (ΔSS / q) / (RSS₁ / ν) - 9
return (F, q, ν, Ḡ_{q,ν}(F))
The key fact is that the first columns of span the first columns of for every . So one factorization of the full design gives the residual sum of squares of every model made of a leading set of columns: of the first columns is . Line L6 therefore needs no second fit. The tail is , the regularized incomplete beta function, which the helper evaluates directly, so a p-value of keeps its digits. If and the code returns and ; if both are 0, is undefined and the code raises an error, as it does for , or a rank-deficient .
The implementation also has the Wald form for , which uses from the same factorization, and the t statistics of the single coefficients.
Example
Eight observations, two predictors and an intercept, so and :
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
| 3 | 1 | 4 | 1 | 5 | 9 | 2 | 6 | |
| 3 | 5 | 6 | 6 | 9 | 13 | 10 | 14 |
The columns are ordered . The least squares fit is .
| line | value |
|---|---|
| L1 to L4: diagonal of | |
| L4: | |
| = drop in RSS from adding to the intercept | |
| = drop in RSS from adding | |
| L5: | |
Overall F-test (, ): , which equals . Then with p-value , far above . Also , and gives the same 96.847.
Partial F-test for (, ): , p-value , above . The t statistic of is , and . The residual sum of squares of the intercept and model, fitted on its own, is , as line L6 says.
A hypothesis that is not a deletion. has . The Wald form gives with and p-value , and the nested form on the design with gives the same number.
Size under the model and outside it. Monte Carlo with replications at level 0.05 (standard error of an estimated size near 0.05: 0.0034); design with an intercept and three uniform predictors, testing the last two ():
| errors | measured size | seed | |
|---|---|---|---|
| normal, equal variance | 12 | 0.0450 | 1 |
| centered exponential, equal variance | 12 | 0.0400 | 2 |
| , equal variance | 12 | 0.0485 | 3 |
| normal, sd | 12 | 0.1240 | 4 |
| normal, sd | 60 | 0.0583 | 5 |
The exactness is proved for the first row; the other rows are measurements. Non-normal errors with equal variance moved the size little here. Variance that depends on a tested predictor more than doubled it at .
Correctness
Householder reflections are orthogonal, so keeps lengths, and . The first term can be made 0, so ; the same argument for the first columns, whose factor is the leading block of , gives . Under normal errors, is a normal vector with covariance , so its coordinates are independent. Its mean is 0 below row , and under also below row . So and are independent chi-square variables with and degrees of freedom, and their scaled ratio is by definition; cancels. The p-value is the upper tail of a continuous law, so it is uniform under and the size is exactly . A Lagrange multiplier argument shows that the restricted fit under raises the residual sum of squares by exactly , so the Wald and nested forms agree. The proofs are in the correctness proof below.
Proof: The nested-model F statistic has the F distribution with q and n - p degrees of freedom under normal errorsfull
We prove that the algorithm computes and from one QR factorization, that the statistic has the law under the null hypothesis with normal errors, that the p-value is uniform under the null, so the size is exactly , and that the Wald form for gives the same number. The model is with a fixed matrix of rank , , whose first columns form (), and . The null hypothesis is : the last coefficients are 0, that is, .
Lemma 1 (what the loop computes). After lines L1 to L4, the transformed matrix is with upper triangular and nonsingular, and the transformed is , where is orthogonal. For each , the first columns of are an orthonormal basis of the span of the first columns of .
Proof. Step applies the Householder reflection , which is symmetric and orthogonal (). The vector is 0 in its first entries, so leaves rows alone, and the choice with , where is the part of column in rows , maps to . The sign of is opposite to , so has no cancellation and whenever . By induction, after step columns are 0 below the diagonal, so after steps , and . Since has rank , at every step: otherwise column of the current matrix would be a combination of the earlier columns, and so would column of . So . Write with the first columns. From with upper triangular, column of is a combination of the first columns of , and since is nonsingular the converse holds too.
The loop runs times, each step over finitely many entries, so the algorithm terminates. Lines L5 to L9 are finite sums and one call of the tail function.
Lemma 2 (the two sums of squares). With , and , where for the null () and full () models.
Proof. keeps lengths, so for any , . Since is nonsingular, makes the first term 0, so the minimum is . For the null model, , and the first columns of are 0 below row . With the leading block (nonsingular), , and the minimum is . Subtract. For the null model is and , the same formula.
Lemma 3 (the null law). Under the model, , so are independent with variance . The means are for , and, under , also for . So under , and , independent, and
Proof. A linear map of a normal vector is normal, with . For a normal vector, uncorrelated coordinates are independent. , which is 0 below row . Under , , and is 0 below row (the first columns of are). So for are iid . A sum of squared iid standard normals is , which gives and ; they use disjoint sets of coordinates, so they are independent. The ratio of independent chi-square variables, each divided by its degrees of freedom, is by definition. cancels, so the law does not depend on or on the null coefficients .
Lemma 4 (the p-value and the size). Line L9 returns , where is the CDF of and . Under , for , so rejecting when the p-value is at most has size exactly .
Proof. is continuous and strictly increasing on , since the F law has a positive density there. Then , of probability . The helper computes with , the standard expression of the F tail through the regularized incomplete beta function: if then has the Beta law, and exactly when this ratio is below .
Lemma 5 (the Wald form). Let be a matrix of rank , , the least squares estimate and . The minimum of over is . So the Wald statistic equals the nested F statistic of the restricted model, and has the law under .
Proof. , since . Write (positive definite) and . Minimize subject to : with a Lagrange multiplier, , so and gives ; the value is . The matrix is positive definite because has full row rank. This value is the minimum because the objective is convex. The restricted set is a translate of a linear subspace of dimension , so the restricted model is a nested linear model after a change of variables: pick with , replace by , and choose a basis of the column space of whose first vectors span . Lemmas 1 to 4 then apply with .
Theorem. For data from the model, the algorithm returns , which has the law under , and a p-value that is uniform on under . With one restriction (, the last column), for the t statistic .
Proof. Lemmas 1 to 4 give the first two claims. For , take in Lemma 5: .
What is not proved. Without normality the law of is not in finite samples. If the errors are iid with mean 0 and finite variance and , then in distribution, so the size tends to . This follows from the Lindeberg-Feller central limit theorem applied to the projection of on the tested directions, together with in probability; we do not prove it here. The measured sizes on the page are only measurements. Under heteroscedasticity the statistic has neither law, and the test is not valid even asymptotically.
Complexity
On a real RAM, step of the loop updates the trailing block at about 4 flops per entry, which sums to flops; applying the reflections to adds , and lines L5 to L8 cost . So the time is , the same as one least squares fit, and the extra space is for the working copy of (it can overwrite , as LAPACK does). Fitting the two models separately would cost about flops; the nested order of columns makes the second fit free. The F tail costs a number of continued fraction steps that does not grow with .
Numerical stability. The textbook route forms and solves the normal equations. That squares the condition number of , and the subtraction of two nearly equal numbers can lose the digits that remain. Householder QR is backward stable, and line L6 computes the difference as a sum of squares, which has no cancellation. With nearly collinear predictors (see variance inflation factor), this is the difference between a correct F and a negative one.
Properties
- Exact under normality. Size for every , every and every value of the null coefficients.
- Invariant. does not change when is replaced by (), when the columns of are replaced by a nonsingular combination of them, when the tested columns are changed by a nonsingular combination plus a combination of , or when the rows are permuted.
- Equal to the likelihood ratio test. For normal errors, the likelihood ratio is , an increasing function of , so the two tests are the same test. Among tests invariant under the transformations above, it is uniformly most powerful (Lehmann and Romano, Chapter 7).
- Power. Under , has the noncentral F law with noncentrality , where is the projection on ; the power increases with .
- One restriction is the t-test. With the F-test is the two-sided t-test of , and the p-values coincide.
Variants and improvements
- General linear hypothesis. . The Wald form needs only the full fit. It equals the nested F of the restricted model, which the Wald test and likelihood ratio test pages treat in general models.
- Sequential (type I) sums of squares. The squares are the drops in RSS as the columns enter one by one, in the given order. They depend on the order unless the columns are orthogonal; this is the analysis of variance table of a regression.
- Robust standard errors. Under heteroscedasticity replace in the Wald form by a heteroscedasticity-consistent estimate and compare with . This is valid only asymptotically.
- Permutation and bootstrap versions. Permute the residuals of the null model (Freedman and Lane) or resample them to get a null law without normality; see permutation test and bootstrap method.
- Model search. Stepwise regression uses partial F statistics to add and drop variables, and leaps and bounds searches all subsets. The p-values of the chosen model are then not valid, because the data chose the hypothesis.
When to use it
Use the F-test to test several coefficients at once (a group of dummy variables for one factor, a set of polynomial terms, all slopes) in a linear model with errors that are close to normal and of equal variance, or with a large and no high leverage points. Use it instead of several t-tests, which do not control the error rate of the joint question. For a single coefficient it is the t-test. For non-nested models use an information criterion such as the Akaike information criterion, not an F-test. For generalized linear models, use the likelihood ratio test on the deviance.
Pitfalls
- Non-nested models. can be negative, and the F law does not hold.
- Heteroscedasticity. The law of the statistic is not justified, even asymptotically, when the error variance depends on the predictors. In the table the size is 0.124 instead of 0.05 at , and 0.0583 at ; a finite table does not show the limit.
- Reading a small F as support for . A non-significant F says that the data cannot tell the models apart, not that the dropped coefficients are 0.
- Testing after selection. Choosing the variables with the data and then testing them with the same data gives p-values that are too small.
- Wrong degrees of freedom. The denominator uses of the full model, with counting the intercept. Software that reports " predictors" means .
- Forming . The normal equations can give a negative with nearly collinear columns; use QR.
- Order in sequential tables. A sequential sum of squares tests a column given only the columns before it; it answers a different question for each order.
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/regression-f-test/. The authors are listed in prov/KE7D2K.jsonl.
"""The F-test for nested linear models, by one Householder QR factorization.
X is an n x p design matrix given as a list of rows. Its first p0 columns span
the null model, and all p columns span the full model. One Householder QR of X,
applied to y as well, gives c = Q^T y. Then RSS_1 = c[p]^2 + ... + c[n-1]^2 and
RSS_0 - RSS_1 = c[p0]^2 + ... + c[p-1]^2 (0-based), with no second fit and no
normal equations. The general linear hypothesis R b = r uses the Wald form,
which gives the same F. The code is in this file and not in
regression_f_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 f_sf, t_sf
RANK_TOL = 1e-10
def householder_qr(X: Sequence[Sequence[float]], y: Sequence[float]):
"""Return (R, c): R is the p x p upper triangular factor of X = Q R and c = Q^T y.
Raises ValueError if a column is, to RANK_TOL relative accuracy, a linear
combination of the columns before it.
"""
n = len(X)
p = len(X[0]) if n else 0
if n == 0 or p == 0 or any(len(row) != p for row in X) or len(y) != n:
raise ValueError("X must be n x p with p >= 1 and y must have n entries")
A = [[float(v) for v in row] for row in X]
c = [float(v) for v in y]
scale = max(math.sqrt(math.fsum(A[i][j] ** 2 for i in range(n))) for j in range(p))
if p > n:
raise ValueError("need n >= p")
for j in range(p): # @line L1
norm = math.sqrt(math.fsum(A[i][j] ** 2 for i in range(j, n)))
if norm <= RANK_TOL * scale:
raise ValueError("X does not have full column rank")
alpha = -norm if A[j][j] >= 0.0 else norm # @line L2
v = [0.0] * n
v[j] = A[j][j] - alpha
for i in range(j + 1, n):
v[i] = A[i][j]
vv = math.fsum(v[i] * v[i] for i in range(j, n))
for k in range(j, p): # @line L3
s = 2.0 * math.fsum(v[i] * A[i][k] for i in range(j, n)) / vv
for i in range(j, n):
A[i][k] -= s * v[i]
s = 2.0 * math.fsum(v[i] * c[i] for i in range(j, n)) / vv # @line L4
for i in range(j, n):
c[i] -= s * v[i]
R = [[A[i][k] if k >= i else 0.0 for k in range(p)] for i in range(p)]
return R, c
def nested_f_test(X: Sequence[Sequence[float]], y: Sequence[float], p0: int):
"""F-test of the null model (first p0 columns of X) against the full model (all p columns).
Returns (F, q, nu, p_value, rss0, rss1) with q = p - p0 and nu = n - p.
"""
n = len(X)
p = len(X[0]) if n else 0
if not 0 <= p0 < p:
raise ValueError("need 0 <= p0 < p, so that q = p - p0 >= 1")
if n <= p:
raise ValueError("need n > p, so that nu = n - p >= 1")
_, c = householder_qr(X, y) # lines L1 to L4
rss1 = math.fsum(v * v for v in c[p:]) # @line L5
extra = math.fsum(v * v for v in c[p0:p]) # @line L6
q, nu = p - p0, n - p # @line L7
if rss1 == 0.0:
if extra == 0.0:
raise ValueError("both sums of squares are 0; F is undefined")
return math.inf, q, nu, 0.0, extra, 0.0
f = (extra / q) / (rss1 / nu) # @line L8
return f, q, nu, f_sf(f, q, nu), rss1 + extra, rss1 # @line L9
def overall_f_test(X: Sequence[Sequence[float]], y: Sequence[float]):
"""The overall F-test: all columns but the first (the intercept) have zero coefficients."""
return nested_f_test(X, y, 1)
def back_substitute(R: Sequence[Sequence[float]], z: Sequence[float]) -> list[float]:
"""Solve R b = z for upper triangular R."""
p = len(R)
b = [0.0] * p
for i in range(p - 1, -1, -1):
b[i] = (z[i] - math.fsum(R[i][k] * b[k] for k in range(i + 1, p))) / R[i][i]
return b
def r_inverse(R: Sequence[Sequence[float]]) -> list[list[float]]:
"""The inverse of an upper triangular R, column by column."""
p = len(R)
cols = [back_substitute(R, [1.0 if i == j else 0.0 for i in range(p)]) for j in range(p)]
return [[cols[j][i] for j in range(p)] for i in range(p)]
def ols_fit(X: Sequence[Sequence[float]], y: Sequence[float]):
"""Return (b, rss, xtx_inv): coefficients, residual sum of squares and (X^T X)^(-1) = R^(-1) R^(-T)."""
p = len(X[0])
R, c = householder_qr(X, y)
b = back_substitute(R, c[:p])
Ri = r_inverse(R)
xtx_inv = [[math.fsum(Ri[i][k] * Ri[j][k] for k in range(p)) for j in range(p)] for i in range(p)]
return b, math.fsum(v * v for v in c[p:]), xtx_inv
def coefficient_t_tests(X: Sequence[Sequence[float]], y: Sequence[float]):
"""For each coefficient: (b_j, standard error, t = b_j / se, two-sided p-value), nu = n - p."""
n, p = len(X), len(X[0])
nu = n - p
if nu < 1:
raise ValueError("need n > p")
b, rss, V = ols_fit(X, y)
s2 = rss / nu
out = []
for j in range(p):
se = math.sqrt(s2 * V[j][j])
t = b[j] / se
out.append((b[j], se, t, min(1.0, 2.0 * t_sf(abs(t), nu))))
return out
def _solve_spd(A: list[list[float]], z: list[float]) -> list[float]:
"""Solve A u = z for a symmetric positive definite A by Cholesky."""
m = len(A)
L = [[0.0] * m for _ in range(m)]
for i in range(m):
for j in range(i + 1):
s = A[i][j] - math.fsum(L[i][k] * L[j][k] for k in range(j))
if i == j:
if s <= RANK_TOL * abs(A[i][i]):
raise ValueError("the restriction matrix does not have full row rank")
L[i][i] = math.sqrt(s)
else:
L[i][j] = s / L[j][j]
w = [0.0] * m
for i in range(m):
w[i] = (z[i] - math.fsum(L[i][k] * w[k] for k in range(i))) / L[i][i]
u = [0.0] * m
for i in range(m - 1, -1, -1):
u[i] = (w[i] - math.fsum(L[k][i] * u[k] for k in range(i + 1, m))) / L[i][i]
return u
def linear_hypothesis_f_test(X: Sequence[Sequence[float]], y: Sequence[float],
Rm: Sequence[Sequence[float]], r: Sequence[float]):
"""Wald form of the F-test of H_0: Rm b = r, with Rm a q x p matrix of full row rank.
F = (Rm b - r)^T [Rm (X^T X)^(-1) Rm^T]^(-1) (Rm b - r) / (q s^2).
Returns (F, q, nu, p_value).
"""
n, p = len(X), len(X[0])
q, nu = len(Rm), n - p
if q < 1 or nu < 1:
raise ValueError("need at least one restriction and n > p")
if any(len(row) != p for row in Rm) or len(r) != q:
raise ValueError("Rm must be q x p and r must have q entries")
b, rss, V = ols_fit(X, y)
d = [math.fsum(Rm[i][j] * b[j] for j in range(p)) - r[i] for i in range(q)]
RV = [[math.fsum(Rm[i][k] * V[k][j] for k in range(p)) for j in range(p)] for i in range(q)]
M = [[math.fsum(RV[i][k] * Rm[j][k] for k in range(p)) for j in range(q)] for i in range(q)]
u = _solve_spd(M, d)
num = math.fsum(di * ui for di, ui in zip(d, u))
s2 = rss / nu
if s2 == 0.0:
raise ValueError("RSS is 0; F is undefined")
f = num / (q * s2)
return f, q, nu, f_sf(f, q, nu)
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)
regression_f_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-f-test/. The authors are listed in prov/KE7D2K.jsonl.
"""Entry point named after the slug. The code lives in regression_f_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from regression_f_core import (
RANK_TOL, back_substitute, coefficient_t_tests, householder_qr, linear_hypothesis_f_test,
nested_f_test, ols_fit, overall_f_test, r_inverse,
)
__all__ = ["RANK_TOL", "back_substitute", "coefficient_t_tests", "householder_qr",
"linear_hypothesis_f_test", "nested_f_test", "ols_fit", "overall_f_test", "r_inverse"]
test_regression_f_test.py 195 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-f-test/. The authors are listed in prov/KE7D2K.jsonl.
import math
import random
from fractions import Fraction
import pytest
from regression_f_test import (
coefficient_t_tests, householder_qr, linear_hypothesis_f_test, nested_f_test, ols_fit,
overall_f_test,
)
from stdist import f_sf
X1 = [1, 2, 3, 4, 5, 6, 7, 8]
X2 = [3, 1, 4, 1, 5, 9, 2, 6]
Y = [3, 5, 6, 6, 9, 13, 10, 14]
DESIGN = [[1, a, b] for a, b in zip(X1, X2)]
def exact_rss(X, y):
"""Residual sum of squares by the normal equations in exact rational arithmetic, or None if singular."""
p = len(X[0])
M = [[Fraction(sum(Fraction(r[i]) * r[j] for r in X)) for j in range(p)]
+ [Fraction(sum(Fraction(r[i]) * v for r, v in zip(X, y)))] for i in range(p)]
for col in range(p):
piv = next((r for r in range(col, p) if M[r][col] != 0), None)
if piv is None:
return None
M[col], M[piv] = M[piv], M[col]
pv = M[col][col]
M[col] = [v / pv for v in M[col]]
for r in range(p):
if r != col and M[r][col] != 0:
f = M[r][col]
M[r] = [a - f * b for a, b in zip(M[r], M[col])]
b = [M[i][p] for i in range(p)]
return sum((Fraction(v) - sum(Fraction(a) * c for a, c in zip(r, b))) ** 2 for r, v in zip(X, y))
def exact_f(X, y, p0):
n, p = len(X), len(X[0])
rss1 = exact_rss(X, y)
if p0 == 0:
rss0 = sum(Fraction(v) ** 2 for v in y)
else:
rss0 = exact_rss([r[:p0] for r in X], y)
return ((rss0 - rss1) / (p - p0)) / (rss1 / (n - p)), rss0, rss1
def close(a, b, rel=1e-9):
return abs(a - b) <= rel * max(1.0, abs(b))
def test_worked_example() -> None:
f, q, nu, pv, rss0, rss1 = overall_f_test(DESIGN, Y)
assert (q, nu) == (2, 5)
assert close(rss1, 3092 / 1143) and close(rss0, 107.5)
assert abs(f - 96.847) < 1e-3 and abs(pv - 1.0045e-4) < 1e-7
f, q, nu, pv, rss0, rss1 = nested_f_test(DESIGN, Y, 2)
assert (q, nu) == (1, 5) and close(rss0, 13.0)
assert abs(f - 19.0281) < 1e-4 and abs(pv - 0.0072757) < 1e-7
fe, _, _ = exact_f(DESIGN, Y, 2)
assert close(f, float(fe), 1e-12)
def test_against_exact_normal_equations() -> None:
rng = random.Random(20261114)
checked = 0
while checked < 500:
p = rng.randint(1, 4)
n = rng.randint(p + 1, p + 5)
X = [[1] + [rng.randint(-5, 5) for _ in range(p - 1)] for _ in range(n)]
if rng.random() < 0.3:
X = [[rng.randint(-5, 5) for _ in range(p)] for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
if exact_rss(X, y) in (None, 0):
continue
p0 = rng.randint(0, p - 1)
fe, rss0e, rss1e = exact_f(X, y, p0)
f, q, nu, pv, rss0, rss1 = nested_f_test(X, y, p0)
assert (q, nu) == (p - p0, n - p)
assert close(rss1, float(rss1e)) and close(rss0, float(rss0e))
assert close(f, float(fe), 1e-8)
assert close(pv, f_sf(float(fe), q, nu), 1e-7)
checked += 1
def test_one_restriction_is_t_squared() -> None:
rng = random.Random(5)
for _ in range(50):
n = rng.randint(5, 12)
X = [[1.0, rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(n)]
y = [rng.gauss(0, 1) for _ in range(n)]
f, _, _, pv, _, _ = nested_f_test(X, y, 2)
_, _, t, tp = coefficient_t_tests(X, y)[2]
assert close(f, t * t, 1e-9) and close(pv, tp, 1e-8)
t = coefficient_t_tests(DESIGN, Y)
assert abs(t[2][2] - 4.3621) < 1e-4 and abs(t[1][2] - 9.5297) < 1e-4
def test_wald_form_equals_nested_form() -> None:
# Dropping the last q columns.
rng = random.Random(11)
for _ in range(40):
n, p = rng.randint(6, 12), rng.randint(2, 5)
X = [[1.0] + [rng.uniform(-2, 2) for _ in range(p - 1)] for _ in range(n)]
y = [rng.gauss(0, 1) for _ in range(n)]
p0 = rng.randint(0, p - 1)
Rm = [[1.0 if j == i else 0.0 for j in range(p)] for i in range(p0, p)]
f1 = nested_f_test(X, y, p0)[0]
f2 = linear_hypothesis_f_test(X, y, Rm, [0.0] * (p - p0))[0]
assert close(f1, f2, 1e-8)
# H_0: b_1 = b_2 is the nested test after the change of basis [1, x1 + x2, x2].
Xr = [[1, a + b, b] for a, b in zip(X1, X2)]
assert close(linear_hypothesis_f_test(DESIGN, Y, [[0, 1, -1]], [0])[0], nested_f_test(Xr, Y, 2)[0])
# H_0: b_1 = 1 is the nested test on y - x1.
y_off = [v - a for v, a in zip(Y, X1)]
Xo = [[1, b, a] for a, b in zip(X1, X2)]
assert close(linear_hypothesis_f_test(DESIGN, Y, [[0, 1, 0]], [1])[0], nested_f_test(Xo, y_off, 2)[0])
def test_overall_f_from_r_squared() -> None:
f, q, nu, _, rss0, rss1 = overall_f_test(DESIGN, Y)
r2 = 1.0 - rss1 / rss0
assert close(f, (r2 / q) / ((1.0 - r2) / nu))
assert abs(r2 - 0.97484) < 1e-5
def test_one_way_anova() -> None:
groups = [[4.2, 5.1, 3.9, 4.8], [5.9, 6.3, 5.5], [4.0, 3.6, 4.4, 3.1, 4.9]]
k, N = len(groups), sum(len(g) for g in groups)
grand = math.fsum(v for g in groups for v in g) / N
means = [math.fsum(g) / len(g) for g in groups]
ssb = math.fsum(len(g) * (m - grand) ** 2 for g, m in zip(groups, means))
ssw = math.fsum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
f_anova = (ssb / (k - 1)) / (ssw / (N - k))
X = [[1.0] + [1.0 if j == gi else 0.0 for j in range(1, k)] for gi, g in enumerate(groups) for _ in g]
y = [v for g in groups for v in g]
f, q, nu, _, _, _ = overall_f_test(X, y)
assert (q, nu) == (k - 1, N - k) and close(f, f_anova)
def test_invariance() -> None:
f0 = nested_f_test(DESIGN, Y, 2)[0]
# y + X0 a leaves F unchanged; so do column scaling and a row permutation.
y2 = [v + 3.0 - 2.0 * a for v, a in zip(Y, X1)]
assert close(nested_f_test(DESIGN, y2, 2)[0], f0)
X3 = [[2.0 * r[0] + r[1], -r[1], 10.0 * r[2]] for r in DESIGN]
assert close(nested_f_test(X3, Y, 2)[0], f0)
order = [3, 0, 7, 5, 1, 6, 2, 4]
assert close(nested_f_test([DESIGN[i] for i in order], [Y[i] for i in order], 2)[0], f0)
def test_qr_factor() -> None:
R, c = householder_qr(DESIGN, Y)
# R^T R = X^T X and |c|^2 = |y|^2.
for i in range(3):
for j in range(3):
rtr = sum(R[k][i] * R[k][j] for k in range(3))
xtx = sum(r[i] * r[j] for r in DESIGN)
assert close(rtr, xtx, 1e-12)
assert close(math.fsum(v * v for v in c), sum(v * v for v in Y), 1e-12)
b, rss, _ = ols_fit(DESIGN, Y)
assert abs(b[1] - 1.2310) < 1e-4 and abs(b[2] - 0.5022) < 1e-4 and close(rss, 3092 / 1143)
def test_edge_cases() -> None:
with pytest.raises(ValueError):
nested_f_test(DESIGN, Y, 3) # q = 0
with pytest.raises(ValueError):
nested_f_test(DESIGN[:3], Y[:3], 1) # n = p
with pytest.raises(ValueError):
nested_f_test([[1, a, 2 * a] for a in X1], Y, 1) # rank deficient
with pytest.raises(ValueError):
linear_hypothesis_f_test(DESIGN, Y, [[0, 1, 0], [0, 2, 0]], [0, 0]) # dependent rows
# An exact fit of the full model: F is infinite or huge, p is 0 or tiny.
y_exact = [1.0 + 2.0 * a - b for a, b in zip(X1, X2)]
f, _, _, pv, _, _ = nested_f_test(DESIGN, y_exact, 1)
assert f > 1e15 and pv < 1e-12
# p0 = 0: the null model is b = 0.
f, q, nu, _, rss0, _ = nested_f_test(DESIGN, Y, 0)
assert q == 3 and close(rss0, float(sum(v * v for v in Y)))
def test_size_by_simulation() -> None:
rng = random.Random(1)
n, reps, alpha = 12, 2000, 0.05
X = [[1.0, rng.uniform(0, 1), rng.uniform(0, 1), rng.uniform(0, 1)] for _ in range(n)]
rejections = 0
for _ in range(reps):
y = [2.0 + 0.5 * r[1] + rng.gauss(0, 1) for r in X] # H_0 true: b_2 = b_3 = 0
rejections += nested_f_test(X, y, 2)[3] <= alpha
assert abs(rejections / reps - alpha) < 0.02
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
History
Fisher developed the analysis of variance in the early 1920s and set it out, with its z test and its use for testing a fitted regression, in Statistical Methods for Research Workers (1925). His statistic was . George W. Snedecor tabulated the variance ratio itself in his 1934 booklet on the analysis of variance and named it F in honor of Fisher. The geometric view of the test as the comparison of two orthogonal projections, and its computation from a QR factorization, came with the numerical linear algebra of the 1960s, after Householder (1958) and Golub (1965) made orthogonal factorizations the standard method for least squares.
References
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 4 (hypothesis testing in the linear model, the F-test of a linear hypothesis from the restricted least squares fit)
- Gene H. Golub and Charles F. Van Loan, Matrix Computations, fourth edition, Johns Hopkins University Press, 2013, Section 5.2 (the Householder QR factorization) and Section 5.3 (the full-rank least squares problem and its residual from Q^T b)
- Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapters VII and VIII (the analysis of variance and its test, including the test of a fitted regression)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 7 (linear hypotheses, the canonical form by an orthogonal transformation and the F-test as the uniformly most powerful invariant test)
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 KE7D2K Edit this page History Report an error Markdown