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 , zero exactly when and are independent; estimated by binning or by nearest-neighbor estimators (Kraskov, Stögbauer & Grassberger, 2004).
- tests of independence for categorical features against a categorical target.
- mRMR (Peng, Long & Ding, 2005) adds features greedily, each time maximizing relevance minus redundancy, , to avoid picking ten copies of the same signal.
and are independent fair coin flips and (exclusive or). What do univariate filters say about and ?
- Both have high mutual information with
- Both have zero correlation and zero mutual information with , although together they determine exactly
- is relevant and is not
- Filters cannot be computed for binary features
Show the answer
B. Both have zero correlation and zero mutual information with , although together they determine exactly
Knowing alone leaves a fair coin, so , and likewise for ; yet 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 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 , removes the lowest-ranked, retrains and repeats; it was introduced to select genes for cancer classification.
Embedded methods select while fitting. The lasso's penalty sets coefficients exactly to zero, and as 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).
| Family | Cost | Sees interactions? | Main risk |
|---|---|---|---|
| Filters | one pass over the features | no (except multivariate filters) | keeps redundant features, misses joint effects |
| Wrappers | many model fits, for stepwise paths | yes, through the model | overfitting the validation data; instability |
| Embedded | about one fit (a path of fits for the lasso) | as far as the model does | arbitrary choice among correlated features; biased importances |
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?
Let features be independent of the target and of each other. For large , each sample correlation with the target is approximately normal with variance , and a Gaussian tail bound gives:
A union bound over the features bounds the chance that any of them exceeds :
The right side drops below 1 once passes the level below, so the largest spurious correlation is of that order. It grows only like , but that is enough: with samples and features the bound gives 0.45, and in simulation the best noise feature typically correlates at about 0.39 with any labels you like.
You have samples, a random target and 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 , and the maximum of 10,000 of them sits near four standard deviations: simulations give about 0.39, and the union bound 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 -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 , run the selector (for example the lasso over a grid of penalties) on each, and estimate each feature's selection probability . Keep the stable set . 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, with the number of selections. In the model-X form of Candès, Fan, Janson & Lv (2018), which treats the rows of as i.i.d. draws from a known distribution, you build for each feature a knockoff such that
- swap invariance: exchanging any subset of features with their knockoffs leaves the joint distribution of unchanged;
- is independent of given , for instance because it is constructed without looking at .
Fit any model to and form statistics that flip sign when and swap, such as from a lasso. A large positive means the real feature beat its fake copy. The knockoff+ filter selects , where is the smallest of the values with
(nothing is selected if no value qualifies). Model-X knockoffs then control the FDR for any conditional distribution of given and any number of features. The original fixed-design knockoffs of Barber & Candès (2015) need no model for , only the homoscedastic Gaussian linear model with at least as many observations as features: their knockoffs mimic the Gram matrix, and for a nonnegative vector , and they proved exactly in finite samples, whatever the design.
In the model-X setting, for an irrelevant feature , swapping with changes nothing about the joint law of : swap invariance handles , and given the other features depends on neither. But the swap flips the sign of . So the signs of the null are independent fair coins, independent of their magnitudes and of everything else:
Hence, at any threshold, as many nulls are expected below as above , and the count of negative statistics, plus one, conservatively estimates the number of false selections. The threshold keeps that estimated false discovery proportion below :
Write the true FDP at as this estimate times a ratio of null counts. The ratio, , 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 by an estimate of the mean target in it. For a binary target, put a prior on the level's rate, centered at the global mean with strength ; the posterior mean is the smoothed encoding
which trusts frequent levels and shrinks rare ones toward . Micci-Barreca (2001) proposed this kind of blend, with a weight that grows with . In a large benchmark with lasso, random forests, gradient boosting, -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.
Computed on the same rows it encodes, row 's value includes its own label, with weight , where is the sum of the other labels in its level:
For a level seen once, and the encoding is a function of 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 ), so the separation the model learned disappears. Out-of-fold encoding computes from the other folds only, which removes ; CatBoost's ordered statistics use only the rows before in a random order (XGBoost, LightGBM & CatBoost).
Collisions are cheap to estimate: active features hashed into buckets produce about colliding pairs, so 10,000 features in 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 noise features correlates at about 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 ; knockoffs control the false discovery rate exactly in finite samples, in the Gaussian linear model with a fixed design and , 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.
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?
- 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
- Nothing, because the classifier itself was cross-validated
- Mutual information cannot be used for selection
- 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.
What does the knockoff filter guarantee about the features it selects, at target level ?
- That every selected feature is truly relevant
- That the probability of selecting any null feature is at most
- That all truly relevant features are selected with probability
- That the expected fraction of null features among those selected is at most , in finite samples
Show the answer
D. That the expected fraction of null features among those selected is at most , in finite samples
Knockoffs control the false discovery rate, , where counts selected nulls and all selections, exactly in finite samples under their assumptions. They say nothing about power, and they do not control the family-wise error rate.
Feature hashing multiplies each feature by a random sign from a second hash function before adding it into its bucket. Why?
- To make the hashed vectors sparse
- So that colliding features cancel in expectation, making hashed inner products unbiased for the original ones
- To avoid collisions altogether
- 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 , and , so the cross terms from collisions vanish on average and . Without signs, collisions would add a systematic positive bias for nonnegative features such as counts.
Stability selection with features, an average of features selected per subsample, and threshold . What bound does the Meinshausen–Bühlmann theorem give on the expected number of falsely selected features?
- About 0.5
- About 0.8
- About 1.33
- About 16
Show the answer
C. About 1.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).