Module contents
Lesson 27 of 27Research 115 min

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

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 ±2\pm 2 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 pp 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 pp 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 mm candidates with true effects μ1,…,μm\mu_1, \dots, \mu_m (accuracies, treatment effects, or anything else), each with an independent estimate Xi∼N(μi,1)X_i \sim \Normal(\mu_i, 1). They are standardized: the unit is each estimate’s standard error. Choose winner i∗=arg max⁡iXii^* = \argmax_i X_i and seek an interval for μi∗\mu_{i^*}.

The naive interval is Xi∗±1.96X_{i^*} \pm 1.96. If all effects are null, μi=0\mu_i = 0, it covers exactly when ∣Xi∗∣≤1.96\abs{X_{i^*}} \le 1.96, and since Xi∗=max⁡iXiX_{i^*} = \max_i X_i,

P(∣Xi∗∣≤1.96)=P(max⁡iXi≤1.96)−P(max⁡iXi<−1.96)=Φ(1.96)m−Φ(−1.96)m.\Pr\big(\abs{X_{i^*}} \le 1.96\big) = \Pr\Big(\max_i X_i \le 1.96\Big) - \Pr\Big(\max_i X_i < -1.96\Big) = \Phi(1.96)^m - \Phi(-1.96)^m.

With m=20m = 20 this gives 0.97520−0.02520≈0.6030.975^{20} - 0.025^{20} \approx 0.603: the “95 % interval” covers 60 % of the time. The point estimate is biased too: E[max⁡iXi]≈1.87\E[\max_i X_i] \approx 1.87 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, P(θs∈Cs ∀s)≥1−α\Pr(\theta_s \in C_s \ \forall s) \ge 1 - \alpha, 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.

InteractiveThe winner's interval
Naive
6 of 25 miss
Selective (truncated normal)
0 of 25 miss
Sample splitting
1 of 25 miss
Simultaneous (Bonferroni)
0 of 25 miss
Selected-parameter coverage and median width over 2000 repetitions (line: 95%)
Naive
60.4 % · width 3.92
Selective (truncated normal)
95.6 % · width 12.23
Sample splitting
95.3 % · width 5.54
Simultaneous (Bonferroni)
97.7 % · width 6.05
Panel axis: interval endpoints minus the selected candidate’s true effect. Arrows show intervals extending outside the plot.
True effects
3.0
20
50 %
Winner bias E[Xi∗−μi∗]\E[X_{i^*} - \mu_{i^*}]1.857
Coverage: naive | selective60.4 % | 95.6 %
Coverage: split | simultaneous95.3 % | 97.7 %
All effects are zero and the winner overestimates by 1.86 on average: expected for the maximum of 20 normal variables. The naive interval covers 60 % of the time; the other three cover 95% apart from Monte Carlo error.
Simulate mm effects, choose the largest and construct an interval using four methods. In the upper panels each row is a repetition: the interval is shifted by the selected effect's true value, so it covers if it crosses the vertical line; red rows fail. Below, coverage and median width across 2000 repetitions. Start with 20 null effects: how often does the naive interval cover and on which side do red rows fail? Switch to “One stands out” and increase effect size: what happens to the selective interval when the winner is clear? Move the split fraction: what do you gain and lose?

The figure shows four things the rest of the lesson explains:

  1. 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.
  2. 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.
  3. Sample splitting covers with fixed width 2⋅1.962≈5.542 \cdot 1.96\sqrt{2} \approx 5.54 when half is held out, but targets the candidate chosen with the other half, which selects the true best less often.
  4. The simultaneous interval (Bonferroni for mm means, Xi∗±z1−α/(2m)X_{i^*} \pm z_{1 - \alpha/(2m)}, with z1−0.05/40≈3.02z_{1 - 0.05/40} \approx 3.02 for m=20m = 20) covers at least 95 % in any scenario with fixed width 6.056.05, without knowing the selection rule: since it covers all mm 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 Y=(Y(1),Y(2))Y = (Y^{(1)}, Y^{(2)}) with independent parts and selection depends only on Y(1)Y^{(1)}, then conditioning on S^=s\hat{S} = s does not change the distribution of Y(2)Y^{(2)}: any procedure valid for fixed θs\theta_s remains valid. There is nothing else to prove.

The cost is power. With fraction pp of data for selection, inference uses 1−p1 - p and standard error is multiplied by 1/1−p1/\sqrt{1 - p}; with p=1/2p = 1/2, by 2≈1.41\sqrt{2} \approx 1.41. An effect of 3 standard errors with all data, detected by a two-sided 5 % test with probability Φ(3−1.96)+Φ(−3−1.96)≈0.85\Phi(3 - 1.96) + \Phi(-3 - 1.96) \approx 0.85, becomes 3/2≈2.123/\sqrt{2} \approx 2.12 and is detected with probability 0.560.56. 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 X\mat{X}. 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

(f,g)(\vb{f}, \vb{g}) is a linear transformation of Gaussian vector (X,Z)(\vb{X}, \vb{Z}), hence jointly Gaussian; for jointly Gaussian vectors, zero correlation is equivalent to independence. Calculate cross-covariance using X⊥ ⁣ ⁣ ⁣⊥Z\vb{X} \indep \vb{Z}:

Cov⁡(f,g)=Cov⁡(X,X)−1τCov⁡(X,Z)+τCov⁡(Z,X)−Cov⁡(Z,Z)=Σ−0+0−Σ=0.\Cov(\vb{f}, \vb{g}) = \Cov(\vb{X}, \vb{X}) - \tfrac{1}{\tau}\Cov(\vb{X}, \vb{Z}) + \tau\Cov(\vb{Z}, \vb{X}) - \Cov(\vb{Z}, \vb{Z}) = \mat{\Sigma} - \mat{0} + \mat{0} - \mat{\Sigma} = \mat{0}.

Means are μ\vb{\mu} because EZ=0\E\vb{Z} = \vb{0}, and covariances are Σ+τ2Σ\mat{\Sigma} + \tau^2\mat{\Sigma} and Σ+τ−2Σ\mat{\Sigma} + \tau^{-2}\mat{\Sigma}. Reconstruction is algebra: f+τ2g=(1+τ2)X+τZ−τZ\vb{f} + \tau^2\vb{g} = (1 + \tau^2)\vb{X} + \tau\vb{Z} - \tau\vb{Z}.

∎

Parameter τ\tau divides Fisher information: f\vb{f} keeps fraction 1/(1+τ2)1/(1 + \tau^2) and g\vb{g} keeps τ2/(1+τ2)\tau^2/(1 + \tau^2), summing to 1. For a Gaussian sample mean, fission with τ=1\tau = 1 has exactly the same distribution as splitting the sample in half, and generally equals a split with fraction p=1/(1+τ2)p = 1/(1 + \tau^2). Fission works with a single observation, any fraction (not just multiples of 1/n1/n), and without changing the design. Other families have versions too: for counts, if X∼Pois⁡(μ)X \sim \Pois(\mu) and Z∣X∼Bin⁡(X,p)Z \given X \sim \Bin(X, p), then Z∼Pois⁡(pμ)Z \sim \Pois(p\mu) and X−Z∼Pois⁡((1−p)μ)X - Z \sim \Pois((1 - p)\mu) are independent (Poisson thinning); for Bernoulli and other exponential families, constructions exist where gg is not independent of ff 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 X1≥XjX_1 \ge X_j for all jj. To infer μ1\mu_1 conditional on this, also fix what is not X1X_1, namely X2,…,XmX_2, \dots, X_m, which by independence does not inform μ1\mu_1. Conditional on all this, X1X_1 remains N(μ1,1)\Normal(\mu_1, 1) but restricted to [max⁡j≠1Xj,∞)[\max_{j \ne 1} X_j, \infty): 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. (z,η⊤y)(\vb{z}, \vb{\eta}\T\vb{y}) is a linear transformation of y\vb{y}, hence jointly Gaussian, and

Cov⁡(z,η⊤y)=Cov⁡(y,η⊤y)−cVar⁡(η⊤y)=Ση−Σηη⊤Ση η⊤Ση=0.\Cov(\vb{z}, \vb{\eta}\T\vb{y}) = \Cov(\vb{y}, \vb{\eta}\T\vb{y}) - \vb{c}\Var(\vb{\eta}\T\vb{y}) = \mat{\Sigma}\vb{\eta} - \frac{\mat{\Sigma}\vb{\eta}}{\vb{\eta}\T\mat{\Sigma}\vb{\eta}}\,\vb{\eta}\T\mat{\Sigma}\vb{\eta} = \vb{0}.

This is Gaussian regression of y\vb{y} on η⊤y\vb{\eta}\T\vb{y}: z\vb{z} is the residual and c\vb{c} the coefficient.

Polyhedron decomposition. Write t=η⊤yt = \vb{\eta}\T\vb{y}, so y=z+c t\vb{y} = \vb{z} + \vb{c}\,t. Then Ay≤b\mat{A}\vb{y} \le \vb{b} is equivalent to (Ac)j t≤bj−(Az)j(\mat{A}\vb{c})_j\,t \le b_j - (\mat{A}\vb{z})_j for each row jj. If (Ac)j>0(\mat{A}\vb{c})_j > 0, division gives an upper bound for tt; if negative, the inequality reverses and gives a lower bound; if zero, the row does not depend on tt and requires only bj−(Az)j≥0b_j - (\mat{A}\vb{z})_j \ge 0. Taking the largest lower bound and smallest upper bound gives the result.

Conditional distribution. Since t⊥ ⁣ ⁣ ⁣⊥zt \indep \vb{z}, conditioning on z\vb{z} does not change the distribution of tt, which is N(θ,η⊤Ση)\Normal(\theta, \vb{\eta}\T\mat{\Sigma}\vb{\eta}). The selection event given z\vb{z} is exactly t∈[V−(z),V+(z)]t \in [\mathcal{V}^-(\vb{z}), \mathcal{V}^+(\vb{z})] (with V0≥0\mathcal{V}^0 \ge 0, depending only on z\vb{z}), and conditioning a variable on belonging to an interval truncates it there.

∎

This is the polyhedral lemma. Its practical consequence is a pivot. Let Fθ,σ2[a,b]F^{[a, b]}_{\theta, \sigma^2} be the distribution function of normal N(θ,σ2)\Normal(\theta, \sigma^2) truncated to [a,b][a, b]. Conditional on selection,

Fθ, η⊤Ση[V−,V+](η⊤y)∼Unif⁡(0,1),F^{[\mathcal{V}^-, \mathcal{V}^+]}_{\theta,\ \vb{\eta}\T\mat{\Sigma}\vb{\eta}}\big(\vb{\eta}\T\vb{y}\big) \sim \Unif(0, 1),

because additionally conditioning on z\vb{z} makes it the probability integral transform of a continuous variable, and a variable uniform conditional on each value of z\vb{z} is also uniform when averaged over z\vb{z}. Since the truncated family has monotone likelihood ratio in θ\theta, Fθ(t)F_\theta(t) decreases in θ\theta for each fixed tt, and the selective interval is

C={θ:α/2≤Fθ, η⊤Ση[V−,V+](η⊤y)≤1−α/2}=[θinf,θsup],C = \big\{\theta : \alpha/2 \le F^{[\mathcal{V}^-, \mathcal{V}^+]}_{\theta,\ \vb{\eta}\T\mat{\Sigma}\vb{\eta}}(\vb{\eta}\T\vb{y}) \le 1 - \alpha/2\big\} = [\theta_{\text{inf}}, \theta_{\text{sup}}],

where endpoints solve Fθ(t)=1−α/2F_\theta(t) = 1 - \alpha/2 and Fθ(t)=α/2F_\theta(t) = \alpha/2 by bisection. It has exact 1−α1 - \alpha coverage conditional on selection.

InteractiveSelection as truncation
Selection region xˉ1≥xˉ2\bar x_1 \ge \bar x_2 and line z+c t\vb{z} + \vb{c}\,t
  • μ1\mu_1 is reported
  • truncation along the line
  • z=y−c xˉ1\vb{z} = \vb{y} - \vb{c}\,\bar x_1, fixed by conditioning
Conditional density of xˉ1\bar x_1 at the selective interval endpoints
Dashed: μ1=−4.39\mu_1 = −4.39, leaves 2.5 %2.5\,\% above xˉ1\bar x_1. Solid: μ1=3.75\mu_1 = 3.75, leaves 2.5 %2.5\,\% below.
naiveselective
0.00
Truncation set for xˉ1\bar x_1[1.30, ∞]
Naive 95% interval[−0.06, 3.86]
Selective 95% interval[−4.39, 3.75]
p-value for μ1=0\mu_1 = 0: naive | selective0.0574 | 0.5933
The point is 0.60 from the boundary: almost any very negative μ1\mu_1 explains landing just inside, and the selective interval has width 8.1.
Two observed means y=(xˉ1,xˉ2)\vb{y} = (\bar x_1, \bar x_2) with correlation ρ\rho. The shaded region contains data for which μ1\mu_1 would be reported. The dashed line is z+c t\vb{z} + \vb{c}\,t: conditioning on z\vb{z} restricts the datum to that line (with ρ=0\rho = 0, only xˉ1\bar x_1 changes), and its section inside the region is the truncation. The second panel shows truncated densities at both selective-interval endpoints. Drag the point toward the region boundary: why does the interval explode? Move it away: what does it resemble? Try “only if significant” (published papers) and the absolute-value rule, whose truncation is two intervals. With ρ≠0\rho \ne 0 the line tilts: why?

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 μ1\mu_1: if the winner is 2.52.5 and runner-up 2.42.4, the selective interval is [−34.4,3.55][-34.4, 3.55]. This is information, not a defect: barely passing the filter says very little about the effect. The “report only if xˉ1≥1.96\bar x_1 \ge 1.96” 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 β^=arg min⁡β12∥y−Xβ∥2+λ∥β∥1\hat{\vb{\beta}} = \argmin_{\vb{\beta}} \tfrac{1}{2}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1, optimality conditions are X⊤(y−Xβ^)=λs^\mat{X}\T(\vb{y} - \mat{X}\hat{\vb{\beta}}) = \lambda\hat{\vb{s}}, with s^j=sign⁡(β^j)\hat{s}_j = \operatorname{sign}(\hat\beta_j) if β^j≠0\hat\beta_j \ne 0 and ∣s^j∣≤1\abs{\hat s_j} \le 1 otherwise. Fix active set EE and its signs s\vb{s}:

  • In the active set, β^E=(XE⊤XE)−1(XE⊤y−λs)\hat{\vb{\beta}}_E = (\mat{X}_E\T\mat{X}_E)\inv(\mat{X}_E\T\vb{y} - \lambda\vb{s}), and requiring diag⁡(s)β^E>0\operatorname{diag}(\vb{s})\hat{\vb{\beta}}_E > \vb{0} gives linear inequalities in y\vb{y}.
  • Outside it, ∣X−E⊤(y−XEβ^E)∣<λ\abs{\mat{X}_{-E}\T(\vb{y} - \mat{X}_E\hat{\vb{\beta}}_E)} < \lambda componentwise, again linear in y\vb{y} because β^E\hat{\vb{\beta}}_E is affine in y\vb{y}.

Thus {E^=E,s^=s}\{\hat E = E, \hat{\vb{s}} = \vb{s}\} is a polyhedron, and the lemma gives exact conditional intervals for each selected-model coefficient. Pay attention to which parameter they cover: θ=η⊤μ\theta = \vb{\eta}\T\vb{\mu} with η=XE(XE⊤XE)−1ej\vb{\eta} = \mat{X}_E(\mat{X}_E\T\mat{X}_E)\inv\vb{e}_j, namely coefficient jj of the projection of Ey\E\vb{y} onto selected columns. It is not the full model’s “true βj\beta_j”, 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 E^=E\hat E = E (a union of 2∣E∣2^{\abs{E}} 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 Σ\mat{\Sigma} 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 tj⋅Mt_{j \cdot M} be the tt statistic of coefficient jj in submodel MM (with j∈Mj \in M). PoSI constant KK is the 1−α1 - \alpha quantile of max⁡Mmax⁡j∈M∣tj⋅M∣\max_M \max_{j \in M} \abs{t_{j \cdot M}}. Intervals β^j⋅M^±K se^j⋅M^\hat\beta_{j \cdot \hat M} \pm K\,\widehat{\text{se}}_{j \cdot \hat M} then cover with probability at least 1−α1 - \alpha whatever rule M^\hat M is used, because all cover simultaneously. The price is width: with pp variables there are order p 2p−1p\,2^{p-1} pairs (j,M)(j, M), KK ranges from about 2log⁡p\sqrt{2\log p} in orthogonal designs to order p\sqrt{p} of Scheffé’s constant in unfavorable designs, and its computation is exponential in pp. For the maximum mean, PoSI reduces to covering all mm means simultaneously, which the first figure’s Bonferroni interval does slightly conservatively (the exact Šidák constant for 20 independent means is 3.0163.016 instead of 3.0233.023).

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 pp candidates (genes, model features, market signals), which truly influence response YY? We want to control FDR, the expected proportion of selected variables that are null. Lesson 18’s Benjamini–Hochberg method needs valid pp values for each variable. In high dimensions, with a nonlinear model or when p>np > n, 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 XjX_j construct a fake copy X~j\tilde X_j, the knockoff, perfectly mimicking how XjX_j relates to other variables but, by construction, unrelated to YY beyond what passes through XX. 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 YY and XX (it can be any black-box model), but the distribution of XX 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, G\mat{G} is a valid covariance. Its Schur complement with respect to block Σ\mat{\Sigma} is Σ−(Σ−D)Σ−1(Σ−D)=2D−DΣ−1D=D1/2(2I−BB⊤)D1/2\mat{\Sigma} - (\mat{\Sigma} - \mat{D})\mat{\Sigma}\inv(\mat{\Sigma} - \mat{D}) = 2\mat{D} - \mat{D}\mat{\Sigma}\inv\mat{D} = \mat{D}^{1/2}\big(2\mat{I} - \mat{B}\mat{B}\T\big)\mat{D}^{1/2}, with B=D1/2Σ−1/2\mat{B} = \mat{D}^{1/2}\mat{\Sigma}^{-1/2}. Assumption 2Σ−D⪰02\mat{\Sigma} - \mat{D} \succeq \mat{0} is equivalent, multiplying by Σ−1/2\mat{\Sigma}^{-1/2} on each side, to B⊤B=Σ−1/2DΣ−1/2⪯2I\mat{B}\T\mat{B} = \mat{\Sigma}^{-1/2}\mat{D}\mat{\Sigma}^{-1/2} \preceq 2\mat{I}; since BB⊤\mat{B}\mat{B}\T and B⊤B\mat{B}\T\mat{B} have the same eigenvalues, also BB⊤⪯2I\mat{B}\mat{B}\T \preceq 2\mat{I}, so the Schur complement is positive semidefinite. If (X,X~)∼N(0,G)(X, \tilde X) \sim \Normal(\vb{0}, \mat{G}), Gaussian conditioning gives E[X~∣X]=(Σ−D)Σ−1X=X−DΣ−1X\E[\tilde X \given X] = (\mat{\Sigma} - \mat{D})\mat{\Sigma}\inv X = X - \mat{D}\mat{\Sigma}\inv X and Cov⁡(X~∣X)=2D−DΣ−1D\Cov(\tilde X \given X) = 2\mat{D} - \mat{D}\mat{\Sigma}\inv\mat{D}, the stated law; conversely, generating X~\tilde X this way produces that joint vector.

Exchangeability: swapping XjX_j and X~j\tilde X_j simultaneously permutes rows and columns jj and p+jp + j of G\mat{G}. Both variances are Σjj\Sigma_{jj}; for k≠jk \ne j, Cov⁡(Xj,Xk)=Cov⁡(X~j,X~k)=Cov⁡(Xj,X~k)=Σjk\Cov(X_j, X_k) = \Cov(\tilde X_j, \tilde X_k) = \Cov(X_j, \tilde X_k) = \Sigma_{jk}, and Cov⁡(Xj,X~j)=Σjj−sj\Cov(X_j, \tilde X_j) = \Sigma_{jj} - s_j is symmetric in the pair. Thus G\mat{G} is unchanged, and a centered Gaussian is determined by covariance. Conditional independence holds because X~\tilde X is generated from XX and external noise.

∎

Vector s\vb{s} determines knockoff quality. Since Cov⁡(Xj,X~j)=Σjj−sj\Cov(X_j, \tilde X_j) = \Sigma_{jj} - s_j, a large sjs_j makes X~j\tilde X_j very different from XjX_j and distinguishes original from copy; with sj=0s_j = 0, X~j=Xj\tilde X_j = X_j and the method has no power. With standardized variables, the equicorrelated choice is sj=min⁡(1,2λmin⁡(Σ))s_j = \min(1, 2\lambda_{\min}(\mat{\Sigma})) for every jj; the usual alternative maximizes ∑jsj\sum_j s_j by semidefinite programming. With highly correlated covariates, λmin⁡(Σ)\lambda_{\min}(\mat{\Sigma}) is small and knockoffs resemble originals too closely: a known limitation.

The filter

With [X,X~]∈Rn×2p[\mat{X}, \tilde{\mat{X}}] \in \R^{n \times 2p} calculate for each jj a statistic WjW_j that is large and positive when XjX_j seems more important than X~j\tilde X_j, and changes sign when the two columns swap. The most used is lasso coefficient difference (LCD): fit lasso of y\vb{y} on 2p2p columns and

Wj=∣β^j∣−∣β^j~∣.W_j = \abs{\hat\beta_j} - \abs{\hat\beta_{\tilde j}}.

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 SS is a set of null variables, swapping XjX_j and X~j\tilde X_j for j∈Sj \in S leaves the joint distribution of ([X,X~],y)([\mat{X}, \tilde{\mat{X}}], \vb{y}) unchanged: exchangeability guarantees this for covariates, and conditional independence together with YY not depending on XjX_j given the rest extends it to the response. But the swap flips sign of WjW_j for j∈Sj \in S and leaves others unchanged. Thus flipping any subset of null signs does not change the distribution of WW, exactly the theorem.

The consequence is a mirror: for any threshold t>0t > 0, the number of nulls with Wj≥tW_j \ge t has the same distribution as those with Wj≤−tW_j \le -t. Since signals tend to give large positive WjW_j, almost everything in {Wj≤−t}\{W_j \le -t\} is null. Thus #{j:Wj≤−t}\#\{j : W_j \le -t\} estimates conservatively the null count among selected {Wj≥t}\{W_j \ge t\}.

Proof

Let V+(t)=#{j nula:Wj≥t}V^+(t) = \#\{j \text{ nula} : W_j \ge t\} and V−(t)=#{j nula:Wj≤−t}V^-(t) = \#\{j \text{ nula} : W_j \le -t\}. On TT,

FDP=V+(T)max⁡(1,#{Wj≥T})=V+(T)1+V−(T)⋅1+V−(T)max⁡(1,#{Wj≥T})≤V+(T)1+V−(T)⋅q,\mathrm{FDP} = \frac{V^+(T)}{\max(1, \#\{W_j \ge T\})} = \frac{V^+(T)}{1 + V^-(T)} \cdot \frac{1 + V^-(T)}{\max(1, \#\{W_j \ge T\})} \le \frac{V^+(T)}{1 + V^-(T)} \cdot q,

because V−(T)≤#{j:Wj≤−T}V^-(T) \le \#\{j : W_j \le -T\} and TT satisfies the threshold condition. It remains to show E[V+(T)/(1+V−(T))]≤1\E[V^+(T)/(1 + V^-(T))] \le 1. Order nulls by ∣Wj∣\abs{W_j} and traverse thresholds from low to high, the order in which the filter seeks TT: by the coin-flip theorem each null contributes to V+V^+ or V−V^- with probability 1/21/2 independently of the rest. Barber and Candès show V+(t)/(1+V−(t))V^+(t)/(1 + V^-(t)) is a supermartingale for the filtration revealing signs as the threshold rises, and TT is a stopping time for it. By optional sampling, its expectation at TT is bounded by expectation at the initial threshold when all m0m_0 nulls count: V+∼Bin⁡(m0,1/2)V^+ \sim \Bin(m_0, 1/2), V−=m0−V+V^- = m_0 - V^+, and direct calculation gives E[V+/(1+m0−V+)]=1−2−m0≤1\E[V^+/(1 + m_0 - V^+)] = 1 - 2^{-m_0} \le 1.

∎

Notably the theorem needs no pp values, correct linear model, n>pn > p, or asymptotics. Everything rests on knockoff exchangeability, which depends on knowing the distribution of XX well.

InteractiveThe knockoff mirror
Each feature’s importance versus its knockoff
Horizontal: original ∣β^j∣\abs{\hat\beta_j}; vertical: knockoff ∣β^j~∣\abs{\hat\beta_{\tilde j}}. 19 features have zero importance for both and overlap at the origin.
  • signal
  • null
  • selected Wj≥tW_j \ge t
  • mirror Wj≤−tW_j \le -t
False discovery proportion versus threshold
q = 0.20
  • Estimated FDP (knockoff+)
  • Actual FDP
  • current threshold tt
0.110
0.20
0.22
0.30
Selected | in mirror13 | 1
Estimated FDP (1+#{Wj≤−t})/#{Wj≥t}(1 + \#\{W_j \le -t\})/\#\{W_j \ge t\}0.154
Actual FDP | power0.154 | 73 %
Knockoff+ threshold TT0.1095
Knockoff+ threshold: T = 0.110. It selects 13 features; the mirror contains 1, giving estimated FDP (1 + 1)/13 = 0.15. Actual FDP, invisible to the filter, is 0.15.
Each point is one of 60 variables (15 are signal): horizontal is original importance, ∣β^j∣\abs{\hat\beta_j}; vertical is knockoff importance. Nulls are symmetric around the diagonal; signals escape toward the lower right. Green is selected, Wj≥tW_j \ge t, red its mirror, Wj≤−tW_j \le -t. The second panel shows mirror-estimated and true FDP versus threshold. Move tt and check that the mirror follows true FDP without knowing it. Hide truth: what remains visible? Raise correlation ρ\rho: why do points hug the axes? Press “Estimate FDR” to average 100 datasets.

In the figure, true FDP for one dataset can exceed qq (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 ⌈1/q⌉\lceil 1/q \rceil selections (5 with q=0.2q = 0.2 and 10 with q=0.1q = 0.1), even in the best case with no mirror points. That +1+1 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 θ\theta (disease prevalence in images, an LLM’s correct-answer rate, a regression coefficient for an expensive-to-measure variable) and have:

  • nn expensive labeled examples (Xi,Yi)(X_i, Y_i): a doctor, human annotator, laboratory experiment;
  • N≫nN \gg n cheap unlabeled examples X~i\tilde X_i;
  • a predictor ff (ML model, language-model judge) giving f(X)≈Yf(X) \approx Y, trained on other data.

There are two obvious answers and neither is good. The classical one ignores predictions and uses only nn labels: valid but wide. The naive one replaces YY with f(X~)f(\tilde X) in NN examples: it gives an extremely narrow interval centered on the wrong value because predictor bias passes unchanged into the conclusion, and width decreasing like 1/N1/\sqrt{N} makes the conclusion look very certain. Angelopoulos, Bates, Fannjiang, Jordan and Zrnic (2023) proposed the correct combination.

If predictor ff 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 σf2/N+σf−Y2/n\sigma_f^2/N + \sigma_{f - Y}^2/n for any ff, 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 σY2/n\sigma_Y^2/n. When N→∞N \to \infty, PPI’s is σY−f2/n\sigma_{Y - f}^2/n: PPI is like classical inference applied to predictor errors instead of YY. If the predictor explains fraction R2R^2 of variance of YY without bias, σY−f2=(1−R2)σY2\sigma_{Y - f}^2 = (1 - R^2)\sigma_Y^2 and PPI is equivalent to having n/(1−R2)n/(1 - R^2) labels: with R2=0.8R^2 = 0.8, 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.

InteractiveFew labels, many predictions
Classic (labels only)
2 of 30 miss
Naive (predictions only)
30 of 30 miss
PPI
0 of 30 miss
Theoretical interval width versus nn, with N=10,000N = 10,000 and R2=0.80R^2 = 0.80
n = 100
  • Classic (labels only)
  • Naive (predictions only)
  • PPI
Variances: classic 1/n1/n; naive R2/NR^2/N (but centered at θ+b\theta + b); PPI R2/N+(1−R2)/nR^2/N + (1 - R^2)/n. With N≫nN \gg n, PPI behaves like a classic interval with n/(1−R2)n/(1 - R^2) labels. The chart excludes leakage: under leakage these formulas no longer hold.
100
10,000
0.80
0.20
Coverage: classic | naive96.5 % | 0.0 %
PPI coverage95.1 %
Mean width: classic | PPI0.390 | 0.179
nn effective for PPI =1/Var⁡(θ^PP)= 1/\Var(\hat\theta^{\mathrm{PP}})481
The naive interval is very narrow and centered at θ + b: its coverage is 0 %. PPI corrects bias with the rectifier and covers 95 %, with width 0.46 times the classic interval.
One thousand simulated experiments with Var⁡Y=1\Var Y = 1: nn labeled, NN unlabeled, and a predictor of quality R2R^2 and bias bb. Each panel shows 30 intervals from one method (the vertical line is true mean θ\theta; red intervals fail), with theoretical width versus nn below. At the initial bias, inspect naive intervals: extremely narrow and nearly always missing. Set b=0b = 0: does naive coverage return? Lower R2R^2 toward 0: what remains of PPI's advantage? Enable PPI++ and compare its width with PPI. Finally enable leakage, simulating training the predictor on the same labeled data.

The figure answers three questions. At initial bias b=0.2b = 0.2, naive intervals never cover because width is tiny relative to bias, while PPI covers 95 %. With b=0b = 0 naive coverage holds in this model, but that cannot be checked without labels, which the naive method lacks. With R2=0R^2 = 0 the figure’s predictor is constant and PPI equals classical inference: no gain or loss. A worse-than-useless predictor that varies independently of YY would make PPI worse than classical inference by adding prediction variance without removing anything: σY−f2=σY2+σf2\sigma_{Y - f}^2 = \sigma_Y^2 + \sigma_f^2 when ff is independent of YY. PPI++ resolves this.

PPI++: choosing how much to trust the predictor

Angelopoulos, Duchi and Zrnic (2023) introduced a weight λ\lambda:

θ^λ=1n∑i=1nYi+λ(1N∑i=1Nf(X~i)−1n∑i=1nf(Xi)).\hat\theta_\lambda = \frac{1}{n}\sum_{i=1}^n Y_i + \lambda\left(\frac{1}{N}\sum_{i=1}^N f(\tilde X_i) - \frac{1}{n}\sum_{i=1}^n f(X_i)\right).

With λ=0\lambda = 0 it is classical; with λ=1\lambda = 1, PPI. For any fixed λ\lambda it remains unbiased, since the parenthesized term has zero expectation. Its variance is

Var⁡(θ^λ)=σY2−2λCov⁡(Y,f)+λ2σf2n+λ2σf2N,\Var(\hat\theta_\lambda) = \frac{\sigma_Y^2 - 2\lambda\Cov(Y, f) + \lambda^2\sigma_f^2}{n} + \frac{\lambda^2\sigma_f^2}{N},

a parabola in λ\lambda minimized at

λ∗=Cov⁡(Y,f)(1+n/N) σf2.\lambda^* = \frac{\Cov(Y, f)}{(1 + n/N)\,\sigma_f^2}.

This is the Monte Carlo control variate formula: the predictor is a control variate whose mean is known nearly exactly thanks to NN unlabeled examples. With λ^\hat\lambda estimated from data, the estimator is asymptotically as good as with λ∗\lambda^* and, since λ=0\lambda = 0 is an option, never asymptotically worse than classical inference: a useless predictor receives λ^≈0\hat\lambda \approx 0 and is ignored.

Beyond the mean: M-estimators

The idea extends to any M-estimator θ∗=arg min⁡θE[ℓθ(X,Y)]\theta^* = \argmin_\theta \E[\ell_\theta(X, Y)] (means, quantiles, linear and logistic regression). The rectified loss

LPP(θ)=1N∑i=1Nℓθ(X~i,f(X~i))+1n∑i=1n(ℓθ(Xi,Yi)−ℓθ(Xi,f(Xi)))L^{\text{PP}}(\theta) = \frac{1}{N}\sum_{i=1}^N \ell_\theta\big(\tilde X_i, f(\tilde X_i)\big) + \frac{1}{n}\sum_{i=1}^n \Big(\ell_\theta(X_i, Y_i) - \ell_\theta\big(X_i, f(X_i)\big)\Big)

is an unbiased estimator of E[ℓθ(X,Y)]\E[\ell_\theta(X, Y)] for each θ\theta, and θ^PP=arg min⁡LPP\hat\theta^{\text{PP}} = \argmin L^{\text{PP}}. By asymptotic M-estimator theory, θ^PP\hat\theta^{\text{PP}} is asymptotically normal with sandwich variance

H−1(VΔ+nNVf)H−1/n,H=∇2 E[ℓθ∗],Vf=Cov⁡(∇ℓθ∗(X,f(X))),VΔ=Cov⁡(∇ℓθ∗(X,Y)−∇ℓθ∗(X,f(X))).\mat{H}\inv\Big(\mat{V}_\Delta + \tfrac{n}{N}\mat{V}_f\Big)\mat{H}\inv / n, \qquad \mat{H} = \hess\,\E[\ell_{\theta^*}], \quad \mat{V}_f = \Cov\big(\grad\ell_{\theta^*}(X, f(X))\big), \quad \mat{V}_\Delta = \Cov\big(\grad\ell_{\theta^*}(X, Y) - \grad\ell_{\theta^*}(X, f(X))\big).

For least-squares linear regression a closed form used in the original paper exists: the PPI coefficient regresses predictions on covariates in NN unlabeled examples, minus the regression of errors f(X)−Yf(X) - Y on covariates in nn labeled examples,

θ^PP=(X~⊤X~)−1X~⊤f(X~)−(X⊤X)−1X⊤(f(X)−y),\hat{\vb{\theta}}^{\text{PP}} = (\tilde{\mat{X}}\T\tilde{\mat{X}})\inv\tilde{\mat{X}}\T f(\tilde{\mat{X}}) - (\mat{X}\T\mat{X})\inv\mat{X}\T\big(f(\mat{X}) - \vb{y}\big),

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).

[ ]Selective interval, splitting and fission from scratchBrowser
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 0.6030.603) 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 5.545.54 wide. Splitting and fission give interchangeable results, as the fission theorem predicts with τ=1\tau = 1.

Lasso and p-values in the final regression

The most widespread mistake: choose variables using data and then read pp values from regression on those selected. The simulation uses the global null (YY depends on none of 30 variables) and chooses the 3 most correlated with YY, the first three lasso or forward selection would add.

[ ]P-values after variable selectionBrowser
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 pp 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 ss slightly below 2λmin⁡2\lambda_{\min} so conditional covariance is nonsingular and Cholesky factorization works.

[ ]Gaussian knockoffs and the knockoff+ filterBrowser
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 ρ=0.6\rho = 0.6, where s=2λmin⁡=0.8s = 2\lambda_{\min} = 0.8: covariance between a variable and its knockoff is Σ11−s≈0.2\Sigma_{11} - s \approx 0.2 and cross-covariance with another variable equals that between originals. The second checks the theorem: mean FDR stays below q=0.2q = 0.2 (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 x2x_2 is weaker), producing realistic bias. The large population and its predictions are calculated once; each repetition draws n=100n = 100 labeled and N=10 000N = 10\,000 unlabeled cases. Estimands are the mean of YY and slope of x3x_3 in linear regression Y∼1+x3Y \sim 1 + x_3.

[ ]PPI from scratch: mean and regression coefficientBrowser
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 x2x_2 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 YY explained by x3x_3 (45 % of its variance in this population): PPI can save only the part of the residual from regressing YY on x3x_3 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 (n=200n = 200) and many model-judge judgments (N=5000N = 5000). Labels are binary: Yi=1Y_i = 1 if the human accepts the answer and f(Xi)=1f(X_i) = 1 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.

[ ]LLM accuracy: humans, judge and PPIBrowser
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 bueno

With a lenient judge (approving 40 % of bad answers), its bias +0.05+0.05 makes naive intervals never cover, PPI barely narrows the classical interval, and PPI++ narrows it somewhat more by reducing judge weight to λ≈0.54\lambda \approx 0.54. 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 XX distribution is misspecified remains a central practical problem.

Common mistakes

Exercises

NumericThe winner's coverage
There are m=10m = 10 candidates with zero true effects and independent estimates Xi∼N(0,1)X_i \sim \Normal(0, 1). Select the largest and give it the naive interval Xi∗±1.96X_{i^*} \pm 1.96. What is its actual coverage? Give a number between 0 and 1.
NumericHow much PPI narrows
With nn labeled cases, infinitely many unlabeled examples and a predictor whose residual Y−f(X)Y - f(X) has variance 0.20.2, versus variance of YY equal to 1, what is the ratio of PPI's standard error to the classical estimator's?
NumericSplitting information with fission
With Gaussian fission f=X+τZf = X + \tau Z, g=X−Z/τg = X - Z/\tau and X∼N(μ,1)X \sim \Normal(\mu, 1), you want inference part gg to retain 80 % of the Fisher information in XX about μ\mu. What τ\tau is needed?
NumericMinimum knockoff+ selections
With the knockoff+ threshold and q=0.1q = 0.1, what is the smallest number of variables the filter can select if it selects any?
QuizWhich workflows give valid inference?
Which of these four workflows produce valid intervals or pp-values for what they report?
QuizA useless predictor
You use PPI (with λ=1\lambda = 1) to estimate a mean with a nonconstant predictor ff independent of YY, and large but finite NN. What happens relative to the classical interval?
QuizNear the boundary
In the maximum-mean example, the winner is X1=2.5X_1 = 2.5. In which case is the selective interval for μ1\mu_1 widest?
ProofPPI is unbiased and its variance
Prove: Let (Xi,Yi)i=1n(X_i, Y_i)_{i=1}^n be iid, (X~i)i=1N(\tilde X_i)_{i=1}^N iid with the same law as XX and independent of the former, and ff a fixed function. Then θ^PP=1N∑if(X~i)−1n∑i(f(Xi)−Yi)\hat\theta^{\text{PP}} = \frac{1}{N}\sum_i f(\tilde X_i) - \frac{1}{n}\sum_i (f(X_i) - Y_i) satisfies E[θ^PP]=E[Y]\E[\hat\theta^{\text{PP}}] = \E[Y] and Var⁡(θ^PP)=σf2/N+σf−Y2/n\Var(\hat\theta^{\text{PP}}) = \sigma_f^2/N + \sigma_{f - Y}^2/n.
0
Let A=1N∑if(X~i)A = \frac{1}{N}\sum_i f(\tilde X_i) and B=1n∑i(f(Xi)−Yi)B = \frac{1}{n}\sum_i (f(X_i) - Y_i), so θ^PP=A−B\hat\theta^{\text{PP}} = A - B.

Step 1 of 4. What is E[A]\E[A]?

ProofWinning makes the mean a truncated normal
Prove: Let Xˉ1,…,Xˉm\bar X_1, \dots, \bar X_m be independent with Xˉj∼N(μj,σj2)\bar X_j \sim \Normal(\mu_j, \sigma_j^2). Conditional on event {Xˉi=max⁡jXˉj}\{\bar X_i = \max_j \bar X_j\} and the other means, Xˉi\bar X_i follows N(μi,σi2)\Normal(\mu_i, \sigma_i^2) truncated to [M−i,∞)[M_{-i}, \infty), with M−i=max⁡j≠iXˉjM_{-i} = \max_{j \ne i} \bar X_j.
0
Let Z=(Xˉj)j≠i\vb{Z} = (\bar X_j)_{j \ne i}, so M−iM_{-i} is a function of Z\vb{Z}.

Step 1 of 4. How is the selection event rewritten?

CodeThe knockoff+ filter
Implement filtro_knockoff(W, q, plus=True), returning a sorted array of indices selected by the knockoff filter. The threshold is the smallest tt among nonzero ∣Wj∣\abs{W_j} such that (c+#{Wj≤−t})/max⁡(1,#{Wj≥t})≤q(c + \#\{W_j \le -t\})/\max(1, \#\{W_j \ge t\}) \le q, with c=1c = 1 if plus and c=0c = 0 otherwise; if no tt satisfies it, select nothing. Tests include hand cases and a simulation with coin-flip signs for null WW as guaranteed by theory, checking that FDR stays below qq.
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)
Shift+Enter to run

Summary

Key idea
When data choose the question, inference must account for that choice: reserving information for the answer (splitting, fission), conditioning on the selection (polyhedral lemma), protecting against any choice (PoSI), constructing a control group (knockoffs), or measuring with real data the error in information borrowed from a model (PPI).
  • The winner’s classical interval among mm null candidates covers Φ(1.96)m−Φ(−1.96)m\Phi(1.96)^m - \Phi(-1.96)^m (60 % with m=20m = 20), and its estimate systematically overstates: the winner’s curse.
  • Sample splitting and data fission provide straightforward validity at the cost of power; Gaussian fission X+τZ\vb{X} + \tau\vb{Z}, X−Z/τ\vb{X} - \vb{Z}/\tau splits information from one observation into two independent parts.
  • The polyhedral lemma turns polyhedral selection (maximum, lasso, forward steps) into truncation of η⊤y\vb{\eta}\T\vb{y} to [V−,V+][\mathcal{V}^-, \mathcal{V}^+]; 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 YY; null signs are coin flips, and knockoff+ controls finite-sample FDR with any importance model provided the distribution of XX is well known.
  • PPI subtracts bias measured on labeled data from mean predictions: it is unbiased for any fixed predictor, its variance is σf2/N+σf−Y2/n\sigma_f^2/N + \sigma_{f - Y}^2/n, and PPI++ chooses predictor weight to be asymptotically no worse than classical inference. Rectified loss extends it to any M-estimator.