Algorithmresearch
Knockoff filter
Also called model-X knockoffs, Barber-Candes knockoffs.
Build copies of the features that keep their correlations but not their link to the response, and select features that beat their copies. Knockoff+ keeps the FDR at most q in finite samples.
- Time
- Θ(n p² + S p³) constructionΘ(n p + p log p) filter
- Space
- Θ(n p) extra
- Where
- S = the number of Jacobi sweeps; n = the number of observations; p = the number of features
- Model
- Real RAM
- Properties
- randomizednot exactofflinerandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rina Foygel Barber, Emmanuel J. Candès, 2015
The knockoff filter selects features in a linear regression and controls the false discovery rate of the selected set, the expected share of selected features with . It does not use p-values. For each feature it builds a knockoff , a fake feature with the same correlations to the other features as but known to have no effect on . It then computes a statistic for each pair, large and positive when explains better than its knockoff, and with a sign that is a fair coin when . The negative estimate how many null features pass any positive threshold, and the filter takes the lowest threshold at which the estimated FDR is at most . The version called knockoff+ adds 1 to the count of negatives and has in finite samples. The plain version controls only a modified FDR.
In plain words
You want to find which of many measured factors really affect an outcome, and you accept a set share of false finds. For each factor, make a fake twin: a made-up factor that is related to the other factors in the same way as the real one, but that cannot affect the outcome. Then let each real factor compete with its twin. A useless factor wins or loses at random, like a coin toss. A useful factor usually wins by a wide margin. Count how many twins win by a wide margin. That count tells you about how many useless factors also won by a wide margin by luck. Keep the factors that won by a margin large enough that this estimate of false finds stays below your limit.
The problem
Input. A design with and full column rank, a response , and a target . The model is with , fixed, and and unknown. The null hypotheses are ; of the are true.
Output. A set of selected features.
Error rate controlled. For knockoff+, the FDR, , where and is the number of null features in . For the plain knockoff filter, the modified FDR . Both bounds hold for every , so the control is strong.
Dependence assumption. None on the features beyond full rank: the knockoffs absorb the correlations of . The assumptions are the Gaussian linear model with fixed and . Model-X knockoffs, the variant named in the aliases, replace them by a known joint law of the rows of and work for any and .
Exact or asymptotic. Finite-sample, as an inequality. The proof is a theorem of Barber and Candès, cited and not proved here; the page proves the steps that lead to it.
The algorithm
Normalize the columns so that has unit diagonal. With , the knockoffs are
where is with orthonormal columns orthogonal to those of . Then and : the knockoffs have the correlations of , and . The equicorrelated choice is , the largest equal value allowed.
KNOCKOFF-FILTER(X, y, q, plus)- 1
normalize the columns of X; Σ ← XᵀX - 2
s ← min(2 λ_min(Σ), 1) ▷ Jacobi eigenvalues of Σ - 3
C ← a square root of 2sI - s²Σ⁻¹, so CᵀC = 2sI - s²Σ⁻¹ - 4
Ũ ← n × p orthonormal, orthogonal to X ▷ Gram-Schmidt - 5
X̃ ← X(I - sΣ⁻¹) + ŨC; W ← statistics on [X X̃] and y - 6
sort the distinct values t of |W_j| ≠ 0 in increasing order - 7
T ← the first t with (plus + #{W_j ≤ -t}) ≤ q · max(#{W_j ≥ t}, 1), or ∞ - 8
return {j : W_j ≥ T}
Here plus is 1 for knockoff+ and 0 for the plain filter. The statistic must satisfy two rules. Sufficiency: depends on the data only through and . Antisymmetry: swapping and changes the sign of and leaves the other unchanged. The code gives two such statistics: the marginal , and the least-squares from the regression of on . The usual choice in practice is a lasso statistic, such as the value of the penalty at which enters the lasso path, signed by whether it enters before its knockoff.
The equicorrelated makes singular when , so has rank below . The lasso and marginal statistics do not mind; the least-squares statistic needs a slightly smaller , and the tests use times the equicorrelated value.
Example
The threshold by hand. Take statistics
and . Line L7 scans upward:
| knockoff+ ratio | plain ratio | |||
|---|---|---|---|---|
| 0.3 | 10 | 4 | 0.5 | 0.4 |
| 1 | 9 | 3 | 0.444 | 0.333 |
| 2 | 9 | 2 | 0.333 | 0.222 |
| 2.5 | 8 | 2 | 0.375 | 0.25 |
| 3 | 8 | 1 | 0.25 | 0.125 |
| 5 | 6 | 1 | 0.333 | 0.167 |
| 5.5 | 6 | 0 | 0.167 | 0.167 |
The plain filter stops at and selects the 8 features with . Knockoff+ needs , first true at , and selects 6. Since the numerator is at least 1, knockoff+ selects nothing unless it can select at least features.
Why the +1. With one feature, null, and , the plain ratio is and the plain filter selects it. This happens with probability , so its FDR is for every . Knockoff+ has ratio and never selects it.
Two correlated features. If has off-diagonal , then , , and : the knockoff is nearly orthogonal to its original. If , then and . A knockoff so close to its original is hard to beat, and power drops.
A simulation. In the tests, a fixed design has , and column correlation about 0.2, so . Five coefficients are 4, five are 0, , and . Over 1000 responses:
| method | FDR | power |
|---|---|---|
| knockoff+, marginal | 0.120 | 0.462 |
| knockoff+, least-squares ( times 0.9) | 0.111 | 0.402 |
| plain knockoff, marginal | 0.227 | 0.853 |
| BH on exact -tests, known | 0.101 | 0.925 |
Knockoff+ stays below , as proved. The plain filter goes above it, by more than four standard errors (the standard error is about 0.005): its guarantee is for the modified FDR only. With only 10 features the knockoff+ rule needs 5 selections before it can select anything, and Benjamini-Hochberg, which is given the true here, is far more powerful. Knockoffs gain when is in the hundreds or thousands, when is unknown, and when a good selection statistic like the lasso is used.
Correctness
Three facts lead to the guarantee, and the correctness proof proves them. First, the construction gives with on the diagonal blocks and off them, and it exists exactly when . Second, swapping and for any set of null features leaves the Gram matrix unchanged and, under the Gaussian model, leaves the law of unchanged, because when . Third, with sufficiency and antisymmetry, this makes the signs of the null independent fair coins, independent of all and of the non-null signs (Lemma 1 of Barber and Candès).
So among the features with , the nulls split into and like coin tosses, and overestimates the number of nulls with . The step from there to at the data-dependent threshold is Theorem 2 of Barber and Candès, proved with a supermartingale and optional stopping; it is cited here. The tests check it in the coin model: for 150 random sets of magnitudes and non-null signs, they enumerate all null sign patterns and compute the FDR of knockoff+ and the modified FDR of the plain filter in exact rational arithmetic, and both are at most . In the same enumeration the plain filter's FDR exceeds .
Proof: Fixed-X knockoffs have the required Gram matrix, and the signs of the null statistics are independent fair coins; FDR control of knockoff+ is citedpartial
We prove what the lines compute and the exchangeability facts on which the FDR guarantee rests: the threshold at lines L6 and L7 is the one of the definition (Lemma 1); the construction at lines L1 to L5 gives the knockoff Gram matrix, and it exists exactly when (Proposition 2); swapping null features with their knockoffs changes neither the Gram matrix nor the law of the inner products with (Lemmas 3 and 4); and so the signs of the null statistics are independent fair coins (Lemma 5). The step from Lemma 5 to for knockoff+, and to the modified FDR bound for the plain filter, is Theorems 1 and 2 of Barber and Candès (2015). We cite them and do not prove them. The tests check them in the coin model by exact enumeration, and measure them in one simulation.
Setting. has full column rank, , and unit column norms after line L1; , so , and is its smallest eigenvalue. with . A feature is null when . Write , and for let be with columns and exchanged for each . A statistic has the sufficiency property if for some function , and the antisymmetry property if for and for .
Lemma 1 (the threshold). For and , let and , or if no qualifies. Lines L6 and L7 return , and for the smallest in the closure of the set of all positive that satisfy the inequality, when that set is not empty.
Proof. Line L6 lists in increasing order, and line L7 returns the first element that satisfies the inequality, which is the minimum. The counts and are constant for in each interval between consecutive elements of , and both are 0 for , where the inequality reads . So a positive satisfies the inequality exactly when the right end of its interval does, with the same selected set, or when , where nothing is selected. Hence restricting to changes neither the selected set nor whether some qualifies, except that a beyond selects nothing, as does. The tests compare the lines with this definition on random integer statistics.
For knockoff+ () with and , , so the filter selects at least features or none.
Proposition 2 (the construction). Let , , and suppose , with any matrix with , and with orthonormal columns and . Then satisfies
Moreover, if and only if , and a matrix with exists only if . Such exists because .
Proof. Using , and the symmetry of :
The eigenvalues of are over the eigenvalues of ; all are exactly when for all , that is, . For the necessity, the orthogonal change of basis turns into the block diagonal matrix with blocks and . A Gram matrix is positive semidefinite, so , that is, . Finally, the orthogonal complement of the column space of has dimension , so orthonormal vectors in it exist; line L4 finds them by Gram-Schmidt on the columns of followed by random vectors, which are independent of the columns with probability 1.
The code computes from the eigendecomposition of , so as required; it clips eigenvalues that are negative only by rounding. The equicorrelated choice is allowed by Proposition 2, and . The tests check the two Gram identities numerically.
Lemma 3 (swapping keeps the Gram matrix). For every , .
Proof. By Proposition 2, for all four inner products , , and equal , since and agree off the diagonal. And , . So the inner product of two columns depends only on their feature indices and, when , on whether they are the same column. Exchanging and preserves both.
Lemma 4 (swapping nulls keeps the law of ). If every is null, then has the same law as .
Proof. For any fixed matrix , . The covariances for and agree by Lemma 3. For the means, the entries of are and . By Proposition 2, for and , so . For , , so the two entries that the swap exchanges are equal, and the means agree. Two Gaussian vectors with equal means and covariances have the same law.
Lemma 5 (i.i.d. signs for the nulls; Barber and Candès, Lemma 1). Let satisfy sufficiency and antisymmetry. Let be independent of , with for non-null and independent uniform signs for null . Then has the same law as .
Proof. Fix a set of nulls and let be on and elsewhere. By antisymmetry, . By sufficiency this is , using Lemma 3, and by Lemma 4 it has the same law as . So has the law of for every fixed , and a random independent of is a mixture of such fixed patterns.
Corollary 6 (the coin model). Given and the signs of the non-null , the signs of the null with are independent and uniform on .
Proof. For any fixed null sign pattern , Lemma 5 says that and have the same law. The map keeps the magnitudes and the non-null signs, and on the nonzero null coordinates it changes a sign pattern into . So, given the magnitudes and the non-null signs, the patterns and have the same conditional probability, for every . The group of sign changes acts transitively on patterns, so the conditional law is uniform, which is independence with fair signs.
The two statistics in the code have the properties. The marginal is a function of , and a swap exchanges and , which flips its sign. For the least-squares statistic, has full rank when (by the block form in Proposition 2, then), and is a function of and . A swap is for a permutation matrix , which gives , so and exchange and changes sign. The tests check both flips numerically.
What is cited. Barber and Candès (2015, Theorem 2) prove that knockoff+ has , and (Theorem 1) that the plain filter has , for statistics with sufficiency and antisymmetry, in the setting above. Their proof starts from Corollary 6 and uses a supermartingale argument with optional stopping. Candès, Fan, Janson and Lv (2018) prove the model-X version. These are not proved here.
What is checked and measured. In the coin model of Corollary 6, the tests draw 150 random sets of magnitudes, non-null signs and null sets, enumerate all null sign patterns, and compute, in exact rational arithmetic, the FDR of knockoff+ and the modified FDR of the plain filter at . Both are at most in every case, as the cited theorems predict, while the FDR of the plain filter exceeds in some cases. A Monte Carlo run on one fixed design measures FDR 0.120 for knockoff+ and 0.227 for the plain filter at .
Complexity
On a real RAM, forming costs . The Jacobi eigenvalue algorithm costs per sweep and is used twice, for and and for the square root . Gram-Schmidt on vectors of length costs , and so do the products at line L5. A Cholesky decomposition of also works when is below . The marginal statistic costs , and the threshold at lines L6 and L7 costs : sort once, then count with binary search or a two-pointer sweep. The space is for . With a fixed design the knockoffs are built once, and each new response costs only the statistic and the threshold.
Properties
- FDR control of knockoff+ in finite samples, for any and any fixed design with . Cited.
- Modified FDR control of the plain filter. Cited. Its FDR can exceed ; shown by a hand example and measured.
- Signs of null statistics are fair coins. Proved.
- No p-values and no . The filter never estimates the noise level, and it allows any statistic with the two properties.
- Randomized. is random, so the selected set depends on a random draw. Two runs on the same data can select different sets.
- Needs at least selections. Knockoff+ selects nothing if fewer than features would be selected.
Variants and improvements
- Model-X knockoffs. Candès, Fan, Janson and Lv (2018) treat the rows of as random with a known law, and build so that swapping any and leaves the joint law of unchanged and is independent of given . Then knockoff+ controls the FDR for any model of given , linear or not, and for . For Gaussian rows with covariance , given is Gaussian with mean and covariance , the same algebra as here.
- SDP knockoffs. Choose a different for each feature to minimize subject to , a semidefinite program. It gives more power than equicorrelated knockoffs when the features have unequal correlations.
- . Barber and Candès add synthetic rows to and , using an estimate of from the full regression.
- Multiple knockoffs, derandomized knockoffs and e-values. Several knockoff copies or repeated runs reduce the randomness of the selected set; one way to aggregate is through e-values.
When to use it
Use knockoffs to select variables in a regression with FDR control when the p-values for individual coefficients are unreliable or unavailable, when is unknown, or when you want to use a selection method such as the lasso and still have a finite-sample guarantee. Fixed-X knockoffs need and a Gaussian linear model; model-X knockoffs need a good model of the features, as in genetics, where the law of genotypes is well understood. With few features, or when exact p-values are available, Benjamini-Hochberg or Storey's method are simpler and often stronger.
Pitfalls
- Using the plain filter and calling it FDR control. Only knockoff+ controls the FDR. The plain filter controls , which is close to the FDR only when many features are selected.
- Statistics that break antisymmetry. A statistic that treats and differently, for example through the order of a coordinate descent with ties, or that uses in a way other than through the inner products, loses the coin-flip property.
- Building knockoffs from . The knockoffs must be computed from alone. Choosing or after looking at voids the proof.
- Unnormalized columns. The equicorrelated formula assumes unit column norms.
- Too few features. With small, knockoff+ often selects nothing at the usual , since it needs at least selections.
- Wrong feature model in model-X. The guarantee holds for the law used to build the knockoffs. If that law is estimated badly, the FDR can be above .
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
# Part of https://algorithm.tamnd.com/knockoff-filter/. The authors are listed in prov/WNY22A.jsonl.
"""The fixed-X knockoff filter of Barber and Candes (2015), in pure Python.
knockoffs(X) normalizes the columns of the n x p design X (n >= 2p) and builds
equicorrelated knockoffs Xk with
Xk^T Xk = Sigma, X^T Xk = Sigma - s I, Sigma = X^T X,
where s = min(2 lambda_min(Sigma), 1), as
Xk = X (I - s Sigma^{-1}) + U C, C^T C = 2 s I - s^2 Sigma^{-1},
with U an n x p orthonormal matrix orthogonal to the columns of X.
A statistic W_j is large and positive when X_j beats its knockoff. Two choices are
given: the marginal one |X_j^T y| - |Xk_j^T y|, and the OLS one on [X Xk].
The filter selects {j : W_j >= T}, with
T = min{t in {|W_j| : W_j != 0} : (offset + #{W_j <= -t}) / max(#{W_j >= t}, 1) <= q},
offset = 1 for knockoff+ (FDR <= q) and 0 for the plain knockoff (modified FDR <= q).
"""
import math
import random
from bisect import bisect_left
from collections.abc import Callable, Sequence
def _dot(a: Sequence[float], b: Sequence[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def _transpose(a: Sequence[Sequence[float]]) -> list[list[float]]:
return [list(r) for r in zip(*a)]
def _matmul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> list[list[float]]:
bt = _transpose(b)
return [[_dot(row, col) for col in bt] for row in a]
def jacobi_eigen(a: Sequence[Sequence[float]], tol: float = 1e-13, max_sweeps: int = 100):
"""Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations: a = V diag(w) V^T."""
n = len(a)
a = [list(map(float, row)) for row in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
scale = max(1.0, max((abs(x) for row in a for x in row), default=0.0))
for _ in range(max_sweeps):
off = math.sqrt(sum(a[i][j] ** 2 for i in range(n) for j in range(i + 1, n)))
if off <= tol * scale:
break
for p in range(n):
for q in range(p + 1, n):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
return [a[i][i] for i in range(n)], v
def _orthonormal_complement(x: Sequence[Sequence[float]], k: int, rng: random.Random) -> list[list[float]]:
"""An n x k matrix with orthonormal columns, orthogonal to the columns of x (Gram-Schmidt, twice)."""
n, p = len(x), len(x[0])
basis: list[list[float]] = []
candidates = [[x[i][j] for i in range(n)] for j in range(p)]
candidates += [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(k)]
for v in candidates:
norm0 = math.sqrt(_dot(v, v))
for _ in range(2):
for b in basis:
c = _dot(b, v)
v = [vi - c * bi for vi, bi in zip(v, b)]
norm = math.sqrt(_dot(v, v))
if norm <= 1e-10 * max(norm0, 1.0):
raise ValueError("the design does not have full column rank, or n < 2p")
basis.append([vi / norm for vi in v])
return _transpose(basis[p:])
def knockoffs(x: Sequence[Sequence[float]], s: float | None = None, rng: random.Random | None = None):
"""Return (Xn, Xk, s): the column-normalized design, its equicorrelated fixed-X knockoffs, and s."""
n, p = len(x), len(x[0])
if n < 2 * p:
raise ValueError("fixed-X knockoffs need n >= 2p")
rng = rng or random.Random(0)
norms = [math.sqrt(sum(x[i][j] ** 2 for i in range(n))) for j in range(p)]
xn = [[x[i][j] / norms[j] for j in range(p)] for i in range(n)] # @line L1
sigma = _matmul(_transpose(xn), xn)
w, v = jacobi_eigen(sigma)
if min(w) <= 1e-12:
raise ValueError("the design does not have full column rank")
if s is None:
s = min(2.0 * min(w), 1.0) # @line L2
if not 0 < s <= 2.0 * min(w) + 1e-12:
raise ValueError("need 0 < s <= 2 lambda_min(Sigma)")
sigma_inv = [[sum(v[i][k] * v[j][k] / w[k] for k in range(p)) for j in range(p)] for i in range(p)]
a = [[(2.0 * s if i == j else 0.0) - s * s * sigma_inv[i][j] for j in range(p)] for i in range(p)]
mu, vv = jacobi_eigen(a)
c = [[math.sqrt(max(mu[k], 0.0)) * vv[j][k] for j in range(p)] for k in range(p)] # @line L3
u = _orthonormal_complement(xn, p, rng) # @line L4
shrink = [[(1.0 if i == j else 0.0) - s * sigma_inv[i][j] for j in range(p)] for i in range(p)]
left, right = _matmul(xn, shrink), _matmul(u, c)
xk = [[left[i][j] + right[i][j] for j in range(p)] for i in range(n)] # @line L5
return xn, xk, s
def marginal_statistic(xn: Sequence[Sequence[float]], xk: Sequence[Sequence[float]]) -> Callable:
"""y -> W with W_j = |X_j^T y| - |Xk_j^T y|."""
xt, xkt = _transpose(xn), _transpose(xk)
return lambda y: [abs(_dot(a, y)) - abs(_dot(b, y)) for a, b in zip(xt, xkt)]
def ols_statistic(xn: Sequence[Sequence[float]], xk: Sequence[Sequence[float]]) -> Callable:
"""y -> W with W_j = |b_j| - |b_{j+p}|, b the least-squares fit of y on [X Xk]. Needs s < 2 lambda_min."""
p = len(xn[0])
aug = [list(r1) + list(r2) for r1, r2 in zip(xn, xk)]
w, v = jacobi_eigen(_matmul(_transpose(aug), aug))
if min(w) <= 1e-9 * max(w):
raise ValueError("[X Xk] is singular; choose s below 2 lambda_min(Sigma)")
gram_inv = [[sum(v[i][k] * v[j][k] / w[k] for k in range(2 * p)) for j in range(2 * p)] for i in range(2 * p)]
m = _matmul(gram_inv, _transpose(aug))
def stat(y: Sequence[float]) -> list[float]:
b = [_dot(row, y) for row in m]
return [abs(b[j]) - abs(b[j + p]) for j in range(p)]
return stat
def knockoff_threshold(w: Sequence, q, plus: bool = True):
"""The smallest t in {|W_j| : W_j != 0} with (offset + #{W <= -t}) <= q max(#{W >= t}, 1); inf if none."""
offset = 1 if plus else 0
ts = sorted({abs(x) for x in w if x != 0}) # @line L6
neg = sorted(-x for x in w if x < 0)
pos = sorted(x for x in w if x > 0)
for t in ts:
n_neg = len(neg) - bisect_left(neg, t)
n_pos = len(pos) - bisect_left(pos, t)
if offset + n_neg <= q * max(n_pos, 1): # @line L7
return t
return math.inf
def knockoff_select(w: Sequence, q, plus: bool = True) -> list[bool]:
t = knockoff_threshold(w, q, plus)
return [x >= t for x in w] # @line L8
test_knockoff_filter.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/knockoff-filter/. The authors are listed in prov/WNY22A.jsonl.
import itertools
import math
import random
import statistics
from fractions import Fraction
import pytest
from knockoff_filter import (
jacobi_eigen,
knockoff_select,
knockoff_threshold,
knockoffs,
marginal_statistic,
ols_statistic,
)
HAND_W = [9, 8, 7.5, 7, 6, 5.5, -5, 4, 3, -2.5, 2, -1, 0.5, -0.3]
def design(rng: random.Random, n: int, p: int, rho: float = 0.5) -> list[list[float]]:
"""Rows share a common factor, so the columns are positively correlated."""
rows = []
for _ in range(n):
z = rng.gauss(0, 1)
rows.append([rho * z + rng.gauss(0, 1) for _ in range(p)])
return rows
def gram(a: list, b: list) -> list[list[float]]:
return [[sum(a[i][j] * b[i][k] for i in range(len(a))) for k in range(len(b[0]))] for j in range(len(a[0]))]
def threshold_brute_force(w: list, q, plus: bool):
"""Smallest admissible t > 0 by the definition: the counts are constant on each interval between |W| values,
so test every |W_j|, every midpoint and a point below the smallest; return the selected set there."""
mags = sorted({abs(x) for x in w if x != 0})
if not mags:
return [False] * len(w)
candidates = sorted(set(mags) | {(a + b) / 2 for a, b in zip(mags, mags[1:])} | {mags[0] / 2})
offset = 1 if plus else 0
for t in candidates:
if Fraction(offset + sum(1 for x in w if x <= -t)) / max(sum(1 for x in w if x >= t), 1) <= q:
return [x >= t for x in w]
return [False] * len(w)
def test_hand_example() -> None:
# knockoff+ at q = 0.2: at t = 5.5 there are 6 positives and no negatives at or beyond -5.5, so (1 + 0)/6 <= 0.2,
# and every smaller t fails, for example t = 5 gives (1 + 1)/6.
assert knockoff_threshold(HAND_W, Fraction(1, 5)) == 5.5
assert sum(knockoff_select(HAND_W, Fraction(1, 5))) == 6
# The plain knockoff stops at t = 3: 8 positives, 1 negative (-5), 1/8 <= 0.2; t = 2.5 gives 2/8.
assert knockoff_threshold(HAND_W, Fraction(1, 5), plus=False) == 3
assert sum(knockoff_select(HAND_W, Fraction(1, 5), plus=False)) == 8
# One null feature with a positive statistic: the plain filter selects it, knockoff+ cannot.
assert knockoff_select([2.0], Fraction(1, 10), plus=False) == [True]
assert knockoff_select([2.0], Fraction(1, 10)) == [False]
assert knockoff_select([0, 0], Fraction(1, 2)) == [False, False]
def test_threshold_matches_definition() -> None:
rng = random.Random(2015)
for _ in range(2000):
p = rng.randint(1, 12)
w = [rng.choice([-1, 1]) * rng.randint(0, 8) for _ in range(p)]
q = Fraction(rng.randint(1, 10), 10)
for plus in (True, False):
assert knockoff_select(w, q, plus) == threshold_brute_force(w, q, plus)
def test_jacobi_eigen() -> None:
rng = random.Random(1846)
for _ in range(30):
n = rng.randint(1, 7)
b = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
a = [[b[i][j] + b[j][i] for j in range(n)] for i in range(n)]
w, v = jacobi_eigen(a)
for i in range(n):
for j in range(n):
assert sum(v[i][k] * w[k] * v[j][k] for k in range(n)) == pytest.approx(a[i][j], abs=1e-10)
assert sum(v[k][i] * v[k][j] for k in range(n)) == pytest.approx(1.0 if i == j else 0.0, abs=1e-10)
def test_knockoff_gram_identities() -> None:
rng = random.Random(7)
for n, p in ((8, 3), (20, 6), (30, 10)):
x = design(rng, n, p)
xn, xk, s = knockoffs(x, rng=random.Random(1))
sigma = gram(xn, xn)
lam_min = min(jacobi_eigen(sigma)[0])
assert s == pytest.approx(min(2 * lam_min, 1.0))
kk, xkx = gram(xk, xk), gram(xn, xk)
for i in range(p):
assert sigma[i][i] == pytest.approx(1.0)
for j in range(p):
assert kk[i][j] == pytest.approx(sigma[i][j], abs=1e-9)
assert xkx[i][j] == pytest.approx(sigma[i][j] - (s if i == j else 0.0), abs=1e-9)
def test_swap_leaves_gram_and_flips_statistics() -> None:
"""Swapping X_j and Xk_j for j in S keeps the Gram matrix of [X Xk] and flips the sign of W_j for j in S."""
rng = random.Random(11)
n, p = 24, 5
x = design(rng, n, p)
xn, xk, s = knockoffs(x, s=None)
_, _, s_small = knockoffs(x)
xn2, xk2, _ = knockoffs(x, s=0.9 * s_small)
y = [rng.gauss(0, 1) for _ in range(n)]
for subset in [(0,), (1, 3), (0, 2, 4)]:
xs = [[xk[i][j] if j in subset else xn[i][j] for j in range(p)] for i in range(n)]
xks = [[xn[i][j] if j in subset else xk[i][j] for j in range(p)] for i in range(n)]
aug, aug_s = [a + b for a, b in zip(xn, xk)], [a + b for a, b in zip(xs, xks)]
g, g_s = gram(aug, aug), gram(aug_s, aug_s)
assert all(g[i][j] == pytest.approx(g_s[i][j], abs=1e-9) for i in range(2 * p) for j in range(2 * p))
w, w_s = marginal_statistic(xn, xk)(y), marginal_statistic(xs, xks)(y)
assert all(w_s[j] == pytest.approx(-w[j] if j in subset else w[j], abs=1e-9) for j in range(p))
xs2 = [[xk2[i][j] if j in subset else xn2[i][j] for j in range(p)] for i in range(n)]
xks2 = [[xn2[i][j] if j in subset else xk2[i][j] for j in range(p)] for i in range(n)]
w, w_s = ols_statistic(xn2, xk2)(y), ols_statistic(xs2, xks2)(y)
assert all(w_s[j] == pytest.approx(-w[j] if j in subset else w[j], abs=1e-7) for j in range(p))
def test_invalid_input() -> None:
with pytest.raises(ValueError):
knockoffs([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) # n < 2p
with pytest.raises(ValueError):
knockoffs([[1.0, 2.0], [2.0, 4.0], [3.0, 6.0], [1.0, 2.0]]) # collinear columns
rng = random.Random(3)
x = design(rng, 10, 3)
with pytest.raises(ValueError):
ols_statistic(*knockoffs(x)[:2]) # s = 2 lambda_min makes [X Xk] singular, unless s was capped at 1
assert knockoff_threshold([], Fraction(1, 10)) == math.inf
def test_exact_fdr_under_coin_flips() -> None:
"""Condition on |W| and the non-null signs; flip the null signs as fair coins, as the sign-flip lemma gives.
Enumerating all 2^m0 patterns gives the exact FDR. knockoff+ stays <= q and the plain filter's
E[V / (R + 1/q)] stays <= q (these are the two theorems of Barber and Candes); the plain filter's
FDR can exceed q."""
rng = random.Random(4)
q = Fraction(1, 5)
worst_plain = Fraction(0)
for _ in range(150):
p = rng.randint(1, 9)
m0 = rng.randint(1, p)
mags = [Fraction(rng.randint(1, 30)) for _ in range(p)]
alt_signs = [rng.choice([1, 1, 1, -1]) for _ in range(p - m0)]
fdr_plus = fdr_plain = mfdr_plain = Fraction(0)
for signs in itertools.product([1, -1], repeat=m0):
w = [s * a for s, a in zip(list(signs) + alt_signs, mags)]
for plus in (True, False):
sel = knockoff_select(w, q, plus)
r, v = sum(sel), sum(sel[:m0])
if plus:
fdr_plus += Fraction(v, max(r, 1))
else:
fdr_plain += Fraction(v, max(r, 1))
mfdr_plain += v / (r + 1 / q)
total = 2**m0
assert fdr_plus / total <= q
assert mfdr_plain / total <= q
worst_plain = max(worst_plain, fdr_plain / total)
assert worst_plain > q
def test_monte_carlo_fdr_on_a_fixed_design() -> None:
rng = random.Random(2018)
n, p, k, amp, sigma_noise = 40, 10, 5, 4.0, 1.0
q, reps = 0.2, 1000
x = design(rng, n, p)
xn, xk, s = knockoffs(x, rng=random.Random(5))
stat = marginal_statistic(xn, xk)
xn2, xk2, _ = knockoffs(x, s=0.9 * s, rng=random.Random(6))
stat_ols = ols_statistic(xn2, xk2)
beta = [amp] * k + [0.0] * (p - k)
# BH on two-sided z-tests of the OLS coefficients, with the noise level known, for comparison.
ev, evec = jacobi_eigen(gram(xn, xn))
sinv = [[sum(evec[i][m] * evec[j][m] / ev[m] for m in range(p)) for j in range(p)] for i in range(p)]
nd = statistics.NormalDist()
results = {"plus": [0.0, 0.0], "plain": [0.0, 0.0], "ols_plus": [0.0, 0.0], "bh": [0.0, 0.0]}
signs_null = 0
for _ in range(reps):
y = [sum(xn[i][j] * beta[j] for j in range(p)) + sigma_noise * rng.gauss(0, 1) for i in range(n)]
y2 = [sum(xn2[i][j] * beta[j] for j in range(p)) + sigma_noise * rng.gauss(0, 1) for i in range(n)]
w, w2 = stat(y), stat_ols(y2)
signs_null += sum(1 for v in w[k:] if v > 0)
xty = [sum(xn[i][j] * y[i] for i in range(n)) for j in range(p)]
z = [sum(sinv[j][m] * xty[m] for m in range(p)) / math.sqrt(sinv[j][j]) for j in range(p)]
pv = sorted((2 * (1 - nd.cdf(abs(z[j]))), j) for j in range(p))
r_bh = max([i + 1 for i in range(p) if pv[i][0] <= (i + 1) * q / p] or [0])
sel_bh = [False] * p
for _, j in pv[:r_bh]:
sel_bh[j] = True
rules = {
"plus": knockoff_select(w, q),
"plain": knockoff_select(w, q, plus=False),
"ols_plus": knockoff_select(w2, q),
"bh": sel_bh,
}
for name, sel in rules.items():
r = sum(sel)
results[name][0] += sum(sel[k:]) / max(r, 1)
results[name][1] += sum(sel[:k]) / k
fdr = {name: v[0] / reps for name, v in results.items()}
power = {name: v[1] / reps for name, v in results.items()}
# Null statistics are positive half the time: 5000 signs, standard error 0.007.
assert abs(signs_null / ((p - k) * reps) - 0.5) < 0.03
# knockoff+ has FDR <= q = 0.2 by the theorem; 1000 runs give a standard error near 0.005.
# With this seed: knockoff+ 0.12 (marginal W) and 0.11 (OLS W); the plain knockoff 0.23, above q.
assert fdr["plus"] <= q + 0.02 and fdr["ols_plus"] <= q + 0.02
assert fdr["plain"] > q
# With p = 10, knockoff+ needs at least 1/q = 5 selections; BH on exact z-tests is more powerful here.
assert 0.3 < power["plus"] < power["plain"] and power["ols_plus"] > 0.3
assert power["bh"] > power["plus"]
assert fdr["bh"] <= q
History
Rina Foygel Barber and Emmanuel Candès introduced the knockoff filter in a paper published in the Annals of Statistics in 2015. They proved the FDR control with a martingale argument that also covers a class of sequential testing problems. Candès, Fan, Janson and Lv (2018) extended the idea to random designs with model-X knockoffs, which removed the limit and the linear model. Later work studied power, knockoffs for hidden Markov models in genetics, derandomized and multiple knockoffs, and robustness to a misspecified feature law.
References
- Rina Foygel Barber and Emmanuel J. Candès, Controlling the false discovery rate via knockoffs, Annals of Statistics 43(5) (2015), pages 2055 to 2085, Definitions 1 and 2 (the knockoff and knockoff+ thresholds), Theorems 1 and 2 (modified FDR and FDR control), Section 2.1 (construction and the equicorrelated choice), Section 2.2 (sufficiency, antisymmetry and example statistics), Lemmas 1 to 3 in Section 2.3 (i.i.d. signs for the nulls)
- Emmanuel Candès, Yingying Fan, Lucas Janson and Jinchi Lv, Panning for gold, model-X knockoffs for high dimensional controlled variable selection, Journal of the Royal Statistical Society Series B 80(3) (2018), pages 551 to 577, model-X knockoffs for a known distribution of the features, with FDR control of knockoff+ for any n and p, and the Gaussian construction
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 WNY22A Edit this page History Report an error Markdown