Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
Origin
M. A. Efroymson, 1960

Stepwise regression chooses which of mm 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 mm 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 Θ(m2)\Theta(m^2) 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 n×mn \times m matrix XX of candidate columns, a response y∈Rny \in \mathbb R^n, a direction (forward, backward or both) and a rule: a criterion c(RSS,∣S∣)c(\mathrm{RSS}, |S|), or two levels αenter≤αremove\alpha_{\text{enter}} \le \alpha_{\text{remove}} for partial F-tests.

Model for a subset. For S⊆{1,…,m}S \subseteq \{1, \dots, m\} the model is y=b01+XSbS+εy = b_0\mathbf 1 + X_Sb_S + \varepsilon, with the coefficient vector written bb. The intercept is always in, so the model has p=∣S∣+1p = |S| + 1 columns, and RSS(S)\mathrm{RSS}(S) is its least squares residual sum of squares. With normal errors and σ^2=RSS(S)/n\hat\sigma^2 = \mathrm{RSS}(S)/n, the criteria are

AIC(S)=nlog⁡2π RSS(S)n+n+2(∣S∣+2),BIC(S)=nlog⁡2π RSS(S)n+n+(∣S∣+2)log⁡n,\mathrm{AIC}(S) = n\log\frac{2\pi\,\mathrm{RSS}(S)}{n} + n + 2(|S| + 2), \qquad \mathrm{BIC}(S) = n\log\frac{2\pi\,\mathrm{RSS}(S)}{n} + n + (|S| + 2)\log n,

where ∣S∣+2|S| + 2 counts the slopes, the intercept and σ2\sigma^2.

Neighborhood. The moves from SS are S∪{j}S \cup \{j\} for j∉Sj \notin S (forward) and S∖{j}S \setminus \{j\} for j∈Sj \in S (backward).

Output. A subset SS 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 (m+1)×(m+1)(m + 1) \times (m + 1) matrix AA: the centered cross-products of the columns of XX and of yy, with yy as the last index. Centering takes care of the intercept. The sweep on index kk with pivot d=akk≠0d = a_{kk} \ne 0 is

akk←−1d,aik←aikd,akj←akjd,aij←aij−aikakjd(i,j≠k),a_{kk} \leftarrow -\frac1d, \quad a_{ik} \leftarrow \frac{a_{ik}}{d}, \quad a_{kj} \leftarrow \frac{a_{kj}}{d}, \quad a_{ij} \leftarrow a_{ij} - \frac{a_{ik}a_{kj}}{d} \quad (i, j \ne k),

and the reverse sweep is the same with aik←−aik/da_{ik} \leftarrow -a_{ik}/d and akj←−akj/da_{kj} \leftarrow -a_{kj}/d. It undoes the sweep. When AA has been swept on the indices of SS, ayy=RSS(S)a_{yy} = \mathrm{RSS}(S), and the RSS after the move that toggles column jj (adds it if j∉Sj \notin S, drops it if j∈Sj \in S) is ayy−ajy2/ajja_{yy} - a_{jy}^2/a_{jj}, for every jj at once.

  1. STEPWISE(X[1..n, 1..m], y[1..n], direction, c)
  2. 1A ← centered cross-products of the columns (x_1, ..., x_m, y) ▷ (m + 1) × (m + 1), one pass over the data
  3. 2S ← ∅ (forward, both) or {1, ..., m} (backward); sweep A on each j ∈ S
  4. 3loop
  5. 4best ← c(A[y,y], |S|); j* ← none ▷ A[y,y] = RSS(S)
  6. 5for each column j whose move is allowed by direction
  7. 6if j ∉ S and A[j,j] ≈ 0 then skip j ▷ x_j lies in the span of S
  8. 7r ← A[y,y] - A[j,y]² / A[j,j] ▷ RSS after toggling j
  9. 8if c(r, |S| ± 1) < best then best ← c(r, |S| ± 1); j* ← j
  10. 9if j* = none then return (S, A[y,y])
  11. 10if j* ∉ S then sweep A on j*; S ← S ∪ {j*}
  12. 11else reverse sweep A on j*; S ← S \ {j*}

Partial F-tests. Efroymson's original rule replaces lines L4 to L11 by two tests. Let rjr_j be the value from line L7. For j∉Sj \notin S the F-to-enter is Fj=(ayy−rj)/(rj/(n−∣S∣−2))F_j = (a_{yy} - r_j)/(r_j/(n - |S| - 2)) on 1 and n−∣S∣−2n - |S| - 2 degrees of freedom. Add the column with the largest FjF_j if its p-value is below αenter\alpha_{\text{enter}}. Then, for j∈Sj \in S, the F-to-remove is Fj=(rj−ayy)/(ayy/(n−∣S∣−1))F_j = (r_j - a_{yy})/(a_{yy}/(n - |S| - 1)) on 1 and n−∣S∣−1n - |S| - 1 degrees of freedom. Drop the column with the smallest FjF_j while its p-value is above αremove\alpha_{\text{remove}}. 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 αenter>αremove\alpha_{\text{enter}} > \alpha_{\text{remove}} 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 n=10n = 10 and three candidate columns:

ii 1 2 3 4 5 6 7 8 9 10
x1x_1 1 -3 3 -2 2 -2 1 1 -2 3
x2x_2 -1 -1 3 -4 0 -4 -1 2 -4 3
x3x_3 -2 -1 -3 3 1 -2 -1 -1 -3 -2
yy -1 -3 -1 4 3 0 2 -2 0 -1

The correlation of x1x_1 and x2x_2 is 0.833. The exact RSS values and the criteria of all eight subsets are:

SS RSS AIC BIC
∅\emptyset 449/10 = 44.900 47.397 48.002
{1}\{1\} 10237/228 = 44.899 49.397 50.305
{2}\{2\} 25148/681 = 36.928 47.443 48.350
{3}\{3\} 2354/103 = 22.854 42.644 43.552
{1,2}\{1, 2\} 184367/9524 = 19.358 42.984 44.194
{1,3}\{1, 3\} 7036/321 = 21.919 44.226 45.437
{2,3}\{2, 3\} 79043/3886 = 20.340 43.479 44.689
{1,2,3}\{1, 2, 3\} 1130812/271239 = 4.169 29.630 31.143

Forward with AIC. From ∅\emptyset (AIC 47.397), line L7 gives the three RSS values of the one-column models, and x3x_3 gives the smallest AIC, 42.644. From {3}\{3\} the moves to {1,3}\{1, 3\} and {2,3}\{2, 3\} give 44.226 and 43.479, both worse, so the method stops at {3}\{3\}. The bidirectional method takes the same path, since dropping x3x_3 again is worse.

Backward with AIC. From {1,2,3}\{1, 2, 3\} (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 αenter=0.05\alpha_{\text{enter}} = 0.05 and αremove=0.10\alpha_{\text{remove}} = 0.10. 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 x3x_3 enters. At the second step, on 1 and 7 degrees of freedom, x1x_1 gives 0.299 (p=0.602p = 0.602) and x2x_2 gives 0.865 (p=0.383p = 0.383), so nothing enters and the method stops at {3}\{3\}. 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 b^S=(1.076,−0.939,0.730)\hat b_S = (1.076, -0.939, 0.730). The columns x1x_1 and x2x_2 act together: alone, x1x_1 removes nothing and x2x_2 little, but their difference predicts yy well. A one-move search from ∅\emptyset 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 n=50n = 50, m=10m = 10 noise columns and a noise response, 2000 data sets from random.Random(20261114) gave a first-step F-to-enter with p<0.05p < 0.05 in 39.1% of the data sets, against the nominal 5%. This is close to 1−0.9510=0.4011 - 0.95^{10} = 0.401, 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 SS the matrix holds −(X~S⊤X~S)−1-(\tilde X_S^\top\tilde X_S)^{-1}, the coefficients b^S\hat b_S and RSS(S)\mathrm{RSS}(S) in its blocks, where X~S\tilde X_S is the centered XSX_S, and that the sweeps on a set give the same result in any order. It then shows that ayy−ajy2/ajja_{yy} - a_{jy}^2/a_{jj} is the RSS after the toggle of jj 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 cc, so no subset is visited twice, the loop ends after at most 2m2^m moves, and the result is a local minimum: no single allowed move lowers cc. 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 x~1,…,x~m\tilde x_1, \dots, \tilde x_m and y~\tilde y be the columns of XX and yy minus their means, and let a=A(0)a = A^{(0)} be the (m+1)×(m+1)(m + 1) \times (m + 1) matrix of their inner products, with yy as the last index. For S⊆{1,…,m}S \subseteq \{1, \dots, m\} write X~S\tilde X_S for the centered columns in SS, GS=X~S⊤X~SG_S = \tilde X_S^\top\tilde X_S, and T={1,…,m,y}∖ST = \{1, \dots, m, y\} \setminus S. Centering removes the intercept: for any SS, the least squares fit of yy on 1\mathbf 1 and XSX_S has the same slopes and residuals as the fit of y~\tilde y on X~S\tilde X_S without intercept, because the residual of a fit with an intercept is orthogonal to 1\mathbf 1.

Lemma 1 (block form of a swept matrix). If GSG_S is nonsingular, sweeping A(0)A^{(0)} on the indices of SS, one after the other in any order, meets only nonzero pivots and gives

A(S)=(−GS−1GS−1aSTaTSGS−1aTT−aTSGS−1aST).A^{(S)} = \begin{pmatrix} -G_S^{-1} & G_S^{-1}a_{ST} \\ a_{TS}G_S^{-1} & a_{TT} - a_{TS}G_S^{-1}a_{ST} \end{pmatrix}.

Proof. By induction on ∣S∣|S|. For S=∅S = \emptyset the formula is A(0)A^{(0)}. Suppose it holds for SS, and sweep on k∈Tk \in T, k≠yk \ne y, with GS∪{k}G_{S \cup \{k\}} nonsingular. The pivot is d=Akk(S)=akk−akSGS−1aSkd = A^{(S)}_{kk} = a_{kk} - a_{kS}G_S^{-1}a_{Sk}, the Schur complement of GSG_S in GS∪{k}G_{S \cup \{k\}}, and det⁡GS∪{k}=ddet⁡GS\det G_{S \cup \{k\}} = d\det G_S, so d≠0d \ne 0. Write g=GS−1aSkg = G_S^{-1}a_{Sk}. The block inverse formula (see Schur complement) gives

GS∪{k}−1=(GS−1+gg⊤/d−g/d−g⊤/d1/d).G_{S\cup\{k\}}^{-1} = \begin{pmatrix} G_S^{-1} + gg^\top/d & -g/d \\ -g^\top/d & 1/d \end{pmatrix}.

Compare the sweep of A(S)A^{(S)} on kk with the formula for S∪{k}S \cup \{k\}, entry by entry, with i,j∈Si, j \in S and t,u∈T∖{k}t, u \in T \setminus \{k\}.

  • Pivot: −1/d-1/d, which is minus the corner 1/d1/d.
  • (i,k)(i, k): Aik(S)/d=gi/dA^{(S)}_{ik}/d = g_i/d, which is minus the entry −gi/d-g_i/d of the inverse.
  • (i,j)(i, j): −(GS−1)ij−gigj/d-(G_S^{-1})_{ij} - g_ig_j/d, minus the top left block.
  • (k,t)(k, t): Akt(S)/d=(akt−g⊤aSt)/dA^{(S)}_{kt}/d = (a_{kt} - g^\top a_{St})/d. The target is row kk of GS∪k−1aS∪k,tG_{S\cup k}^{-1}a_{S\cup k, t}, which is −g⊤aSt/d+akt/d-g^\top a_{St}/d + a_{kt}/d. They agree.
  • (i,t)(i, t): Ait(S)−Aik(S)Akt(S)/d=(GS−1aSt)i−gi(akt−g⊤aSt)/dA^{(S)}_{it} - A^{(S)}_{ik}A^{(S)}_{kt}/d = (G_S^{-1}a_{St})_i - g_i(a_{kt} - g^\top a_{St})/d. The target is (GS−1aSt)i+gig⊤aSt/d−giakt/d(G_S^{-1}a_{St})_i + g_ig^\top a_{St}/d - g_ia_{kt}/d. They agree.
  • (t,u)(t, u): Atu(S)−Atk(S)Aku(S)/dA^{(S)}_{tu} - A^{(S)}_{tk}A^{(S)}_{ku}/d with Atk(S)=atk−atSgA^{(S)}_{tk} = a_{tk} - a_{tS}g. Expanding the target atu−at,S∪kGS∪k−1aS∪k,ua_{tu} - a_{t,S\cup k}G_{S\cup k}^{-1}a_{S\cup k,u} with the block inverse gives atu−atSGS−1aSu−(atk−atSg)(aku−g⊤aSu)/da_{tu} - a_{tS}G_S^{-1}a_{Su} - (a_{tk} - a_{tS}g)(a_{ku} - g^\top a_{Su})/d, the same.

The entries in row kk and columns ii or tt follow by symmetry. So the result is the formula for S∪{k}S \cup \{k\}. The formula depends only on the set, so the order of the sweeps does not matter. □\square

Lemma 2 (reading the swept matrix). In A(S)A^{(S)}: ASy(S)=b^SA^{(S)}_{Sy} = \hat b_S, the least squares slopes of yy on XSX_S with intercept; Ayy(S)=RSS(S)A^{(S)}_{yy} = \mathrm{RSS}(S); for j∉Sj \notin S, Ajj(S)=∥ej∥2A^{(S)}_{jj} = \|e_j\|^2 and Ajy(S)=ej⊤eyA^{(S)}_{jy} = e_j^\top e_y, where eje_j and eye_y are the residuals of x~j\tilde x_j and y~\tilde y after projection on the span of X~S\tilde X_S.

Proof. By Lemma 1, ASy(S)=GS−1X~S⊤y~A^{(S)}_{Sy} = G_S^{-1}\tilde X_S^\top\tilde y, the solution of the normal equations. With H=X~SGS−1X~S⊤H = \tilde X_SG_S^{-1}\tilde X_S^\top, the orthogonal projection on the span of X~S\tilde X_S, the lower right block is u~⊤(I−H)v~\tilde u^\top(I - H)\tilde v for u,v∈Tu, v \in T, and I−HI - H is symmetric and idempotent, so this is eu⊤eve_u^\top e_v. For u=v=yu = v = y it is RSS(S)\mathrm{RSS}(S). □\square

Lemma 3 (the RSS after one move). Let A=A(S)A = A^{(S)}. For j∉Sj \notin S with Ajj≠0A_{jj} \ne 0, RSS(S∪{j})=Ayy−Ajy2/Ajj\mathrm{RSS}(S \cup \{j\}) = A_{yy} - A_{jy}^2/A_{jj}. For j∈Sj \in S, RSS(S∖{j})=Ayy−Ajy2/Ajj\mathrm{RSS}(S \setminus \{j\}) = A_{yy} - A_{jy}^2/A_{jj} as well.

Proof. Adding: the span of X~S∪{j}\tilde X_{S \cup \{j\}} is the span of X~S\tilde X_S plus the orthogonal direction eje_j, so the new residual is ey−(ej⊤ey/∥ej∥2)eje_y - (e_j^\top e_y/\|e_j\|^2)e_j, whose squared norm is ∥ey∥2−(ej⊤ey)2/∥ej∥2\|e_y\|^2 - (e_j^\top e_y)^2/\|e_j\|^2. Lemma 2 turns this into the formula. Dropping: let S′=S∖{j}S' = S \setminus \{j\}, and write ej′e'_j and ey′e'_y for the residuals on S′S'. The adding case gives RSS(S)=RSS(S′)−(ej′⊤ey′)2/∥ej′∥2\mathrm{RSS}(S) = \mathrm{RSS}(S') - (e_j'^\top e'_y)^2/\|e'_j\|^2. By Lemma 1, A(S)A^{(S)} is A(S′)A^{(S')} swept on jj, with pivot ∥ej′∥2\|e'_j\|^2 by Lemma 2, so Ajj=−1/∥ej′∥2A_{jj} = -1/\|e'_j\|^2 and Ajy=ej′⊤ey′/∥ej′∥2A_{jy} = e_j'^\top e'_y/\|e'_j\|^2. Then −Ajy2/Ajj=(ej′⊤ey′)2/∥ej′∥2-A_{jy}^2/A_{jj} = (e_j'^\top e'_y)^2/\|e'_j\|^2, and Ayy−Ajy2/Ajj=RSS(S′)A_{yy} - A_{jy}^2/A_{jj} = \mathrm{RSS}(S'). □\square

Lemma 4 (reverse sweep). The reverse sweep on k∈Sk \in S applied to A(S)A^{(S)} gives A(S∖{k})A^{(S \setminus \{k\})}.

Proof. Let BB be the sweep of a matrix CC on kk, with pivot d=ckk≠0d = c_{kk} \ne 0. The reverse sweep of BB on kk has pivot e=bkk=−1/de = b_{kk} = -1/d. It sets the pivot to −1/e=d=ckk-1/e = d = c_{kk}; it sets bikb_{ik} to −bik/e=−(cik/d)/(−1/d)=cik-b_{ik}/e = -(c_{ik}/d)/(-1/d) = c_{ik}, and the same for bkjb_{kj}; and for i,j≠ki, j \ne k it sets bijb_{ij} to bij−bikbkj/e=(cij−cikckj/d)+cikckj/d=cijb_{ij} - b_{ik}b_{kj}/e = (c_{ij} - c_{ik}c_{kj}/d) + c_{ik}c_{kj}/d = c_{ij}. So the reverse sweep inverts the sweep. By Lemma 1 the order of sweeps is free, so A(S)A^{(S)} is A(S∖{k})A^{(S \setminus \{k\})} swept on kk, and the reverse sweep on kk returns A(S∖{k})A^{(S \setminus \{k\})}. □\square

Lemma 5 (the F statistics). The F-to-enter of j∉Sj \notin S and the F-to-remove of j∈Sj \in S, computed from line L7, are the squared t statistics of b^j\hat b_j in the models S∪{j}S \cup \{j\} and SS, with n−∣S∣−2n - |S| - 2 and n−∣S∣−1n - |S| - 1 residual degrees of freedom.

Proof. For a model MM with pp columns including the intercept and a column j∈Mj \in M, the extra sum of squares RSS(M∖{j})−RSS(M)\mathrm{RSS}(M \setminus \{j\}) - \mathrm{RSS}(M) divided by RSS(M)/(n−p)\mathrm{RSS}(M)/(n - p) equals tj2t_j^2 (the one-column case of the regression F-test). For entering, M=S∪{j}M = S \cup \{j\} has p=∣S∣+2p = |S| + 2 columns; for removing, M=SM = S has p=∣S∣+1p = |S| + 1. Lemma 3 gives both residual sums of squares. □\square

Theorem. With a criterion cc, the algorithm stops after at most 2m2^m moves and returns a subset SS with c(RSS(S),∣S∣)≤c(RSS(S′),∣S′∣)c(\mathrm{RSS}(S), |S|) \le c(\mathrm{RSS}(S'), |S'|) for every allowed neighbor S′S' whose design is nonsingular. With partial F-tests, it stops after visiting at most 2m2^m subsets.

Proof. By Lemmas 1 to 4, after each move the matrix equals A(S)A^{(S)} for the current SS, and line L7 gives RSS(S′)\mathrm{RSS}(S') for each neighbor S′S' exactly. A neighbor with a singular design is skipped by line L6, since then Ajj=∥ej∥2=0A_{jj} = \|e_j\|^2 = 0. Line L8 chooses a move only if it strictly lowers cc, so the values of cc along the path strictly decrease. Each subset has one value of cc, so no subset appears twice, and there are 2m2^m 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 2m2^m times. □\square

The theorem does not say that SS minimizes cc over all subsets, and that is false in general: on the example of the page, forward selection with AIC stops at {3}\{3\} while {1,2,3}\{1, 2, 3\} has a smaller AIC.

Complexity

Line L1 costs about nm2nm^2 flops for the (m+1)(m+2)/2(m + 1)(m + 2)/2 distinct cross-products. Each step scores all mm moves in O(m)O(m) and does one sweep in about 2m22m^2 flops, so ss steps cost Θ(sm2)\Theta(sm^2) after the pass over the data, and the space is Θ(m2)\Theta(m^2). Forward selection without drops takes at most mm steps, and backward elimination at most mm, so they cost Θ(nm2+m3)\Theta(nm^2 + m^3). The bidirectional method has only the bound s≤2ms \le 2^m from the strict decrease. Refitting each candidate model by QR instead of sweeping would cost Θ(n∣S∣2)\Theta(n|S|^2) per candidate and Θ(nm4)\Theta(nm^4) 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 b^j\hat b_j 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 p<0.25p < 0.25, refitted, and got a significant overall F-test. The nominal levels αenter\alpha_{\text{enter}} and αremove\alpha_{\text{remove}} 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' CpC_p change only the function cc 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 mm 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 yy (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 mm 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 R2R^2 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 ajj=0a_{jj} = 0; 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 n−∣S∣−2>0n - |S| - 2 > 0, 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.

stdist.pyI0RawGitHub
# 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

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

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