Algorithmcore
Two-way analysis of variance
Also called two-way ANOVA, two-factor ANOVA.
Tests the main effects of two factors and their interaction by F ratios of nested residual sums of squares. Exact F laws under normal errors; unbalanced data need type I, II or III.
- Time
- Θ(n p^2) worst · best
- Space
- Θ(n p) extra
- Where
- n = the total number of observations; p = the number of cells, a times b
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald A. Fisher, Frank Yates, 1925
Two-way analysis of variance tests the effects of two factors on a response, for example a fertilizer (factor A) and a crop variety (factor B), measured in every combination. It tests three null hypotheses: no effect of A, no effect of B, and no interaction, which means that the effect of A is the same at every level of B. Each test is a regression F-test: the drop in the residual sum of squares when the term is added to a smaller model, per degree of freedom, over the residual mean square of the full model. Under normal errors with a common variance each statistic has an exact F law. When every cell has the same number of observations, the sums of squares are orthogonal and the analysis has one answer. When the cells are unbalanced, the sum of squares of a term depends on which other terms are in the smaller model, and there are three standard choices, called type I, II and III. They test different hypotheses, so a report must say which one it used.
In plain words
You grow plants under two treatments at once, say fertilizer and watering, in every combination. You want to know whether fertilizer matters, whether watering matters, and whether the best fertilizer depends on the watering. Two-way ANOVA answers the three questions from one experiment, each by comparing the spread it explains with the noise between plants that got the same treatment pair. If every combination has the same number of plants, the three questions separate cleanly. If some combinations have more plants than others, the factors overlap. The part of the variation that fertilizer "explains" then depends on whether watering was taken into account first, and different programs report different numbers. Say which convention you used.
The problem
Model. Factor A has levels and factor B has levels . Cell holds observations , , with . The model is
with iid errors and the sum-to-zero constraints and . Then is the mean of the cell means, is the deviation of the unweighted row mean of the cell means, the same for columns, and the interaction. The additive model sets every .
Hypotheses. : all (no interaction); : no A effect; : no B effect. With an interaction, "no A effect" needs a definition, and the types define it differently (below).
Statistics. For column sets let be the residual sum of squares of the least squares fit of on the columns of . The columns are the intercept , the effect-coded columns of A (level gets , level gets ), the columns of B, and the products AB. The term's sum of squares is on degrees of freedom, and
| term | type I (A first) | type II | type III |
|---|---|---|---|
| A | |||
| B | |||
| AB | same | same |
Type III with effect coding tests , equal unweighted marginal means of the cell means. Type II tests "no A effect" in the additive model; with an interaction its hypothesis is a weighted one whose weights depend on the cell counts. Type I is sequential and depends on the order of the factors.
Null distribution. Exact: each has the law when the term's hypothesis holds, for every (Lemma 2 of the correctness proof). Under the alternative it is noncentral F.
Rejection rule, size and p-value. Reject when , with size exactly for each test. The p-value is the upper tail . The three tests together are not a family with error rate .
Sensitivity. Each test reacts only to its own term. The interaction test reacts to non-parallel profiles of the cell means. When the interaction is large, the main effects average over effects of different sizes or signs, and the main effect tests can miss real effects or show effects that hold at no single level.
The algorithm
TWO-WAY-ANOVA(y[1..n], A-labels, B-labels, type) ▷ every cell nonempty, n > a·b- 1
build the columns: 1, the effect columns of A and B, their products AB - 2
SSE ← RSS(1, A, B, AB) ▷ RSS by modified Gram-Schmidt, two passes - 3
if type = I: SS_A ← RSS(1) - RSS(1, A); SS_B ← RSS(1, A) - RSS(1, A, B) - 4
if type = II: SS_A ← RSS(1, B) - RSS(1, A, B); SS_B ← RSS(1, A) - RSS(1, A, B) - 5
if type = III: SS_A ← RSS(1, B, AB) - SSE; SS_B ← RSS(1, A, AB) - SSE - 6
SS_AB ← RSS(1, A, B) - SSE - 7
for each term: F ← (SS / d) / (SSE / (n - a·b)); p ← F̄(F; d, n - a·b) - 8
return the table of SS, d, F and p
orthogonalizes the columns of one by one with modified Gram-Schmidt, each twice, and removes the component of along each new unit vector; what is left is the residual. This is the QR decomposition without storing . The normal equations are never formed. An empty cell makes the interaction columns linearly dependent, and the code raises an error. For balanced data the code also has the closed forms of the correctness proof.
Example
Balanced. A 2 x 3 layout with :
| row mean | ||||
|---|---|---|---|---|
| 12, 14 | 18, 16 | 21, 23 | 17.333 | |
| 15, 13 | 24, 22 | 30, 28 | 22 | |
| column mean | 13.5 | 20 | 25.5 | 19.667 |
| source | SS | d | F | p |
|---|---|---|---|---|
| A | 1 | 32.667 | 0.00124 | |
| B | 2 | 72.167 | 0.0000636 | |
| AB | 2 | 5.1667 | 0.04957 | |
| error | 12 | 6 |
The critical values are and , so all three terms are significant at 5%, the interaction just. The cell means 13, 17, 22 in row 1 and 14, 23, 29 in row 2 show why: the A difference grows from 1 to 7 across the levels of B. Types I, II and III give the same table, in either order.
Unbalanced. A 2 x 2 layout with cells , , and , cell means 4, 7, 6 and 11, and on 3 degrees of freedom:
| test of | SS | F | p |
|---|---|---|---|
| A, type I with A first | 29.01 | 0.0125 | |
| A, type II (= type I with B first) | 9.941 | 0.0511 | |
| A, type III | 9.529 | 0.0538 | |
| B, type I with A first (= type II) | 17.50 | 0.0249 | |
| B, type I with B first | 36.57 | 0.0091 | |
| B, type III | 16.94 | 0.0260 | |
| AB, every type | 1.059 | 0.3792 |
The test of A is significant at 5% by type I with A first and not by types II and III. Type I with A first credits A with the variation it shares with B, because the large cell is at the high levels of both factors. The type III value is the squared marginal contrast: , with , and . With treatment (0/1) coding instead of effect coding, the same "type III" comparison gives and . On the balanced data above it gives instead of and instead of . It tests the A difference at the reference level only, where the cell means are 13 and 14, and the B differences at only.
Correctness
Each sum of squares is for nested column spaces, where is an orthogonal projection, and for the full model. The two projections have orthogonal ranges, so under normal errors the two squared lengths are independent chi-square variables, and the F ratio has an exact F law when . With effect coding this condition for type III A is equal unweighted marginal means. In a balanced layout the subspaces of A, B and AB are mutually orthogonal, because every inner product factors into a sum of a zero-sum vector. So each difference is the projection onto the term's own subspace, whatever the order, and all types agree. The proofs and the exact unbalanced computation are in the correctness proof below.
Proof: Two-way ANOVA sums of squares are differences of nested residual sums of squares with exact F laws, orthogonal in balanced layoutsfull
We prove that each sum of squares the code returns is the squared length of a projection, that each F statistic has an exact F law under the hypothesis that this projection of the mean is zero, that the three types coincide in balanced layouts, and that in unbalanced layouts they test different hypotheses. Factor A has levels , factor B has levels , and cell holds observations, . The model is with iid errors. For a set of columns, is their span in , its orthogonal projection, and .
Lemma 1 (nested differences). If , then , and is the orthogonal projection onto , of rank .
Proof. because . So is symmetric and idempotent. By Pythagoras, , since and are orthogonal ().
Lemma 2 (exact F law). Let denote the full model: the intercept, the effect columns of A, the of B and their products, with columns. Every cell holds data, so these columns are linearly independent and is the set of vectors that are constant on each cell. For nested with , the statistic
has the law whenever , where is the vector of cell means .
Proof. , so . because both and project into . Lemma 2 of the one-way ANOVA proof (projections of a normal vector) gives independent and laws after division by .
The code (L3 to L6) computes exactly these differences: type I uses the chain , type II compares with for A and with for B, type III compares with the full model for A, and the interaction compares with the full model. The residual sums of squares come from modified Gram-Schmidt with reorthogonalization: the residual of after subtracting its components along an orthonormal basis of is .
Lemma 3 (what type III tests). With the sum-to-zero (effect) coding, the type III hypothesis for A, , is , where is the unweighted mean of the cell means of row .
Proof. Every vector of cell means can be written uniquely as with , and : take , , and the rest. The effect columns of A, B and AB span exactly the vectors of the forms , and with these constraints, by the coding. So the full model has in it with unique coefficients, and if and only if . Because and , holds if and only if , that is if and only if every is 0.
With treatment (0/1) coding the columns of B and AB span a different subspace, and the same comparison tests the A differences at the last level of B only. The test file shows that the two codings give different "type III" sums of squares on the same data. Type II for A, by contrast, is the same for every coding, because it depends only on the subspaces and ; its hypothesis is "no A effect" in the additive model, and in general it is a weighted hypothesis on the cell means whose weights depend on the .
Lemma 4 (balanced layouts are orthogonal). If for every cell, then is the orthogonal sum , where holds the constant vectors, the vectors with , the vectors with , the vectors with zero row and column sums, and the vectors with zero sum in every cell. So for every term the type I (in either order), type II and type III sums of squares are all equal to the squared length of the projection onto that term's own subspace:
and .
Proof. Inner products: . , and the same way. The constant vector is orthogonal to , and because their entries sum to times a zero sum. Every vector of , , and is constant on cells, and a vector of sums to zero on each cell, so is orthogonal to the other four. The dimensions add up to , so the sum is all of . The span of the effect columns of A is , and similarly for B and AB. Every model in Lemma 2 is a sum of some of , and for orthogonal subspaces . So each difference is the projection onto the one subspace that adds, whatever else is in the model. The closed forms are the projections: the projection onto is at every unit of row , and so on.
Lemma 5 (unbalanced layouts are not orthogonal). In general the types differ. In the 2 x 2 layout with cells , , and :
- type I with A first: , ;
- type I with B first: , ;
- type II: , ;
- type III: , ;
- the interaction: in every type, and on 3 degrees of freedom.
Proof. These are exact rational computations of the residual sums of squares of the nested models by the normal equations, done in the test file with fractions.Fraction; the code's floating point values agree to . For type III, Lemma 3 gives a closed form to compare with. The row marginal contrast is , with variance . The sum of squares of a one degree of freedom hypothesis is , which matches. The A columns and the B columns are not orthogonal after the constant is removed, because the cell counts are not proportional, so the sum of squares of A depends on whether B is in the model.
The order of the type I chain matters, but each chain still adds up: , since both equal .
Termination. Each residual sum of squares orthogonalizes at most columns of length against each other, two passes each, and the code computes at most five of them. So it stops after arithmetic operations. The F tails stop as in the one-way proof.
Theorem. For a two-way layout with every cell nonempty and , the code returns for each term the difference of residual sums of squares of the two nested models named by the chosen type, and each F statistic has the exact law under the normal model when the corresponding projection of the cell means is zero. In balanced layouts the three types coincide and equal the classical closed forms; in unbalanced layouts they test different hypotheses, and type III with effect coding tests equal unweighted marginal means.
Proof. Lemmas 1 to 5.
Complexity
On a real RAM, one RSS orthogonalizes at most columns of length , each against all earlier ones, twice: operations. The code computes at most five RSS values, so the time is and the extra space is for the orthonormal basis. For balanced data the closed forms cost . A sparse or structured solver can do better for many levels, but is small in practice.
Numerical stability. Modified Gram-Schmidt with one reorthogonalization pass keeps the computed basis orthogonal to working precision, so the RSS values have small relative error even when the columns are nearly dependent (few observations in some cells). Solving the normal equations squares the condition number of the column matrix. The closed forms subtract means before squaring, as in one-way ANOVA. Differences of two RSS values can cancel when the term explains little; the result is then small in absolute terms, which is the right answer.
Properties
- Exact. Each F test has size exactly under the normal model with equal variances.
- Balanced means orthogonal. With equal cell counts the sums of squares do not depend on the order or the type. With proportional counts, , the A and B columns are still orthogonal after the mean is removed, so types I and II agree in either order, but type III still differs.
- Additive model. Without the AB term the error has degrees of freedom. With one observation per cell the interaction cannot be separated from the error, and the additive model is the randomized block design analysis.
- Invariance of type II. Types I and II depend only on the column spaces, so any full-rank coding gives the same values. Type III depends on the coding of the interaction; with effect coding it tests equal unweighted marginal means.
- Hierarchy. Type II respects marginality: it never tests a main effect after an interaction that contains it.
Variants and improvements
- More factors. The same nested comparisons give k-way ANOVA. With two-level factors this is the factorial design analysis, where Yates's algorithm computes all effects at once.
- Random and mixed effects. If the levels of B are a sample (subjects, batches), B and AB are random, and the F test of A uses the AB mean square as the denominator in the balanced case. The general tool is the linear mixed model fitted by restricted maximum likelihood.
- Rank methods. The Friedman test handles the additive layout with one observation per cell without normality.
- Multiple comparisons. Tukey's test on the marginal means of a balanced layout, with the error mean square of the full model.
When to use it
Use two-way ANOVA when two crossed factors are applied in every combination and the errors are close to normal with equal variances. Look at the interaction test and the profile plot of the cell means first. If the interaction is clear, interpret the effects of A within each level of B. In unbalanced data, prefer type II when there is no interaction, and type III with effect coding when you want equal-weight marginal means; never use type III with treatment coding.
Pitfalls
- Not saying which type. In the unbalanced example, A has p = 0.0125, 0.0511 or 0.0538 depending on the type.
- Type III with treatment coding. It silently tests a simple effect at the reference level, instead of on the balanced data.
- Main effects in the presence of interaction. A main effect averages over the levels of the other factor and can be zero while every simple effect is large.
- One observation per cell with an interaction term. The full model then has no error degrees of freedom.
- Empty cells. With an empty cell the interaction model is not of full rank, and the type III hypothesis is not defined.
- Treating repeated measures as independent. Use a block or mixed model analysis instead.
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
# 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)
two_way_anova.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-way-anova/. The authors are listed in prov/E9ZZA5.jsonl.
"""Two-way analysis of variance with sequential (type I), type II and type III sums of squares.
Each sum of squares is a difference of residual sums of squares of two nested
least squares fits, RSS(smaller) - RSS(larger). The factors are coded by
sum-to-zero (effect) columns: level j < L of a factor with L levels gets the
indicator of j minus the indicator of level L. With this coding the type III
hypotheses are the equal marginal means of the cell means, as in the
textbooks; with treatment (0/1) coding the "type III" main effect would test
a simple effect at the last level of the other factor instead.
Residual sums of squares come from modified Gram-Schmidt with one
reorthogonalization pass, so no normal equations X^T X are formed.
For balanced data all three types agree with the classical closed forms in
balanced_two_way.
"""
import math
from collections.abc import Hashable, Sequence
from typing import NamedTuple
from stdist import f_sf
class Row(NamedTuple):
source: str
ss: float
df: int
f: float
p: float
def effect_columns(labels: Sequence[Hashable], levels: Sequence[Hashable]) -> list[list[float]]:
"""Sum-to-zero coding: one column per level except the last."""
last = levels[-1]
return [[1.0 if v == lev else (-1.0 if v == last else 0.0) for v in labels]
for lev in levels[:-1]]
def rss(columns: list[list[float]], y: Sequence[float]) -> float:
"""Residual sum of squares of the least squares fit of y on the columns (full column rank)."""
basis: list[list[float]] = []
r = list(y)
for col in columns:
v = list(col)
for _ in range(2): # modified Gram-Schmidt, then one reorthogonalization pass
for q in basis:
c = math.fsum(a * b for a, b in zip(q, v))
v = [a - c * b for a, b in zip(v, q)]
norm = math.sqrt(math.fsum(a * a for a in v))
if norm <= 1e-10 * math.sqrt(math.fsum(a * a for a in col)):
raise ValueError("the columns are linearly dependent (an empty cell?)")
q = [a / norm for a in v]
basis.append(q)
for _ in range(2):
c = math.fsum(a * b for a, b in zip(q, r))
r = [a - c * b for a, b in zip(r, q)]
return math.fsum(a * a for a in r)
def two_way_anova(y: Sequence[float], a: Sequence[Hashable], b: Sequence[Hashable],
ss_type: int = 2, interaction: bool = True) -> list[Row]:
"""ANOVA table rows for A, B, (A:B,) and Error. Every cell must hold data."""
n = len(y)
if not (len(a) == len(b) == n):
raise ValueError("y, a and b must have the same length")
la, lb = sorted(set(a), key=str), sorted(set(b), key=str)
cells = {(u, v) for u, v in zip(a, b)}
if interaction and len(cells) < len(la) * len(lb):
raise ValueError("a cell is empty; the interaction model is not estimable")
one = [[1.0] * n] # @line L1
ca = effect_columns(a, la)
cb = effect_columns(b, lb)
cab = [[x * z for x, z in zip(u, v)] for u in ca for v in cb] if interaction else []
full = one + ca + cb + cab
df_e = n - len(full)
if df_e < 1:
raise ValueError("no degrees of freedom are left for the error")
sse = rss(full, y) # @line L2
if ss_type == 1: # sequential: A, then B given A, then A:B given both
r1, ra, rab = rss(one, y), rss(one + ca, y), rss(one + ca + cb, y)
ss = {"A": r1 - ra, "B": ra - rab} # @line L3
elif ss_type == 2: # each main effect after the other main effect
rab = rss(one + ca + cb, y)
ss = {"A": rss(one + cb, y) - rab, "B": rss(one + ca, y) - rab} # @line L4
elif ss_type == 3: # each term after all others, sum-to-zero coding
ss = {"A": rss(one + cb + cab, y) - sse, "B": rss(one + ca + cab, y) - sse} # @line L5
rab = rss(one + ca + cb, y)
else:
raise ValueError("ss_type must be 1, 2 or 3")
df = {"A": len(ca), "B": len(cb)}
if interaction:
ss["A:B"] = rab - sse # @line L6
df["A:B"] = len(cab)
mse = sse / df_e
rows = []
for name in ss:
f = (ss[name] / df[name]) / mse # @line L7
rows.append(Row(name, ss[name], df[name], f, f_sf(f, df[name], df_e)))
rows.append(Row("Error", sse, df_e, math.nan, math.nan))
return rows # @line L8
def balanced_two_way(cells: Sequence[Sequence[Sequence[float]]]) -> dict[str, float]:
"""Closed-form sums of squares of a balanced a x b layout, cells[i][j] holding n values."""
na, nb, n = len(cells), len(cells[0]), len(cells[0][0])
cm = [[math.fsum(c) / n for c in row] for row in cells]
am = [math.fsum(row) / nb for row in cm]
bm = [math.fsum(cm[i][j] for i in range(na)) / na for j in range(nb)]
g = math.fsum(am) / na
return {
"A": nb * n * math.fsum((m - g) ** 2 for m in am),
"B": na * n * math.fsum((m - g) ** 2 for m in bm),
"A:B": n * math.fsum((cm[i][j] - am[i] - bm[j] + g) ** 2 for i in range(na) for j in range(nb)),
"Error": math.fsum((v - cm[i][j]) ** 2 for i in range(na) for j in range(nb)
for v in cells[i][j]),
}
test_two_way_anova.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-way-anova/. The authors are listed in prov/E9ZZA5.jsonl.
import math
import random
from fractions import Fraction
import pytest
from two_way_anova import balanced_two_way, two_way_anova
UNBALANCED = {("a1", "b1"): [3, 5], ("a1", "b2"): [7], ("a2", "b1"): [6], ("a2", "b2"): [10, 12, 11]}
BALANCED = [[[12, 14], [18, 16], [21, 23]], [[15, 13], [24, 22], [30, 28]]]
def flatten(cells: dict) -> tuple[list, list, list]:
y, a, b = [], [], []
for (u, v), vals in cells.items():
for x in vals:
y.append(x)
a.append(u)
b.append(v)
return y, a, b
def rss_exact(cols: list[list[int]], y: list[int]) -> Fraction:
"""RSS by solving the normal equations X^T X beta = X^T y in exact arithmetic."""
k = len(cols)
m = [[sum(Fraction(p) * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
+ [sum(Fraction(p) * v for p, v in zip(cols[i], y))] for i in range(k)]
for c in range(k):
piv = next(r for r in range(c, k) if m[r][c] != 0)
m[c], m[piv] = m[piv], m[c]
for r in range(k):
if r != c and m[r][c] != 0:
f = m[r][c] / m[c][c]
m[r] = [x - f * z for x, z in zip(m[r], m[c])]
beta = [m[i][k] / m[i][i] for i in range(k)]
return sum((v - sum(beta[i] * cols[i][t] for i in range(k))) ** 2 for t, v in enumerate(y))
def brute_force(y: list[int], a: list, b: list) -> dict[int, dict[str, Fraction]]:
"""Types I, II and III as explicit comparisons of nested models, in exact arithmetic."""
la, lb = sorted(set(a), key=str), sorted(set(b), key=str)
one = [[1] * len(y)]
ca = [[1 if v == l else (-1 if v == la[-1] else 0) for v in a] for l in la[:-1]]
cb = [[1 if v == l else (-1 if v == lb[-1] else 0) for v in b] for l in lb[:-1]]
cab = [[p * q for p, q in zip(u, v)] for u in ca for v in cb]
r = lambda cols: rss_exact(cols, y)
full, add = r(one + ca + cb + cab), r(one + ca + cb)
inter = add - full
return {
1: {"A": r(one) - r(one + ca), "B": r(one + ca) - add, "A:B": inter},
2: {"A": r(one + cb) - add, "B": r(one + ca) - add, "A:B": inter},
3: {"A": r(one + cb + cab) - full, "B": r(one + ca + cab) - full, "A:B": inter},
0: {"Error": full},
}
def table(rows) -> dict[str, float]:
return {row.source: row.ss for row in rows}
def test_unbalanced_example_exact() -> None:
y, a, b = flatten(UNBALANCED)
exact = brute_force(y, a, b)
assert exact[1] == {"A": Fraction(1083, 28), "B": Fraction(1587, 68), "A:B": Fraction(24, 17)}
assert exact[2]["A"] == Fraction(676, 51) and exact[2]["B"] == Fraction(1587, 68)
assert exact[3] == {"A": Fraction(216, 17), "B": Fraction(384, 17), "A:B": Fraction(24, 17)}
assert exact[0]["Error"] == 4
for t in (1, 2, 3):
got = table(two_way_anova(y, a, b, t))
for name, value in exact[t].items():
assert abs(got[name] - float(value)) < 1e-10
assert abs(got["Error"] - 4.0) < 1e-10
def test_type_three_is_the_marginal_mean_contrast() -> None:
# Type III SS of A tests (mu11 + mu12)/2 = (mu21 + mu22)/2: psi_hat^2 / sum(c^2 / n).
y, a, b = flatten(UNBALANCED)
mean = {key: Fraction(sum(v), len(v)) for key, v in UNBALANCED.items()}
size = {key: len(v) for key, v in UNBALANCED.items()}
for factor, sign in (("A", lambda u, v: 1 if u == "a1" else -1),
("B", lambda u, v: 1 if v == "b1" else -1),
("A:B", lambda u, v: 1 if (u == "a1") == (v == "b1") else -1)):
c = {key: Fraction(sign(*key), 1 if factor == "A:B" else 2) for key in mean}
psi = sum(c[key] * mean[key] for key in mean)
ss = psi ** 2 / sum(c[key] ** 2 / size[key] for key in mean)
assert ss == brute_force(y, a, b)[3][factor]
def test_random_unbalanced_layouts() -> None:
rng = random.Random(5)
for _ in range(25):
la, lb = rng.randint(2, 3), rng.randint(2, 3)
y, a, b = [], [], []
for i in range(la):
for j in range(lb):
for _ in range(rng.randint(1, 3)):
y.append(rng.randint(-20, 20))
a.append(f"a{i}")
b.append(f"b{j}")
if len(y) <= la * lb:
y.append(1)
a.append("a0")
b.append("b0")
exact = brute_force(y, a, b)
for t in (1, 2, 3):
got = table(two_way_anova(y, a, b, t))
for name, value in exact[t].items():
assert abs(got[name] - float(value)) <= 1e-9 * max(1.0, float(value))
def test_balanced_types_agree_with_closed_form() -> None:
y, a, b = [], [], []
for i, row in enumerate(BALANCED):
for j, cell in enumerate(row):
for v in cell:
y.append(v)
a.append(f"A{i + 1}")
b.append(f"B{j + 1}")
closed = balanced_two_way(BALANCED)
assert abs(closed["A"] - 196 / 3) < 1e-12 and abs(closed["B"] - 866 / 3) < 1e-12
assert abs(closed["A:B"] - 62 / 3) < 1e-12 and closed["Error"] == 12.0
grand = sum(y) / len(y)
assert abs(sum(closed.values()) - sum((v - grand) ** 2 for v in y)) < 1e-9
for t in (1, 2, 3):
got = table(two_way_anova(y, a, b, t))
for name in closed:
assert abs(got[name] - closed[name]) < 1e-9
rows = {row.source: row for row in two_way_anova(y, a, b)}
assert abs(rows["A:B"].f - 31 / 6) < 1e-12 and rows["A:B"].df == 2
assert abs(rows["A:B"].p - 0.04957118207549574) < 1e-10
def test_sequential_order_matters_when_unbalanced() -> None:
y, a, b = flatten(UNBALANCED)
ab = table(two_way_anova(y, a, b, 1))
ba = table(two_way_anova(y, b, a, 1)) # B entered first
assert abs(ba["A"] - 1024 / 21) < 1e-10 and abs(ab["A"] - 1083 / 28) < 1e-10
assert abs((ab["A"] + ab["B"]) - (ba["A"] + ba["B"])) < 1e-10 # the joint SS does not depend on order
def test_additive_model_size() -> None:
# One observation per cell, no interaction: the F-test of A has size alpha under the null.
rng = random.Random(6)
reps, alpha, rej = 2000, 0.05, 0
a = [f"t{i}" for i in range(4) for _ in range(5)]
b = [f"k{j}" for _ in range(4) for j in range(5)]
for _ in range(reps):
y = [rng.gauss(0.0, 1.0) + 3.0 * j for _ in range(4) for j in range(5)]
rej += two_way_anova(y, a, b, 1, interaction=False)[0].p <= alpha
assert abs(rej / reps - alpha) < 4.0 * math.sqrt(alpha * (1 - alpha) / reps)
def test_errors() -> None:
with pytest.raises(ValueError):
two_way_anova([1.0, 2.0, 3.0], ["a", "a", "b"], ["x", "y", "x"]) # empty cell
with pytest.raises(ValueError):
two_way_anova([1.0, 2.0, 3.0, 4.0], ["a", "a", "b", "b"], ["x", "y", "x", "y"]) # no error df
with pytest.raises(ValueError):
two_way_anova([1.0] * 8, ["a", "b"] * 4, ["x"] * 4 + ["y"] * 4, ss_type=4)
History
Fisher developed the analysis of variance for crossed classifications in the agricultural experiments at Rothamsted in the 1920s, and described it in Statistical Methods for Research Workers (1925) and The Design of Experiments (1935). Yates (1934) treated tables with unequal numbers in the cells. He proposed the method of fitting constants, which corresponds to type II, and the method of weighted squares of means, which corresponds to type III. The names type I to type IV come from the SAS GLM procedure of the 1970s.
References
- Frank Yates, The analysis of multiple classifications with unequal numbers in the different classes, Journal of the American Statistical Association 29(185), 1934, pp. 51 to 66 (fitting constants and the weighted squares of means for unbalanced two-way data)
- Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 5 (introduction to factorial designs, the two-factor factorial design and its analysis of variance)
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 8 (analysis of variance, two-way classifications with equal and unequal numbers per cell; chapter-level locator)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Chapter 11 (analysis of variance and regression; chapter-level locator)
- Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapter VIII (further applications of the analysis of variance)
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 E9ZZA5 Edit this page History Report an error Markdown