Algorithmintro
Stepwise regression
Also called forward selection, backward elimination.
Chooses the columns of a regression by adding or dropping one column at a time while a criterion such as AIC improves. It is fast and greedy, and it can miss the best subset.
- Time
- Θ(n m^2 + s m^2) worstΘ(n m^2) best
- Space
- Θ(m^2) extra
- Counts
- flops n m^2 + 2 s m^2 + O(n m + s m) worst
- Where
- m = the number of candidate columns; n = the number of observations; s = the number of steps taken
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- M. A. Efroymson, 1960
Stepwise regression chooses which of candidate columns to keep in a linear regression by local moves. Forward selection starts from the model with only the intercept and adds one column at a time. Backward elimination starts from all columns and drops one at a time. The bidirectional form allows both moves at each step. Each step takes the single move that most improves a criterion, either a penalized likelihood such as the Akaike information criterion or a partial F-test, and the method stops when no single move improves it. With the sweep operator each step costs after one pass over the data. The method is a greedy algorithm: it finds a subset that no single move can improve, which need not be the best subset, and the usual tests and intervals of the chosen model are not valid.
In plain words
Many candidate predictors are available and only some help. Trying every combination is slow when there are many. Stepwise regression grows or shrinks the model one predictor at a time: at each step it looks at every predictor that could come in or go out, takes the one that helps most, and stops when no single change helps. This is quick and easy to explain. But two predictors that are only useful together can both be left out, because neither one looks useful alone. And because the method picked the predictors that looked best in this sample, the chosen model looks better than it is.
The problem
Input. An matrix of candidate columns, a response , a direction (forward, backward or both) and a rule: a criterion , or two levels for partial F-tests.
Model for a subset. For the model is , with the coefficient vector written . The intercept is always in, so the model has columns, and is its least squares residual sum of squares. With normal errors and , the criteria are
where counts the slopes, the intercept and .
Neighborhood. The moves from are for (forward) and for (backward).
Output. A subset that no allowed move improves, its RSS and the path of moves. The best subset of each size is a different problem, solved exactly by leaps and bounds.
The algorithm
All fits come from one matrix : the centered cross-products of the columns of and of , with as the last index. Centering takes care of the intercept. The sweep on index with pivot is
and the reverse sweep is the same with and . It undoes the sweep. When has been swept on the indices of , , and the RSS after the move that toggles column (adds it if , drops it if ) is , for every at once.
STEPWISE(X[1..n, 1..m], y[1..n], direction, c)- 1
A ← centered cross-products of the columns (x_1, ..., x_m, y) ▷ (m + 1) × (m + 1), one pass over the data - 2
S ← ∅ (forward, both) or {1, ..., m} (backward); sweep A on each j ∈ S - 3
loop - 4
best ← c(A[y,y], |S|); j* ← none ▷ A[y,y] = RSS(S) - 5
for each column j whose move is allowed by direction - 6
if j ∉ S and A[j,j] ≈ 0 then skip j ▷ x_j lies in the span of S - 7
r ← A[y,y] - A[j,y]² / A[j,j] ▷ RSS after toggling j - 8
if c(r, |S| ± 1) < best then best ← c(r, |S| ± 1); j* ← j - 9
if j* = none then return (S, A[y,y]) - 10
if j* ∉ S then sweep A on j*; S ← S ∪ {j*} - 11
else reverse sweep A on j*; S ← S \ {j*}
Partial F-tests. Efroymson's original rule replaces lines L4 to L11 by two tests. Let be the value from line L7. For the F-to-enter is on 1 and degrees of freedom. Add the column with the largest if its p-value is below . Then, for , the F-to-remove is on 1 and degrees of freedom. Drop the column with the smallest while its p-value is above . Each F statistic is the square of the t statistic of the column in the larger of the two models, so this is the regression F-test for one coefficient. With the two tests can undo each other and cycle, so the implementation keeps the set of visited subsets and stops at the first repeat.
Example
Take and three candidate columns:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | -3 | 3 | -2 | 2 | -2 | 1 | 1 | -2 | 3 | |
| -1 | -1 | 3 | -4 | 0 | -4 | -1 | 2 | -4 | 3 | |
| -2 | -1 | -3 | 3 | 1 | -2 | -1 | -1 | -3 | -2 | |
| -1 | -3 | -1 | 4 | 3 | 0 | 2 | -2 | 0 | -1 |
The correlation of and is 0.833. The exact RSS values and the criteria of all eight subsets are:
| RSS | AIC | BIC | |
|---|---|---|---|
| 449/10 = 44.900 | 47.397 | 48.002 | |
| 10237/228 = 44.899 | 49.397 | 50.305 | |
| 25148/681 = 36.928 | 47.443 | 48.350 | |
| 2354/103 = 22.854 | 42.644 | 43.552 | |
| 184367/9524 = 19.358 | 42.984 | 44.194 | |
| 7036/321 = 21.919 | 44.226 | 45.437 | |
| 79043/3886 = 20.340 | 43.479 | 44.689 | |
| 1130812/271239 = 4.169 | 29.630 | 31.143 |
Forward with AIC. From (AIC 47.397), line L7 gives the three RSS values of the one-column models, and gives the smallest AIC, 42.644. From the moves to and give 44.226 and 43.479, both worse, so the method stops at . The bidirectional method takes the same path, since dropping again is worse.
Backward with AIC. From (AIC 29.630) each drop gives 42.984 or more, so backward elimination stops at once with all three columns, which is the best subset by a margin of 13 units of AIC.
Partial F-tests with and . At the first step the F-to-enter values on 1 and 8 degrees of freedom are 0.000, 1.727 and 7.717, with p-values 0.990, 0.225 and 0.024, so enters. At the second step, on 1 and 7 degrees of freedom, gives 0.299 () and gives 0.865 (), so nothing enters and the method stops at . In the full model the F-to-remove values on 1 and 6 degrees of freedom are 23.27, 25.55 and 21.86, with p-values between 0.002 and 0.004: all three columns are clearly needed.
The full fit is . The columns and act together: alone, removes nothing and little, but their difference predicts well. A one-move search from never sees the pair. Here backward elimination finds the best subset; with other data it fails in the same way that forward selection fails here (Beale, Kendall and Mann 1967).
Measured selection bias. With , noise columns and a noise response, 2000 data sets from random.Random(20261114) gave a first-step F-to-enter with in 39.1% of the data sets, against the nominal 5%. This is close to , the rate for 10 independent tests: the first step reports the best of 10 tests as if it were one.
Correctness
The proof in this folder shows that after the sweeps on the matrix holds , the coefficients and in its blocks, where is the centered , and that the sweeps on a set give the same result in any order. It then shows that is the RSS after the toggle of for both adds and drops, so line L7 scores every neighbor exactly, and that the partial F statistics are the squared t statistics. With a criterion each move strictly lowers , so no subset is visited twice, the loop ends after at most moves, and the result is a local minimum: no single allowed move lowers . With F-tests the set of visited subsets ends the loop. Nothing more is proved. The result is not in general the best subset, and the example above is a counterexample.
Proof: Stepwise regression by sweeps scores every single move exactly and stops at a local minimum of the criterionfull
The arithmetic is exact. Let and be the columns of and minus their means, and let be the matrix of their inner products, with as the last index. For write for the centered columns in , , and . Centering removes the intercept: for any , the least squares fit of on and has the same slopes and residuals as the fit of on without intercept, because the residual of a fit with an intercept is orthogonal to .
Lemma 1 (block form of a swept matrix). If is nonsingular, sweeping on the indices of , one after the other in any order, meets only nonzero pivots and gives
Proof. By induction on . For the formula is . Suppose it holds for , and sweep on , , with nonsingular. The pivot is , the Schur complement of in , and , so . Write . The block inverse formula (see Schur complement) gives
Compare the sweep of on with the formula for , entry by entry, with and .
- Pivot: , which is minus the corner .
- : , which is minus the entry of the inverse.
- : , minus the top left block.
- : . The target is row of , which is . They agree.
- : . The target is . They agree.
- : with . Expanding the target with the block inverse gives , the same.
The entries in row and columns or follow by symmetry. So the result is the formula for . The formula depends only on the set, so the order of the sweeps does not matter.
Lemma 2 (reading the swept matrix). In : , the least squares slopes of on with intercept; ; for , and , where and are the residuals of and after projection on the span of .
Proof. By Lemma 1, , the solution of the normal equations. With , the orthogonal projection on the span of , the lower right block is for , and is symmetric and idempotent, so this is . For it is .
Lemma 3 (the RSS after one move). Let . For with , . For , as well.
Proof. Adding: the span of is the span of plus the orthogonal direction , so the new residual is , whose squared norm is . Lemma 2 turns this into the formula. Dropping: let , and write and for the residuals on . The adding case gives . By Lemma 1, is swept on , with pivot by Lemma 2, so and . Then , and .
Lemma 4 (reverse sweep). The reverse sweep on applied to gives .
Proof. Let be the sweep of a matrix on , with pivot . The reverse sweep of on has pivot . It sets the pivot to ; it sets to , and the same for ; and for it sets to . So the reverse sweep inverts the sweep. By Lemma 1 the order of sweeps is free, so is swept on , and the reverse sweep on returns .
Lemma 5 (the F statistics). The F-to-enter of and the F-to-remove of , computed from line L7, are the squared t statistics of in the models and , with and residual degrees of freedom.
Proof. For a model with columns including the intercept and a column , the extra sum of squares divided by equals (the one-column case of the regression F-test). For entering, has columns; for removing, has . Lemma 3 gives both residual sums of squares.
Theorem. With a criterion , the algorithm stops after at most moves and returns a subset with for every allowed neighbor whose design is nonsingular. With partial F-tests, it stops after visiting at most subsets.
Proof. By Lemmas 1 to 4, after each move the matrix equals for the current , and line L7 gives for each neighbor exactly. A neighbor with a singular design is skipped by line L6, since then . Line L8 chooses a move only if it strictly lowers , so the values of along the path strictly decrease. Each subset has one value of , so no subset appears twice, and there are subsets. When line L9 returns, no allowed neighbor has a smaller value, which is the claim. With F-tests the implementation records each subset it reaches and stops at the first repeat, so the loop runs at most times.
The theorem does not say that minimizes over all subsets, and that is false in general: on the example of the page, forward selection with AIC stops at while has a smaller AIC.
Complexity
Line L1 costs about flops for the distinct cross-products. Each step scores all moves in and does one sweep in about flops, so steps cost after the pass over the data, and the space is . Forward selection without drops takes at most steps, and backward elimination at most , so they cost . The bidirectional method has only the bound from the strict decrease. Refitting each candidate model by QR instead of sweeping would cost per candidate and for a forward path.
Properties
- Local, not global. The result cannot be improved by one add or one drop. Forward, backward and bidirectional searches can end at different subsets, as in the example.
- Unstable. A small change of the data can change an early choice and so the whole path. The chosen subset varies a lot under resampling.
- Biased estimates. A column enters because its estimated effect was large in this sample, so its is biased away from 0, and the residual variance of the chosen model is biased down.
- Invalid tests. The F and t tests of the chosen model ignore the search. Freedman (1983) screened 50 noise columns at , refitted, and got a significant overall F-test. The nominal levels and are not error rates of anything.
- Exact arithmetic. The sweep uses only field operations, so with rational data the path and the RSS values are exact, as in the table above.
Variants and improvements
- Penalized criteria. AIC, its small-sample form AICc, BIC and Mallows' change only the function of line L8. BIC stops earlier.
- Best subset search. Leaps and bounds uses the same sweeps inside a branch and bound search and finds the best subset of each size exactly, for up to about 30 to 40.
- Forward stagewise and the lasso. Taking many tiny steps toward the most correlated column instead of whole moves leads to least angle regression and the lasso path, which shrink the coefficients and are more stable.
- Selective inference. Valid p-values and intervals after a forward path are given by the truncated normal laws of the polyhedral lemma, since the event that forward selection with a fixed number of steps takes a given path with given signs is a polyhedron in (Tibshirani, Taylor, Lockhart and Tibshirani 2016). See post-selection inference.
- Feature selection in learning. The same greedy search with cross-validated error as the criterion is the wrapper method of feature selection.
When to use it
Use stepwise regression for a quick screen of a moderate number of candidate columns when the purpose is a first look or a prediction checked on new data, and report it as a search, not as a test. For prediction, the lasso or cross-validation of the whole procedure is usually better. For inference about effects, prespecify the model from subject knowledge; if selection is unavoidable, use sample splitting or selective inference. When is at most about 30 to 40 and the best subset is wanted, use leaps and bounds instead.
Pitfalls
- Reporting the chosen model as if it were prespecified. The p-values, intervals and of the final fit are too optimistic, as the measured 39% rate above shows for one step.
- Correlated candidates. A pair or group that works only together can be missed by forward selection, and the order of entry among correlated columns is close to arbitrary. Check the variance inflation factors.
- Collinear columns. A column in the span of the current model has pivot ; dividing by a tiny rounded pivot gives nonsense. The implementation refuses such a column (line L6) with a relative tolerance.
- Small samples. The F-to-enter needs , and with few residual degrees of freedom the criteria favor too many columns; use AICc or stop earlier.
- Categorical predictors. A factor with several dummy columns should enter or leave as a group; moving single dummy columns makes the model depend on the coding.
- Missing values. Programs that drop rows with missing values per model compare criteria on different rows. Fix the rows before the search.
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)
stepwise_regression.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stepwise-regression/. The authors are listed in prov/GX5W9T.jsonl.
"""Stepwise regression (forward selection, backward elimination, both) by the sweep operator.
The model is y = b0 + X_S b_S + e with an intercept that is always in the model
and a subset S of the p candidate columns of X. Each step looks at every
single-variable move (add one column, or drop one column), takes the best one
and stops when no move is good enough. Two stopping rules are given:
- a penalized criterion, AIC (c = 2) or BIC (c = log n): take the move with the
smallest criterion and stop when no move makes it strictly smaller;
- partial F-tests (Efroymson 1960): add the column with the largest F-to-enter
if its p-value is below alpha_enter, drop the column with the smallest
F-to-remove if its p-value is above alpha_remove.
All fits come from one (p + 1) x (p + 1) centered cross-product matrix, kept
swept on the current subset. With the response as the last index y, after a
sweep on S the entry a[y][y] is RSS(S), and for every column j the residual sum
of squares after the move "toggle j" is a[y][y] - a[j][y]^2 / a[j][j].
The arithmetic is generic, so Fraction input gives exact results.
"""
import math
from fractions import Fraction
from typing import NamedTuple
from stdist import f_sf
COLLINEAR_TOL = 1e-10
def _total(values):
values = list(values)
if values and all(isinstance(v, float) for v in values):
return math.fsum(values)
return sum(values, Fraction(0) if values and isinstance(values[0], Fraction) else 0)
def centered_sscp(x, y):
"""The (p + 1) x (p + 1) matrix of centered sums of squares and cross products of [X, y]."""
n = len(y)
if n == 0 or len(x) != n:
raise ValueError("X and y need the same positive number of rows")
cols = [[row[j] for row in x] for j in range(len(x[0]))] + [list(y)]
means = [_total(c) / n for c in cols]
dev = [[v - m for v in c] for c, m in zip(cols, means)]
m = len(cols)
a = [[None] * m for _ in range(m)]
for i in range(m):
for j in range(i, m):
a[i][j] = a[j][i] = _total(u * v for u, v in zip(dev[i], dev[j]))
return a
def sweep(a, k, reverse=False):
"""Sweep (or reverse sweep) the symmetric matrix a on index k, in place (Goodnight 1979)."""
d = a[k][k]
if d == 0:
raise ZeroDivisionError("zero pivot in sweep")
m = len(a)
s = -1 if reverse else 1
col = [a[i][k] for i in range(m)]
for i in range(m):
if i == k:
continue
f = col[i] / d
if f != 0:
row_i = a[i]
for j in range(m):
if j != k:
row_i[j] -= f * col[j]
for i in range(m):
if i != k:
a[i][k] = s * col[i] / d
a[k][i] = s * col[i] / d
a[k][k] = -1 / d
def gaussian_loglik(rss, n):
"""The maximized normal log-likelihood of a regression with residual sum of squares rss."""
return -0.5 * n * (math.log(2 * math.pi * float(rss) / n) + 1)
def aic(loglik, k):
"""Akaike information criterion, -2 log L + 2k, with k estimated parameters."""
return -2.0 * loglik + 2.0 * k
def aicc(loglik, k, n):
"""AIC with the Hurvich-Tsai small-sample correction 2k(k + 1)/(n - k - 1)."""
if n - k - 1 <= 0:
raise ValueError("AICc needs n > k + 1")
return aic(loglik, k) + 2.0 * k * (k + 1) / (n - k - 1)
def bic(loglik, k, n):
"""Schwarz's Bayesian information criterion, -2 log L + k log n."""
return -2.0 * loglik + k * math.log(n)
def criterion_value(rss, n, size, criterion):
"""AIC or BIC of the normal regression with an intercept, `size` columns and the variance: k = size + 2."""
if rss <= 0:
return -math.inf
ll = gaussian_loglik(rss, n)
k = size + 2
if criterion == "aic":
return aic(ll, k)
if criterion == "bic":
return bic(ll, k, n)
raise ValueError("criterion must be 'aic' or 'bic'")
class StepwiseResult(NamedTuple):
subset: tuple # the selected column indices, sorted
rss: object # residual sum of squares of the selected model
path: list # the moves, as ("add" or "drop", column, rss after the move)
cycled: bool # True if the F-test rule came back to a subset it had seen
def stepwise(x, y, direction="both", criterion="aic", alpha_enter=0.05, alpha_remove=0.10, start=None):
"""Stepwise selection. direction is 'forward', 'backward' or 'both'; criterion is 'aic', 'bic' or 'f'."""
if direction not in ("forward", "backward", "both"):
raise ValueError("direction must be 'forward', 'backward' or 'both'")
if criterion not in ("aic", "bic", "f"):
raise ValueError("criterion must be 'aic', 'bic' or 'f'")
n = len(y)
a = centered_sscp(x, y) # @line L1
p = len(a) - 1
yy = p
d0 = [a[j][j] for j in range(p)]
if start is None:
start = range(p) if direction == "backward" else ()
inside = [False] * p
for j in sorted(set(start)):
if a[j][j] <= COLLINEAR_TOL * d0[j]:
raise ValueError("the start subset has collinear columns")
sweep(a, j) # @line L2
inside[j] = True
path = []
seen = {tuple(j for j in range(p) if inside[j])}
def rss_toggle(j):
return a[yy][yy] - a[j][yy] * a[j][yy] / a[j][j] # @line L7
def can_add(j):
return not inside[j] and a[j][j] > COLLINEAR_TOL * d0[j] and n - sum(inside) - 2 > 0 # @line L6
def apply(j):
new_rss = rss_toggle(j)
path.append(("drop" if inside[j] else "add", j, new_rss))
if not inside[j]:
sweep(a, j) # @line L10
else:
sweep(a, j, reverse=True) # @line L11
inside[j] = not inside[j]
cycled = False
while True: # @line L3
size = sum(inside)
if criterion != "f":
cur = criterion_value(a[yy][yy], n, size, criterion) # @line L4
best_j, best_val = None, cur
for j in range(p): # @line L5
if inside[j] and direction in ("backward", "both"):
val = criterion_value(rss_toggle(j), n, size - 1, criterion)
elif can_add(j) and direction in ("forward", "both"):
val = criterion_value(rss_toggle(j), n, size + 1, criterion)
else:
continue
if val < best_val - 1e-12 * max(1.0, abs(best_val)): # @line L8
best_j, best_val = j, val
if best_j is None: # @line L9
break
apply(best_j)
continue
moved = False
if direction in ("forward", "both"):
best_j, best_f = None, -1.0
for j in range(p):
if can_add(j):
new = rss_toggle(j)
df2 = n - size - 2
f = math.inf if new <= 0 else float(a[yy][yy] - new) / (float(new) / df2)
if f > best_f:
best_j, best_f = j, f
if best_j is not None and f_sf(best_f, 1, n - size - 2) < alpha_enter:
apply(best_j)
moved = True
if direction in ("backward", "both"):
while sum(inside) > 0:
size = sum(inside)
rss = a[yy][yy]
worst_j, worst_f = None, math.inf
for j in range(p):
if inside[j]:
f = math.inf if rss <= 0 else float(rss_toggle(j) - rss) / (float(rss) / (n - size - 1))
if f < worst_f:
worst_j, worst_f = j, f
if f_sf(worst_f, 1, n - size - 1) > alpha_remove:
apply(worst_j)
moved = True
continue
break
if not moved:
break
key = tuple(j for j in range(p) if inside[j])
if key in seen:
cycled = True
break
seen.add(key)
subset = tuple(j for j in range(p) if inside[j])
return StepwiseResult(subset, a[yy][yy], path, cycled)
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
test_stepwise_regression.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stepwise-regression/. The authors are listed in prov/GX5W9T.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from stdist import f_sf
from stepwise_regression import (
aic, aicc, bic, centered_sscp, criterion_value, gaussian_loglik, stepwise, sweep,
)
# x1 and x2 are strongly correlated and y follows their difference, so each one alone is weak.
X1 = [1, -3, 3, -2, 2, -2, 1, 1, -2, 3]
X2 = [-1, -1, 3, -4, 0, -4, -1, 2, -4, 3]
X3 = [-2, -1, -3, 3, 1, -2, -1, -1, -3, -2]
Y = [-1, -3, -1, 4, 3, 0, 2, -2, 0, -1]
X = [[a, b, c] for a, b, c in zip(X1, X2, X3)]
def solve_exact(a, b):
"""Gauss-Jordan elimination in exact rational arithmetic."""
k = len(a)
m = [[Fraction(v) for v in row] + [Fraction(b[i])] for i, row in enumerate(a)]
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] = [u - f * v for u, v in zip(m[r], m[c])]
return [m[i][k] / m[i][i] for i in range(k)]
def fit_exact(x, y, s):
"""Least squares with an intercept and the columns s, from the normal equations: (coefficients, RSS)."""
rows = [[Fraction(1)] + [Fraction(r[j]) for j in s] for r in x]
k = len(rows[0])
xtx = [[sum(r[i] * r[j] for r in rows) for j in range(k)] for i in range(k)]
xty = [sum(r[i] * Fraction(v) for r, v in zip(rows, y)) for i in range(k)]
b = solve_exact(xtx, xty)
rss = sum((Fraction(v) - sum(bi * ri for bi, ri in zip(b, r))) ** 2 for r, v in zip(rows, y))
return b, rss
def all_criteria(x, y, crit):
n, p = len(y), len(x[0])
return {s: criterion_value(float(fit_exact(x, y, s)[1]), n, len(s), crit)
for r in range(p + 1) for s in itertools.combinations(range(p), r)}
def test_sweep_entries_and_reverse_sweep_are_exact():
x = [[Fraction(v) for v in r] for r in X]
y = [Fraction(v) for v in Y]
a0 = centered_sscp(x, y)
for r in range(4):
for s in itertools.combinations(range(3), r):
a = [row[:] for row in a0]
for j in s:
sweep(a, j)
b, rss = fit_exact(X, Y, s)
assert a[3][3] == rss
for pos, j in enumerate(s):
assert a[j][3] == b[pos + 1]
for j in range(3):
if j not in s:
toggled = fit_exact(X, Y, tuple(sorted(s + (j,))))[1]
assert a[3][3] - a[j][3] ** 2 / a[j][j] == toggled
for j in reversed(s):
sweep(a, j, reverse=True)
assert a == a0
def test_forward_misses_the_best_subset_and_backward_finds_it():
table = all_criteria(X, Y, "aic")
best = min(table, key=table.get)
assert best == (0, 1, 2)
fwd = stepwise(X, Y, "forward", "aic")
assert fwd.subset == (2,)
assert table[fwd.subset] > table[best] + 10
assert stepwise(X, Y, "backward", "aic").subset == best
assert stepwise(X, Y, "both", "aic").subset == (2,)
assert fit_exact(X, Y, (2,))[1] == Fraction(fwd.rss).limit_denominator(10**6)
def test_result_is_a_local_minimum_and_path_rss_is_exact():
rng = random.Random(20261114)
for _ in range(25):
n, p = 14, 5
x = [[rng.randint(-4, 4) for _ in range(p)] for _ in range(n)]
y = [x[i][0] - x[i][2] + rng.randint(-3, 3) for i in range(n)]
for crit in ("aic", "bic"):
table = all_criteria(x, y, crit)
for direction in ("forward", "backward", "both"):
res = stepwise(x, y, direction, crit)
s = set(res.subset)
here = table[res.subset]
for j in range(p):
t = tuple(sorted(s ^ {j}))
if direction == "forward" and j in s:
continue
if direction == "backward" and j not in s:
continue
assert table[t] >= here - 1e-9
inside = set(range(p)) if direction == "backward" else set()
for move, j, rss in res.path:
inside ^= {j}
assert math.isclose(rss, float(fit_exact(x, y, tuple(sorted(inside)))[1]), rel_tol=1e-9)
def test_orthogonal_columns_make_forward_selection_exact():
# Columns of a 2^3 factorial design are orthogonal and centered, so RSS is additive in the columns.
x = [[a, b, a * b] for a in (-1, 1) for b in (-1, 1) for _ in range(2)]
rng = random.Random(7)
for _ in range(30):
y = [rng.randint(-5, 5) for _ in range(8)]
for crit in ("aic", "bic"):
table = all_criteria(x, y, crit)
got = stepwise(x, y, "forward", crit).subset
assert table[got] <= min(table.values()) + 1e-9
def test_information_criteria_match_their_formulas():
n = len(Y)
for s in [(), (2,), (0, 1, 2)]:
b, rss = fit_exact(X, Y, s)
s2 = rss / n
resid = [Fraction(v) - b[0] - sum(b[i + 1] * Fraction(r[j]) for i, j in enumerate(s)) for r, v in zip(X, Y)]
direct = math.fsum(-0.5 * math.log(2 * math.pi * float(s2)) - float(e * e / (2 * s2)) for e in resid)
ll = gaussian_loglik(float(rss), n)
assert math.isclose(ll, direct, rel_tol=1e-12)
k = len(s) + 2
assert math.isclose(aic(ll, k), -2 * direct + 2 * k, rel_tol=1e-12)
assert math.isclose(bic(ll, k, n), -2 * direct + k * math.log(n), rel_tol=1e-12)
assert math.isclose(aicc(ll, k, n), aic(ll, k) + 2 * k * (k + 1) / (n - k - 1), rel_tol=1e-12)
assert math.isclose(criterion_value(float(rss), n, len(s), "aic"),
n * math.log(float(rss) / n) + n * (math.log(2 * math.pi) + 1) + 2 * k, rel_tol=1e-12)
with pytest.raises(ValueError):
aicc(0.0, 9, 10)
def test_f_rule_uses_partial_f_tests():
n = len(Y)
res = stepwise(X, Y, "forward", "f", alpha_enter=1.0)
assert len(res.path) == 3
first = res.path[0][1]
rss0 = fit_exact(X, Y, ())[1]
best_f = max(float(rss0 - fit_exact(X, Y, (j,))[1]) / (float(fit_exact(X, Y, (j,))[1]) / (n - 2)) for j in range(3))
f_first = float(rss0 - fit_exact(X, Y, (first,))[1]) / (float(fit_exact(X, Y, (first,))[1]) / (n - 2))
assert math.isclose(f_first, best_f)
assert 0.0 < f_sf(f_first, 1, n - 2) < 1.0
strict = stepwise(X, Y, "both", "f", alpha_enter=0.05, alpha_remove=0.10)
assert strict.subset == (2,) and not strict.cycled
back = stepwise(X, Y, "backward", "f", alpha_remove=0.10)
assert back.subset == (0, 1, 2)
def test_bad_arguments():
with pytest.raises(ValueError):
stepwise(X, Y, "sideways")
with pytest.raises(ValueError):
stepwise(X, Y, "both", "cp")
with pytest.raises(ValueError):
centered_sscp([], [])
History
Efroymson (1960) described stepwise regression with F-to-enter and F-to-remove for the computers of the time, and the method spread through the statistical program libraries of the 1960s and 1970s. Beale, Kendall and Mann (1967) and Hocking (1976) showed with examples that stepwise methods can miss the best subset and compared them with all-subsets methods. Goodnight (1979) wrote out the sweep operator that these programs use. Freedman (1983) showed that screening noise columns and refitting produces significant tests, and Miller's book (first edition 1990) made the bias of the estimates after selection a central topic.
References
- M. A. Efroymson, Multiple regression analysis, in A. Ralston and H. S. Wilf (eds.), Mathematical Methods for Digital Computers, Wiley, New York, 1960, pp. 191 to 203, The whole chapter (the stepwise method with F-to-enter and F-to-remove, computed by pivots on the correlation matrix)
- James H. Goodnight, A tutorial on the SWEEP operator, The American Statistician 33(3), 1979, pp. 149 to 158, The whole paper (the sweep operator, its inverse and the regression statistics it leaves in the swept matrix)
- R. R. Hocking, The analysis and selection of variables in linear regression, Biometrics 32(1), 1976, pp. 1 to 49, Sections on stepwise methods and their comparison with all-subsets methods
- E. M. L. Beale, M. G. Kendall and D. W. Mann, The discarding of variables in multivariate analysis, Biometrika 54(3/4), 1967, pp. 357 to 366, The examples in which forward and backward stepwise methods miss the best subset
- David A. Freedman, A note on screening regression equations, The American Statistician 37(2), 1983, pp. 152 to 155, The whole paper (screening pure noise columns and refitting gives a significant overall F-test)
- Ryan J. Tibshirani, Jonathan Taylor, Richard Lockhart and Robert Tibshirani, Exact post-selection inference for sequential regression procedures, Journal of the American Statistical Association 111(514), 2016, pp. 600 to 620, The part on forward stepwise regression (its path and signs after a fixed number of steps as a polyhedral event in y)
- Alan Miller, Subset Selection in Regression, second edition, Chapman and Hall/CRC, 2002, Chapter 3 (forward selection, backward elimination, Efroymson's algorithm and their failures) and Chapter 6 (selection bias in the estimates)
- Frank E. Harrell, Jr., Regression Modeling Strategies, second edition, Springer, 2015, Section 4.3 (the problems of stepwise variable selection)
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 GX5W9T Edit this page History Report an error Markdown