Algorithm Search⌘K

Algorithmadvanced

Leaps and bounds algorithm

Also called Furnival-Wilson algorithm, best subset regression.

An exact branch and bound search for the subsets of each size with the smallest residual sum of squares. It cuts every branch whose bound shows that it cannot win.

Time
Θ(n m^2 + 2^m m^2) worstΘ(n m^2 + m^3) best
Space
Θ(m^3) extra
Counts
flops n m^2 + 2 m^3 + 2 v m^2 worst
Where
m = the number of candidate columns; n = the number of observations; v = the number of search nodes visited, at most 2^(m+1) - 1
Properties
deterministicexactofflinerecursive
Origin
George M. Furnival, Robert W. Wilson Jr., 1974

Best subset regression is the problem of finding, for each size ss, the subset of ss of the mm candidate columns whose least squares fit has the smallest residual sum of squares. The leaps and bounds algorithm of Furnival and Wilson (1974) is one exact algorithm for that problem; others are full enumeration and mixed integer programming. It is a depth-first branch and bound search over the 2m2^m subsets. Its bound is that a subset never has a smaller residual sum of squares than a superset, so the fit of the largest model below a node bounds every model below it. Each node of the search costs one sweep of an (m+1)×(m+1)(m + 1) \times (m + 1) matrix. The answer is exactly the one that fitting all 2m2^m models would give, and in practice the search visits a small fraction of them, which makes it usable for mm up to about 30 to 40.

In plain words

Suppose there are 20 candidate predictors and the goal is the best model with 5 of them. There are 15,504 such models, and the best model of every size needs about a million fits. Leaps and bounds avoids most of them. It walks a tree of choices: at each step one predictor is put in or kept out for good. Before going down a branch it fits the largest model in that branch. Removing predictors can only make a fit worse, so if even that largest model is no better than the best models found so far, nothing in the branch can be, and the branch is skipped. The result is the true best, not a guess, which is what stepwise regression gives.

The problem

Input. An n×mn \times m matrix XX of candidate columns, a response y∈Rny \in \mathbb R^n with n≥m+2n \ge m + 2, and the number k≥1k \ge 1 of best subsets wanted per size. The columns of XX together with the intercept must be linearly independent.

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. RSS(S)\mathrm{RSS}(S) is the least squares residual sum of squares.

Output. For each s=0,1,…,ms = 0, 1, \dots, m, the kk subsets of size ss with the smallest RSS and their RSS values. Ties are broken arbitrarily.

Why sizes. AIC, BIC, Mallows' CpC_p and the adjusted R2R^2 all compare models of the same size by RSS alone: each is an increasing function of RSS for a fixed size. So the best model under any of them is among the m+1m + 1 winners of the sizes, and one search serves every such criterion.

The algorithm

The search uses the sweep operator of the stepwise page on the centered cross-product matrix AA of (x1,…,xm,y)(x_1, \dots, x_m, y), with yy as the last index. When AA is swept on a set SS, its entry A[y,y]A[y,y] is RSS(S)\mathrm{RSS}(S); the reverse sweep removes a column again. A search node is a pair (F,C)(F, C) of disjoint sets: the subsets below it are the TT with F⊆T⊆F∪CF \subseteq T \subseteq F \cup C. The node carries RR, the matrix swept on FF, and BB, the matrix swept on F∪CF \cup C. The cutoff for size ss is the RSS of the kk-th best subset of size ss found so far, or ∞\infty if fewer than kk are known.

  1. LEAPS-AND-BOUNDS(X[1..n, 1..m], y[1..n], k)
  2. 1A ← centered cross-products of (x_1, ..., x_m, y) ▷ (m + 1) × (m + 1)
  3. 2B ← A swept on 1, ..., m ▷ B[y,y] = RSS of the full model; error if collinear
  4. 3record ∅ with RSS A[y,y], and {1, ..., m} with RSS B[y,y]
  5. 4VISIT(∅, {1, ..., m}, A, B)
  6. 5return the k best recorded subsets of each size
  7. VISIT(F, C, R, B) ▷ R swept on F, B swept on F ∪ C
  8. 6if C = ∅ then return
  9. 7if cutoff(s) ≤ B[y,y] for every s with |F| ≤ s ≤ |F| + |C| then return ▷ the cut
  10. 8j ← the column of C with the largest B[j,y]² / (-B[j,j]) ▷ dropping it from F ∪ C costs most
  11. 9R' ← R swept on j; record F ∪ {j} with RSS R'[y,y]
  12. 10VISIT(F ∪ {j}, C \ {j}, R', B)
  13. 11B' ← B reverse swept on j; record (F ∪ C) \ {j} with RSS B'[y,y]
  14. 12VISIT(F, C \ {j}, R, B')

Line L7 is the bound: every TT below the node has RSS(T)≥RSS(F∪C)=B[y,y]\mathrm{RSS}(T) \ge \mathrm{RSS}(F \cup C) = B[y,y], and if that is already no better than the cutoff of every size the node covers, no subset below can enter a list. Line L8 puts the column that matters most into the "in" branch first, so good subsets are found early and the cutoffs fall fast; the "out" branch then has a larger bound and is cut more often. The quantity B[j,y]2/(−B[j,j])B[j,y]^2/(-B[j,j]) is the increase of RSS when jj is dropped from F∪CF \cup C. Furnival and Wilson organize the same nodes as a pair of trees of pivots that share work between them; the binary tree here has the same bound and the same answer.

Example

Take the data of the stepwise page (n=10n = 10, x1x_1, x2x_2, x3x_3 and yy) and add a fourth column x4=(−2,−1,−3,2,0,0,−2,−3,−3,−3)x_4 = (-2, -1, -3, 2, 0, 0, -2, -3, -3, -3), with k=1k = 1. The trace of the search, in depth-first order, with RSS(F) and the bound RSS(F ∪ C):

node FF; CC RSS(FF) bound action
∅\emptyset; {1,2,3,4}\{1,2,3,4\} 44.900 4.147 branch on x1x_1
{1}\{1\}; {2,3,4}\{2,3,4\} 44.899 4.147 branch on x2x_2
{1,2}\{1,2\}; {3,4}\{3,4\} 19.358 4.147 branch on x3x_3
{1,2,3}\{1,2,3\}; {4}\{4\} 4.169 4.147 two leaves
{1,2}\{1,2\}; {4}\{4\} 19.358 8.829 two leaves
{1}\{1\}; {3,4}\{3,4\} 44.899 18.785 branch on x4x_4, four leaves below
∅\emptyset; {2,3,4}\{2,3,4\} 44.900 20.283 branch on x3x_3
{3}\{3\}; {2,4}\{2,4\} 22.854 20.283 branch on x2x_2
{2,3}\{2,3\}; {4}\{4\} 20.340 20.283 cut: cutoffs 19.358 (size 2) and 4.169 (size 3) are below 20.283
{3}\{3\}; {4}\{4\} 22.854 22.040 two leaves
∅\emptyset; {2,4}\{2,4\} 44.900 25.734 branch on x4x_4
{4}\{4\}; {2}\{2\} 25.796 25.734 cut: cutoffs 22.854 (size 1) and 19.358 (size 2) are below 25.734
∅\emptyset; {2}\{2\} 44.900 36.928 two leaves

The best subsets are ∅\emptyset (44.900), {3}\{3\} (22.854), {1,2}\{1, 2\} (19.358), {1,2,3}\{1, 2, 3\} (4.169) and {1,2,3,4}\{1, 2, 3, 4\} (4.147). The search visits 27 of the 31 nodes of the full tree. With four columns the two cuts save only leaves, because both subsets at a cut node were already recorded when the node was made. The saving grows quickly with mm.

Measured node counts. For random data with n=4mn = 4m, normal columns with all correlations 0.5, slopes 1 on the first third of the columns, 0.3 up to half of them and 0 on the rest, normal noise with standard deviation 2, k=1k = 1 and random.Random(20261114):

mm 10 15 20 25
nodes visited 173 751 2707 26207
fraction of 2m2^m 0.169 0.023 0.0026 0.00078
time of the Python code under 0.01 s 0.02 s 0.14 s 1.93 s

The counts depend on the data: when many subsets of a size have nearly equal RSS, few nodes are cut. The worst case is the full tree.

Correctness

The proof in this folder first shows the bound: if T⊆UT \subseteq U then RSS(T)≥RSS(U)\mathrm{RSS}(T) \ge \mathrm{RSS}(U), because the column space of the larger model contains that of the smaller, and least squares over a larger space cannot fit worse. It then uses the sweep identities of the stepwise proof to show that RR and BB stay swept on FF and F∪CF \cup C, so every recorded RSS is exact. Every node has had both FF and F∪CF \cup C recorded when it is visited, and branching splits the subsets below a node into those with jj and those without. So each subset is either recorded or lies below a cut node, and at a cut its RSS is at least the bound, which is at least the cutoff then, which is at least the final cutoff, because cutoffs only fall. Hence no unrecorded subset is strictly better than the kk-th recorded one of its size, and the lists are exact.

Proof: Leaps and bounds returns exactly the best subsets of each size, because a subset never fits better than a supersetfull

The arithmetic is exact. The intercept is in every model, the columns of XX together with 1\mathbf 1 are linearly independent, and RSS(S)\mathrm{RSS}(S) is the least squares residual sum of squares of yy on 1\mathbf 1 and XSX_S. "Swept on SS" means the centered cross-product matrix AA after the sweeps on the indices of SS. The facts about sweeps used below are proved as Lemmas 1 to 4 of the proof on the stepwise regression page: the swept matrix depends only on the set; a sweep on SS has A[y,y]=RSS(S)A[y,y] = \mathrm{RSS}(S); the pivots are nonzero when the columns are independent; and the reverse sweep on kk turns the matrix swept on SS into the matrix swept on S∖{k}S \setminus \{k\}.

Lemma 1 (the bound). If T⊆UT \subseteq U then RSS(T)≥RSS(U)\mathrm{RSS}(T) \ge \mathrm{RSS}(U).

Proof. Let LTL_T and LUL_U be the column spaces of (1,XT)(\mathbf 1, X_T) and (1,XU)(\mathbf 1, X_U). Every column of the first matrix is a column of the second, so LT⊆LUL_T \subseteq L_U. RSS(S)=min⁡v∈LS∥y−v∥2\mathrm{RSS}(S) = \min_{v \in L_S}\|y - v\|^2, and a minimum over a larger set is not larger. □\square

Lemma 2 (the node invariant). Whenever VISIT(F,C,R,B)\mathrm{VISIT}(F, C, R, B) is called, F∩C=∅F \cap C = \emptyset, RR is swept on FF, BB is swept on F∪CF \cup C, and both FF and F∪CF \cup C have been recorded with their exact RSS.

Proof. By induction on the calls. The call of line L4 has F=∅F = \emptyset, C={1,…,m}C = \{1, \dots, m\}, R=AR = A and BB swept on all columns by line L2, and line L3 recorded both sets. Suppose the invariant holds at a call that reaches line L8 and picks j∈Cj \in C. Line L9 sweeps RR on j∉Fj \notin F, so R′R' is swept on F∪{j}F \cup \{j\}, and records F∪{j}F \cup \{j\} with R′[y,y]=RSS(F∪{j})R'[y,y] = \mathrm{RSS}(F \cup \{j\}). The call of line L10 has the sets F∪{j}F \cup \{j\} and C∖{j}C \setminus \{j\}, whose union is F∪CF \cup C, recorded before; so the invariant holds there. Line L11 reverse sweeps BB on j∈F∪Cj \in F \cup C, so B′B' is swept on (F∪C)∖{j}(F \cup C) \setminus \{j\}, and records that set with its exact RSS. The call of line L12 has the sets FF, recorded before, and C∖{j}C \setminus \{j\}, with union (F∪C)∖{j}(F \cup C) \setminus \{j\}, just recorded. RR is unchanged and still swept on FF. Every pivot is nonzero because every set involved is a subset of {1,…,m}\{1, \dots, m\}, whose columns are independent with 1\mathbf 1. □\square

Lemma 3 (termination). The search makes at most 2m+1−12^{m+1} - 1 calls of VISIT.

Proof. Each call that branches makes two calls with ∣C∣|C| smaller by 1, and a call with C=∅C = \emptyset makes none. So the calls form a binary tree of depth at most mm, with at most 2m+1−12^{m+1} - 1 nodes. □\square

Lemma 4 (every subset is recorded or cut). For every T⊆{1,…,m}T \subseteq \{1, \dots, m\}, either TT is recorded, or some call VISIT(F,C,R,B)\mathrm{VISIT}(F, C, R, B) with F⊆T⊆F∪CF \subseteq T \subseteq F \cup C returned at line L7.

Proof. The root call has ∅⊆T⊆{1,…,m}\emptyset \subseteq T \subseteq \{1, \dots, m\}. Take a call with F⊆T⊆F∪CF \subseteq T \subseteq F \cup C. If T=FT = F or T=F∪CT = F \cup C, it is recorded by Lemma 2. Otherwise C≠∅C \ne \emptyset, so line L6 does not return. If line L7 returns, the second case holds. Otherwise the call branches on some j∈Cj \in C: if j∈Tj \in T, then F∪{j}⊆T⊆F∪CF \cup \{j\} \subseteq T \subseteq F \cup C for the call of line L10, and if j∉Tj \notin T, then F⊆T⊆(F∪C)∖{j}F \subseteq T \subseteq (F \cup C) \setminus \{j\} for the call of line L12. By Lemma 3 this descent ends, and it can end only in one of the two cases. □\square

Theorem. For each size ss, let Ls\mathcal L_s be the final list of size ss and csc_s the RSS of its kk-th entry (∞\infty if it has fewer than kk entries). Then Ls\mathcal L_s holds min⁡(k,(ms))\min(k, \binom ms) distinct subsets of size ss with their exact RSS, and every subset TT of size ss that is not in Ls\mathcal L_s has RSS(T)≥cs\mathrm{RSS}(T) \ge c_s. So Ls\mathcal L_s is a list of kk best subsets of size ss.

Proof. The record operation keeps, for each size, the kk smallest RSS values among the distinct subsets offered to it, with ties kept in the order of arrival. So the cutoff of each size never increases over time, and a recorded subset that is not in the final list was pushed out by kk subsets with RSS at most its own. Now take TT of size ss not in Ls\mathcal L_s. If TT was recorded, it was pushed out or not taken, so RSS(T)≥cs\mathrm{RSS}(T) \ge c_s. Otherwise, by Lemma 4, a call with F⊆T⊆F∪CF \subseteq T \subseteq F \cup C returned at line L7 at some time τ\tau. Then ∣F∣≤s≤∣F∣+∣C∣|F| \le s \le |F| + |C|, so the test of line L7 included ss, and with cs(τ)c_s(\tau) the cutoff of size ss at time τ\tau,

RSS(T)≥RSS(F∪C)=B[y,y]≥cs(τ)≥cs,\mathrm{RSS}(T) \ge \mathrm{RSS}(F \cup C) = B[y,y] \ge c_s(\tau) \ge c_s,

by Lemma 1, Lemma 2, the test of line L7 and the fact that cutoffs do not increase. In both cases RSS(T)≥cs\mathrm{RSS}(T) \ge c_s. If (ms)≥k\binom ms \ge k, a cutoff cs(τ)c_s(\tau) is finite only after kk subsets of size ss were recorded, and no cut can happen for size ss while cs=∞c_s = \infty; so if fewer than kk subsets of size ss were ever recorded, no subset of size ss was cut, all were recorded by Lemma 4, and the list holds (ms)\binom ms of them. □\square

Corollary (criteria). Let g(r,s)g(r, s) be increasing in rr for each ss, as AIC, BIC, Mallows' CpC_p and minus the adjusted R2R^2 are as functions of (RSS,∣S∣)(\mathrm{RSS}, |S|). With k=1k = 1, the subset that minimizes g(RSS(S),∣S∣)g(\mathrm{RSS}(S), |S|) over all SS can be taken among the m+1m + 1 size winners. Proof. For any SS of size ss with winner WsW_s, RSS(Ws)≤RSS(S)\mathrm{RSS}(W_s) \le \mathrm{RSS}(S) by the theorem, so g(RSS(Ws),s)≤g(RSS(S),s)g(\mathrm{RSS}(W_s), s) \le g(\mathrm{RSS}(S), s). □\square

Complexity

The cross-products cost about nm2nm^2 flops and the sweeps of line L2 about 2m32m^3. Each visited node other than the root costs one sweep and one copy of an (m+1)×(m+1)(m + 1) \times (m + 1) matrix, Θ(m2)\Theta(m^2), plus O(m)O(m) for lines L7 and L8. So the time is Θ(nm2+vm2)\Theta(nm^2 + vm^2) with vv visited nodes. In the worst case nothing is cut and v=2m+1−1v = 2^{m+1} - 1. At least one node is needed per size, so v≥mv \ge m in every case. The recursion holds two matrices per level and the depth is at most mm, so the extra space is Θ(m3)\Theta(m^3). No algorithm is known to be polynomial in the worst case: best subset regression of a given size is NP-hard (Welch 1982; Natarajan 1995), cited here and not proved, so an exact method must expect exponential time on some inputs.

Properties

  • Exact. The output equals that of full enumeration, up to ties. This is the difference from stepwise regression.
  • Exact arithmetic is possible. Only field operations are used, so with rational input the search and its RSS values are exact. With floating point the cut compares numbers with rounding error, so a subset whose RSS is within rounding of the cutoff can be lost; such a subset is a near tie.
  • One search, many criteria. Every criterion that is increasing in RSS for each size is minimized by one of the size winners.
  • Wider lists. With k>1k > 1 the search returns the kk best of each size, which shows how many subsets are nearly as good as the winner; there are often many.

Variants and improvements

  • Furnival and Wilson's two trees. The original arranges the pivots so that the subsets are produced in an order that reuses work, and reports the best subsets by RSS, by adjusted R2R^2 or by CpC_p.
  • Bound on the criterion. If only the best single model under a criterion cc is wanted, cut when c(B[y,y],s)≥c(B[y,y], s) \ge the best value found for every ss the node covers. This cuts more than the per-size rule.
  • Mixed integer programming. Bertsimas, King and Mazumder (2016) write best subset of size ss as a mixed integer quadratic program with big-M constraints and solve it with a modern solver, warm started by a first-order heuristic. This reaches much larger mm than leaps and bounds, often with a proof of optimality.
  • Convex relaxations. The lasso replaces the count of columns by the sum of absolute coefficients and is solved in polynomial time. It selects a different, shrunken model; Hastie, Tibshirani and Tibshirani (2020) found best subset better at high signal to noise ratio and the lasso better at low.

When to use it

Use leaps and bounds when mm is at most about 30 to 40, the model is linear least squares, and the best subsets of each size are wanted, for example to see how the fit changes with size or how many subsets are nearly equally good. For larger mm use mixed integer programming or a penalized method. Remember that the best subset of a sample is a selected model: its RSS is optimistic, and its tests are not valid without a correction for the search (see post-selection inference). Choose the size by a criterion such as BIC or by cross-validation of the whole search.

Pitfalls

  • Over-reading the winner. With many candidates, many subsets fit nearly as well as the best, and the winner changes with small changes of the data. Look at the kk best, not only the first.
  • Collinear columns. The full model of line L2 must be of full rank. Remove exact duplicates first; nearly collinear columns make the sweeps inaccurate in floating point.
  • Generalized linear models. The bound uses the exact RSS of least squares. For logistic or Poisson models the deviance of a subset is not obtained by a sweep; the usual workaround runs the search on the weighted least squares problem of the last IRLS step, which is an approximation.
  • Grouped columns. The dummy columns of one factor should enter together; the plain search treats them as separate columns.

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.

leaps_and_bounds.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/leaps-and-bounds/. The authors are listed in prov/EKM5SR.jsonl.
"""Leaps and bounds: the best subsets of each size for least squares, by branch and bound.

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 columns of X. For each size s = 0, ..., p the
search returns the nbest subsets of size s with the smallest residual sum of
squares RSS(S), the same answer as the check of all 2^p subsets.

The search tree is binary. A node is a pair (F, C): every subset T with
F <= T <= F | C is below it. The node keeps two swept copies of the centered
cross-product matrix: R is swept on F and holds RSS(F), and B is swept on
F | C and holds RSS(F | C). Since a subset never has a smaller RSS than a
superset, RSS(F | C) is a lower bound for every subset below the node. If no
size in [|F|, |F| + |C|] can still use a subset with RSS at or above this
bound, the node is cut. Otherwise the node branches on one column c of C:
the "in" child sweeps c into R, the "out" child sweeps c out of B, so each
child costs one sweep of a (p + 1) x (p + 1) matrix (Furnival and Wilson 1974
use a pair of such trees; this is the same bound with a binary tree).
The arithmetic is generic, so Fraction input gives exact results.
"""

import math
from fractions import Fraction
from typing import NamedTuple

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


class LeapsResult(NamedTuple):
    best: list    # best[s] = list of (rss, subset) for size s, smallest RSS first, at most nbest items
    nodes: int    # nodes of the search tree that were visited
    sweeps: int   # sweeps done, including the p sweeps of the root bound matrix


def leaps_and_bounds(x, y, nbest=1):
    """The nbest subsets of each size with the smallest RSS, in a model with an intercept."""
    if nbest < 1:
        raise ValueError("nbest must be at least 1")
    a = centered_sscp(x, y)  # @line L1
    p = len(a) - 1
    yy = p
    if len(y) < p + 2:
        raise ValueError("need n >= p + 2")
    d0 = [a[j][j] for j in range(p)]
    full = [row[:] for row in a]
    for j in range(p):
        if not full[j][j] > COLLINEAR_TOL * d0[j]:
            raise ValueError("the columns of X (with the intercept) are linearly dependent")
        sweep(full, j)  # @line L2
    best = [[] for _ in range(p + 1)]
    seen = set()
    stats = {"nodes": 0, "sweeps": p}

    def record(subset, rss):
        key = tuple(sorted(subset))
        if key in seen:
            return
        seen.add(key)
        lst = best[len(key)]
        if len(lst) < nbest or rss < lst[-1][0]:
            lst.append((rss, key))
            lst.sort(key=lambda t: t[0])
            if len(lst) > nbest:
                lst.pop()

    def cutoff(s):
        lst = best[s]
        return lst[-1][0] if len(lst) == nbest else math.inf

    def visit(f, c, r, b):
        stats["nodes"] += 1
        if not c:  # @line L6
            return
        bound = b[yy][yy]
        if all(cutoff(s) <= bound for s in range(len(f), len(f) + len(c) + 1)):  # @line L7
            return
        # Branch on the column whose removal from F | C raises the RSS most.
        j = max(c, key=lambda k: b[k][yy] * b[k][yy] / -b[k][k])  # @line L8
        rest = [k for k in c if k != j]
        r_in = [row[:] for row in r]
        sweep(r_in, j)  # @line L9
        stats["sweeps"] += 1
        record(f + [j], r_in[yy][yy])  # @line L9
        visit(f + [j], rest, r_in, b)  # @line L10
        b_out = [row[:] for row in b]
        sweep(b_out, j, reverse=True)  # @line L11
        stats["sweeps"] += 1
        record(f + rest, b_out[yy][yy])  # @line L11
        visit(f, rest, r, b_out)  # @line L12

    record([], a[yy][yy])  # @line L3
    record(list(range(p)), full[yy][yy])  # @line L3
    visit([], list(range(p)), a, full)  # @line L4
    return LeapsResult(best, stats["nodes"], stats["sweeps"])  # @line L5
test_leaps_and_bounds.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/leaps-and-bounds/. The authors are listed in prov/EKM5SR.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from leaps_and_bounds import centered_sscp, leaps_and_bounds, sweep


def solve(a, b):
    """Gaussian elimination with partial pivoting; works for floats and Fractions."""
    k = len(a)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(k):
        piv = max(range(c, k), key=lambda r: abs(m[r][c]))
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, k):
            f = m[r][c] / m[c][c]
            m[r] = [u - f * v for u, v in zip(m[r], m[c])]
    out = [0] * k
    for i in reversed(range(k)):
        out[i] = (m[i][k] - sum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
    return out


def rss_direct(x, y, s):
    """RSS of the fit with an intercept and the columns s, from the normal equations on raw data."""
    one = Fraction(1) if isinstance(y[0], Fraction) else 1.0
    rows = [[one] + [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] * v for r, v in zip(rows, y)) for i in range(k)]
    b = solve(xtx, xty)
    return sum((v - sum(bi * ri for bi, ri in zip(b, r))) ** 2 for r, v in zip(rows, y))


def exhaustive(x, y, nbest):
    p = len(x[0])
    out = []
    for size in range(p + 1):
        vals = sorted(rss_direct(x, y, s) for s in itertools.combinations(range(p), size))
        out.append(vals[:nbest])
    return out


def correlated_data(rng, n, p, rho=0.6):
    x = []
    for _ in range(n):
        z0 = rng.gauss(0, 1)
        x.append([math.sqrt(1 - rho) * rng.gauss(0, 1) + math.sqrt(rho) * z0 for _ in range(p)])
    beta = [rng.choice([0.0, 0.0, 0.5, 1.0, -1.0]) for _ in range(p)]
    y = [sum(b * v for b, v in zip(beta, r)) + rng.gauss(0, 1) for r in x]
    return x, y


def test_matches_all_subsets_for_p_up_to_10():
    rng = random.Random(20261114)
    for p in range(1, 11):
        for nbest in (1, 3):
            x, y = correlated_data(rng, 3 * p + 5, p)
            got = leaps_and_bounds(x, y, nbest)
            want = exhaustive(x, y, nbest)
            for size in range(p + 1):
                vals = [r for r, _ in got.best[size]]
                assert len(vals) == len(want[size])
                for g, w in zip(vals, want[size]):
                    assert math.isclose(g, w, rel_tol=1e-9, abs_tol=1e-9)
                for r, s in got.best[size]:
                    assert len(s) == size
                    assert math.isclose(r, rss_direct(x, y, s), rel_tol=1e-9, abs_tol=1e-9)


def test_exact_in_fractions():
    rng = random.Random(5)
    for _ in range(3):
        p, n = 6, 12
        x = [[Fraction(rng.randint(-5, 5)) for _ in range(p)] for _ in range(n)]
        y = [Fraction(x[i][0] - 2 * x[i][3] + rng.randint(-4, 4)) for i in range(n)]
        got = leaps_and_bounds(x, y, 2)
        want = exhaustive(x, y, 2)
        for size in range(p + 1):
            assert [r for r, _ in got.best[size]] == want[size]


def test_bounding_rule_a_superset_never_has_a_larger_rss():
    rng = random.Random(11)
    p, n = 5, 10
    x = [[Fraction(rng.randint(-3, 3)) for _ in range(p)] for _ in range(n)]
    y = [Fraction(rng.randint(-6, 6)) for _ in range(n)]
    rss = {s: rss_direct(x, y, s) for r in range(p + 1) for s in itertools.combinations(range(p), r)}
    for t in rss:
        for s in rss:
            if set(t) <= set(s):
                assert rss[s] <= rss[t]


def test_sweep_out_of_full_model_gives_the_subset_rss():
    rng = random.Random(3)
    x = [[Fraction(rng.randint(-3, 3)) for _ in range(4)] for _ in range(9)]
    y = [Fraction(rng.randint(-6, 6)) for _ in range(9)]
    a = centered_sscp(x, y)
    for j in range(4):
        sweep(a, j)
    for j in (3, 1):
        sweep(a, j, reverse=True)
    assert a[4][4] == rss_direct(x, y, (0, 2))


def test_pruning_visits_far_fewer_nodes_than_the_full_tree():
    rng = random.Random(42)
    p = 14
    x, y = correlated_data(rng, 60, p, rho=0.3)
    res = leaps_and_bounds(x, y)
    assert res.nodes < 2 ** (p + 1) // 20
    assert res.sweeps == p + res.nodes - 1  # one sweep for each child node


def test_collinear_columns_are_rejected():
    x = [[1.0, 2.0], [2.0, 4.0], [3.0, 6.0], [4.0, 8.0]]
    with pytest.raises(ValueError):
        leaps_and_bounds(x, [1.0, 2.0, 2.0, 5.0])
    with pytest.raises(ValueError):
        leaps_and_bounds([[1.0], [2.0]], [1.0, 2.0], 0)

History

Programs of the 1960s fitted all 2m2^m subsets in an order in which each subset is one pivot away from the one before. Beale, Kendall and Mann (1967) and Hocking and Leslie (1967) gave the first searches that skip subsets by bounding their fit. Furnival and Wilson (1974) combined the superset bound with an ordering of the pivots, found the best subsets of each size for far more columns than full enumeration allows, and their method became the standard all-subsets routine. Welch (1982) proved that the problem is NP-hard. Bertsimas, King and Mazumder (2016) brought mixed integer programming to the problem.

References

  1. George M. Furnival and Robert W. Wilson, Jr., Regressions by leaps and bounds, Technometrics 16(4), 1974, pp. 499 to 511, The whole paper (the bound by the residual sum of squares of a superset, the pair of search trees of pivots, and the timings)
  2. R. R. Hocking and R. N. Leslie, Selection of the best subset in regression analysis, Technometrics 9(4), 1967, pp. 531 to 540, The whole paper (an earlier search that skips subsets by comparing reductions in the residual sum of squares)
  3. 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 whole paper (an early method that avoids the full enumeration of subsets)
  4. William J. Welch, Algorithmic complexity: three NP-hard problems in computational statistics, Journal of Statistical Computation and Simulation 15(1), 1982, pp. 17 to 25, The whole paper (best subset regression of a given size is NP-hard)
  5. B. K. Natarajan, Sparse approximate solutions to linear systems, SIAM Journal on Computing 24(2), 1995, pp. 227 to 234, The whole paper (finding the sparsest solution within a given residual norm is NP-hard)
  6. Dimitris Bertsimas, Angela King and Rahul Mazumder, Best subset selection via a modern optimization lens, Annals of Statistics 44(2), 2016, pp. 813 to 852, The whole paper (best subset as a mixed integer quadratic program, solved with certificates of optimality for much larger problems)
  7. Trevor Hastie, Robert Tibshirani and Ryan Tibshirani, Best subset, forward stepwise or lasso? Analysis and recommendations based on extensive comparisons, Statistical Science 35(4), 2020, pp. 579 to 592, The whole paper (simulations in which best subset beats the lasso at high signal to noise ratio and loses at low)
  8. Alan Miller, Subset Selection in Regression, second edition, Chapman and Hall/CRC, 2002, Chapter 3 (generating all subsets, branch and bound and the Furnival-Wilson method)

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