Simple Algorithm
Machine Learning · Convergence · 26 min

Feature Selection & Encoding

Filters, wrappers, embedded methods, target encoding and hashing.

With thousands of candidate features, a few carry signal, most carry noise, and the best of the noise looks convincing. This lesson defines relevance precisely, compares filters, wrappers and embedded methods, shows how selecting features outside cross-validation manufactures accuracy, controls false selections with stability selection and knockoffs, and ends with the encoding of high-cardinality categories, where selection and leakage meet.

What you’ll learn

  • Define strong and weak relevance, and explain why univariate filters miss interactions and keep redundant features.
  • Compare filters, wrappers and embedded methods by cost and failure modes, and read a lasso path as a selection procedure.
  • Show that selection outside cross-validation biases error estimates, and bound the best spurious correlation among noise features.
  • State the guarantees of stability selection and of knockoffs, and sketch why knockoffs control the false discovery rate in finite samples.
  • Derive smoothed and out-of-fold target encoding and the unbiasedness of signed feature hashing, and place entity embeddings among the encodings.

What makes a feature relevant

Feature selection serves three goals that pull in different directions: better predictions, cheaper and faster predictors, and understanding of the process that generated the data (Guyon & Elisseeff, 2003). For prediction, a redundant feature is harmless or even helpful, since averaging two noisy copies of a signal reduces noise; for understanding, which of two redundant features is "the" relevant one may be undecidable.

Filters score each feature on its own, before and independently of the model:

  • Correlation with the target: cheap, but sees only linear, marginal dependence.
  • Mutual information I(Xj;Y)=DKL(p(xj,y) ∥ p(xj)p(y))I(X_j;Y)=\KL\big(p(x_j,y)\,\|\,p(x_j)p(y)\big), zero exactly when XjX_j and YY are independent; estimated by binning or by nearest-neighbor estimators (Kraskov, Stögbauer & Grassberger, 2004).
  • χ2\chi^2 tests of independence for categorical features against a categorical target.
  • mRMR (Peng, Long & Ding, 2005) adds features greedily, each time maximizing relevance minus redundancy, I(Xj;Y)−1∣S∣∑s∈SI(Xj;Xs)I(X_j;Y)-\frac1{\abs S}\sum_{s\in S}I(X_j;X_s), to avoid picking ten copies of the same signal.
Check your understanding

X1X_1 and X2X_2 are independent fair coin flips and Y=X1⊕X2Y=X_1\oplus X_2 (exclusive or). What do univariate filters say about X1X_1 and X2X_2?

  1. Both have high mutual information with YY
  2. Both have zero correlation and zero mutual information with YY, although together they determine YY exactly
  3. X1X_1 is relevant and X2X_2 is not
  4. Filters cannot be computed for binary features
Show the answer

B. Both have zero correlation and zero mutual information with YY, although together they determine YY exactly

Knowing X1X_1 alone leaves YY a fair coin, so I(X1;Y)=0I(X_1;Y)=0, and likewise for X2X_2; yet I(X1,X2;Y)=1I(X_1,X_2;Y)=1 bit. Both features are strongly relevant, and every univariate filter discards them. Interactions are why wrappers and embedded methods exist.

Wrappers and embedded methods

Wrappers search over subsets, scoring each by the validated performance of the actual model (Kohavi & John, 1997). Forward selection adds the feature that helps most, backward elimination removes the one that hurts least; each full path costs O(d2)O(d^2) model fits and can overfit the validation data used to steer it. Recursive feature elimination (RFE; Guyon, Weston, Barnhill & Vapnik, 2002) trains a linear SVM, ranks features by their squared weights wj2w_j^2, removes the lowest-ranked, retrains and repeats; it was introduced to select genes for cancer classification.

Embedded methods select while fitting. The lasso's ℓ1\ell_1 penalty sets coefficients exactly to zero, and as λ\lambda grows features leave the model one by one; when it recovers exactly the right features depends on restricted-eigenvalue and irrepresentability-type conditions (Sparse Recovery Guarantees). The elastic net keeps groups of correlated features together. Tree ensembles produce importance scores as a by-product, with their own biases (Feature Importance & Its Pitfalls).

FamilyCostSees interactions?Main risk
Filtersone pass over the featuresno (except multivariate filters)keeps redundant features, misses joint effects
Wrappersmany model fits, O(d2)O(d^2) for stepwise pathsyes, through the modeloverfitting the validation data; instability
Embeddedabout one fit (a path of fits for the lasso)as far as the model doesarbitrary choice among correlated features; biased importances
Whatever the family, the selection is part of the learning algorithm: its effect on accuracy can only be measured if it is repeated inside every training fold.

Selection bias: accuracy from noise

Ambroise & McLachlan (2002) examined published cancer classifiers built from thousands of microarray genes. When the genes were chosen on all samples and only the final classifier was cross-validated, the error estimates came out near zero, a selection bias; redoing the selection inside each fold, "external" cross-validation, removed the illusion. They recommended 10-fold rather than leave-one-out cross-validation, or the .632+ bootstrap estimator, designed for overfitted rules. How strong can pure noise look?

DerivationThe best of many noise features
  1. rj ∼˙ N(0,1n),P(∣rj∣>t)≲2e−nt2/2r_j\ \dot\sim\ \mathcal N\big(0,\tfrac1n\big),\qquad P\big(\abs{r_j}>t\big)\lesssim2e^{-nt^2/2}

    Let dd features be independent of the target and of each other. For large nn, each sample correlation with the target is approximately normal with variance 1/n1/n, and a Gaussian tail bound gives:

  2. P(max⁡j≤d∣rj∣>t)≲2d e−nt2/2P\Big(\max_{j\le d}\abs{r_j}>t\Big)\lesssim2d\,e^{-nt^2/2}

    A union bound over the dd features bounds the chance that any of them exceeds tt:

  3. t∗=2ln⁡(2d)n,n=100, d=104: t∗≈0.45t^\ast=\sqrt{\frac{2\ln(2d)}{n}},\qquad n=100,\ d=10^4:\ t^\ast\approx0.45

    The right side drops below 1 once tt passes the level below, so the largest spurious correlation is of that order. It grows only like log⁡d\sqrt{\log d}, but that is enough: with n=100n=100 samples and d=10,000d=10{,}000 features the bound gives 0.45, and in simulation the best noise feature typically correlates at about 0.39 with any labels you like.

Predict before you look

You have n=100n=100 samples, a random target and 10,00010{,}000 features of pure noise. About how large is the largest absolute correlation between a feature and the target?

Show the answer

0.39

Each correlation has standard deviation about 1/100=0.11/\sqrt{100}=0.1, and the maximum of 10,000 of them sits near four standard deviations: simulations give about 0.39, and the union bound 2ln⁡(2d)/n\sqrt{2\ln(2d)/n} gives 0.45. A correlation of 0.39 would look like a solid finding in isolation, which is why selection must be repeated inside each fold and why reported effects of selected features are inflated (the winner's curse).

The same selection effect breaks classical inference. A pp-value or confidence interval computed for a coefficient as if the selected model had been fixed in advance is invalid, because the data chose the model. Valid alternatives either protect against every model the procedure could have selected (Berk, Brown, Buja, Zhang & Zhao, 2013) or condition on the event that the procedure selected this one, as exact post-selection inference for the lasso does (Lee, Sun, Sun & Taylor, 2016).

Controlling false selections

Stability selection (Meinshausen & Bühlmann, 2010) asks which features a selector picks reliably. Draw many random subsamples of size ⌊n/2⌋\lfloor n/2\rfloor, run the selector (for example the lasso over a grid Λ\Lambda of penalties) on each, and estimate each feature's selection probability Π^jλ\hat\Pi_j^\lambda. Keep the stable set {j:max⁡λ∈ΛΠ^jλ≥πthr}\{j:\max_{\lambda\in\Lambda}\hat\Pi_j^\lambda\ge\pi_{\text{thr}}\}. Correlated twins, which the lasso alternates between, each get selected about half the time instead of one of them being declared relevant by accident.

Knockoffs control the false discovery rate instead, FDR=E[V/max⁡(R,1)]\mathrm{FDR}=\E\big[V/\max(R,1)\big] with RR the number of selections. In the model-X form of Candès, Fan, Janson & Lv (2018), which treats the rows of XX as i.i.d. draws from a known distribution, you build for each feature XjX_j a knockoff X~j\tilde X_j such that

  1. swap invariance: exchanging any subset of features with their knockoffs leaves the joint distribution of (X,X~)(X,\tilde X) unchanged;
  2. X~\tilde X is independent of YY given XX, for instance because it is constructed without looking at YY.

Fit any model to [X,X~][X,\tilde X] and form statistics WjW_j that flip sign when XjX_j and X~j\tilde X_j swap, such as Wj=∣β^j∣−∣β^j~∣W_j=\abs{\hat\beta_j}-\abs{\hat\beta_{\tilde j}} from a lasso. A large positive WjW_j means the real feature beat its fake copy. The knockoff+ filter selects {j:Wj≥τ}\{j:W_j\ge\tau\}, where τ\tau is the smallest of the values t∈{∣Wj∣:Wj≠0}t\in\{\abs{W_j}:W_j\ne0\} with

1+#{j:Wj≤−t}max⁡(1,#{j:Wj≥t})≤q\frac{1+\#\{j:W_j\le-t\}}{\max\big(1,\#\{j:W_j\ge t\}\big)}\le q

(nothing is selected if no value qualifies). Model-X knockoffs then control the FDR for any conditional distribution of YY given XX and any number of features. The original fixed-design knockoffs of Barber & Candès (2015) need no model for XX, only the homoscedastic Gaussian linear model with at least as many observations as features: their knockoffs mimic the Gram matrix, X~⊤X~=X⊤X\tilde X^\top\tilde X=X^\top X and X⊤X~=X⊤X−diag⁡(s)X^\top\tilde X=X^\top X-\diag(\mathbf s) for a nonnegative vector s\mathbf s, and they proved FDR≤q\mathrm{FDR}\le q exactly in finite samples, whatever the design.

DerivationWhy knockoffs control the false discovery rate (sketch)
  1. (sign(Wj))j null =d i.i.d. ±1,independent of (∣Wj∣)j\big(\mathrm{sign}(W_j)\big)_{j\ \text{null}}\ \overset{d}{=}\ \text{i.i.d. }\pm1,\quad\text{independent of }\big(\abs{W_j}\big)_j

    In the model-X setting, for an irrelevant feature jj, swapping XjX_j with X~j\tilde X_j changes nothing about the joint law of (X,X~,Y)(X,\tilde X,Y): swap invariance handles (X,X~)(X,\tilde X), and given the other features YY depends on neither. But the swap flips the sign of WjW_j. So the signs of the null WjW_j are independent fair coins, independent of their magnitudes and of everything else:

  2. FDP^(t)=1+#{j:Wj≤−t}max⁡(1,#{j:Wj≥t}) ≥ 1+#{j null:Wj≤−t}max⁡(1,#{j:Wj≥t})\widehat{\mathrm{FDP}}(t)=\frac{1+\#\{j:W_j\le-t\}}{\max(1,\#\{j:W_j\ge t\})}\ \ge\ \frac{1+\#\{j\ \text{null}:W_j\le-t\}}{\max(1,\#\{j:W_j\ge t\})}

    Hence, at any threshold, as many nulls are expected below −t-t as above tt, and the count of negative statistics, plus one, conservatively estimates the number of false selections. The threshold τ\tau keeps that estimated false discovery proportion below qq:

  3. FDR=E[#{null Wj≥τ}1+#{null Wj≤−τ}⏟E[ ⋅ ]≤1⋅1+#{null Wj≤−τ}max⁡(1,#{j:Wj≥τ})⏟≤ FDP^(τ) ≤ q] ≤ q\mathrm{FDR}=\E\Big[\underbrace{\frac{\#\{\text{null }W_j\ge\tau\}}{1+\#\{\text{null }W_j\le-\tau\}}}_{\E[\,\cdot\,]\le1}\cdot\underbrace{\frac{1+\#\{\text{null }W_j\le-\tau\}}{\max(1,\#\{j:W_j\ge\tau\})}}_{\le\ \widehat{\mathrm{FDP}}(\tau)\ \le\ q}\Big]\ \le\ q

    Write the true FDP at τ\tau as this estimate times a ratio of null counts. The ratio, #{null Wj≥τ}/(1+#{null Wj≤−τ})\#\{\text{null }W_j\ge\tau\}/(1+\#\{\text{null }W_j\le-\tau\}), is a supermartingale in the threshold when the null signs are revealed one by one, so by optional stopping its expectation is at most 1:

Encoding high-cardinality categories

A category with thousands of levels (a zip code, a product, a user) is itself a selection problem: one-hot encoding creates a feature per level, most of them rare. Three families of encodings avoid that.

Target encoding replaces level cc by an estimate of the mean target in it. For a binary target, put a Beta(ayˉ, a(1−yˉ))\mathrm{Beta}(a\bar y,\,a(1-\bar y)) prior on the level's rate, centered at the global mean yˉ\bar y with strength aa; the posterior mean is the smoothed encoding

x~c=nc yˉc+a yˉnc+a,\tilde x_c=\frac{n_c\,\bar y_c+a\,\bar y}{n_c+a},

which trusts frequent levels and shrinks rare ones toward yˉ\bar y. Micci-Barreca (2001) proposed this kind of blend, with a weight that grows with ncn_c. In a large benchmark with lasso, random forests, gradient boosting, kk-nearest neighbors and SVMs, Pargent, Pfisterer, Thomas & Bischl (2022) found regularized target encoding consistently the best of the encodings they compared for high-cardinality features.

DerivationWhy in-sample target encoding leaks
  1. x~i=Sc,−i+yi+a yˉnc+a\tilde x_i=\frac{S_{c,-i}+y_i+a\,\bar y}{n_c+a}

    Computed on the same rows it encodes, row ii's value includes its own label, with weight 1/(nc+a)1/(n_c+a), where Sc,−iS_{c,-i} is the sum of the other labels in its level:

  2. nc=1:x~i=yi+ayˉ1+a∈{ayˉ1+a, 1+ayˉ1+a}n_c=1:\qquad\tilde x_i=\frac{y_i+a\bar y}{1+a}\in\Big\{\frac{a\bar y}{1+a},\ \frac{1+a\bar y}{1+a}\Big\}

    For a level seen once, Sc,−i=0S_{c,-i}=0 and the encoding is a function of yiy_i alone: positives and negatives get two different values, and a single threshold separates those rows perfectly. At prediction time the encoding cannot contain the new row's own label (a level never seen in training gets yˉ\bar y), so the separation the model learned disappears. Out-of-fold encoding computes x~i\tilde x_i from the other folds only, which removes yiy_i; CatBoost's ordered statistics use only the rows before ii in a random order (XGBoost, LightGBM & CatBoost).

Collisions are cheap to estimate: kk active features hashed into mm buckets produce about (k2)/m\binom k2/m colliding pairs, so 10,000 features in 2202^{20} buckets give about 48 collisions, harmless for a linear model, while a million features in the same buckets leave about 61% of them sharing a bucket.

Entity embeddings (Guo & Berkhahn, 2016) learn a dense vector per level inside a neural network, trained with the rest of the model. Similar levels end up close together, the vectors can be reused as features by other learners, and the authors used them to reach third place in a Kaggle competition. For "dirty" categories that are really free text (misspelled cities, job titles), similarity encodings based on string overlap help (Cerda, Varoquaux & Kégl, 2018).

Key takeaways

  • Relevance is conditional: strongly relevant features are needed by the Bayes predictor, weakly relevant ones are interchangeable, and features useless alone can be decisive together.
  • Filters are cheap and blind to interactions; wrappers see interactions but overfit their validation data; embedded methods such as the lasso select while fitting but choose arbitrarily among correlated features.
  • The best of dd noise features correlates at about 2ln⁡(2d)/n\sqrt{2\ln(2d)/n} with any target, so selection must be repeated inside each training fold, and inference after selection must account for it.
  • Stability selection bounds the expected number of false selections by qΛ2/((2πthr−1)p)q_\Lambda^2/((2\pi_{\text{thr}}-1)p); knockoffs control the false discovery rate exactly in finite samples, in the Gaussian linear model with a fixed design and n≥pn\ge p, or for any response model when the features' distribution is known (model-X).
  • Target encoding is an empirical-Bayes shrinkage that must be computed out of fold; signed hashing preserves inner products in expectation; embeddings learn dense codes for categories.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You keep the 20 features with the highest mutual information with the label, computed on the full dataset, then report the 10-fold cross-validated accuracy of a classifier trained on those 20. What is wrong?

  1. The selection used the labels of every held-out fold, so the estimate is optimistically biased; the selection must be redone inside each training fold
  2. Nothing, because the classifier itself was cross-validated
  3. Mutual information cannot be used for selection
  4. Ten folds are too many; leave-one-out would fix it
Show the answer

A. The selection used the labels of every held-out fold, so the estimate is optimistically biased; the selection must be redone inside each training fold

Selection is part of the learning procedure. Done on all the data, it picked features that fit the held-out labels too, including features that only correlate with them by chance, so every fold is contaminated. Repeating the selection inside each training fold gives an honest estimate.

Question 2

What does the knockoff filter guarantee about the features it selects, at target level qq?

  1. That every selected feature is truly relevant
  2. That the probability of selecting any null feature is at most qq
  3. That all truly relevant features are selected with probability 1−q1-q
  4. That the expected fraction of null features among those selected is at most qq, in finite samples
Show the answer

D. That the expected fraction of null features among those selected is at most qq, in finite samples

Knockoffs control the false discovery rate, E[V/max⁡(R,1)]≤q\E\big[V/\max(R,1)\big]\le q, where VV counts selected nulls and RR all selections, exactly in finite samples under their assumptions. They say nothing about power, and they do not control the family-wise error rate.

Question 3

Feature hashing multiplies each feature by a random sign ξ(j)∈{−1,+1}\xi(j)\in\{-1,+1\} from a second hash function before adding it into its bucket. Why?

  1. To make the hashed vectors sparse
  2. So that colliding features cancel in expectation, making hashed inner products unbiased for the original ones
  3. To avoid collisions altogether
  4. To make the hash function invertible
Show the answer

B. So that colliding features cancel in expectation, making hashed inner products unbiased for the original ones

The hashed inner product is ∑j,kξ(j)ξ(k)xjxk′ 1{h(j)=h(k)}\sum_{j,k}\xi(j)\xi(k)x_jx'_k\,\mathbf 1\{h(j)=h(k)\}, and E[ξ(j)ξ(k)]=1{j=k}\E[\xi(j)\xi(k)]=\mathbf 1\{j=k\}, so the cross terms from collisions vanish on average and E⟨ϕ(x),ϕ(x′)⟩=⟨x,x′⟩\E\langle\phi(\mathbf x),\phi(\mathbf x')\rangle=\langle\mathbf x,\mathbf x'\rangle. Without signs, collisions would add a systematic positive bias for nonnegative features such as counts.

Question 4

Stability selection with p=500p=500 features, an average of qΛ=20q_\Lambda=20 features selected per subsample, and threshold πthr=0.8\pi_{\text{thr}}=0.8. What bound does the Meinshausen–Bühlmann theorem give on the expected number of falsely selected features?

  1. About 0.5
  2. About 0.8
  3. About 1.33
  4. About 16
Show the answer

C. About 1.33

E[V]≤qΛ2(2πthr−1) p=4000.6×500≈1.33\E[V]\le\dfrac{q_\Lambda^2}{(2\pi_{\text{thr}}-1)\,p}=\dfrac{400}{0.6\times500}\approx1.33, under the theorem's exchangeability and better-than-random-guessing assumptions. Raising the threshold to 0.9 would lower it to 1.0.

Further reading

  • I. Guyon & A. Elisseeff, "An introduction to variable and feature selection," Journal of Machine Learning Research 3, 1157–1182 (2003).
  • C. Ambroise & G. J. McLachlan, "Selection bias in gene extraction on the basis of microarray gene-expression data," Proceedings of the National Academy of Sciences 99(10), 6562–6566 (2002).
  • N. Meinshausen & P. Bühlmann, "Stability selection," Journal of the Royal Statistical Society B 72(4), 417–473 (2010).
  • R. F. Barber & E. J. Candès, "Controlling the false discovery rate via knockoffs," Annals of Statistics 43(5), 2055–2085 (2015).
  • E. Candès, Y. Fan, L. Janson & J. Lv, "Panning for gold: 'model-X' knockoffs for high dimensional controlled variable selection," Journal of the Royal Statistical Society B 80(3), 551–577 (2018).