Module contents
Lesson 23 of 24Core 95 min

Feature selection

Systematize selection of useful feature subsets: filters (univariate statistics, mutual information, mRMR), wrappers (sequential selection, recursive elimination) and embedded methods (lasso, tree importance). Focus on two errors invalidating results—selection outside validation and unstable subsets—and their controls: stability measures and stability selection, with a bridge to m05 knockoffs for false-discovery-rate control.

After this lesson you can

  • Apply and compare filter, wrapper and embedded methods on the same problem.
  • Estimate mutual information between continuous features and target and use mRMR to avoid redundancy.
  • Implement recursive feature elimination with cross-validation.
  • Place selection inside the pipeline and empirically demonstrate the bias of selecting outside it.
  • Measure selection stability with Jaccard and Nogueira indices, apply stability selection and position m05 knockoffs as an alternative controlling the false discovery rate.

Before you start

Motivation: when features are plentiful

For each alert a threat-detection team has hundreds of candidate signals: network counts, process anomalies, domain reputation, time and geography. A quantitative finance team has hundreds of possible factors explaining an asset’s returns. A genomics lab has twenty thousand genes and sixty patients. In each case only a few features contribute; the practical question is which.

Features are removed for four reasons that do not always align. Cost: measuring, storing and computing signals costs resources and adds production latency. Variance: with small nn and large dd every useless feature is another direction in which a model fits noise (nearest-neighbor curse of dimensionality is an extreme). Interpretability: an eight-feature model can be read, audited and explained. Maintenance: each feature is a dependency that can break, drift or disappear. Guyon and Elisseeff (2003) emphasize these goals differ, and the best subset for one may not be best for another: minimum prediction error does not necessarily explain best.

Feature selection is not a cleaning step before modeling. It is part of fitting: it decides from data and thus spends data. Choosing kk features among pp makes on the order of pp comparisons, with the resulting multiple testing problem. Two mistakes invalidate many published results and organize this lesson:

  • Selection outside validation. If validation labels helped choose features, validation measures something else. The lab shows pure noise n=60n = 60 and p=1000p = 1000 where choosing 20 features on all rows and then validating yields CV accuracy 0.8990.899 although any model’s true accuracy is 0.50.5.
  • Unstable subsets. Different data from the same phenomenon lead to different selections. A subset changing every resample is not a finding; it is one of many equally good explanations.

First clarify relevance, then three method families, and finally both errors and tools to control them.

Relevance, redundancy and interaction

Let X1,…,XpX_1, \dots, X_p be features, YY the response and XSX_S the vector of features in subset S⊆{1,…,p}S \subseteq \{1, \dots, p\}.

The distinction between marginal and conditional relevance makes the problem hard. Three behaviors a good method must distinguish:

  1. Useless alone, essential together. The limiting case is XOR.
  2. Useful alone, redundant together. Several tumor-size measures (radius, perimeter, area) say the same thing; once one is known the rest add little.
  3. Useful alone and synergistic with another. Common in real data: some information is marginal and some joint.
Proof

Given X1=aX_1 = a, Y=a⊕X2Y = a \oplus X_2 is Bernoulli with parameter 1/21/2 because X2X_2 is, and does not depend on aa: Y⊥ ⁣ ⁣ ⁣⊥X1Y \indep X_1. By symmetry Y⊥ ⁣ ⁣ ⁣⊥X2Y \indep X_2. But YY is a function of (X1,X2)(X_1, X_2), hence H(Y∣X1,X2)=0H(Y \given X_1, X_2) = 0 and I(X1,X2;Y)=H(Y)−H(Y∣X1,X2)=ln⁡2−0I(X_1, X_2; Y) = H(Y) - H(Y \given X_1, X_2) = \ln 2 - 0. Also Y∼Bern⁡(1/2)Y \sim \Bern(1/2), so H(Y)=ln⁡2H(Y) = \ln 2: the pair explains everything, each feature alone nothing.

∎

This is maximal separation but illustrates something general. Cover (1974) proved the two best individual features need not form the best pair even when conditionally independent given class; Cover and Van Campenhout (1977) proved any subset ordering by Bayes error is possible for some distribution subject only to monotonicity (a subset never has lower error than a superset). Thus for fixed size kk, no search examining fewer than (pk)\binom{p}{k} subsets can guarantee the optimum without structural assumptions. All methods here are shortcuts, each failing on some data. The first interactive shows the filter’s failure.

InteractiveUseless separately, decisive together
XOR data: n=400n = 400; the class is XOR of the signs of x1x_1 and x2x_2. Above and right are each feature’s distributions by class.
x₁ by classx₂x₂
  • class 0 (matching signs)
  • class 1 (different signs)
  • tree prediction region (with x3=0x_3 = 0)
0.45
0.00
400
Tree with active features, test accuracy96.6 %
Joint mutual information of (x1,x2)(x_1, x_2) with the class0.630 nats
Univariate filter|r|FMI
x₁0.0470.90.044
x₂0.0752.20.010
x₃0.0390.60.025
In bold, FF above the 5% critical value (3.87). A mutual information filter with k=2k = 2 would choose x₁ and x₃.
With x₁ and x₂ together, the tree reaches 96.6% accuracy on 2000 new examples. Their histograms are the same for both classes, and separate mutual information is 0.044 and 0.010 nats; for the pair it is 0.630.
Four Gaussian groups centered at (±1,±1)(\pm 1, \pm 1) with deviation ss; class (blue circle or orange square) is XOR of signs x1x_1 and x2x_2. x3x_3 is pure noise at the same scale. Above, class distribution of x1x_1; right, x2x_2: at τ=0\tau = 0 they match. The table gives each feature's absolute class correlation, ANOVA FF and neighbor-estimated mutual information, plus joint (x1,x2)(x_1, x_2) information. The tree (CART depth 5) trains on enabled features and is evaluated on 2000 new examples; shading shows predicted regions. Disable x2x_2 and reenable; enable x3x_3 and change sample; raise τ\tau until x1x_1 gains marginal signal and see that equally essential x2x_2 still does not.

With initial sample (n=400n = 400, s=0.45s = 0.45), univariate scores of x1x_1 and x2x_2 are indistinguishable from noise feature x3x_3: F=0.9F = 0.9 and 2.22.2 versus 0.60.6, all below 5% critical value 3.93.9, with mutual information of a few hundredths of a nat. Yet the two-feature tree gets 97 %97\,\% on new data and pair information is 0.630.63 nats, near maximum ln⁡2=0.693\ln 2 = 0.693 of nonoverlapping XOR. A filter with k=2k = 2 picks two of three almost randomly and changes choice with sample.

The interactive suggests several observations revisited later:

  • Univariate filters miss interactions. Removing features for low marginal correlation is the table’s error.
  • Forward selection misses them on its first step too: from empty, neither x1x_1 nor x2x_2 improves the model. If it stops without improvement it chooses nothing; if it continues the first choice is random among three and finds the pair only if lucky. A wrapper evaluating the pair finds it, as does backward selection starting from all features.
  • Trees are not immune. With x3x_3 active, all three root gains are nearly zero and sample randomness decides the split. On the initial sample accuracy falls 96.6 %96.6\,\% to 93.6 %93.6\,\%; other samples lose nothing or fall below 80 %80\,\% (press ‘Otra muestra’ twice), depending on whether the first split spends itself on x3x_3.
  • Noise also passes filters. Change sample: sometimes FF of x3x_3 exceeds the 5% critical value while x1x_1 and x2x_2 remain below. With three features this is anecdotal; with a thousand it is normal and causes selection bias.

Filters

Classical statistics

For binary response and continuous features, the natural filter is Pearson label correlation (point-biserial) or equivalently one-way ANOVA FF test, checking whether feature means differ by class. For categorical features against a class, Pearson’s χ2\chi^2 test on contingency tables (scikit-learn chi2, requiring nonnegative values such as counts). With two classes FF and rr are the same criterion.

F=(n−2) r21−r2,r=Corr⁡(Xj,Y).F = \frac{(n - 2)\, r^2}{1 - r^2}, \qquad r = \Corr(X_j, Y).

(You prove this in exercises.) This equivalence explains why SelectKBest(f_classif) and ranking by ∣r∣\abs{r} select identically with two classes.

Two cautions on these tests’ pp values. First, ranking by pp value equals ranking by FF, and choosing the kk smallest controls nothing; to claim “these features associate with class,” pp tests require controlling the false discovery rate, e.g., Benjamini–Hochberg. Second, even then the test is marginal independence: “associated with class” does not mean “useful for prediction given others.”

Mutual information

Mutual information I(X;Y)I(X; Y) is Kullback–Leibler divergence between the joint distribution and product of marginals: zero exactly when X⊥ ⁣ ⁣ ⁣⊥YX \indep Y, capturing any dependence, not just linear. For continuous XX and discrete class YY every histogram depends on grid choice; the standard estimator uses nearest neighbors, following Kraskov, Stögbauer and Grassberger (2004) and for mixed data Ross (2014), implemented in mutual_info_classif. Its version follows (the information lesson’s neighbor entropy estimators derive details).

For each example ii, class yiy_i and NyiN_{y_i} examples of that class:

  1. did_i is the Chebyshev distance from xix_i to its kk-th nearest neighbor of the same class; ki=min⁡(k,Nyi−1)k_i = \min(k, N_{y_i} - 1).
  2. mim_i counts examples of any class at distance at most did_i from xix_i, excluding itself.
I^(X;Y)=ψ(n)+1n∑i=1n[ψ(ki)−ψ(Nyi)−ψ(mi)],\hat I(X; Y) = \psi(n) + \frac{1}{n}\sum_{i=1}^{n}\Big[\psi(k_i) - \psi(N_{y_i}) - \psi(m_i)\Big],

where ψ\psi is digamma. Intuition comes from density ratios: near xix_i, p(x∣yi)≈ki/(NyiV)p(x \given y_i) \approx k_i/(N_{y_i} V) and p(x)≈mi/(nV)p(x) \approx m_i/(n V) share ball volume VV; ratio kin/(Nyimi)k_i n/(N_{y_i} m_i) and I=Eln⁡p(X∣Y)p(X)I = \E \ln\frac{p(X \given Y)}{p(X)} is its mean log. If XX says nothing about YY, neighbors of xix_i have all classes in size proportion and mi≈kin/Nyim_i \approx k_i n/N_{y_i}: ratio 1, information 0. If classes separate, the kk same-class neighbors are nearly all within that radius, mi≈kim_i \approx k_i and ratio n/Nyin/N_{y_i}. Digammas replace logarithms to correct small-kk bias. With k=3k = 3 (usual) variance is moderate; raising kk reduces variance and increases bias toward 0 for highly localized dependence. For two continuous variables Kraskov algorithm 1 counts marginal neighbors within the ball containing kk joint-space neighbors.

Redundancy and mRMR

Keeping the kk highest mutual-information features has the earlier flaw: features can repeat information. The question is how much a new feature adds to those selected, exactly measured by conditional mutual information.

Proof

Expand information of XjX_j with pair (XS,Y)(X_S, Y) in two ways using the chain rule. First YY then XSX_S: I(Xj;XS,Y)=I(Xj;Y)+I(Xj;XS∣Y)I(X_j; X_S, Y) = I(X_j; Y) + I(X_j; X_S \given Y). First XSX_S then YY: I(Xj;XS,Y)=I(Xj;XS)+I(Xj;Y∣XS)I(X_j; X_S, Y) = I(X_j; X_S) + I(X_j; Y \given X_S). Equating and rearranging yields the identity. The second claim applies the chain rule to (XS,Xj)(X_S, X_j) and YY.

∎

The three terms have names. I(Xj;Y)I(X_j; Y) is relevance; I(Xj;XS)I(X_j; X_S) redundancy with selected features, subtracted; I(Xj;XS∣Y)I(X_j; X_S \given Y) interaction: what XjX_j and XSX_S share once class is known. It adds, not subtracts, and in XOR is everything: with S={1}S = \{1\} and j=2j = 2, I(X2;Y)=0I(X_2; Y) = 0, I(X2;X1)=0I(X_2; X_1) = 0 and I(X2;X1∣Y)=ln⁡2I(X_2; X_1 \given Y) = \ln 2, because given YY, X2=X1⊕YX_2 = X_1 \oplus Y is determined by X1X_1.

Estimating I(Xj;XS∣Y)I(X_j; X_S \given Y) for large SS is hard. mRMR (minimum redundancy, maximum relevance; Peng, Long and Ding, 2005) simplifies cheaply: replace joint redundancy by mean pairwise redundancy and drop the interaction term. The greedy step selects

j⋆=arg max⁡j∉S [ I(Xj;Y)−1∣S∣∑s∈SI(Xj;Xs)].j^\star = \argmax_{j \notin S}\ \Big[\, I(X_j; Y) - \frac{1}{\abs{S}} \sum_{s \in S} I(X_j; X_s) \Big].

This filter takes order O(p m)\bigO(p\, m) information estimates to choose mm features. It beats pure mutual information with redundancy and cannot improve on synergy by construction: in XOR its x2x_2 score is 0, like the filter.

Wrappers

With 2p2^p subsets, search is heuristic:

  • Forward sequential selection. Start empty and add the feature maximizing CV score improvement. Reaching kk features among pp evaluates ∑i=0k−1(p−i)=kp−k(k−1)/2\sum_{i=0}^{k-1}(p - i) = kp - k(k-1)/2 subsets, each with KK fits in KK-fold CV. With p=100p = 100 and k=10k = 10 this is 955955 subsets and 47754775 fits at five folds.
  • Backward selection. Start with all features and remove the least damaging at each step. It sees interactions but costs O(p2)\bigO(p^2) full-model fits and requires fitting with pp features (not always possible with p>np > n).
  • Recursive feature elimination (RFE; Guyon, Weston, Barnhill and Vapnik, 2002, for linear SVMs on cancer genes). Fit on remaining features, rank by ∣wj∣\abs{w_j}, discard the step smallest and repeat. Costs O(p/step)\bigO(p/\text{step}) fits: a cheap wrapper because the model itself indicates what to remove without trying all subsets.

RFE has three traps. Units: ∣wj∣\abs{w_j} compares features only if standardized. Correlation: near-duplicate features share weight, so each seems unimportant. With large step, the whole group may be removed at once despite essential information; with step = 1, refitting after removing one transfers its weight to others. Guyon et al. describe one-at-a-time removal and use larger blocks only to save computation with thousands of genes. Size: how many features to keep is a hyperparameter chosen using RFECV, which runs RFE in each fold, measures validation accuracy for each size mm and maximizes the mean.

The last sentence hides wrapper risk: the winning subset’s CV score is the maximum of many noisy scores. This is “best of NN” bias from nested cross-validation, corrected likewise: honest estimation of “search best subset and fit” needs an outer loop unseen by search.

Embedded methods

Lasso performs in one fit what wrappers do with hundreds, using a linear model on all features and thus seeing conditional relevance within linearity: linear lasso misses XOR like a filter because no linear combination of x1x_1 and x2x_2 separates it. With objective 12n∥y−Xβ∥2+λ∥β∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1 and standardized features, optimality conditions say a feature enters when ∣xj⊤r∣/n\abs{\vb{x}_j\T\vb{r}}/n, its covariance with residuals, reaches λ\lambda. Two theoretical cautions. Exact recovery of true set SS requires irrepresentability (Zhao and Yu, 2006): with C=X⊤X/n\mat{C} = \mat{X}\T\mat{X}/n partitioned into SS and complement NN blocks, ∥CNSCSS−1sign⁡(βS)∥∞≤1−η\norm{\mat{C}_{NS}\mat{C}_{SS}^{-1}\operatorname{sign}(\vb{\beta}_S)}_\infty \le 1 - \eta must hold for some η>0\eta > 0. Each component regresses a noise feature on true ones weighted by coefficient signs: no noise feature can be too well represented by true features. Zhao and Yu show the condition is sufficient and, in weak form (η=0\eta = 0), necessary for consistent signed-support recovery: if it fails no λ\lambda choice achieves it, and lasso includes noise or removes true features. Second, near duplicates are selected (or share weight) according to tiny noise differences, so choices change across samples. The third interactive shows correlation’s effect.

Trees usually use mean decrease impurity (MDI) importance. As you know it is biased toward features with many distinct values: more split candidates make chance training impurity reduction more likely. Selection inherits this, and the lab shows an MDI threshold retaining only continuous noise and dropping the sole informative feature. Permutation importance on unseen data lacks this problem; its interpretation is covered in another lesson and here serves only as selection criterion.

Selection bias

You saw this as data leakage. Here we quantify it. With response independent of all features, each sample correlation with YY is approximately N(0,1/n)\Normal(0, 1/n), and by the maximal inequality the expected maximum of pp absolute values is at most 2ln⁡(2p)/n\sqrt{2\ln(2p)/n}: with n=60n = 60, 0.500.50 for p=1000p = 1000 and 0.570.57 for p=10 000p = 10\,000. The bound grows with ln⁡p\sqrt{\ln p} slowly but indefinitely. In the interactive it appears on test tt scale: with n=60n = 60 and p=1000p = 1000, maximum noise-feature ∣t∣\abs{t} averages 3.73.7, corresponding to pp value below 10−310^{-3} for a feature chosen in advance. Selected using all rows, features carry those rows’ noise, and subsequent CV evaluates them on those same rows.

Ambroise and McLachlan (2002) measured this in the setting behind published near-zero classification errors with a few genes. On colon cancer data (62 tissues, 2000 genes), they randomly permuted labels 20 times, eliminating signal, and chose genes using SVM recursive elimination. With selection outside leave-one-out CV, mean estimated error was almost zero with 128 genes and 10% with only 8. Selection inside 10-fold CV and .632+ bootstrap yielded 40–45%, consistent with learning nothing. The interactive reproduces this with a controllable model.

InteractiveSelection leakage
Accuracy with k=20k = 20 features in 36 distinct datasets (n=60n = 60, p=1000p = 1000, stratified 5-fold CV) · calculating…
chanceselection outsideselection insidetrue accuracy
Mean of 36 repetitions versus features retained (vertical line marks k=20k = 20)
  • selection using all rows, then CV
  • selection inside each fold
  • true accuracy (new data)
  • chance (50%)
Data
1000
60
20
CV with selection outside the loop…
CV with selection inside the pipeline…
True procedure accuracy (1000 new examples)…
Explicit model: pp independent N(0,1)\Normal(0, 1) features and balanced class. Without signal none depends on class. With signal, 10 features have means separated by δ=1\delta = 1 standard deviation. Selector chooses kk highest Welch ∣t∣\abs{t} features and classifier is diagonal LDA. For each dataset (one point) compute 5-fold CV with selection before CV on all rows (orange), CV repeating selection within each fold (blue), and true accuracy of the procedure trained on nn rows on 1000 new examples (gray). Below are means over kk. Without signal raise pp to 10 000 and vary kk. With signal compare orange and gray: optimism persists when there is something to learn.

Three observations confirmed by the scikit-learn lab. Without signal, outside-CV selection yields far above chance accuracy, with gap increasing in pp and kk (each feature brings a small spurious label correlation and the classifier sums them): with n=60n = 60 and k=20k = 20, 76 %76\,\% with p=100p = 100, 92 %92\,\% with p=1000p = 1000 and 97 %97\,\% with p=10 000p = 10\,000. Inside-CV selection averages 50 %50\,\%, the correct answer. With signal, outside selection still inflates estimates above new-data accuracy: optimism about 4–8 points for kk from 1 to 12, rising to 25 with k=200k = 200 when nearly all selected features are noise. Inside-CV selection matches true accuracy for small kk and is 2–3.5 points below for k≥5k \ge 5: it trains on 80 %80\,\% rather than 100 %100\,\% of rows, the usual CV pessimism.

The rule is mechanical: everything looking at labels belongs inside validation. This includes choosing top kk, how many to keep (kk is a hyperparameter: CV selection is search and its winning score optimistic, requiring nested CV), importance thresholds and supervised transformations. Operations not looking at yy (scaling, imputation) leak less but remain procedural errors. In scikit-learn use a Pipeline whose first supervised step is the selector and CV fitting the whole pipeline in each fold (the CV pipeline section builds this from scratch).

Stability

Even with correct validation, a feature set is a statistical result that changes with sample. Two sources: small nn relative to pp (score noise comparable to feature differences), and correlation (if xax_a and xbx_b say the same thing, small sample changes decide which remains). Measure stability using MM selections S^1,…,S^M\hat S_1, \dots, \hat S_M from resamples.

Jaccard. The simplest is mean pairwise Jaccard similarity,

Φ^J=1(M2)∑a<b∣S^a∩S^b∣∣S^a∪S^b∣.\hat\Phi_J = \frac{1}{\binom{M}{2}}\sum_{a < b}\frac{\abs{\hat S_a \cap \hat S_b}}{\abs{\hat S_a \cup \hat S_b}}.

It is 1 if all selections match and 0 if none share features. Its flaw is that it is not chance-corrected, and baseline depends on kk and pp: two random kk-feature subsets among pp have E∣A∩B∣=k2/p\E\abs{A \cap B} = k^2/p and typical Jaccard around k/(2p−k)k/(2p - k). With p=60p = 60, chance gives 0.050.05 for k=5k = 5 and 0.330.33 for k=30k = 30. Whether 0.40.4 is good depends on kk.

Nogueira measure. Nogueira, Sechidis and Brown (2018) require five properties (defined for different subset sizes, strictly monotonic in agreement, bounded, maximal exactly for identical selections, and chance-corrected), show no common measure has all, and propose one that does, with confidence intervals and tests. Let p^f\hat p_f be selection frequency of feature ff across MM selections and kˉ\bar k mean size. With sf2=MM−1p^f(1−p^f)s_f^2 = \frac{M}{M-1}\hat p_f(1 - \hat p_f) unbiased variance of the “ff selected” indicator,

Φ^=1−1p∑f=1psf2kˉp(1−kˉp).\hat\Phi = 1 - \frac{\frac{1}{p}\sum_{f=1}^{p} s_f^2}{\frac{\bar k}{p}\left(1 - \frac{\bar k}{p}\right)}.

The numerator is mean feature-indicator variance; denominator is that under independent feature selection with probability kˉ/p\bar k/p, as in random selection. It is 1 for identical selections and has expectation 0 for random fixed-size selections, regardless of kk (checked in the cell).

A lab warning: stable does not mean correct. A filter can always select the same wrong features, e.g., neighbors highly correlated with true ones.

Stability selection

Meinshausen and Bühlmann (2010) suggest looking at how frequently each feature is selected rather than trusting one selection, keeping those chosen almost always.

Its value is false-positive control. Let S^Λ(I)=⋃λ∈ΛS^λ(I)\hat S^\Lambda(I) = \bigcup_{\lambda \in \Lambda}\hat S^\lambda(I) and qΛ=E∣S^Λ(I)∣q_\Lambda = \E\abs{\hat S^\Lambda(I)} be expected selected count. Let SS be true features, N=ScN = S^c noise and V=∣N∩S^estable∣V = \abs{N \cap \hat S^{\text{estable}}} false positives.

Proof

Write S^(I)\hat S(I) for S^Λ(I)\hat S^\Lambda(I) and π^k=P∗(k∈S^(I))\hat\pi_k = \Pr^*(k \in \hat S(I)).

Step 1: noise features are selected with probability at most q/pq/p. By (H1), θ=P(k∈S^(I))\theta = \Pr(k \in \hat S(I)) is equal for all k∈Nk \in N, and E∣N∩S^∣=∣N∣θ\E\abs{N \cap \hat S} = \abs{N}\theta. By (H2), E∣S∩S^∣≥∣S∣θ\E\abs{S \cap \hat S} \ge \abs{S}\theta. Summing gives q≥(∣S∣+∣N∣)θ=pθq \ge (\abs{S} + \abs{N})\theta = p\theta.

Step 2: frequent selection implies selection in both halves. If II is a uniform subsample of size n/2n/2, complement IcI^c is too, so P∗(k∈S^(Ic))=π^k\Pr^*(k \in \hat S(I^c)) = \hat\pi_k and by Bonferroni P∗(k∈S^(I)∩S^(Ic))≥2π^k−1\Pr^*\big(k \in \hat S(I) \cap \hat S(I^c)\big) \ge 2\hat\pi_k - 1.

Step 3: Markov. If π^k≥πthr\hat\pi_k \ge \pi_{\text{thr}} then 2π^k−1≥2πthr−1>02\hat\pi_k - 1 \ge 2\pi_{\text{thr}} - 1 > 0, hence 1[π^k≥πthr]≤P∗(k∈S^(I)∩S^(Ic))/(2πthr−1)\ind[\hat\pi_k \ge \pi_{\text{thr}}] \le \Pr^*\big(k \in \hat S(I) \cap \hat S(I^c)\big)/(2\pi_{\text{thr}} - 1).

Step 4: expectation over data. II and IcI^c are disjoint and data iid, so S^(I)\hat S(I) and S^(Ic)\hat S(I^c) are independent identically distributed: E P∗(k∈S^(I)∩S^(Ic))=θ2\E\,\Pr^*\big(k \in \hat S(I) \cap \hat S(I^c)\big) = \theta^2. Summing over k∈Nk \in N,

E[V]≤∣N∣θ22πthr−1≤∣N∣2πthr−1⋅q2p2≤q2(2πthr−1) p.■\E[V] \le \frac{\abs{N}\theta^2}{2\pi_{\text{thr}} - 1} \le \frac{\abs{N}}{2\pi_{\text{thr}} - 1}\cdot\frac{q^2}{p^2} \le \frac{q^2}{(2\pi_{\text{thr}} - 1)\,p}. \qquad \blacksquare∎

Two readings. This is a guarantee, not an estimate: the bound is conservative and requires exchangeable noise. Noise features strongly correlated with true ones violate the assumption and invalidate the bound. It replaces choosing λ\lambda with choosing πthr\pi_{\text{thr}} and qq, much easier: authors report little change with πthr\pi_{\text{thr}} between 0.60.6 and 0.90.9, and suggest fixing qq (hence Λ\Lambda) and πthr\pi_{\text{thr}} to reach the desired false-positive bound. With q=10q = 10, p=1000p = 1000 and πthr=0.9\pi_{\text{thr}} = 0.9 the bound is 100/(0.8⋅1000)=0.125100/(0.8 \cdot 1000) = 0.125.

InteractiveStability paths
Selection frequency of each feature across B=80B = 80 subsamples of n/2=50n/2 = 50 examples versus λ/λmax (p=60p = 60, 5 true features) · calculating…
  • true feature x₅
  • true feature x₁₇
  • true feature x₂₉
  • true feature x₄₁
  • true feature x₅₃
  • 55 noise features
  • threshold
  • enters stable set
0.80
…
Correlation ρ\rho between neighbors
1.50
Features selected per subsample in Λ\Lambda, qΛq_\Lambda…
Bound qΛ2/((2πthr−1) p)q_\Lambda^2/((2\pi_{\text{thr}} - 1)\,p) on expected false positives…
Stable set (true / false)…
Lasso with all data and λmin⁡\lambda_{\min} (true / false)…
Explicit model: n=100n = 100, p=60p = 60, AR(1) correlation between neighboring features (ρ\rho), y=x⊤β+σεy = \vb{x}\T\vb{\beta} + \sigma\eps with five true features (colored) and 55 noise (gray). For each λ\lambda each curve is lasso selection frequency across 80 half-data subsamples. Red line is πthr\pi_{\text{thr}} (drag it or use slider); shading is Λ\Lambda, maximum λ\lambda to λmin⁡\lambda_{\min}. Features whose curves touch the line within Λ\Lambda form the stable set (dots). Below are bound and actual false positives. Start with ρ=0.6\rho = 0.6 and σ=1.5\sigma = 1.5: full-data lasso with λmin⁡\lambda_{\min} includes noise, stable set does not. Raise threshold, then ρ\rho and σ\sigma, and observe losses.

Initially full-data lasso at λmin⁡\lambda_{\min} chooses 8 features, 3 noise. With πthr=0.8\pi_{\text{thr}} = 0.8 the stable set is exactly the 5 true features; qΛ≈10.5q_\Lambda \approx 10.5 and bound 3.13.1: expected false positives at most 3.1, here 0. The bound is true and uninformative because it holds over an entire problem class. Raising ρ\rho to 0.90.9 or noise to σ=3\sigma = 3 makes the stable set lose true features at πthr=0.9\pi_{\text{thr}} = 0.9: selection probabilities split with correlated neighbors or fall under noise. Stability selection thus trades power for fewer false positives. Range Λ\Lambda matters: take λmin⁡\lambda_{\min} to 0.04 λmax⁡0.04\,\lambda_{\max} and full-data lasso selects 24 features (19 noise), qΛq_\Lambda rises to 28 and bound to 21.8, guaranteeing nothing; yet at πthr=0.8\pi_{\text{thr}} = 0.8 only one noise feature enters. Thus Meinshausen and Bühlmann recommend fixing Λ\Lambda from desired qq, not vice versa.

Knockoffs: controlling false discovery rate

The bound controls the expected number of false positives. Often the desired quantity is their proportion: false discovery rate FDR=E[V/max⁡(R,1)]\mathrm{FDR} = \E[V/\max(R, 1)], with RR selected features, which Benjamini–Hochberg controls using pp values. Knockoffs (Barber and Candès, 2015) achieve feature-selection control in regression without pp values: for each feature XjX_j construct a copy X~j\tilde X_j mimicking original correlation structure (X~⊤X~=X⊤X\tilde{\mat{X}}\T\tilde{\mat{X}} = \mat{X}\T\mat{X} and each copy’s same correlation with other originals) without looking at y\vb{y}, adding no response information beyond originals. Compute statistic WjW_j comparing importance of XjX_j and its copy (e.g., lasso entry λ\lambda), then threshold WjW_j so copies, known false discoveries, estimate false discoveries among originals. In a Gaussian-noise linear model with n≥pn \ge p, Barber–Candès knockoff+ controls FDR exactly in finite samples without design, coefficient-size or noise-level assumptions (basic knockoff controls the weaker variant E[V/(R+1/α)]\E[V/(R + 1/\alpha)] with target α\alpha). Construction and proof are in knockoffs; in practice stability selection suits robustness with any base method, knockoffs a guarantee on false-discovery proportion.

A reminder connecting the sections: both stability selection and knockoffs identify features associated with response with few false positives. Neither establishes causes. Predictive selection differs from identifying what acts on YY; that is causality, including post-selection inference (pp values from a model fitted on features chosen using the same data lack their nominal distribution).

Lab 1: feature selection from scratch

First mutual information. Implement both nearest-neighbor estimators (continuous feature with discrete class, and two continuous variables), compare with mutual_info_classif, and test XOR.

[ ]Nearest-neighbor mutual information from scratchBrowser
import numpy as np
from scipy.special import digamma
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import mutual_info_classif

def mi_cd(X, y, k=3, seed=0):
    """I(X; Y) con X continuo (n, d) e Y discreta: estimador de Ross (2014), variante de KSG."""
    rng = np.random.default_rng(seed)
    X = np.asarray(X, dtype=float).reshape(len(y), -1)
    X = X / X.std(axis=0)
    X = X + 1e-10 * np.abs(X).mean() * rng.standard_normal(X.shape)   # rompe los empates
    n = len(y)
    radio, k_i, n_y = np.empty(n), np.empty(n), np.empty(n)
    for c in np.unique(y):
        idx = np.flatnonzero(y == c)
        kc = min(k, len(idx) - 1)
        D = np.abs(X[idx][:, None, :] - X[idx][None, :, :]).max(axis=2)       # distancia de Chebyshev
        np.fill_diagonal(D, np.inf)
        radio[idx] = np.partition(D, kc - 1, axis=1)[:, kc - 1]               # distancia al k-ésimo vecino de su clase
        k_i[idx], n_y[idx] = kc, len(idx)
    D = np.abs(X[:, None, :] - X[None, :, :]).max(axis=2)
    m = (D <= radio[:, None]).sum(axis=1) - 1                                  # vecinos de cualquier clase dentro de ese radio
    return max(0.0, digamma(n) + digamma(k_i).mean() - digamma(n_y).mean() - digamma(m).mean())

def mi_cc(x, z, k=3, seed=0):
    """I(X; Z) entre dos variables continuas: KSG, algoritmo 1."""
    rng = np.random.default_rng(seed)
    x = x / x.std() + 1e-10 * rng.standard_normal(len(x))
    z = z / z.std() + 1e-10 * rng.standard_normal(len(z))
    n = len(x)
    dx, dz = np.abs(x[:, None] - x[None, :]), np.abs(z[:, None] - z[None, :])
    dj = np.maximum(dx, dz)
    np.fill_diagonal(dj, np.inf)
    eps = np.partition(dj, k - 1, axis=1)[:, k - 1]                            # distancia al k-ésimo vecino en el espacio conjunto
    nx, nz = (dx < eps[:, None]).sum(axis=1) - 1, (dz < eps[:, None]).sum(axis=1) - 1
    return max(0.0, digamma(k) + digamma(n) - (digamma(nx + 1) + digamma(nz + 1)).mean())

datos = load_breast_cancer()
X, y, nombres = datos.data, datos.target, np.array(datos.feature_names)
propia = np.array([mi_cd(X[:, j], y) for j in range(X.shape[1])])
sk = mutual_info_classif(X, y, n_neighbors=3, random_state=0)
print(f"Breast cancer (n = {len(y)}, p = {X.shape[1]}): diferencia máxima con mutual_info_classif = {np.abs(propia - sk).max():.4f}")
for j in np.argsort(-propia)[:4]:
    print(f"  {nombres[j]:22s} propia {propia[j]:.4f}   sklearn {sk[j]:.4f}")

# XOR: cada variable por separado no dice nada; el par sí
rng = np.random.default_rng(0)
c = rng.integers(0, 2, (400, 2))
Z = (2 * c - 1) + 0.5 * rng.standard_normal((400, 2))
yx = c[:, 0] ^ c[:, 1]
print(f"XOR (n = 400): I(x1; y) = {mi_cd(Z[:, 0], yx):.3f}   I(x2; y) = {mi_cd(Z[:, 1], yx):.3f}   I((x1, x2); y) = {mi_cd(Z, yx):.3f}   (ln 2 = {np.log(2):.3f})")

Differences from scikit-learn, a few thousandths (largest 0.00550.0055), come from noise both add to break ties (data are rounded). For XOR the estimator reproduces theory: each feature alone is a few hundredths of a nat, pair 0.580.58, below ln⁡2\ln 2 because groups overlap slightly.

Now filters against redundancy. Split train/test, compute using training only and compare top five by FF, top five by mutual information and mRMR, with mean absolute correlation among selected features measuring redundancy. (Selection happens once on training and evaluation uses untouched test: no leakage.)

[ ]Filters and greedy mRMRBrowser
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import f_classif

def mrmr(X, y, m, k=3):
    """mRMR voraz (criterio de la diferencia): máx. I(Xj; Y) menos la media de I(Xj; Xs) sobre las ya elegidas."""
    p = X.shape[1]
    rel = np.array([mi_cd(X[:, j], y, k) for j in range(p)])
    red = np.zeros(p)                              # suma de I(Xj; Xs) sobre las elegidas
    elegidas = [int(np.argmax(rel))]
    while len(elegidas) < m:
        s = elegidas[-1]
        for j in range(p):
            if j not in elegidas:
                red[j] += mi_cc(X[:, j], X[:, s], k)
        puntuacion = rel - red / len(elegidas)
        puntuacion[elegidas] = -np.inf
        elegidas.append(int(np.argmax(puntuacion)))
    return elegidas, rel

Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mu, sd = Xtr.mean(0), Xtr.std(0)
Ztr, Zte = (Xtr - mu) / sd, (Xte - mu) / sd          # estandarizado con el entrenamiento
elegidas_mrmr, rel = mrmr(Ztr, ytr, 5)
F, _ = f_classif(Ztr, ytr)
conjuntos = {"ANOVA F": np.argsort(-F)[:5], "información mutua": np.argsort(-rel)[:5], "mRMR": np.array(elegidas_mrmr)}

def evalua(idx):
    modelo = LogisticRegression(max_iter=1000).fit(Ztr[:, idx], ytr)
    C = np.abs(np.corrcoef(Ztr[:, idx].T))
    redundancia = (C.sum() - len(idx)) / (len(idx) * (len(idx) - 1))
    return modelo.score(Zte[:, idx], yte), redundancia

for nombre, idx in conjuntos.items():
    acc, red = evalua(idx)
    print(f"{nombre:18s} |corr| media entre las elegidas {red:.2f}   exactitud en test {acc:.3f}   {', '.join(nombres[idx])}")
print(f"las 30 variables: exactitud en test {LogisticRegression(max_iter=1000).fit(Ztr, ytr).score(Zte, yte):.3f}   (171 ejemplos de test: un acierto de diferencia = {1/len(yte):.3f})")

Both filters choose five features with mean correlation 0.880.88: perimeters, radii and areas of the same tumor, measuring the same thing. mRMR lowers this to 0.410.41 by selecting other types (texture, smoothness). But test accuracies 0.9360.936, 0.9300.930 and 0.9470.947 differ by one to three correct out of 171 and establish nothing. Choices and redundancy are robust: five of 30 features capture nearly everything all 30 provide (0.9590.959), because the problem is easy. Redundancy matters when kk is small and data difficult.

Wrappers. Implement RFE with scikit-learn’s rule (ranking_ is 1 for retained features, larger for earlier removal), and RFECV evaluating each feature count in each fold using one-at-a-time removal.

[ ]RFE and RFECV from scratchBrowser
from sklearn.feature_selection import RFE, RFECV
from sklearn.model_selection import StratifiedKFold

def rfe(factory, X, y, n_features, step=1):
    """Eliminación recursiva: ajusta, descarta las `step` variables de menor |coef| y repite. ranking_ = 1 para las que quedan."""
    soporte = np.ones(X.shape[1], dtype=bool)
    ranking = np.ones(X.shape[1], dtype=int)
    while soporte.sum() > n_features:
        n_quitar = min(step, soporte.sum() - n_features)
        idx = np.flatnonzero(soporte)
        modelo = factory().fit(X[:, idx], y)
        importancia = np.linalg.norm(np.atleast_2d(modelo.coef_), axis=0)
        soporte[idx[np.argsort(importancia)[:n_quitar]]] = False
        ranking[~soporte] += 1
    return soporte, ranking

def rfecv(factory, X, y, cv):
    """RFE con un paso de una variable en cada pliegue; la exactitud de validación se mide en cada tamaño."""
    p = X.shape[1]
    puntuacion = np.zeros(p + 1)                     # puntuacion[m] = exactitud media con las m variables que quedan
    for tr, va in cv.split(X, y):
        soporte = np.ones(p, dtype=bool)
        while True:
            idx = np.flatnonzero(soporte)
            modelo = factory().fit(X[tr][:, idx], y[tr])
            puntuacion[len(idx)] += modelo.score(X[va][:, idx], y[va]) / cv.get_n_splits()
            if len(idx) == 1:
                break
            soporte[idx[np.argmin(np.linalg.norm(np.atleast_2d(modelo.coef_), axis=0))]] = False
    mejor = int(np.argmax(puntuacion[1:])) + 1       # empate: el menor número de variables
    return mejor, puntuacion[1:]

fabrica = lambda: LogisticRegression(max_iter=1000)
soporte, ranking = rfe(fabrica, Ztr, ytr, 5)
ref = RFE(fabrica(), n_features_to_select=5).fit(Ztr, ytr)
print("RFE propio == sklearn:", np.array_equal(soporte, ref.support_) and np.array_equal(ranking, ref.ranking_))
print("  elegidas:", ", ".join(nombres[soporte]))
print("  exactitud en test:", round(fabrica().fit(Ztr[:, soporte], ytr).score(Zte[:, soporte], yte), 3))

cv = StratifiedKFold(5, shuffle=True, random_state=0)
m_estrella, curva = rfecv(fabrica, Ztr, ytr, cv)
ref_cv = RFECV(fabrica(), step=1, cv=cv, scoring="accuracy").fit(Ztr, ytr)
print(f"RFECV propio: {m_estrella} variables; sklearn: {ref_cv.n_features_}")
print("  exactitud de CV con 1, 2, 3, 5, 10, 20, 30 variables:", ", ".join(f"{curva[m-1]:.3f}" for m in (1, 2, 3, 5, 10, 20, 30)))
se = np.sqrt(curva.max() * (1 - curva.max()) / len(ytr))
print(f"  error típico binomial de esa exactitud: {se:.3f}; el menor tamaño dentro de una desviación típica del máximo es {int(np.argmax(curva >= curva.max() - se)) + 1}")

Our RFE exactly reproduces scikit-learn support and ranking, and RFECV chooses the same feature count. The curve rises fast to five features (0.9720.972), then slowly to 0.9870.987 at 30. Its maximum at 18 selects “best of 30” noisy scores; the one-standard-error rule (smallest model within one standard error of maximum, proposed by Breiman et al. for tree pruning) keeps 6, with binomial standard error 0.0060.006 (underestimating real noise since folds share data). Best size depends on feature cost; the curve maximum cannot be reported as final-model accuracy.

Embedded methods and stability. First lasso coordinate descent across many subsamples at once (NumPy vectors over subsamples), and stability selection on top, with the third interactive’s model (different concrete data because random generator differs).

[ ]Lasso and stability selection from scratchBrowser
from sklearn.linear_model import LassoCV

def datos_dispersos(n=100, p=60, rho=0.6, sigma=1.5, seed=0):
    """X con correlación AR(1) entre variables vecinas; 5 variables reales (posiciones 4, 16, 28, 40, 52)."""
    rng = np.random.default_rng(seed)
    E = rng.standard_normal((n, p))
    X = E.copy()
    for j in range(1, p):
        X[:, j] = rho * X[:, j - 1] + np.sqrt(1 - rho**2) * E[:, j]
    beta = np.zeros(p)
    beta[[4, 16, 28, 40, 52]] = [2.0, -1.5, 1.2, -1.0, 0.8]
    return X, X @ beta + sigma * rng.standard_normal(n), beta

def lasso_lote(Xb, yb, lam, beta, r, barridos=200, tol=1e-5):
    """Descenso por coordenadas para B lassos a la vez. Xb: (B, p, m) estandarizado; beta y r se actualizan en sitio."""
    B, p, m = Xb.shape
    for _ in range(barridos):
        cambio = 0.0
        for j in range(p):
            xj = Xb[:, j, :]
            rho = (xj * r).sum(axis=1) / m + beta[:, j]
            nuevo = np.sign(rho) * np.maximum(np.abs(rho) - lam, 0.0)      # umbral suave
            d = nuevo - beta[:, j]
            r -= xj * d[:, None]
            beta[:, j] = nuevo
            cambio = max(cambio, np.abs(d).max())
        if cambio < tol:
            break

def seleccion_estable(X, y, q=10, B=100, seed=0):
    """Stability selection: frecuencia de selección del lasso en B submuestras de la mitad, para λ >= λ_q (|S| medio ≈ q)."""
    rng = np.random.default_rng(seed)
    n, p = X.shape
    Xc, yc = (X - X.mean(0)) / X.std(0), y - y.mean()
    lam_max = np.abs(Xc.T @ yc).max() / n
    idx = np.stack([rng.permutation(n)[: n // 2] for _ in range(B)])
    Xs = X[idx] - X[idx].mean(axis=1, keepdims=True)
    Xs = np.ascontiguousarray((Xs / Xs.std(axis=1, keepdims=True)).transpose(0, 2, 1))   # (B, p, n/2)
    ys = y[idx] - y[idx].mean(axis=1, keepdims=True)
    beta, r = np.zeros((B, p)), ys.copy()
    visto = np.zeros((B, p), dtype=bool)                      # unión de las variables elegidas con λ >= λ actual
    frec = np.zeros(p)
    for lam in lam_max * np.logspace(0, np.log10(0.04), 24):
        lasso_lote(Xs, ys, lam, beta, r)
        sel = beta != 0
        visto |= sel
        frec = np.maximum(frec, sel.mean(axis=0))              # máx. sobre λ de la frecuencia de selección
        if sel.sum(axis=1).mean() >= q:
            break
    qL = visto.sum(axis=1).mean()
    return frec, qL, lam / lam_max

def cota_falsos_positivos(q, p, umbral):
    return q**2 / ((2 * umbral - 1) * p)

X, y, beta = datos_dispersos()
n, p = X.shape
real = beta != 0
frec, qL, razon = seleccion_estable(X, y, q=10)
print(f"Λ llega hasta λ/λmáx = {razon:.3f}; q_Λ = {qL:.1f} variables por submuestra (de p = {p})")
Xc, yc = (X - X.mean(0)) / X.std(0), y - y.mean()
lasso = LassoCV(cv=5, random_state=0).fit(Xc, yc)
sel = lasso.coef_ != 0
print(f"LassoCV (λ elegido por CV): {sel.sum()} variables, {(sel & real).sum()} reales y {(sel & ~real).sum()} falsas")
print(f"frecuencia de selección: reales {np.round(frec[real], 2)}   las 5 mayores de ruido {np.round(np.sort(frec[~real])[::-1][:5], 2)}")
for umbral in (0.6, 0.8, 0.9):
    est = frec >= umbral
    print(f"π_thr = {umbral}: {est.sum()} variables, {(est & real).sum()} reales y {(est & ~real).sum()} falsas;  cota E[V] <= {cota_falsos_positivos(qL, p, umbral):.2f}")

CV-selected lasso retains 14 features, 9 false. Stability selection puts three of five true features at frequency 1 and the other two at 0.890.89 and 0.610.61: weakest (β=0.8\beta = 0.8) is below the top two noise (0.660.66 and 0.630.63), so no threshold separates it. Thus πthr=0.6\pi_{\text{thr}} = 0.6 includes five true and 2 false, while 0.80.8 and 0.90.9 admit no false but lose one or two true. Bounds (9.129.12, 3.043.04 and 2.282.28 expected false positives) greatly exceed observed (2, 0, 0): worst-case guarantees. Bound πthr=0.6\pi_{\text{thr}} = 0.6 exceeds stable set size (7 features), and 0.90.9 (2.28 for a set of 3) is little better: as bound is qΛ2/pq_\Lambda^2/p times a factor above 1, it informs only if qΛq_\Lambda is small relative to p\sqrt{p}, here qΛ=10.5q_\Lambda = 10.5 versus 60≈7.7\sqrt{60} \approx 7.7. With p=1000p = 1000 and q=10q = 10 as before it does inform.

Stability measures: the two functions, also two coding exercises below, and their random-selection baseline.

[ ]Jaccard and Nogueira and their baselinesBrowser
from itertools import combinations

def jaccard_estabilidad(selecciones):
    """Media de |A ∩ B| / |A ∪ B| sobre todos los pares de subconjuntos (índices de variables)."""
    conj = [set(map(int, s)) for s in selecciones]
    valores = [len(a & b) / len(a | b) if a | b else 1.0 for a, b in combinations(conj, 2)]
    return float(np.mean(valores))

def nogueira(Z):
    """Medida de Nogueira, Sechidis y Brown (2018). Z: matriz (M, p) de 0 y 1, una fila por selección."""
    Z = np.asarray(Z, dtype=float)
    M, p = Z.shape
    pf = Z.mean(axis=0)                                  # frecuencia de selección de cada variable
    k_medio = Z.sum(axis=1).mean()
    var_insesgada = M / (M - 1) * pf * (1 - pf)
    return 1 - var_insesgada.mean() / ((k_medio / p) * (1 - k_medio / p))

def a_matriz(selecciones, p):
    Z = np.zeros((len(selecciones), p))
    for i, s in enumerate(selecciones):
        Z[i, list(s)] = 1
    return Z

# Línea base: subconjuntos de tamaño k elegidos al azar entre p = 60
rng = np.random.default_rng(0)
for k in (5, 12, 30):
    azar = [rng.choice(p, k, replace=False) for _ in range(300)]
    print(f"k = {k:2d} al azar: Jaccard medio {jaccard_estabilidad(azar):.3f} (aprox. k/(2p - k) = {k / (2 * p - k):.3f})   Nogueira {nogueira(a_matriz(azar, p)):+.3f}")

Random Jaccard rises 0.050.05 to 0.340.34 going from k=5k = 5 to k=30k = 30, while Nogueira gives zero (−0.001-0.001 to 0.0000.000) in all three: chance-corrected. Now three selectors across ten 80 %80\,\% subsamples of the same data. Measure stability and correctness, since true features are known here.

[ ]Which selector is stable? Which is correct?Browser
from sklearn.feature_selection import f_regression

M = 10
sub = np.stack([rng.permutation(n)[: int(0.8 * n)] for _ in range(M)])
sel_f, sel_lasso = [], []
for i in range(M):
    Xi, yi = X[sub[i]], y[sub[i]]
    F_i, _ = f_regression(Xi, yi)
    sel_f.append(np.argsort(-F_i)[:5])
    c = LassoCV(cv=5, random_state=0).fit((Xi - Xi.mean(0)) / Xi.std(0), yi - yi.mean())
    sel_lasso.append(np.flatnonzero(c.coef_))
print(f"{M} submuestras del 80 %: top-5 por F y lasso con λ por CV calculados")
[ ]Stability selection on the same subsamplesBrowser
sel_estable = [np.flatnonzero(seleccion_estable(X[sub[i]], y[sub[i]], q=10, B=20, seed=i)[0] >= 0.8) for i in range(M)]
for nombre, S in [("top-5 por F de regresión", sel_f), ("lasso con λ por CV", sel_lasso), ("stability selection (π_thr = 0.8)", sel_estable)]:
    tam = np.mean([len(s) for s in S])
    print(f"{nombre:36s} tamaño medio {tam:5.1f}   Jaccard {jaccard_estabilidad(S):.3f}   Nogueira {nogueira(a_matriz(S, p)):.3f}   reales {np.mean([real[s].sum() for s in S]):.1f}/5   falsas {np.mean([(~real[s]).sum() for s in S]):.1f}")

Three profiles. Lasso with CV λ\lambda recovers all five true features in every subsample but selects about 19 total and is least stable (Nogueira 0.420.42). Stability selection is most stable (0.860.86) and admits least noise, losing one or two true features. Top five by FF is fairly stable (0.750.75) and consistently wrong: fewer than 3 of 5 true, over 2 false on average, correlated neighbors. Stable is not correct. (Ten subsamples and 20 inner subsamples give noisy figures; retain method ordering.)

Finally tree importance: a forest with one informative binary and four noise features (three continuous, one 10-level categorical), comparing MDI threshold with permutation importance on test data.

[ ]MDI versus permutation as selection criterionBrowser
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.feature_selection import SelectFromModel

rng = np.random.default_rng(0)
n = 600
x_info = rng.integers(0, 2, n)                                    # binaria, informativa
y_c = (rng.random(n) < np.where(x_info == 1, 0.70, 0.30)).astype(int)
ruido = {"continua A": rng.standard_normal(n), "continua B": rng.standard_normal(n), "continua C": rng.standard_normal(n),
         "categórica (10 niveles)": rng.integers(0, 10, n).astype(float)}
Xc_ = np.column_stack([x_info] + list(ruido.values()))
nom = ["binaria informativa"] + list(ruido)
Xa, Xb, ya, yb = train_test_split(Xc_, y_c, test_size=0.4, random_state=0)
bosque = RandomForestClassifier(100, random_state=0).fit(Xa, ya)
perm = permutation_importance(bosque, Xb, yb, n_repeats=10, random_state=0).importances_mean
print(f"{'variable':26s}{'MDI (entrenamiento)':>22s}{'permutación (test)':>22s}")
for j in np.argsort(-bosque.feature_importances_):
    print(f"{nom[j]:26s}{bosque.feature_importances_[j]:22.3f}{perm[j]:22.3f}")
sfm = SelectFromModel(bosque, prefit=True)
print("SelectFromModel (umbral = media de las importancias MDI) conserva:", [nom[j] for j in np.flatnonzero(sfm.get_support())])

The forest has deep trees and continuous features offer hundreds of splits fitting training noise, rewarded by MDI. The sole informative binary ranks fourth behind three continuous noise features, and SelectFromModel’s mean-importance threshold keeps only three noise features. On test, permutation puts binary far ahead and others near zero. Do not use MDI to choose across differing cardinalities.

Lab 2: selection within a scikit-learn pipeline

The goal is fair-CV procedure comparison and using scikit-learn to see outside versus inside selection. Start where this is clearest, high dimensions. A function generates second-interactive data; for each dataset calculate outside-selection CV, CV with SelectKBest in a Pipeline, and true accuracy on 2000 new examples.

[ ]Selection outside or inside the loopBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline

def generar(n, p, q, delta, rng):
    """Etiqueta equilibrada; p variables N(0, 1); las q primeras desplazadas ±delta/2 según la clase."""
    y = np.repeat([0, 1], n // 2)
    X = rng.standard_normal((n, p))
    X[:, :q] += (y[:, None] - 0.5) * delta
    return X, y

def una_repeticion(n, p, q, delta, k, rng):
    X, y = generar(n, p, q, delta, rng)
    cv = StratifiedKFold(5, shuffle=True, random_state=int(rng.integers(1 << 30)))
    clf = LogisticRegression(max_iter=1000)
    # Fuera: se eligen las k variables con todas las filas y después se valida
    Xk = SelectKBest(f_classif, k=k).fit_transform(X, y)
    fuera = cross_val_score(clf, Xk, y, cv=cv).mean()
    # Dentro: el selector es un paso del pipeline y se reajusta en cada pliegue
    tuberia = make_pipeline(SelectKBest(f_classif, k=k), LogisticRegression(max_iter=1000))
    dentro = cross_val_score(tuberia, X, y, cv=cv).mean()
    # Real: el procedimiento entrenado con las n filas, en 2000 ejemplos nuevos del mismo modelo
    Xn, yn = generar(2000, p, q, delta, rng)
    real = tuberia.fit(X, y).score(Xn, yn)
    return fuera, dentro, real

rng = np.random.default_rng(0)
print("n = 60, p = 1000, k = 20, 12 repeticiones")
for etiqueta, q in [("sin señal", 0), ("10 variables reales (delta = 1)", 10)]:
    res = np.array([una_repeticion(60, 1000, q, 1.0, 20, rng) for _ in range(12)])
    m, s = res.mean(axis=0), res.std(axis=0)
    print(f"  {etiqueta:33s} fuera {m[0]:.3f} ± {s[0]:.3f}   dentro {m[1]:.3f} ± {s[1]:.3f}   real {m[2]:.3f} ± {s[2]:.3f}")

With no signal, outside selection yields CV accuracy 0.8990.899 against true 0.5030.503; inside the pipeline 0.4970.497, chance, though with large dataset-to-dataset deviation 0.0830.083: honest estimation with n=60n = 60 is noisy. With ten true features outside says 0.9650.965 when the procedure achieves 0.8480.848 on new data; inside says 0.8290.829, slightly pessimistic as expected.

Choosing kk by CV is another search and must be nested. On pure noise with kk chosen among {2,10,50,200}\{2, 10, 50, 200\} by GridSearchCV, the search’s best reported score is optimistic and nested CV corrects it:

[ ]Choosing k also belongs inside the loop (nested CV)Browser
from sklearn.model_selection import GridSearchCV

def una_repeticion_k(n, p, rng):
    X, y = generar(n, p, 0, 0.0, rng)                                  # ruido puro: el acierto real es 0.5
    sem = int(rng.integers(1 << 30))
    interna = StratifiedKFold(3, shuffle=True, random_state=sem)
    externa = StratifiedKFold(4, shuffle=True, random_state=sem + 1)
    tuberia = make_pipeline(SelectKBest(f_classif), LogisticRegression(max_iter=1000))
    busqueda = GridSearchCV(tuberia, {"selectkbest__k": [2, 10, 50, 200]}, cv=interna)
    anidada = cross_val_score(busqueda, X, y, cv=externa).mean()      # elegir k también va dentro del bucle externo
    return busqueda.fit(X, y).best_score_, anidada

rng = np.random.default_rng(1)
res = np.array([una_repeticion_k(60, 500, rng) for _ in range(6)])
print("Ruido puro, n = 60, p = 500, k elegido por CV entre {2, 10, 50, 200}; 6 repeticiones, el acierto real es 0.5")
print(f"  best_score_ de GridSearchCV: {res[:, 0].mean():.3f}     CV anidada: {res[:, 1].mean():.3f}")

Search congratulates itself with 0.5720.572 on a problem with nothing to learn; nested CV gives 0.5080.508. Six repetitions are too few to quantify the gap, but direction matches “best of NN” theory.

Forward sequential selection in a scikit-learn pipeline on the first ten breast cancer features (means). The wrapper is expensive (each candidate takes KK fits), so reduce the problem to three of ten features.

[ ]SequentialFeatureSelector inside a pipelineBrowser
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import SequentialFeatureSelector

datos = load_breast_cancer()
X, y, nombres = datos.data, datos.target, np.array(datos.feature_names)
Z10 = (X[:, :10] - X[:, :10].mean(0)) / X[:, :10].std(0)          # las 10 variables «mean»
cv5 = StratifiedKFold(5, shuffle=True, random_state=0)
sfs = SequentialFeatureSelector(LogisticRegression(max_iter=1000), n_features_to_select=3, direction="forward", cv=3)
fuera = cross_val_score(LogisticRegression(max_iter=1000), sfs.fit_transform(Z10, y), y, cv=cv5).mean()
dentro = cross_val_score(make_pipeline(sfs, LogisticRegression(max_iter=1000)), Z10, y, cv=cv5).mean()
print("elegidas con todos los datos:", ", ".join(nombres[:10][sfs.fit(Z10, y).get_support()]))
print(f"forward, 3 de 10 variables: CV con la selección fuera {fuera:.3f}, dentro del pipeline {dentro:.3f}")

There is no appreciable difference here (0.9170.917 versus 0.9190.919): with n=569n = 569 and just 10 candidates, selection cannot learn noise at that rate. This does not justify leakage: bias grows with p/np/n and kk, and the pipeline is free. Finally compare all three families in scikit-learn, all inside pipelines with identical CV:

[ ]Filter, wrapper and embedded with the same APIBrowser
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectFromModel, mutual_info_classif, RFE

def con_escalado(*pasos):
    return make_pipeline(StandardScaler(), *pasos, LogisticRegression(max_iter=1000))

familias = {
    "sin selección": con_escalado(),
    "filtro: SelectKBest(F), k = 5": con_escalado(SelectKBest(f_classif, k=5)),
    "filtro: SelectKBest(MI), k = 5": con_escalado(SelectKBest(lambda a, b: mutual_info_classif(a, b, random_state=0), k=5)),
    "envoltura: RFE, 5 variables": con_escalado(RFE(LogisticRegression(max_iter=1000), n_features_to_select=5)),
    "embebido: L1 (SelectFromModel)": con_escalado(SelectFromModel(LogisticRegression(l1_ratio=1, solver="liblinear", C=0.1))),
}
for nombre, modelo in familias.items():
    puntuaciones = cross_val_score(modelo, X, y, cv=cv5)
    n_elegidas = modelo.fit(X, y)[1].get_support().sum() if len(modelo) > 2 else X.shape[1]
    print(f"{nombre:34s} exactitud de CV {puntuaciones.mean():.3f} ± {puntuaciones.std():.3f}   variables en el ajuste final: {n_elegidas}")

On this easy 30-feature problem no family beats no selection (0.9790.979): removing features saves cost and shrinks the model, not improves accuracy. With 5 features wrapper (RFE, 0.9680.968) loses less than filters (both 0.9470.947), which pick redundant features; L1 embedded picks 8 and reaches 0.9770.977. The filter–no-selection difference (0.0320.032) is about one fold standard deviation (0.030.03); the comparison shows pattern, not a winner.

Common mistakes

Exercises

QuizWho sees XOR?
Two features x1x_1, x2x_2 form XOR with class: each alone is independent. Which method can detect their joint relevance?
QuizTwenty genes among twenty thousand
A paper reports 95% accuracy with 20 genes selected among 20 000 using all data, then cross-validates. What follows?
NumericStability-selection bound
In stability selection the method selects q=10q = 10 features per subsample on average, there are p=1000p = 1000 features and πthr=0.9\pi_{\text{thr}} = 0.9. What Meinshausen–Bühlmann bound applies to expected noise features in the stable set?
NumericForward selection fits
With p=100p = 100 features and five-fold CV, how many model fits does forward sequential selection use to reach k=10k = 10 features? (Count search fits, not final fit.)
NumericStability of four selections
With p=6p = 6 features, four resamples select {1,2}\{1, 2\}, {1,2}\{1, 2\}, {1,3}\{1, 3\} and {1,2}\{1, 2\}. What is Nogueira, Sechidis and Brown stability?
QuizWhich importances can guide selection?
You train Random Forest with one informative binary feature and several noise features, continuous and categorical. Which statements about selection importance are true?

More than one answer may be correct.

QuizWhy mRMR misses XOR
On XOR, with S={1}S = \{1\} already selected, mRMR scores x2x_2 as I(X2;Y)−I(X2;X1)I(X_2; Y) - I(X_2; X_1). Why can it not distinguish it from noise?
QuizWhen does the bound fail?
Stability-selection bound E[V]≤qΛ2/((2πthr−1) p)\E[V] \le q_\Lambda^2/((2\pi_{\text{thr}} - 1)\,p) requires assumptions. In which situations is it not guaranteed?

More than one answer may be correct.

QuizA Jaccard of 0.4
Two methods select subsets of sizes k=5k = 5 and k=30k = 30 from p=60p = 60 features, both with mean resample Jaccard 0.40.4. What can be said?
ProofANOVA F is correlation
Prove: For feature xx and binary class with nn examples, let rr be Pearson correlation between xx and the class indicator. One-way two-group ANOVA FF equals F=(n−2) r2/(1−r2)F = (n - 2)\,r^2/(1 - r^2).
0
Let SST=∑i(xi−xˉ)2\mathrm{SST} = \sum_i (x_i - \bar x)^2 be total sum of squares, SSB\mathrm{SSB} between-group sum and SSW\mathrm{SSW} within-group sum, with SST=SSB+SSW\mathrm{SST} = \mathrm{SSB} + \mathrm{SSW}. Two-group ANOVA FF is F=SSB/(SSW/(n−2))F = \mathrm{SSB}/(\mathrm{SSW}/(n - 2)).

Step 1 of 3. What is the relation between r2r^2 and sums of squares?

CodeRecursive feature elimination
Implement rfe(estimator_factory, X, y, n_features, step=1): fit estimator_factory() on remaining features, discard the step with smallest absolute coefficient (column norm of coef_ if multiple rows), and repeat until n_features remain; on the last iteration remove only the excess. Return (soporte, ranking): soporte is a boolean array of length pp marking retained features, and ranking an integer array with 1 for retained and larger values for earlier removal (same-step removals share rank). Tests compare with sklearn.feature_selection.RFE.
import numpy as np

def rfe(estimator_factory, X, y, n_features, step=1):
  """Devuelve (soporte, ranking) como RFE de scikit-learn."""
  p = X.shape[1]
  soporte = np.ones(p, dtype=bool)
  ranking = np.ones(p, dtype=int)
  # tu código
  return soporte, ranking
Shift+Enter to run
CodeJaccard stability
Implement jaccard_stability(selections): receive a list of M≥2M \ge 2 selections (each a list, tuple or array of feature indices) and return the mean over all pairs a<ba < b of ∣Sa∩Sb∣/∣Sa∪Sb∣|S_a \cap S_b| / |S_a \cup S_b|. If both sets in a pair are empty, similarity is 1.
def jaccard_stability(selections):
  """Media de la similitud de Jaccard entre todos los pares de selecciones."""
  return 0.0
Shift+Enter to run
CodeNogueira measure
Implement nogueira_stability(Z): Z is a 0/1 matrix with MM rows (one selection each) and pp columns. Return Φ^=1−1p∑fsf2kˉp(1−kˉp)\hat\Phi = 1 - \frac{\frac1p\sum_f s_f^2}{\frac{\bar k}{p}(1 - \frac{\bar k}{p})}, with sf2=MM−1p^f(1−p^f)s_f^2 = \frac{M}{M-1}\hat p_f(1 - \hat p_f), p^f\hat p_f the frequency of column ff and kˉ\bar k the mean ones per row. Assume 0<kˉ<p0 < \bar k < p.
import numpy as np

def nogueira_stability(Z):
  """Medida de estabilidad de Nogueira, Sechidis y Brown (2018)."""
  Z = np.asarray(Z, dtype=float)
  return 0.0
Shift+Enter to run

Summary

Key idea
Feature selection is part of fitting: it decides from data and is evaluated and validated as part of the procedure. Filters see marginal relevance, wrappers and embedded methods joint relevance, and two invalidating risks are selection outside validation and trusting an unstable subset.
  • Relevance. Marginal relevance, conditional relevance and redundancy differ. XOR demonstrates Y⊥ ⁣ ⁣ ⁣⊥X1Y \indep X_1, Y⊥ ⁣ ⁣ ⁣⊥X2Y \indep X_2 and I(X1,X2;Y)=ln⁡2I(X_1, X_2; Y) = \ln 2. Two good individual features need not form a good pair (Cover), and exhaustive search costs 2p2^p.
  • Filters. FF, χ2\chi^2 and neighbor mutual information (Ross, KSG), cheap and model-free. They miss interactions. With two classes F=(n−2)r2/(1−r2)F = (n - 2)r^2/(1 - r^2). mRMR subtracts mean pairwise redundancy but drops identity I(Xj;Y∣XS)=I(Xj;Y)−I(Xj;XS)+I(Xj;XS∣Y)I(X_j; Y \given X_S) = I(X_j; Y) - I(X_j; X_S) + I(X_j; X_S \given Y)‘s I(Xj;XS∣Y)I(X_j; X_S \given Y) term.
  • Wrappers. Sequential selection (kp−k(k−1)/2kp - k(k-1)/2 subsets with KK fits each), RFE (O(p/step)\bigO(p/\text{step}) fits) and RFECV. They see interactions when evaluating sets, and the winning score is a maximum of noisy scores: nested CV is needed.
  • Embedded. Lasso and elastic net select while fitting; support recovery requires conditions (irrepresentability). MDI favors continuous or many-level features; select using test-data permutation importance.
  • Selection bias. Choosing on all rows and validating afterward inflates estimates with or without signal. Everything looking at labels belongs in the CV-refitted Pipeline, including kk selection.
  • Stability. Use chance-corrected Nogueira, not Jaccard alone. Stability selection uses half-data selection frequency, threshold πthr\pi_{\text{thr}} and guarantee E[V]≤qΛ2/((2πthr−1)p)\E[V] \le q_\Lambda^2/((2\pi_{\text{thr}} - 1)p) under noise exchangeability and a method no worse than chance. Knockoffs control false discovery rate. Stable is not correct, and association is not causation.