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
- 11LassoElastic netRandom forestBias of mean decrease in impurity importanceData leakagePreprocessing and model pipelinesNested cross-validation
- 07Mutual informationNearest-neighbor entropy and MI estimators
- 05The multiple testing problemFalse discovery rateBenjamini-Hochberg procedurePearson chi-squared tests and G-testOne- and two-way analysis of varianceKnockoffs and the knockoff filter
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 and large 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 features among makes on the order of 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 and where choosing 20 features on all rows and then validating yields CV accuracy although any model’s true accuracy is .
- 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 be features, the response and the vector of features in subset .
The distinction between marginal and conditional relevance makes the problem hard. Three behaviors a good method must distinguish:
- Useless alone, essential together. The limiting case is XOR.
- Useful alone, redundant together. Several tumor-size measures (radius, perimeter, area) say the same thing; once one is known the rest add little.
- Useful alone and synergistic with another. Common in real data: some information is marginal and some joint.
Proof
Given , is Bernoulli with parameter because is, and does not depend on : . By symmetry . But is a function of , hence and . Also , so : 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 , no search examining fewer than 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.
With initial sample (, ), univariate scores of and are indistinguishable from noise feature : and versus , all below 5% critical value , with mutual information of a few hundredths of a nat. Yet the two-feature tree gets on new data and pair information is nats, near maximum of nonoverlapping XOR. A filter with 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 nor 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 active, all three root gains are nearly zero and sample randomness decides the split. On the initial sample accuracy falls to ; other samples lose nothing or fall below (press ‘Otra muestra’ twice), depending on whether the first split spends itself on .
- Noise also passes filters. Change sample: sometimes of exceeds the 5% critical value while and 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 test, checking whether feature means differ by class. For categorical features against a class, Pearson’s test on contingency tables (scikit-learn chi2, requiring nonnegative values such as counts). With two classes and are the same criterion.
(You prove this in exercises.) This equivalence explains why SelectKBest(f_classif) and ranking by select identically with two classes.
Two cautions on these tests’ values. First, ranking by value equals ranking by , and choosing the smallest controls nothing; to claim “these features associate with class,” 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 is Kullback–Leibler divergence between the joint distribution and product of marginals: zero exactly when , capturing any dependence, not just linear. For continuous and discrete class 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 , class and examples of that class:
- is the Chebyshev distance from to its -th nearest neighbor of the same class; .
- counts examples of any class at distance at most from , excluding itself.
where is digamma. Intuition comes from density ratios: near , and share ball volume ; ratio and is its mean log. If says nothing about , neighbors of have all classes in size proportion and : ratio 1, information 0. If classes separate, the same-class neighbors are nearly all within that radius, and ratio . Digammas replace logarithms to correct small- bias. With (usual) variance is moderate; raising 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 joint-space neighbors.
Redundancy and mRMR
Keeping the 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 with pair in two ways using the chain rule. First then : . First then : . Equating and rearranging yields the identity. The second claim applies the chain rule to and .
∎The three terms have names. is relevance; redundancy with selected features, subtracted; interaction: what and share once class is known. It adds, not subtracts, and in XOR is everything: with and , , and , because given , is determined by .
Estimating for large 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
This filter takes order information estimates to choose features. It beats pure mutual information with redundancy and cannot improve on synergy by construction: in XOR its score is 0, like the filter.
Wrappers
With subsets, search is heuristic:
- Forward sequential selection. Start empty and add the feature maximizing CV score improvement. Reaching features among evaluates subsets, each with fits in -fold CV. With and this is subsets and fits at five folds.
- Backward selection. Start with all features and remove the least damaging at each step. It sees interactions but costs full-model fits and requires fitting with features (not always possible with ).
- Recursive feature elimination (RFE; Guyon, Weston, Barnhill and Vapnik, 2002, for linear SVMs on cancer genes). Fit on remaining features, rank by , discard the
stepsmallest and repeat. Costs fits: a cheap wrapper because the model itself indicates what to remove without trying all subsets.
RFE has three traps. Units: 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 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 ” 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 and separates it. With objective and standardized features, optimality conditions say a feature enters when , its covariance with residuals, reaches . Two theoretical cautions. Exact recovery of true set requires irrepresentability (Zhao and Yu, 2006): with partitioned into and complement blocks, must hold for some . 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 (), necessary for consistent signed-support recovery: if it fails no 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 is approximately , and by the maximal inequality the expected maximum of absolute values is at most : with , for and for . The bound grows with slowly but indefinitely. In the interactive it appears on test scale: with and , maximum noise-feature averages , corresponding to value below 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.
Three observations confirmed by the scikit-learn lab. Without signal, outside-CV selection yields far above chance accuracy, with gap increasing in and (each feature brings a small spurious label correlation and the classifier sums them): with and , with , with and with . Inside-CV selection averages , the correct answer. With signal, outside selection still inflates estimates above new-data accuracy: optimism about 4–8 points for from 1 to 12, rising to 25 with when nearly all selected features are noise. Inside-CV selection matches true accuracy for small and is 2–3.5 points below for : it trains on rather than of rows, the usual CV pessimism.
The rule is mechanical: everything looking at labels belongs inside validation. This includes choosing top , how many to keep ( is a hyperparameter: CV selection is search and its winning score optimistic, requiring nested CV), importance thresholds and supervised transformations. Operations not looking at (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 relative to (score noise comparable to feature differences), and correlation (if and say the same thing, small sample changes decide which remains). Measure stability using selections from resamples.
Jaccard. The simplest is mean pairwise Jaccard similarity,
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 and : two random -feature subsets among have and typical Jaccard around . With , chance gives for and for . Whether is good depends on .
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 be selection frequency of feature across selections and mean size. With unbiased variance of the “ selected” indicator,
The numerator is mean feature-indicator variance; denominator is that under independent feature selection with probability , as in random selection. It is 1 for identical selections and has expectation 0 for random fixed-size selections, regardless of (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 and be expected selected count. Let be true features, noise and false positives.
Proof
Write for and .
Step 1: noise features are selected with probability at most . By (H1), is equal for all , and . By (H2), . Summing gives .
Step 2: frequent selection implies selection in both halves. If is a uniform subsample of size , complement is too, so and by Bonferroni .
Step 3: Markov. If then , hence .
Step 4: expectation over data. and are disjoint and data iid, so and are independent identically distributed: . Summing over ,
∎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 with choosing and , much easier: authors report little change with between and , and suggest fixing (hence ) and to reach the desired false-positive bound. With , and the bound is .
Initially full-data lasso at chooses 8 features, 3 noise. With the stable set is exactly the 5 true features; and bound : expected false positives at most 3.1, here 0. The bound is true and uninformative because it holds over an entire problem class. Raising to or noise to makes the stable set lose true features at : selection probabilities split with correlated neighbors or fall under noise. Stability selection thus trades power for fewer false positives. Range matters: take to and full-data lasso selects 24 features (19 noise), rises to 28 and bound to 21.8, guaranteeing nothing; yet at only one noise feature enters. Thus Meinshausen and Bühlmann recommend fixing from desired , 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 , with selected features, which Benjamini–Hochberg controls using values. Knockoffs (Barber and Candès, 2015) achieve feature-selection control in regression without values: for each feature construct a copy mimicking original correlation structure ( and each copy’s same correlation with other originals) without looking at , adding no response information beyond originals. Compute statistic comparing importance of and its copy (e.g., lasso entry ), then threshold so copies, known false discoveries, estimate false discoveries among originals. In a Gaussian-noise linear model with , Barber–Candès knockoff+ controls FDR exactly in finite samples without design, coefficient-size or noise-level assumptions (basic knockoff controls the weaker variant with target ). 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 ; that is causality, including post-selection inference ( 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.
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 ), 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 , below because groups overlap slightly.
Now filters against redundancy. Split train/test, compute using training only and compare top five by , 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.)
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 : perimeters, radii and areas of the same tumor, measuring the same thing. mRMR lowers this to by selecting other types (texture, smoothness). But test accuracies , and 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 (), because the problem is easy. Redundancy matters when 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.
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 (), then slowly to 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 (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).
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 and : weakest () is below the top two noise ( and ), so no threshold separates it. Thus includes five true and 2 false, while and admit no false but lose one or two true. Bounds (, and expected false positives) greatly exceed observed (2, 0, 0): worst-case guarantees. Bound exceeds stable set size (7 features), and (2.28 for a set of 3) is little better: as bound is times a factor above 1, it informs only if is small relative to , here versus . With and as before it does inform.
Stability measures: the two functions, also two coding exercises below, and their random-selection baseline.
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 to going from to , while Nogueira gives zero ( to ) in all three: chance-corrected. Now three selectors across ten subsamples of the same data. Measure stability and correctness, since true features are known here.
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")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 recovers all five true features in every subsample but selects about 19 total and is least stable (Nogueira ). Stability selection is most stable () and admits least noise, losing one or two true features. Top five by is fairly stable () 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.
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.
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 against true ; inside the pipeline , chance, though with large dataset-to-dataset deviation : honest estimation with is noisy. With ten true features outside says when the procedure achieves on new data; inside says , slightly pessimistic as expected.
Choosing by CV is another search and must be nested. On pure noise with chosen among by GridSearchCV, the search’s best reported score is optimistic and nested CV corrects it:
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 on a problem with nothing to learn; nested CV gives . Six repetitions are too few to quantify the gap, but direction matches “best of ” theory.
Forward sequential selection in a scikit-learn pipeline on the first ten breast cancer features (means). The wrapper is expensive (each candidate takes fits), so reduce the problem to three of ten features.
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 ( versus ): with and just 10 candidates, selection cannot learn noise at that rate. This does not justify leakage: bias grows with and , and the pipeline is free. Finally compare all three families in scikit-learn, all inside pipelines with identical CV:
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 (): removing features saves cost and shrinks the model, not improves accuracy. With 5 features wrapper (RFE, ) loses less than filters (both ), which pick redundant features; L1 embedded picks 8 and reaches . The filter–no-selection difference () is about one fold standard deviation (); the comparison shows pattern, not a winner.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 3. What is the relation between and sums of squares?
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 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, rankingjaccard_stability(selections): receive a list of selections (each a list, tuple or array of feature indices) and return the mean over all pairs of . 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.0nogueira_stability(Z): Z is a 0/1 matrix with rows (one selection each) and columns. Return , with , the frequency of column and the mean ones per row. Assume .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.0Summary
- Relevance. Marginal relevance, conditional relevance and redundancy differ. XOR demonstrates , and . Two good individual features need not form a good pair (Cover), and exhaustive search costs .
- Filters. , and neighbor mutual information (Ross, KSG), cheap and model-free. They miss interactions. With two classes . mRMR subtracts mean pairwise redundancy but drops identity ‘s term.
- Wrappers. Sequential selection ( subsets with fits each), RFE ( 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 selection. - Stability. Use chance-corrected Nogueira, not Jaccard alone. Stability selection uses half-data selection frequency, threshold and guarantee under noise exchangeability and a method no worse than chance. Knockoffs control false discovery rate. Stable is not correct, and association is not causation.