Frontier: post-selection inference and inference with ML predictions
Explore current research at the intersection of classical statistics and machine learning. When data choose the hypothesis, classical guarantees fail; study sample splitting and data fission, conditional selective inference through the polyhedral lemma, knockoffs for FDR-controlled variable selection, and prediction-powered inference (PPI), which uses an ML model to narrow intervals without losing validity.
After this lesson you can
- Demonstrate by simulation that classical intervals after selecting the largest effect lack nominal coverage.
- Apply sample splitting and data fission and quantify their cost in power.
- Explain conditional selective inference through the polyhedral lemma and implement it for the maximum mean.
- Construct Gaussian model-X knockoffs and apply the knockoff filter to control FDR in variable selection.
- Implement prediction-powered inference for a mean and a coefficient, measuring its gain with few labeled data.
- Critically read a recent paper in the field and identify its assumptions, guarantees and limitations.
Before you start
- 05Confidence interval and coverageFalse discovery rateBenjamini-Hochberg procedureResearcher degrees of freedom and p-hackingType S and M errors and the winner's curseGaussian linear modelDelta methodM-estimators and Z-estimatorsExchangeability
- 11LassoHoldout train, validation and test splitPreprocessing and model pipelines
- 04Gaussian conditioning
Motivation: twenty architectures and one interval
You train 20 model variants (different depths, learning rates, tokenizer) and evaluate them on the same validation set of 2000 examples. The best scores 71.3 %. You attach its 95 % binomial confidence interval, about points, and report it. That interval is wrong for more than a technical detail: you calculated it as if the variant were fixed before seeing data, when the data actually chose it. Among 20 similar candidates, the luckiest on that sample wins, and observed accuracy systematically overestimates true accuracy.
The statistics in earlier lessons almost always implicitly assume the question is fixed before seeing data: which parameter to estimate, hypothesis to test, variables to include. Modern data science breaks that assumption at every step. Variables are chosen with lasso, then values read from the final regression. Twenty specifications are tried and the significant one published (researcher degrees of freedom). The best model on a benchmark is selected and scored on that same benchmark. Increasingly, costly human labels are replaced with model predictions (a classifier or LLM judge) and intervals calculated as if predictions were real data.
This lesson surveys research that turned these problems into theory with precise guarantees:
- Post-selection inference. Why the winner’s interval fails and three fixes: split data (or split each datum by fission), condition on selection (polyhedral lemma and truncated normal), or protect against every selection simultaneously (PoSI).
- Model-X knockoffs. Select variables for a black-box model with exact finite-sample false discovery rate control, without values.
- Prediction-powered inference (PPI). Use an ML model to narrow intervals with few labeled data without losing validity, even if the model is biased.
This is research-level material: nearly all results are less than fifteen years old, and some open problems at the end remain unsolved.
The problem: the winner always overestimates
Formalize the example. There are candidates with true effects (accuracies, treatment effects, or anything else), each with an independent estimate . They are standardized: the unit is each estimate’s standard error. Choose winner and seek an interval for .
The naive interval is . If all effects are null, , it covers exactly when , and since ,
With this gives : the “95 % interval” covers 60 % of the time. The point estimate is biased too: with 20 standard normals, when the chosen effect is 0. This winner’s curse is closely related to type-M errors: among results passing a filter, those passing by luck exaggerate the effect.
What should an interval guarantee here? The usual answer in the literature is coverage conditional on selection.
Two alternatives to conditional coverage appear in the literature and this lesson. Simultaneous coverage requires all possible intervals to cover at once, , protecting against any selection rule, even unknown or informal; this is the philosophy of PoSI and FWER corrections. When many parameters are selected, Benjamini and Yekutieli proposed controlling the false coverage rate (FCR), the expected proportion of reported intervals that fail, exactly parallel to FDR.
The figure shows four things the rest of the lesson explains:
- The naive interval always fails on the same side. Its red rows lie to the right: the interval sits above the true effect. That is bias, not noise.
- The selective interval covers 95 % in every scenario, but is very wide under the global null (median width exceeds 12). When the winner clearly stands out it shrinks toward the naive interval: selection carried little information.
- Sample splitting covers with fixed width when half is held out, but targets the candidate chosen with the other half, which selects the true best less often.
- The simultaneous interval (Bonferroni for means, , with for ) covers at least 95 % in any scenario with fixed width , without knowing the selection rule: since it covers all means simultaneously, it also covers the chosen one.
Simple solutions: split the data or split each datum
The oldest solution is familiar from holdout validation: use one part of data to choose and another independent part for inference. If with independent parts and selection depends only on , then conditioning on does not change the distribution of : any procedure valid for fixed remains valid. There is nothing else to prove.
The cost is power. With fraction of data for selection, inference uses and standard error is multiplied by ; with , by . An effect of 3 standard errors with all data, detected by a two-sided 5 % test with probability , becomes and is detected with probability . Selection also uses half the information and chooses less well.
Splitting has a subtler limitation: some problems do not permit splitting the sample. One read count per gene, an image, a time series, a fixed design where removing rows changes matrix . Leiner, Duan, Wasserman and Ramdas (2021) observed that for certain families each datum can be split into two independent random variables with external noise.
Proof
is a linear transformation of Gaussian vector , hence jointly Gaussian; for jointly Gaussian vectors, zero correlation is equivalent to independence. Calculate cross-covariance using :
Means are because , and covariances are and . Reconstruction is algebra: .
∎Parameter divides Fisher information: keeps fraction and keeps , summing to 1. For a Gaussian sample mean, fission with has exactly the same distribution as splitting the sample in half, and generally equals a split with fraction . Fission works with a single observation, any fraction (not just multiples of ), and without changing the design. Other families have versions too: for counts, if and , then and are independent (Poisson thinning); for Bernoulli and other exponential families, constructions exist where is not independent of but has a known conditional distribution.
Conditional selective inference: selection as truncation
Splitting discards information: the part used to choose cannot count again. The alternative is to use all data for both purposes and correct inference for selection. The idea, developed by Lee, Sun, Sun and Taylor (2016) and Fithian, Sun and Taylor (2014), treats selection as an event to condition on.
Start with the maximum mean. If candidate 1 won, we know for all . To infer conditional on this, also fix what is not , namely , which by independence does not inform . Conditional on all this, remains but restricted to : a truncated normal. Its distribution function at the observed datum is a uniform pivot; inversion gives the interval. The general case needs only linear algebra.
Proof
Independence. is a linear transformation of , hence jointly Gaussian, and
This is Gaussian regression of on : is the residual and the coefficient.
Polyhedron decomposition. Write , so . Then is equivalent to for each row . If , division gives an upper bound for ; if negative, the inequality reverses and gives a lower bound; if zero, the row does not depend on and requires only . Taking the largest lower bound and smallest upper bound gives the result.
Conditional distribution. Since , conditioning on does not change the distribution of , which is . The selection event given is exactly (with , depending only on ), and conditioning a variable on belonging to an interval truncates it there.
∎This is the polyhedral lemma. Its practical consequence is a pivot. Let be the distribution function of normal truncated to . Conditional on selection,
because additionally conditioning on makes it the probability integral transform of a continuous variable, and a variable uniform conditional on each value of is also uniform when averaged over . Since the truncated family has monotone likelihood ratio in , decreases in for each fixed , and the selective interval is
where endpoints solve and by bisection. It has exact coverage conditional on selection.
The figure shows typical selective-inference behavior. Far from the boundary, truncation matters little to likelihood and the selective interval resembles the naive one. Near it, data are compatible with very low : if the winner is and runner-up , the selective interval is . This is information, not a defect: barely passing the filter says very little about the effect. The “report only if ” rule shows pure publication bias: a result barely exceeding the threshold is compatible with almost any effect.
Lasso and other polyhedral procedures
The lemma is useful because many common procedures select via polyhedra: forward stepwise regression, marginal screening and especially lasso. For lasso , optimality conditions are , with if and otherwise. Fix active set and its signs :
- In the active set, , and requiring gives linear inequalities in .
- Outside it, componentwise, again linear in because is affine in .
Thus is a polyhedron, and the lemma gives exact conditional intervals for each selected-model coefficient. Pay attention to which parameter they cover: with , namely coefficient of the projection of onto selected columns. It is not the full model’s “true ”, which may not exist or be identifiable; it is the selected submodel’s coefficient, the one meaningful after selection.
Three nuances from later research. First, conditioning on less is better: conditioning only on (a union of polyhedra, one per sign vector) gives shorter intervals than conditioning also on signs, wasting less information (Fithian, Sun and Taylor show optimal conditioning is the minimum making inference valid). Second, intervals can be very long near the boundary; adding noise to selection (randomized selection) or reserving information as fission does shortens them greatly by smoothing boundaries. Third, everything depends on known and Gaussianity, though asymptotic results relax both.
PoSI: protection against any selection
Selective inference requires knowing the selection rule mathematically. In practice analysts choose models by inspecting plots, trying and discarding, in ways nobody could write as a polyhedron. Berk, Brown, Buja, Zhang and Zhao (2013) proposed the conservative alternative: intervals valid simultaneously for all possible submodels.
In the fixed-design linear model, let be the statistic of coefficient in submodel (with ). PoSI constant is the quantile of . Intervals then cover with probability at least whatever rule is used, because all cover simultaneously. The price is width: with variables there are order pairs , ranges from about in orthogonal designs to order of Scheffé’s constant in unfavorable designs, and its computation is exponential in . For the maximum mean, PoSI reduces to covering all means simultaneously, which the first figure’s Bonferroni interval does slightly conservatively (the exact Šidák constant for 20 independent means is instead of ).
Model-X knockoffs: variable selection with FDR control
Change the question. Instead of an interval for a chosen parameter, we want to choose variables: of candidates (genes, model features, market signals), which truly influence response ? We want to control FDR, the expected proportion of selected variables that are null. Lesson 18’s Benjamini–Hochberg method needs valid values for each variable. In high dimensions, with a nonlinear model or when , nobody knows how to calculate them.
Barber and Candès’ idea (2015), extended by Candès, Fan, Janson and Lv (2018) to model-X, is to construct a control group. For each variable construct a fake copy , the knockoff, perfectly mimicking how relates to other variables but, by construction, unrelated to beyond what passes through . Compare each variable’s importance with its copy: a variable no more important than its fake double does not deserve selection.
Notice the assumption change from classical regression: nothing is assumed about the relationship between and (it can be any black-box model), but the distribution of is assumed known. This makes sense when far more data lack responses than have them (large biobank genotypes, for example), or a good physical model of covariates exists.
Proof
First, is a valid covariance. Its Schur complement with respect to block is , with . Assumption is equivalent, multiplying by on each side, to ; since and have the same eigenvalues, also , so the Schur complement is positive semidefinite. If , Gaussian conditioning gives and , the stated law; conversely, generating this way produces that joint vector.
Exchangeability: swapping and simultaneously permutes rows and columns and of . Both variances are ; for , , and is symmetric in the pair. Thus is unchanged, and a centered Gaussian is determined by covariance. Conditional independence holds because is generated from and external noise.
∎Vector determines knockoff quality. Since , a large makes very different from and distinguishes original from copy; with , and the method has no power. With standardized variables, the equicorrelated choice is for every ; the usual alternative maximizes by semidefinite programming. With highly correlated covariates, is small and knockoffs resemble originals too closely: a known limitation.
The filter
With calculate for each a statistic that is large and positive when seems more important than , and changes sign when the two columns swap. The most used is lasso coefficient difference (LCD): fit lasso of on columns and
Any importance measure from any model (random forest, neural network) works, provided originals and knockoffs are treated symmetrically. The key property is:
The proof idea is this. If is a set of null variables, swapping and for leaves the joint distribution of unchanged: exchangeability guarantees this for covariates, and conditional independence together with not depending on given the rest extends it to the response. But the swap flips sign of for and leaves others unchanged. Thus flipping any subset of null signs does not change the distribution of , exactly the theorem.
The consequence is a mirror: for any threshold , the number of nulls with has the same distribution as those with . Since signals tend to give large positive , almost everything in is null. Thus estimates conservatively the null count among selected .
Proof
Let and . On ,
because and satisfies the threshold condition. It remains to show . Order nulls by and traverse thresholds from low to high, the order in which the filter seeks : by the coin-flip theorem each null contributes to or with probability independently of the rest. Barber and Candès show is a supermartingale for the filtration revealing signs as the threshold rises, and is a stopping time for it. By optional sampling, its expectation at is bounded by expectation at the initial threshold when all nulls count: , , and direct calculation gives .
∎Notably the theorem needs no values, correct linear model, , or asymptotics. Everything rests on knockoff exchangeability, which depends on knowing the distribution of well.
In the figure, true FDP for one dataset can exceed (the theorem controls expectation, not each realization), but the average over many datasets stays below. With weak signals the filter selects nothing: since the numerator is at least 1, knockoff+ needs at least selections (5 with and 10 with ), even in the best case with no mirror points. That is the price of the exact guarantee, so knockoff+ has little power when signals are few.
Prediction-powered inference
The final problem comes directly from ML. You want to estimate a quantity (disease prevalence in images, an LLM’s correct-answer rate, a regression coefficient for an expensive-to-measure variable) and have:
- expensive labeled examples : a doctor, human annotator, laboratory experiment;
- cheap unlabeled examples ;
- a predictor (ML model, language-model judge) giving , trained on other data.
There are two obvious answers and neither is good. The classical one ignores predictions and uses only labels: valid but wide. The naive one replaces with in examples: it gives an extremely narrow interval centered on the wrong value because predictor bias passes unchanged into the conclusion, and width decreasing like makes the conclusion look very certain. Angelopoulos, Bates, Fannjiang, Jordan and Zrnic (2023) proposed the correct combination.
If predictor is fixed (trained on data independent of both samples) and the samples are independent and from the same population, the estimator is unbiased with variance for any , however poor or biased. You will prove it in the exercises with one line of expectations and one of variances. Validity comes for free; the predictor determines only width.
Compare variances. Classical variance is . When , PPI’s is : PPI is like classical inference applied to predictor errors instead of . If the predictor explains fraction of variance of without bias, and PPI is equivalent to having labels: with , five times as many. Predictor bias does not spoil validity, and constant bias does not even cost width (it is simply subtracted); random error costs width.
The figure answers three questions. At initial bias , naive intervals never cover because width is tiny relative to bias, while PPI covers 95 %. With naive coverage holds in this model, but that cannot be checked without labels, which the naive method lacks. With the figure’s predictor is constant and PPI equals classical inference: no gain or loss. A worse-than-useless predictor that varies independently of would make PPI worse than classical inference by adding prediction variance without removing anything: when is independent of . PPI++ resolves this.
PPI++: choosing how much to trust the predictor
Angelopoulos, Duchi and Zrnic (2023) introduced a weight :
With it is classical; with , PPI. For any fixed it remains unbiased, since the parenthesized term has zero expectation. Its variance is
a parabola in minimized at
This is the Monte Carlo control variate formula: the predictor is a control variate whose mean is known nearly exactly thanks to unlabeled examples. With estimated from data, the estimator is asymptotically as good as with and, since is an option, never asymptotically worse than classical inference: a useless predictor receives and is ignored.
Beyond the mean: M-estimators
The idea extends to any M-estimator (means, quantiles, linear and logistic regression). The rectified loss
is an unbiased estimator of for each , and . By asymptotic M-estimator theory, is asymptotically normal with sandwich variance
For least-squares linear regression a closed form used in the original paper exists: the PPI coefficient regresses predictions on covariates in unlabeled examples, minus the regression of errors on covariates in labeled examples,
and its variance is the sum of both sandwich variances, because the regressions use independent samples. You will implement it below.
Implementation from scratch
Post-selection intervals
First, three remedies for the winner’s interval: truncated-normal selective inference, splitting and Gaussian fission. The pivot is calculated on a logarithmic scale with log_ndtr because near the boundary both tails being divided are tiny and linear scale loses all digits. Bisection is vectorized: it solves thousands of intervals at once in a simulation study using ADEMP (aims, data-generating mechanisms, estimands, methods, performance measures).
import numpy as np
from scipy.special import log_ndtr, ndtri
def sf_trunc(y, mu, a, sd=1.0):
"""P(Y > y) para Y ~ N(mu, sd²) truncada a [a, ∞), calculada en escala logarítmica."""
return np.exp(log_ndtr(-(y - mu) / sd) - log_ndtr(-(a - mu) / sd))
def ci_selectivo(y, a, sd=1.0, alpha=0.05, iters=60):
"""Invierte el pivote de la normal truncada: mu con P_mu(Y > y | Y ≥ a) = alpha/2 y 1 - alpha/2.
y, a pueden ser arrays. La supervivencia crece con mu, así que la bisección es directa."""
y, a = np.broadcast_arrays(np.asarray(y, float), np.asarray(a, float))
# Cerca del borde el extremo inferior se aleja como a − log(40) sd²/(y − a): el corchete se adapta a ello.
izq = np.minimum(y - 40 * sd, a - 8 * sd**2 / np.maximum(y - a, 1e-9))
def raiz(objetivo):
lo, hi = izq, y + 5 * sd # supervivencia ≈ 0 a la izquierda, ≈ 1 a la derecha
for _ in range(iters): # todas las repeticiones a la vez
mid = 0.5 * (lo + hi)
arriba = sf_trunc(y, mid, a, sd) > objetivo
hi, lo = np.where(arriba, mid, hi), np.where(arriba, lo, mid)
return 0.5 * (lo + hi)
return raiz(alpha / 2), raiz(1 - alpha / 2)
for y, a in [(2.5, 1.8), (2.5, 2.4), (2.5, 0.5)]:
lo, hi = ci_selectivo(y, a)
print(f"ganador {y}, segundo {a}: selectivo [{float(lo):6.2f}, {float(hi):5.2f}] ingenuo [{y - 1.96:.2f}, {y + 1.96:.2f}]")
def estudio(mu, R=4000, p=0.5, tau=1.0, alpha=0.05, seed=0):
"""ADEMP. Datos: X_i ~ N(mu_i, 1). Estimando: mu del elegido. Métodos: cuatro. Medidas: cobertura y anchura."""
rng = np.random.default_rng(seed)
m, z, filas = len(mu), ndtri(1 - alpha / 2), np.arange(R)
X = mu + rng.standard_normal((R, m))
gana = X.argmax(1)
y, segundo = X[filas, gana], np.sort(X, 1)[:, -2]
res = {"ingenuo": (y - z, y + z, mu[gana])}
res["selectivo"] = (*ci_selectivo(y, segundo), mu[gana])
# división: X = p X1 + (1 - p) X2, con X1 ~ N(mu, 1/p) para elegir y X2 ~ N(mu, 1/(1 - p)) para inferir
X1 = mu + rng.standard_normal((R, m)) / np.sqrt(p)
X2 = mu + rng.standard_normal((R, m)) / np.sqrt(1 - p)
g1, s2 = X1.argmax(1), 1 / np.sqrt(1 - p)
res["división"] = (X2[filas, g1] - z * s2, X2[filas, g1] + z * s2, mu[g1])
# fisión: f = X + tau Z elige y g = X - Z / tau infiere (independientes)
Z = rng.standard_normal((R, m))
f, g = X + tau * Z, X - Z / tau
gf, sg = f.argmax(1), np.sqrt(1 + 1 / tau**2)
res["fisión"] = (g[filas, gf] - z * sg, g[filas, gf] + z * sg, mu[gf])
for k, (lo, hi, th) in res.items():
cubre = np.mean((lo <= th) & (th <= hi))
print(f" {k:10s} cobertura {cubre:.3f} anchura mediana {np.median(hi - lo):5.2f}")
print("\n20 efectos nulos")
estudio(np.zeros(20))
print("\nuno destaca: mu = (3, 0, ..., 0)")
estudio(np.r_[3.0, np.zeros(19)])The numbers confirm the figure and theory. Under the global null the naive interval covers 60 % (the formula gave ) and the other three 95 % within Monte Carlo error. Selective median width above 12 is the price of using the same data to choose and infer when nothing stands out; when an effect stands out it falls to just over 5, below splitting, always wide. Splitting and fission give interchangeable results, as the fission theorem predicts with .
Lasso and p-values in the final regression
The most widespread mistake: choose variables using data and then read values from regression on those selected. The simulation uses the global null ( depends on none of 30 variables) and chooses the 3 most correlated with , the first three lasso or forward selection would add.
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
def pvalores_ols(X, y):
"""Valores p bilaterales de OLS con intercepto (modelo lineal gaussiano), sin el intercepto."""
A = np.column_stack([np.ones(len(y)), X])
b, *_ = np.linalg.lstsq(A, y, rcond=None)
gl = len(y) - A.shape[1]
s2 = np.sum((y - A @ b) ** 2) / gl
se = np.sqrt(s2 * np.diag(np.linalg.inv(A.T @ A)))
return 2 * stats.t.sf(np.abs(b / se), gl)[1:]
def cribado(X, y, k):
"""Índices de las k variables con mayor |correlación| con y."""
Xc = (X - X.mean(0)) / X.std(0)
return np.argsort(-np.abs(Xc.T @ (y - y.mean())))[:k]
n, p, k, R = 100, 30, 3, 2000
falsos_mismo = falsos_division = 0
for _ in range(R):
X = rng.standard_normal((n, p))
y = rng.standard_normal(n) # nula global
S = cribado(X, y, k)
falsos_mismo += np.sum(pvalores_ols(X[:, S], y) < 0.05)
a, b = slice(0, n // 2), slice(n // 2, n) # elegir con una mitad, contrastar con la otra
S2 = cribado(X[a], y[a], k)
falsos_division += np.sum(pvalores_ols(X[b][:, S2], y[b]) < 0.05)
print(f"falsos positivos al 5 %, mismos datos: {falsos_mismo / (k * R):.3f}")
print(f"falsos positivos al 5 %, división 50/50: {falsos_division / (k * R):.3f}")Using the same data, 41 % of selected variables appear “significant” at 5 %, eight times nominal, although none has an effect. Splitting restores 5 %. To use the full sample instead, the polyhedral lemma with the screening (or lasso) polyhedron yields correct conditional values; implemented in R library selectiveInference and Python package selectinf by the same group.
Model-X knockoffs and the filter
Now equicorrelated Gaussian knockoffs and the knockoff+ filter with scikit-learn lasso as the importance measure. Set slightly below so conditional covariance is nonsingular and Cholesky factorization works.
import numpy as np
from sklearn.linear_model import Lasso
def knockoffs_gaussianos(X, Sigma, rng):
"""Knockoffs model-X equicorrelacionados: s = min(1, 2 λmin(Σ)) (Σ con diagonal unidad)."""
p = Sigma.shape[0]
s = min(1.0, 2 * np.linalg.eigvalsh(Sigma).min()) * 0.999
D = s * np.eye(p)
Sinv_D = np.linalg.solve(Sigma, D) # Σ⁻¹ D
media = X - X @ Sinv_D # cada fila: x − D Σ⁻¹ x
V = 2 * D - D @ Sinv_D # 2D − D Σ⁻¹ D
return media + rng.standard_normal(X.shape) @ np.linalg.cholesky(V).T
def umbral_knockoff(W, q, plus=True):
"""Menor t entre los |W_j| no nulos con FDP estimado ≤ q; infinito si no hay ninguno."""
extra = 1 if plus else 0
for t in np.sort(np.abs(W[W != 0])):
if (extra + np.sum(W <= -t)) / max(1, np.sum(W >= t)) <= q:
return t
return np.inf
def experimento(rng, n=300, p=60, k=15, A=0.22, rho=0.3, q=0.2):
Sigma = (1 - rho) * np.eye(p) + rho # equicorrelación: λmin = 1 − rho
X = rng.standard_normal((n, p)) @ np.linalg.cholesky(Sigma).T
beta = np.zeros(p)
S = rng.choice(p, k, replace=False)
beta[S] = A * rng.choice([-1, 1], k)
y = X @ beta + rng.standard_normal(n)
Xk = knockoffs_gaussianos(X, Sigma, rng) # sin mirar y
lam = 0.2 * np.sqrt(2 * np.log(2 * p) / n) # penalización moderada: deja entrar algunas nulas
coef = Lasso(alpha=lam, fit_intercept=False).fit(np.hstack([X, Xk]), y).coef_
W = np.abs(coef[:p]) - np.abs(coef[p:]) # diferencia de coeficientes del lasso
T = umbral_knockoff(W, q)
sel = np.flatnonzero(W >= T)
return np.sum(beta[sel] == 0) / max(1, len(sel)), np.sum(beta[sel] != 0) / k, len(sel)
rng = np.random.default_rng(1)
# comprobación de la construcción: covarianza conjunta empírica frente a G
p, rho = 4, 0.6 # λmin = 0.4, así que s = 0.8 < 1
Sig = (1 - rho) * np.eye(p) + rho
Xc = rng.standard_normal((200_000, p)) @ np.linalg.cholesky(Sig).T
G = np.cov(np.hstack([Xc, knockoffs_gaussianos(Xc, Sig, rng)]).T)
print("Cov(X1, X1~) empírica:", round(G[0, p], 3), " teórica Σ11 − s =", round(1 - min(1, 2 * (1 - rho)) * 0.999, 3))
print("Cov(X1, X2~) empírica:", round(G[0, p + 1], 3), " teórica Σ12 =", rho)
res = np.array([experimento(rng) for _ in range(60)])
eM = 2 * res[:, 0].std(ddof=1) / np.sqrt(len(res))
print(f"\nFDR estimado en 60 conjuntos: {res[:, 0].mean():.3f} ± {eM:.3f} (objetivo q = 0.2)")
print(f"potencia media: {res[:, 1].mean():.2f} seleccionadas por conjunto: {res[:, 2].mean():.1f}")The first check verifies construction with , where : covariance between a variable and its knockoff is and cross-covariance with another variable equals that between originals. The second checks the theorem: mean FDR stays below (Monte Carlo error a few hundredths over 60 repetitions) and power is around 70 %.
PPI for a mean and a coefficient
The predictor is a random forest trained on another 1000 observations from a similar but different population (where the effect of is weaker), producing realistic bias. The large population and its predictions are calculated once; each repetition draws labeled and unlabeled cases. Estimands are the mean of and slope of in linear regression .
import numpy as np
from scipy.special import ndtri
from sklearn.ensemble import RandomForestRegressor
rng = np.random.default_rng(0)
def generar(m, efecto_x2=0.5):
X = rng.uniform(-2, 2, size=(m, 3))
y = np.sin(2 * X[:, 0]) + efecto_x2 * X[:, 1] ** 2 + 0.8 * X[:, 2] + 0.5 * rng.standard_normal(m)
return X, y
# 1) el predictor se entrena con datos propios, de una población algo distinta, y no se vuelven a usar
Xtr, ytr = generar(1000, efecto_x2=0.3)
modelo = RandomForestRegressor(n_estimators=40, max_depth=6, random_state=0).fit(Xtr, ytr)
# 2) población objetivo y predicciones, calculadas una sola vez
Xpob, ypob = generar(50_000)
fpob = modelo.predict(Xpob)
Dpob = np.column_stack([np.ones(len(Xpob)), Xpob[:, 2]]) # regresión Y ~ 1 + x3
theta = {"media": ypob.mean(), "pendiente": np.linalg.lstsq(Dpob, ypob, rcond=None)[0][1]}
print(f"sesgo del predictor E[f − Y] = {np.mean(fpob - ypob):+.3f} R² = {1 - np.var(ypob - fpob) / np.var(ypob):.2f}")
print(f"objetivos: media {theta['media']:.3f}, pendiente {theta['pendiente']:.3f}")
def ic_media(y, f, fu):
n, N = len(y), len(fu)
rect = f - y # errores del predictor
return {"clásico": (y.mean(), y.std(ddof=1) / np.sqrt(n)),
"ingenuo": (fu.mean(), fu.std(ddof=1) / np.sqrt(N)),
"PPI": (fu.mean() - rect.mean(), np.sqrt(fu.var(ddof=1) / N + rect.var(ddof=1) / n))}
def ols_sandwich(A, r):
"""Coeficientes de OLS de r sobre A y su covarianza sándwich (HC0)."""
G = A.T @ A / len(A)
b = np.linalg.solve(G, A.T @ r / len(A))
e = r - A @ b
Gi = np.linalg.inv(G)
return b, Gi @ ((A * e[:, None] ** 2).T @ A / len(A)) @ Gi / len(A)
def ic_pendiente(A, y, f, Au, fu):
bc, Vc = ols_sandwich(A, y)
bf, Vf = ols_sandwich(Au, fu) # predicciones sobre covariables, sin etiqueta
bd, Vd = ols_sandwich(A, f - y) # rectificador: errores sobre covariables
return {"clásico": (bc[1], np.sqrt(Vc[1, 1])), "ingenuo": (bf[1], np.sqrt(Vf[1, 1])),
"PPI": (bf[1] - bd[1], np.sqrt(Vf[1, 1] + Vd[1, 1]))}
R, n, N, z = 300, 100, 10_000, ndtri(0.975)
cubre = {e: {k: 0 for k in ("clásico", "ingenuo", "PPI")} for e in theta}
ancho = {e: {k: 0.0 for k in ("clásico", "ingenuo", "PPI")} for e in theta}
for _ in range(R):
idx = rng.choice(len(Xpob), n + N, replace=False)
L, U = idx[:n], idx[n:]
salida = {"media": ic_media(ypob[L], fpob[L], fpob[U]),
"pendiente": ic_pendiente(Dpob[L], ypob[L], fpob[L], Dpob[U], fpob[U])}
for e, out in salida.items():
for k, (est, se) in out.items():
cubre[e][k] += abs(est - theta[e]) <= z * se
ancho[e][k] += 2 * z * se / R
for e in theta:
print(f"\n{e}")
for k in cubre[e]:
print(f" {k:8s} cobertura {cubre[e][k] / R:.3f} anchura media {ancho[e][k]:.3f}")Both tables tell the same story. Naive intervals are tiny with catastrophic coverage: forest bias (trained where had a weaker effect) shifts the mean, and its tendency to flatten extremes attenuates slope. Classical and PPI cover around 95 % (with 300 repetitions Monte Carlo coverage error is slightly over one point), but PPI intervals are much narrower: 47 % less for the mean and 28 % less for slope. Slope gains less because its classical standard error already removes the part of explained by (45 % of its variance in this population): PPI can save only the part of the residual from regressing on captured by the predictor, less than the total variance it captures for the mean.
Evaluating a language model with PPI
The use case that popularized PPI: estimate a language model’s task accuracy with few human judgments () and many model-judge judgments (). Labels are binary: if the human accepts the answer and if the judge does. For browser execution the judge is simulated with its sensitivity and false-approval rate; below is a skeleton for real judgments using a local model. Since unlabeled predictions enter only through their mean and variance, their count can be simulated with a binomial.
import numpy as np
def evaluar(n=200, N=5000, acierto=0.70, sens=0.90, falsos=0.40, R=4000, seed=1):
"""acierto: tasa real; sens: P(juez aprueba | humano aprueba); falsos: P(juez aprueba | humano suspende)."""
g = np.random.default_rng(seed)
z = 1.959964
Y = (g.random((R, n)) < acierto).astype(float)
fL = np.where(Y == 1, g.random((R, n)) < sens, g.random((R, n)) < falsos).astype(float)
pf = acierto * sens + (1 - acierto) * falsos # P(juez aprueba)
mU = g.binomial(N, pf, size=R) / N # media de los N juicios sin humano
vU = mU * (1 - mU) * N / (N - 1)
d = fL - Y
cov = ((Y - Y.mean(1, keepdims=True)) * (fL - fL.mean(1, keepdims=True))).sum(1) / (n - 1)
lam = cov / ((1 + n / N) * fL.var(1, ddof=1)) # PPI++
r = Y - lam[:, None] * fL
metodos = {
"clásico": (Y.mean(1), Y.std(1, ddof=1) / np.sqrt(n)),
"ingenuo": (mU, np.sqrt(vU / N)),
"PPI": (mU - d.mean(1), np.sqrt(vU / N + d.var(1, ddof=1) / n)),
"PPI++": (Y.mean(1) + lam * (mU - fL.mean(1)), np.sqrt(r.var(1, ddof=1) / n + lam**2 * vU / N)),
}
print(f"juez: sensibilidad {sens}, falsos aprobados {falsos} -> sesgo {pf - acierto:+.3f}, λ medio {lam.mean():.2f}")
for k, (est, se) in metodos.items():
print(f" {k:8s} cobertura {np.mean(np.abs(est - acierto) <= z * se):.3f} anchura media {np.mean(2 * z * se):.4f}")
evaluar() # juez indulgente y poco fiable
print()
evaluar(sens=0.95, falsos=0.10) # juez buenoWith a lenient judge (approving 40 % of bad answers), its bias makes naive intervals never cover, PPI barely narrows the classical interval, and PPI++ narrows it somewhat more by reducing judge weight to . With a good judge, PPI cuts classical width around 40 %, equivalent to about 580 human-reviewed answers instead of 200. Even with a good judge, naive coverage falls short: half a point of bias suffices when the interval is two and a half points wide.
For a real judge, only the source of vectors fL and fU changes. The skeleton below is not run here (it requires downloading a model and benefits from a GPU), using library transformers:
from transformers import pipeline
juez = pipeline("text-generation", model=NOMBRE_DEL_MODELO_JUEZ, device_map="auto")
def juicio(pregunta, respuesta, referencia):
prompt = (f"Pregunta: {pregunta}\nRespuesta de referencia: {referencia}\n"
f"Respuesta a evaluar: {respuesta}\n¿Es correcta la respuesta a evaluar? Contesta solo SÍ o NO.\n")
salida = juez(prompt, max_new_tokens=3, do_sample=False, return_full_text=False)[0]["generated_text"]
return 1.0 if salida.strip().upper().startswith("S") else 0.0
# fL: juicios sobre las n respuestas que también revisó un humano; fU: sobre las N restantes.
# El juez no debe haberse ajustado ni elegido mirando las n etiquetas humanas que se usan para rectificar.
With libraries
All three method families have author-maintained implementations. They are unavailable in the browser, so these snippets do not run; consult documentation in case signatures change.
# PPI: paquete ppi-python (Angelopoulos, Zrnic y colaboradores)
from ppi_py import ppi_mean_ci, ppi_ols_ci
lo, hi = ppi_mean_ci(Y, Yhat, Yhat_unlabeled, alpha=0.05) # media; lam=None (por defecto) ajusta λ como PPI++, lam=1 es PPI
lo, hi = ppi_ols_ci(X, Y, Yhat, X_unlabeled, Yhat_unlabeled, alpha=0.05)
# Knockoffs: paquete knockpy
from knockpy import KnockoffFilter
filtro = KnockoffFilter(ksampler="gaussian", fstat="lasso")
seleccion = filtro.forward(X=X, y=y, Sigma=Sigma, fdr=0.2) # vector 0/1 de variables elegidas
For selective inference after lasso or stepwise selection, the reference is R package selectiveInference (functions fixedLassoInf and fsInf) by the polyhedral lemma authors.
Outlook and open questions
The lesson’s three ideas share a philosophy with exchangeability and permutation tests: obtain exact finite-sample guarantees with black-box models, placing assumptions where they can be checked (selection rule, covariate distribution, independence of predictor and correction data), not on the response model. Active directions include:
- LLM evaluation with automatic judges. PPI and variants combine a few human judgments with many automatic ones; open questions include what to do when the judge is chosen or tuned on the same data, how to stratify by question type, and how to compare multiple models without winner’s curse.
- Synthetic data. If a generative model produces “training” data or simulated surveys, PPI offers a way to use them without inheriting their biases, provided some real data are available to rectify.
- Selection with e-values. Lesson 25’s e-values combine well with selection: Wang and Ramdas’ e-BH procedure controls FDR with e-values under arbitrary dependence, and e-values permit selection and reporting with guarantees simpler than conditional ones.
- Connections to other modules. Conformal prediction (module 30) shares finite-sample black-box guarantees with knockoffs and PPI; double machine learning (module 27) corrects prediction bias with holdout data, like the rectifier; LLM evaluation (module 20) and benchmark model comparison (module 31) directly use PPI and winner’s-curse correction.
- Knockoffs with non-Gaussian covariates. Constructions exist for hidden Markov chains (genotypes), graphical models and generative-network approximations, but robustness when distribution is misspecified remains a central practical problem.
Common mistakes
Exercises
Step 1 of 4. What is ?
Step 1 of 4. How is the selection event rewritten?
filtro_knockoff(W, q, plus=True), returning a sorted array of indices selected by the knockoff filter. The threshold is the smallest among nonzero such that , with if plus and otherwise; if no satisfies it, select nothing. Tests include hand cases and a simulation with coin-flip signs for null as guaranteed by theory, checking that FDR stays below .import numpy as np
def filtro_knockoff(W, q, plus=True):
"""Índices j (ordenados) con W_j >= T, siendo T el umbral de knockoff (+)."""
W = np.asarray(W, dtype=float)
# tu código: recorre los |W_j| no nulos de menor a mayor y quédate con el primero que cumple la condición
return np.array([], dtype=int)Summary
- The winner’s classical interval among null candidates covers (60 % with ), and its estimate systematically overstates: the winner’s curse.
- Sample splitting and data fission provide straightforward validity at the cost of power; Gaussian fission , splits information from one observation into two independent parts.
- The polyhedral lemma turns polyhedral selection (maximum, lasso, forward steps) into truncation of to ; inverting the truncated-normal pivot gives exact conditional intervals, wide near the boundary. The parameter covered belongs to the selected submodel.
- PoSI covers all submodels at once and is therefore valid for any rule, even informal, at the cost of wider intervals.
- Model-X knockoffs mimic covariate dependence without a relationship to ; null signs are coin flips, and knockoff+ controls finite-sample FDR with any importance model provided the distribution of is well known.
- PPI subtracts bias measured on labeled data from mean predictions: it is unbiased for any fixed predictor, its variance is , and PPI++ chooses predictor weight to be asymptotically no worse than classical inference. Rectified loss extends it to any M-estimator.