Concepts / Feature Selection Fundamentals

Feature Selection Fundamentals

Recursive Feature Elimination repeatedly removes features until a specified number, such as the 40 in the source example, is reached.

  • Programming

Why Let an Algorithm Choose the Features

Feature selection answers a practical question. When you are unsure which columns of your data to feed into a machine learning algorithm, can an automatic method pick the useful ones for you? Recursive Feature Elimination, usually called RFE, is one such method. It works by recursively eliminating features until a specified number is reached. In the source example that number is 40, so the method starts with the full set of columns and keeps removing them until 40 remain.

Automatic feature selection is most useful when you do not know in advance which inputs matter. Reducing the number of features also has practical benefits. A smaller feature set means less data to process at prediction time, and fewer inputs to explain when you need to justify what a model does. Keep these benefits in mind, because the rest of this article shows that they come at a real cost in computation.

What do you think happens?

As RFE works through its rounds, does the number of features still in play go up, down, or stay the same from one round to the next?

  • It goes up each round

  • It goes down each round

  • It stays the same until the end

Reveal answer
Answer:

It goes down each round.

RFE removes features repeatedly, so each round leaves fewer features than the round before, until the number specified by n_features_to_select remains.

Tracing the Elimination Loop

RFE wraps an estimator, which is the model it trains again and again while deciding what to remove. In the source setup the estimator is a RandomForestClassifier with 100 trees and a fixed random_state of 42. On each round RFE fits the estimator on the features that are still in play, ranks those features, and drops the weakest. Then it repeats the same fit-rank-eliminate cycle on the smaller set.

All featuresfull column setFit foreston features still in playRank featuresby importanceDrop weakestone feature removedCount reached?target fromn_features_to_selectTarget features40 in the source exampleround beginsimportanceslowest removedcount fallsno, repeatyes, stop
On each round, what gets fitted, which feature is dropped, and how the feature count falls until the target number remains.

The loop explains the cost that the source warns about. Because the random forest is trained once for each feature that is dropped, the total work grows with the number of eliminations. The more features RFE must remove before reaching its target, the more models it trains. The source describes RFE as computationally expensive for exactly this reason.

Setting Up RFE in Python

The setup has three parts: the estimator RFE will retrain, the stopping point given by n_features_to_select, and the fit call that runs the loop. The code below follows the logic of the source example, reordered so every name is defined before it is used. It assumes that X_train, X_test, y_train, and y_test already exist, and that the feature table has been split into training and test portions.

python
Output (expected)
A boolean array with one True or False per original column
Notes on the code
  • RandomForestClassifier is the estimator RFE retrains on each round
  • n_features_to_select=40 tells RFE where to stop eliminating
  • fit runs the whole elimination loop on the training data
  • get_support returns one True or False entry per original feature

Reading the Selected-Feature Mask

After fit has run, get_support returns a mask with one entry per original feature. The mask is positional. Its first entry describes the first original column, its second entry describes the second column, and so on. A True entry means that column survived elimination and a False entry means it was dropped. Reading the mask is therefore a matter of lining it up against the original column list.

col_0True, keptcol_1False, droppedcol_2True, keptcol_3True, keptcol_4False, droppedposition orderposition orderposition orderposition order
Each position in the mask corresponds to the same position in the original columns. This illustration uses five made-up columns to show which ones survive.
Worked example

Which columns survive a five-column mask

A selector was fitted on a table with five columns named col_0 through col_4. Its mask is True, False, True, True, False. Which columns does the selector keep?

  1. 1
    Pair each mask entry with its column

    Entry 0 belongs to col_0, entry 1 to col_1, entry 2 to col_2, entry 3 to col_3, and entry 4 to col_4.

  2. 2
    Keep the True positions

    Entries 0, 2, and 3 are True, so col_0, col_2, and col_3 survive.

  3. 3
    Drop the False positions

    Entries 1 and 4 are False, so col_1 and col_4 are eliminated.

  4. 4
    Keep the original order

    The surviving columns stay in their original order, which is the order transform uses when it reduces the data.

Result

The selector keeps col_0, col_2, and col_3, and drops col_1 and col_4.

Fitting Once and Transforming Everything Else

Once RFE has fit, the selector can shrink both the training and test data down to the chosen features. The fit step is the only step that learns which features to keep, and it does so using training data alone. Calling transform on the training data and on the test data then applies that already-learned choice. The columns come back in the correct order, so the reduced arrays line up with each other.

Training dataX_train, y_trainRFE fitselects featurestransformkeeps selected columnsLogistic regressionfitted on reduced trainingsetTest accuracyscored on reduced test setTest dataX_test, y_testfit only herelearned choicereduced traintransform onlyreduced test
Training data drives the selection. Test data is only transformed and scored, so it never influences which features are kept.
python
Output (expected)
Two test accuracy values, one for the logistic regression and one for the forest inside RFE
Notes on the code
  • transform applies the already-learned selection to the training data
  • transform applies the same selection to the test data without re-selecting
  • The logistic regression is fitted only on the reduced training set
  • The first score call uses the reduced test set
  • selector.score scores the forest inside RFE using only the selected features

Weighing RFE Against Other Selection Methods

The source compared RFE with univariate selection and with model-based selection. In its experiment RFE chose features that performed better than either alternative. It also missed one feature that mattered, so even its best selection is not guaranteed to be perfect. The performance gain came at a cost in time, because RFE trains many models where model-based selection trains one.

ApproachModels trainedRelative costWhat the source reports
RFE with a random forestOne per dropped featureComputationally expensiveSelected better-performing features, but took significantly longer
Model-based selectionOne modelLowerSelected features that performed worse than RFE's choice
Univariate selectionScores each feature on its ownLowerSelected features that performed worse than RFE's choice

Cost and results for the selection approaches compared in the source experiment

RFE is worth its cost when the quality of the selected features matters more than the time spent finding them, and when a single-pass method is not good enough for your data. When speed of selection is the priority, or when you are unsure whether the extra accuracy is needed, a cheaper approach is a reasonable first choice.

Mistakes Beginners Make With RFE

  • Common mistake

    Expecting the mask to hold feature names

    What it looks like

    Printing the mask and assuming it says which columns were kept by name

    Why it fails

    get_support returns True or False values by position, one per original feature.

    Do this instead

    Pair each mask entry with the original column at the same position, as in the mask-reading example.

  • Common mistake

    Fitting the selector on the test set

    What it looks like
    Calling selector.fit(X_test, y_test) to get a fresh selection
    Why it fails

    The test set then influences which features are kept, so the test score is no longer an honest measure.

    Do this instead

    Fit only on training data, then use transform and score on the test set.

  • Common mistake

    Forgetting that RFE is expensive

    What it looks like

    Running RFE with a large forest on a huge feature table and wondering why it is slow

    Why it fails

    RFE retrains the estimator once for each dropped feature, so the work grows with the number of eliminations.

    Do this instead

    Weigh the extra accuracy against the longer run time before choosing RFE.

  • Common mistake

    Assuming RFE always finds the perfect set

    What it looks like

    Trusting the selected set without checking it

    Why it fails

    The source reports that RFE still missed one feature in its experiment.

    Do this instead

    Compare the selected set's results against other approaches before relying on it.

Practice Tracing the Selector

EASY

A selector was fitted with n_features_to_select set to 40. Its mask has True at positions 0, 3, and 7, and False everywhere else in the first ten positions. Which original columns are kept among the first ten, and what should you pass to transform to reduce the test data?

Hints
  • Match each True position to the original column at the same index.
  • transform takes the test data and uses the selection learned during fit.
  • The test data is never passed to fit.
MEDIUM

Explain, in your own words, why calling fit on the training data and transform on the test data gives a fairer test score than fitting on both.

Hints
  • Think about whether the test data should influence which features are chosen.

Key Takeaways

  • RFE repeatedly fits an estimator, ranks the features, and drops the weakest one, until the number set by n_features_to_select remains.
  • get_support returns a True or False mask with one entry per original feature, matched to columns by position.
  • Fit the selector on training data only, then use transform and score on the test data so the test set never influences which features are kept.
  • RFE trains a model once for each dropped feature, so it is computationally expensive. It can select better features than univariate or model-based selection, but it is not guaranteed to find the perfect set.
  • Reducing features can speed up prediction and make models easier to interpret, and a simpler model can match a complex one once the right features are chosen.

Related concepts

More concepts starting with F