Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 qq and n−pn - p 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. y=Xb+εy = Xb + \varepsilon, where XX is a fixed n×pn \times p matrix of rank p<np < n (its pp columns include the intercept column if there is one), b∈Rpb \in \mathbb{R}^p is the coefficient vector, and ε∼N(0,σ2In)\varepsilon \sim N(0, \sigma^2 I_n) with σ\sigma unknown. Order the columns so that the first p0p_0 form the null design X0X_0, 0≤p0<p0 \le p_0 < p, and let q=p−p0q = p - p_0 and ν=n−p\nu = n - p.

Hypotheses. H0H_0: the last qq coefficients are 0, so E[y]∈col⁡(X0)\mathbb{E}[y] \in \operatorname{col}(X_0); H1H_1: they are not all 0. The general linear hypothesis H0:Rb=rH_0: Rb = r, with RR a q×pq \times p matrix of rank qq, reduces to this form by a change of basis (see Variants).

Statistic. With RSS1=min⁡β∥y−Xβ∥2\mathrm{RSS}_1 = \min_\beta \lVert y - X\beta\rVert^2 and RSS0=min⁡γ∥y−X0γ∥2\mathrm{RSS}_0 = \min_\gamma \lVert y - X_0\gamma\rVert^2,

F=(RSS0−RSS1)/qRSS1/(n−p)=(RSS0−RSS1)/qs2,s2=RSS1n−p.F = \frac{(\mathrm{RSS}_0 - \mathrm{RSS}_1)/q}{\mathrm{RSS}_1/(n - p)} = \frac{(\mathrm{RSS}_0 - \mathrm{RSS}_1)/q}{s^2}, \qquad s^2 = \frac{\mathrm{RSS}_1}{n - p}.

Null distribution. Exact: F∼Fq,n−pF \sim F_{q, n-p} under H0H_0, for every b0b_0 and every σ\sigma. Reject at level α\alpha when F≥F(q,n−p,1−α)F \ge F_{(q, n-p, 1-\alpha)}, the upper α\alpha point (lower 1−α1 - \alpha quantile) of Fq,n−pF_{q, n-p}. The test is one-sided in FF: a large FF is evidence against H0H_0, and a small one is not.

Special cases. The overall F-test has X0=1X_0 = \mathbf 1 (intercept only), q=p−1q = p - 1, and then RSS0=TSS\mathrm{RSS}_0 = \mathrm{TSS}, so F=R2/(p−1)(1−R2)/(n−p)F = \frac{R^2/(p - 1)}{(1 - R^2)/(n - p)} with R2R^2 the coefficient of determination. The partial F-test drops one group of predictors. With one dropped column, F=t2F = t^2 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

  1. REGRESSION-F-TEST(X[1..n, 1..p], y[1..n], p₀) ▷ the first p₀ columns span the null model
  2. 1for j ← 1 to p do ▷ Householder QR of X, applied to y
  3. 2a ← X[j..n, j]; α ← −sign(a₁)·‖a‖; v ← a − α·e₁ ▷ ‖a‖ = 0 means rank < p
  4. 3apply I − 2vvᵀ/(vᵀv) to columns j..p of X, rows j..n
  5. 4apply the same reflection to y[j..n] ▷ after the loop y holds c = Qᵀy
  6. 5RSS₁ ← c[p+1]² + ... + c[n]²
  7. 6ΔSS ← c[p₀+1]² + ... + c[p]² ▷ = RSS₀ − RSS₁
  8. 7q ← p − p₀; ν ← n − p
  9. 8F ← (ΔSS / q) / (RSS₁ / ν)
  10. 9return (F, q, ν, Ḡ_{q,ν}(F))

The key fact is that the first kk columns of QQ span the first kk columns of XX for every kk. So one factorization of the full design gives the residual sum of squares of every model made of a leading set of columns: RSS\mathrm{RSS} of the first kk columns is ∑i>kci2\sum_{i > k} c_i^2. Line L6 therefore needs no second fit. The tail is Gˉq,ν(f)=P(Fq,ν>f)=Iν/(ν+qf)(ν/2,q/2)\bar G_{q,\nu}(f) = P(F_{q,\nu} > f) = I_{\nu/(\nu + qf)}(\nu/2, q/2), the regularized incomplete beta function, which the helper evaluates directly, so a p-value of 10−1510^{-15} keeps its digits. If RSS1=0\mathrm{RSS}_1 = 0 and ΔSS>0\Delta\mathrm{SS} > 0 the code returns F=∞F = \infty and p=0p = 0; if both are 0, FF is undefined and the code raises an error, as it does for q=0q = 0, n=pn = p or a rank-deficient XX.

The implementation also has the Wald form for Rb=rRb = r, which uses (X⊤X)−1=RQR−1RQR−⊤(X^\top X)^{-1} = R_{\text{QR}}^{-1}R_{\text{QR}}^{-\top} from the same factorization, and the t statistics of the single coefficients.

Example

Eight observations, two predictors and an intercept, so p=3p = 3 and ν=5\nu = 5:

ii 1 2 3 4 5 6 7 8
x1x_{1} 1 2 3 4 5 6 7 8
x2x_{2} 3 1 4 1 5 9 2 6
yy 3 5 6 6 9 13 10 14

The columns are ordered (1,x1,x2)(\mathbf 1, x_1, x_2). The least squares fit is y^=0.7647+1.2310 x1+0.5022 x2\hat y = 0.7647 + 1.2310\,x_1 + 0.5022\,x_2.

line value
L1 to L4: diagonal of RR −2.8284, 6.4807, −6.3892-2.8284,\ 6.4807,\ -6.3892
L4: c=Q⊤yc = Q^\top y −23.3345, 9.7211, −3.2086, −0.1676, −0.0363, 1.0949, 0.0814, 1.2126-23.3345,\ 9.7211,\ -3.2086,\ -0.1676,\ -0.0363,\ 1.0949,\ 0.0814,\ 1.2126
c12=nyˉ2c_1^2 = n\bar y^2 544.5544.5
c22c_2^2 = drop in RSS from adding x1x_1 to the intercept 94.594.5
c32c_3^2 = drop in RSS from adding x2x_2 10.294810.2948
L5: RSS1=c42+⋯+c82\mathrm{RSS}_1 = c_4^2 + \dots + c_8^2 2.70522.7052
s2=2.7052/5s^2 = 2.7052/5 0.541030.54103

Overall F-test (p0=1p_0 = 1, q=2q = 2): ΔSS=94.5+10.2948=104.7948\Delta\mathrm{SS} = 94.5 + 10.2948 = 104.7948, which equals TSS−RSS1=107.5−2.7052\mathrm{TSS} - \mathrm{RSS}_1 = 107.5 - 2.7052. Then F=(104.7948/2)/0.54103=96.847F = (104.7948/2)/0.54103 = 96.847 with p-value 1.0045×10−41.0045 \times 10^{-4}, far above F(2,5,0.95)=5.7861F_{(2, 5, 0.95)} = 5.7861. Also R2=0.97484R^2 = 0.97484, and R2/2(1−R2)/5\frac{R^2/2}{(1 - R^2)/5} gives the same 96.847.

Partial F-test for x2x_2 (p0=2p_0 = 2, q=1q = 1): F=10.2948/0.54103=19.028F = 10.2948/0.54103 = 19.028, p-value 0.00727570.0072757, above F(1,5,0.95)=6.6079F_{(1, 5, 0.95)} = 6.6079. The t statistic of x2x_2 is b^2/se⁡(b^2)=0.5022/0.11512=4.3621\hat b_2/\operatorname{se}(\hat b_2) = 0.5022/0.11512 = 4.3621, and 4.36212=19.0284.3621^2 = 19.028. The residual sum of squares of the intercept and x1x_1 model, fitted on its own, is 13=10.2948+2.705213 = 10.2948 + 2.7052, as line L6 says.

A hypothesis that is not a deletion. H0:b1=b2H_0: b_1 = b_2 has R=(0,1,−1)R = (0, 1, -1). The Wald form gives F=12.033F = 12.033 with q=1q = 1 and p-value 0.01790.0179, and the nested form on the design (1,x1+x2,x2)(\mathbf 1, x_1 + x_2, x_2) with p0=2p_0 = 2 gives the same number.

Size under the model and outside it. Monte Carlo with r=4000r = 4000 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 (q=2q = 2):

errors nn measured size seed
normal, equal variance 12 0.0450 1
centered exponential, equal variance 12 0.0400 2
t3t_3, equal variance 12 0.0485 3
normal, sd 0.1+3x320.1 + 3x_3^2 12 0.1240 4
normal, sd 0.1+3x320.1 + 3x_3^2 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 n=12n = 12.

Correctness

Householder reflections are orthogonal, so Q⊤Q^\top keeps lengths, and ∥y−Xβ∥2=∥c1..p−Rβ∥2+∑i>pci2\lVert y - X\beta\rVert^2 = \lVert c_{1..p} - R\beta\rVert^2 + \sum_{i > p} c_i^2. The first term can be made 0, so RSS1=∑i>pci2\mathrm{RSS}_1 = \sum_{i>p} c_i^2; the same argument for the first p0p_0 columns, whose factor is the leading block of RR, gives RSS0=∑i>p0ci2\mathrm{RSS}_0 = \sum_{i > p_0} c_i^2. Under normal errors, c=Q⊤yc = Q^\top y is a normal vector with covariance σ2I\sigma^2 I, so its coordinates are independent. Its mean is 0 below row pp, and under H0H_0 also below row p0p_0. So ΔSS/σ2\Delta\mathrm{SS}/\sigma^2 and RSS1/σ2\mathrm{RSS}_1/\sigma^2 are independent chi-square variables with qq and n−pn - p degrees of freedom, and their scaled ratio is Fq,n−pF_{q, n-p} by definition; σ\sigma cancels. The p-value is the upper tail of a continuous law, so it is uniform under H0H_0 and the size is exactly α\alpha. A Lagrange multiplier argument shows that the restricted fit under Rb=rRb = r raises the residual sum of squares by exactly (Rb^−r)⊤[R(X⊤X)−1R⊤]−1(Rb^−r)(R\hat b - r)^\top[R(X^\top X)^{-1}R^\top]^{-1}(R\hat b - r), 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 RSS1\mathrm{RSS}_1 and RSS0−RSS1\mathrm{RSS}_0 - \mathrm{RSS}_1 from one QR factorization, that the statistic has the Fq,n−pF_{q, n-p} law under the null hypothesis with normal errors, that the p-value is uniform under the null, so the size is exactly α\alpha, and that the Wald form for Rb=rRb = r gives the same number. The model is y=Xb+εy = Xb + \varepsilon with XX a fixed n×pn \times p matrix of rank pp, n>pn > p, whose first p0p_0 columns form X0X_0 (0≤p0<p0 \le p_0 < p), and ε∼N(0,σ2In)\varepsilon \sim N(0, \sigma^2 I_n). The null hypothesis is H0H_0: the last q=p−p0q = p - p_0 coefficients are 0, that is, E[y]∈col⁡(X0)\mathbb{E}[y] \in \operatorname{col}(X_0).

Lemma 1 (what the loop computes). After lines L1 to L4, the transformed matrix is Q⊤X=(R0)Q^\top X = \binom{R}{0} with RR upper triangular p×pp \times p and nonsingular, and the transformed yy is c=Q⊤yc = Q^\top y, where Q=P1P2⋯PpQ = P_1 P_2 \cdots P_p is orthogonal. For each k≤pk \le p, the first kk columns of QQ are an orthonormal basis of the span of the first kk columns of XX.

Proof. Step jj applies the Householder reflection Pj=I−2vv⊤/(v⊤v)P_j = I - 2vv^\top/(v^\top v), which is symmetric and orthogonal (Pj2=IP_j^2 = I). The vector vv is 0 in its first j−1j - 1 entries, so PjP_j leaves rows 1,…,j−11, \dots, j - 1 alone, and the choice v=a−αejv = a - \alpha e_j with ∣α∣=∥a∥|\alpha| = \|a\|, where aa is the part of column jj in rows j..nj..n, maps aa to αej\alpha e_j. The sign of α\alpha is opposite to aja_j, so vj=aj−αv_j = a_j - \alpha has no cancellation and v⊤v>0v^\top v > 0 whenever a≠0a \ne 0. By induction, after step jj columns 1..j1..j are 0 below the diagonal, so after pp steps Pp⋯P1X=(R0)P_p \cdots P_1 X = \binom{R}{0}, and Q⊤=Pp⋯P1Q^\top = P_p \cdots P_1. Since XX has rank pp, a≠0a \ne 0 at every step: otherwise column jj of the current matrix would be a combination of the earlier columns, and so would column jj of XX. So ∣Rjj∣=∥a∥>0|R_{jj}| = \|a\| > 0. Write Q=(Q1,Q2)Q = (Q_1, Q_2) with Q1Q_1 the first pp columns. From X=Q1RX = Q_1 R with RR upper triangular, column kk of XX is a combination of the first kk columns of Q1Q_1, and since RR is nonsingular the converse holds too. □\square

The loop runs pp 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 c=Q⊤yc = Q^\top y, RSS1=∑i>pci2\mathrm{RSS}_1 = \sum_{i > p} c_i^2 and RSS0−RSS1=∑p0<i≤pci2\mathrm{RSS}_0 - \mathrm{RSS}_1 = \sum_{p_0 < i \le p} c_i^2, where RSSm=min⁡β∥y−Xmβ∥2\mathrm{RSS}_m = \min_\beta \|y - X_m \beta\|^2 for the null (m=0m = 0) and full (m=1m = 1) models.

Proof. Q⊤Q^\top keeps lengths, so for any β∈Rp\beta \in \mathbb{R}^p, ∥y−Xβ∥2=∥c−(Rβ0)∥2=∥c1..p−Rβ∥2+∑i>pci2\|y - X\beta\|^2 = \|c - \binom{R\beta}{0}\|^2 = \|c_{1..p} - R\beta\|^2 + \sum_{i > p} c_i^2. Since RR is nonsingular, β=R−1c1..p\beta = R^{-1}c_{1..p} makes the first term 0, so the minimum is ∑i>pci2\sum_{i > p} c_i^2. For the null model, X0=Q1R⋅,1..p0X_0 = Q_1 R_{\cdot, 1..p_0}, and the first p0p_0 columns of RR are 0 below row p0p_0. With R00R_{00} the leading p0×p0p_0 \times p_0 block (nonsingular), ∥y−X0γ∥2=∥c1..p0−R00γ∥2+∑i>p0ci2\|y - X_0\gamma\|^2 = \|c_{1..p_0} - R_{00}\gamma\|^2 + \sum_{i > p_0} c_i^2, and the minimum is ∑i>p0ci2\sum_{i > p_0} c_i^2. Subtract. For p0=0p_0 = 0 the null model is E[y]=0\mathbb{E}[y] = 0 and RSS0=∥y∥2=∥c∥2\mathrm{RSS}_0 = \|y\|^2 = \|c\|^2, the same formula. □\square

Lemma 3 (the null law). Under the model, c=Q⊤y∼N(Q⊤Xb,σ2In)c = Q^\top y \sim N(Q^\top X b, \sigma^2 I_n), so c1,…,cnc_1, \dots, c_n are independent with variance σ2\sigma^2. The means are E[ci]=0\mathbb{E}[c_i] = 0 for i>pi > p, and, under H0H_0, also for p0<i≤pp_0 < i \le p. So under H0H_0, U=(RSS0−RSS1)/σ2∼χq2U = (\mathrm{RSS}_0 - \mathrm{RSS}_1)/\sigma^2 \sim \chi^2_q and V=RSS1/σ2∼χn−p2V = \mathrm{RSS}_1/\sigma^2 \sim \chi^2_{n-p}, independent, and

F=(RSS0−RSS1)/qRSS1/(n−p)=U/qV/(n−p)∼Fq,n−p.F = \frac{(\mathrm{RSS}_0 - \mathrm{RSS}_1)/q}{\mathrm{RSS}_1/(n - p)} = \frac{U/q}{V/(n - p)} \sim F_{q, n-p}.

Proof. A linear map of a normal vector is normal, with Cov⁡(Q⊤y)=σ2Q⊤Q=σ2I\operatorname{Cov}(Q^\top y) = \sigma^2 Q^\top Q = \sigma^2 I. For a normal vector, uncorrelated coordinates are independent. E[c]=Q⊤Xb=(Rb0)\mathbb{E}[c] = Q^\top X b = \binom{Rb}{0}, which is 0 below row pp. Under H0H_0, Xb=X0b0Xb = X_0 b_0, and Q⊤X0b0Q^\top X_0 b_0 is 0 below row p0p_0 (the first p0p_0 columns of (R0)\binom{R}{0} are). So ci/σc_i/\sigma for p0<i≤np_0 < i \le n are iid N(0,1)N(0, 1). A sum of kk squared iid standard normals is χk2\chi^2_k, which gives UU and VV; 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 Fq,n−pF_{q, n-p} by definition. σ\sigma cancels, so the law does not depend on σ\sigma or on the null coefficients b0b_0. □\square

Lemma 4 (the p-value and the size). Line L9 returns Gˉ(F)\bar G(F), where GG is the CDF of Fq,n−pF_{q, n-p} and Gˉ=1−G\bar G = 1 - G. Under H0H_0, P(Gˉ(F)≤u)=uP(\bar G(F) \le u) = u for u∈[0,1]u \in [0, 1], so rejecting when the p-value is at most α\alpha has size exactly α\alpha.

Proof. GG is continuous and strictly increasing on (0,∞)(0, \infty), since the F law has a positive density there. Then {Gˉ(F)≤u}={F≥G−1(1−u)}\{\bar G(F) \le u\} = \{F \ge G^{-1}(1 - u)\}, of probability uu. The helper computes Gˉ(f)=Iν/(ν+qf)(ν/2,q/2)\bar G(f) = I_{\nu/(\nu + q f)}(\nu/2, q/2) with ν=n−p\nu = n - p, the standard expression of the F tail through the regularized incomplete beta function: if F=(U/q)/(V/ν)F = (U/q)/(V/\nu) then V/(V+U)=ν/(ν+qF)V/(V + U) = \nu/(\nu + qF) has the Beta(ν/2,q/2)(\nu/2, q/2) law, and F>fF > f exactly when this ratio is below ν/(ν+qf)\nu/(\nu + q f). □\square

Lemma 5 (the Wald form). Let RR be a q×pq \times p matrix of rank qq, r∈Rqr \in \mathbb{R}^q, b^\hat b the least squares estimate and s2=RSS1/(n−p)s^2 = \mathrm{RSS}_1/(n - p). The minimum of ∥y−Xβ∥2\|y - X\beta\|^2 over {β:Rβ=r}\{\beta : R\beta = r\} is RSS1+(Rb^−r)⊤[R(X⊤X)−1R⊤]−1(Rb^−r)\mathrm{RSS}_1 + (R\hat b - r)^\top [R (X^\top X)^{-1} R^\top]^{-1} (R\hat b - r). So the Wald statistic (Rb^−r)⊤[R(X⊤X)−1R⊤]−1(Rb^−r)/(qs2)(R\hat b - r)^\top [R(X^\top X)^{-1}R^\top]^{-1}(R\hat b - r)/(q s^2) equals the nested F statistic of the restricted model, and has the Fq,n−pF_{q, n-p} law under H0:Rb=rH_0: Rb = r.

Proof. ∥y−Xβ∥2=RSS1+(β−b^)⊤X⊤X(β−b^)\|y - X\beta\|^2 = \mathrm{RSS}_1 + (\beta - \hat b)^\top X^\top X (\beta - \hat b), since X⊤(y−Xb^)=0X^\top(y - X\hat b) = 0. Write A=X⊤XA = X^\top X (positive definite) and d=Rb^−rd = R\hat b - r. Minimize (β−b^)⊤A(β−b^)(\beta - \hat b)^\top A(\beta - \hat b) subject to Rβ=rR\beta = r: with a Lagrange multiplier, A(β−b^)=R⊤λA(\beta - \hat b) = R^\top \lambda, so β−b^=A−1R⊤λ\beta - \hat b = A^{-1}R^\top\lambda and R(β−b^)=−dR(\beta - \hat b) = -d gives λ=−(RA−1R⊤)−1d\lambda = -(RA^{-1}R^\top)^{-1}d; the value is λ⊤RA−1R⊤λ=d⊤(RA−1R⊤)−1d\lambda^\top R A^{-1} R^\top \lambda = d^\top (RA^{-1}R^\top)^{-1} d. The matrix RA−1R⊤RA^{-1}R^\top is positive definite because RR 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 p−qp - q, so the restricted model is a nested linear model after a change of variables: pick βr\beta_r with Rβr=rR\beta_r = r, replace yy by y−Xβry - X\beta_r, and choose a basis of the column space of XX whose first p−qp - q vectors span Xker⁡RX\ker R. Lemmas 1 to 4 then apply with p0=p−qp_0 = p - q. □\square

Theorem. For data from the model, the algorithm returns F=((RSS0−RSS1)/q)/(RSS1/(n−p))F = ((\mathrm{RSS}_0 - \mathrm{RSS}_1)/q)/(\mathrm{RSS}_1/(n - p)), which has the Fq,n−pF_{q, n-p} law under H0H_0, and a p-value that is uniform on [0,1][0, 1] under H0H_0. With one restriction (q=1q = 1, the last column), F=t2F = t^2 for the t statistic t=b^p/se⁡(b^p)t = \hat b_p/\operatorname{se}(\hat b_p).

Proof. Lemmas 1 to 4 give the first two claims. For q=1q = 1, take R=ep⊤R = e_p^\top in Lemma 5: F=b^p2/(s2[(X⊤X)−1]pp)=t2F = \hat b_p^2/(s^2 [(X^\top X)^{-1}]_{pp}) = t^2. □\square

What is not proved. Without normality the law of FF is not Fq,n−pF_{q, n-p} in finite samples. If the errors are iid with mean 0 and finite variance and max⁡ihii→0\max_i h_{ii} \to 0, then qF→χq2qF \to \chi^2_q in distribution, so the size tends to α\alpha. This follows from the Lindeberg-Feller central limit theorem applied to the projection of ε\varepsilon on the tested directions, together with s2→σ2s^2 \to \sigma^2 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. ■\blacksquare

Complexity

On a real RAM, step jj of the loop updates the (n−j+1)×(p−j+1)(n - j + 1) \times (p - j + 1) trailing block at about 4 flops per entry, which sums to 2np2−2p3/32np^2 - 2p^3/3 flops; applying the reflections to yy adds O(np)O(np), and lines L5 to L8 cost O(n)O(n). So the time is Θ(np2)\Theta(np^2), the same as one least squares fit, and the extra space is Θ(np)\Theta(np) for the working copy of XX (it can overwrite XX, as LAPACK does). Fitting the two models separately would cost about 2np2+2np022np^2 + 2np_0^2 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 nn.

Numerical stability. The textbook route forms X⊤XX^\top X and solves the normal equations. That squares the condition number of XX, and the subtraction RSS0−RSS1\mathrm{RSS}_0 - \mathrm{RSS}_1 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 α\alpha for every n>pn > p, every σ\sigma and every value of the null coefficients.
  • Invariant. FF does not change when yy is replaced by ay+X0gay + X_0 g (a≠0a \ne 0), when the columns of X0X_0 are replaced by a nonsingular combination of them, when the tested columns are changed by a nonsingular combination plus a combination of X0X_0, or when the rows are permuted.
  • Equal to the likelihood ratio test. For normal errors, the likelihood ratio is (RSS0/RSS1)n/2=(1+qF/(n−p))n/2(\mathrm{RSS}_0/\mathrm{RSS}_1)^{n/2} = (1 + qF/(n-p))^{n/2}, an increasing function of FF, 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 H1H_1, FF has the noncentral F law with noncentrality λ=∥(I−H0)Xb∥2/σ2\lambda = \lVert (I - H_0)Xb\rVert^2/\sigma^2, where H0H_0 is the projection on col⁡(X0)\operatorname{col}(X_0); the power increases with λ\lambda.
  • One restriction is the t-test. With q=1q = 1 the F-test is the two-sided t-test of bp=0b_p = 0, and the p-values coincide.

Variants and improvements

  • General linear hypothesis. H0:Rb=rH_0: Rb = r. The Wald form F=(Rb^−r)⊤[R(X⊤X)−1R⊤]−1(Rb^−r)/(qs2)F = (R\hat b - r)^\top[R(X^\top X)^{-1}R^\top]^{-1}(R\hat b - r)/(qs^2) 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 cp0+12,…,cp2c_{p_0+1}^2, \dots, c_p^2 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 s2(X⊤X)−1s^2(X^\top X)^{-1} in the Wald form by a heteroscedasticity-consistent estimate and compare qFqF with χq2\chi^2_q. 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 nn 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. RSS0−RSS1\mathrm{RSS}_0 - \mathrm{RSS}_1 can be negative, and the F law does not hold.
  • Heteroscedasticity. The FF 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 n=12n = 12, and 0.0583 at n=60n = 60; a finite table does not show the limit.
  • Reading a small F as support for H0H_0. 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 n−pn - p of the full model, with pp counting the intercept. Software that reports "kk predictors" means p=k+1p = k + 1.
  • Forming X⊤XX^\top X. The normal equations can give a negative ΔSS\Delta\mathrm{SS} 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.

regression_f_core.pyI0RawGitHub
# 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 z=12log⁡Fz = \tfrac12 \log F. 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

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
  • a full proof of flops.worst
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