TExcelTAD

Wrapper Methods

Filters score each feature alone. But features work in teams: two columns can be useless separately and decisive together, and ten columns can say the same thing ten times. Wrapper methods judge a feature subset by what actually matters, the validated score of the model trained on it. They "wrap" a search around the model: propose a subset, train, score, propose a better one. They find better subsets than filters for the model at hand, at the cost of training it many times.

searchforward, backward, RFE model on subsettrain + cross-validate best subsetwhen search stops subset score one model fit per subset per fold: accurate but expensive

Search strategies

Trying every subset is impossible beyond a handful of features: p features have 2**p subsets, over a million for 20 features. Wrappers search greedily instead:

Strategy Starts with Each step Fits per step
Forward selection no features add the feature that improves the score most one per remaining feature
Backward elimination all features remove the feature whose removal hurts least one per current feature
Recursive feature elimination (RFE) all features train once, drop the feature(s) with the smallest importance or coefficient one
RFECV all features RFE, and cross-validation picks how many to keep one per fold

Forward and backward selection score subsets directly (sound but slow); RFE uses the model's own importances to decide what to drop (fast, but only as good as those importances).

From scratch: forward selection

The diabetes dataset that ships with scikit-learn has 10 numeric features (age, sex, BMI, blood pressure and six blood measurements) and a disease-progression score. Greedy forward selection with the 5-fold cross-validated R2 score, written out:

python · try it yourself
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score, KFold

data = load_diabetes()
X, y, names = data.data, data.target, data.feature_names
cv = KFold(5, shuffle=True, random_state=0)

chosen, remaining, best_so_far = [], list(range(X.shape[1])), -np.inf
while remaining:
    scores = {j: cross_val_score(LinearRegression(), X[:, chosen + [j]], y, cv=cv, scoring="r2").mean()
              for j in remaining}
    j_best = max(scores, key=scores.get)
    if scores[j_best] <= best_so_far + 0.002:     # stop when the gain is negligible
        break
    chosen.append(j_best)
    remaining.remove(j_best)
    best_so_far = scores[j_best]
    print(f"add {names[j_best]:4s} -> CV R2 = {best_so_far:.3f}")
all_r2 = cross_val_score(LinearRegression(), X, y, cv=cv, scoring="r2").mean()
print("selected:", [names[j] for j in chosen], f"| all 10 features: CV R2 = {all_r2:.3f}")
add bmi  -> CV R2 = 0.333
add s5   -> CV R2 = 0.444
add bp   -> CV R2 = 0.464
add s3   -> CV R2 = 0.474
add sex  -> CV R2 = 0.491
selected: ['bmi', 's5', 'bp', 's3', 'sex'] | all 10 features: CV R2 = 0.489

The first two features (BMI and s5, a blood-serum measurement) carry most of the signal; the search stops after 5 features with a score at least as good as using all ten (0.491 against 0.489). That is the typical outcome: a smaller model, about as accurate, easier to explain and cheaper to collect data for.

The scikit-learn wrappers

SequentialFeatureSelector implements forward and backward selection, RFE and RFECV the elimination family. On a synthetic problem with 5 informative, 5 redundant (linear combinations of the informative ones) and 10 noise features:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.feature_selection import SequentialFeatureSelector, RFE, RFECV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold

X, y = make_classification(n_samples=400, n_features=20, n_informative=5, n_redundant=5,
                           n_repeated=0, shuffle=False, random_state=0)
# with shuffle=False, columns 0-4 are informative, 5-9 redundant, 10-19 noise
cv = StratifiedKFold(5, shuffle=True, random_state=0)
model = LogisticRegression(max_iter=1000)

sfs = SequentialFeatureSelector(model, n_features_to_select=5, direction="forward", cv=cv).fit(X, y)
print("forward, 5 features:", np.flatnonzero(sfs.get_support()).tolist())
rfe = RFE(model, n_features_to_select=5).fit(X, y)
print("RFE, 5 features:    ", np.flatnonzero(rfe.get_support()).tolist())
rfecv = RFECV(model, cv=cv, scoring="accuracy").fit(X, y)
print("RFECV keeps", int(rfecv.n_features_), "features:", np.flatnonzero(rfecv.get_support()).tolist())
print("noise features kept by RFECV:", int(rfecv.get_support()[10:].sum()))
forward, 5 features: [1, 2, 7, 8, 13]
RFE, 5 features:     [1, 2, 4, 5, 7]
RFECV keeps 4 features: [1, 2, 4, 5]
noise features kept by RFECV: 0

None of the methods needs to pick exactly columns 0 to 4: a redundant column is a linear mix of informative ones, so it can stand in for one of them with no loss. What matters is the noise columns (10 to 19): forward selection let one in (column 13), RFE and RFECV none, and RFECV decided that 4 columns are enough.

Wrappers inside cross-validation

A wrapper looks at the labels many times, so its choice must be validated on rows it never saw. Put it in the pipeline and cross-validate the whole pipeline: then every outer fold runs its own search on its own training rows. This is nested cross-validation (inner folds choose features, outer folds score the procedure), see Nested Cross-Validation:

python · try it yourself
from sklearn.datasets import load_diabetes
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_diabetes(return_X_y=True)
inner, outer = KFold(5, shuffle=True, random_state=1), KFold(5, shuffle=True, random_state=2)
pipe = make_pipeline(StandardScaler(),
                     SequentialFeatureSelector(LinearRegression(), n_features_to_select=4, cv=inner),
                     LinearRegression())
scores = cross_val_score(pipe, X, y, cv=outer, scoring="r2")
print("outer-fold R2:", scores.round(3).tolist(), "| mean", round(scores.mean(), 3))
fits = 5 * sum(5 * (10 - s) for s in range(4)) + 5
print("models trained:", fits)
outer-fold R2: [0.386, 0.5, 0.479, 0.404, 0.476] | mean 0.449
models trained: 855

An honest 0.449, lower than the 0.491 of the first example, whose search had looked at every row; part of that gap is the optimism of selecting and scoring on the same rows (the rest: 4 features here, 5 there, and different folds). It comes at the price of 855 model fits for a 10-feature dataset and a single linear model; with a gradient-boosted model and 200 features, a wrapper becomes a serious compute bill.

Pitfalls

  • Selecting on the full data, then cross-validating: the subset was chosen with the test rows' help; the score is optimistic. Always wrap the selector in the pipeline.
  • Overfitting the search: with many features and few rows, the greedy search finds subsets that fit the validation folds by chance. Small, stable gains are suspicious; check that the selected subset is similar across outer folds.
  • Cost: forward selection on p features needs about p * k / 2 cross-validated fits to choose k. Start with a filter to cut thousands of features to a few hundred, then wrap.
  • Model-specific: a subset that is best for a linear model may not be best for a tree ensemble. Select with the model you will deploy.

Practice

  1. With 30 features, how many subsets would an exhaustive search try, and how many cross-validated fits does forward selection need to choose all 30 in order?
Answer

2**30, about 1.07 billion subsets. Forward selection evaluates 30 + 29 + ... + 1 = 465 subsets (each with k-fold cross-validation, so 465k fits).

  1. RFE with a random forest drops features with the lowest impurity importance. Why can this go wrong with two highly correlated features?
Answer

The forest splits its importance between the two copies, so each looks only half as important and both may be dropped early, even though one of them is needed. Permutation importance has the same weakness; dropping one copy at a time (step=1) and checking the validated score helps.

Test yourself

What distinguishes a wrapper method from a filter?

  1. It is faster
  2. It scores feature subsets by training and validating the model on them
  3. It uses only the variance
  4. It never looks at the labels

Recursive feature elimination drops features based on...

  1. Their names
  2. The fitted model's coefficients or importances, refitting after each drop
  3. Random choice
  4. Their mutual information

You run forward selection on all rows, then report 5-fold CV accuracy of the chosen subset. What is wrong?

  1. Nothing
  2. The subset was chosen using the test folds, so the score is optimistic; the selector must run inside each training fold
  3. Forward selection cannot be cross-validated
  4. Accuracy is the wrong metric