TExcelTAD
Home › Machine Learning › Feature Selection

Feature Selection

More features are not always better. Irrelevant or redundant features add noise, slow training, make models harder to explain and increase the risk of overfitting — especially when you have few rows. Feature selection keeps only the most useful columns. Unlike PCA, it keeps original features, so the model stays interpretable.

There are three families of methods:

Family How it works Examples
Filter score each feature independently of any model variance threshold, correlation, ANOVA F-test, mutual information
Wrapper repeatedly train a model on feature subsets recursive feature elimination (RFE), sequential selection
Embedded selection happens during training Lasso (zero coefficients), tree importances

A data set with noise features

make_classification lets us control exactly how many features are informative. We create 25 features, only 4 of them useful:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier

X, y = make_classification(n_samples=300, n_features=25, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1,
                           shuffle=False, random_state=1)
# with shuffle=False the informative features are the first 4 columns

all_feat = cross_val_score(KNeighborsClassifier(), X, y, cv=5).mean()
useful = cross_val_score(KNeighborsClassifier(), X[:, :4], y, cv=5).mean()
print(f"KNN with all 25 features:      {all_feat:.3f}")
print(f"KNN with the 4 useful features: {useful:.3f}")
KNN with all 25 features:      0.917
KNN with the 4 useful features: 0.977

The 21 noise features clearly hurt a distance-based model like KNN: every irrelevant column adds random noise to the distances. Let's see whether selection methods can find the good ones on their own.

Filter: remove constant features

The cheapest check: a feature that barely changes carries no information. VarianceThreshold drops features below a variance cut-off:

python · try it yourself
import numpy as np
from sklearn.feature_selection import VarianceThreshold

X = np.array([[1, 0.0, 3.1, 7],
              [2, 0.0, 2.9, 7],
              [3, 0.1, 3.0, 7],
              [4, 0.0, 3.2, 7]])
selector = VarianceThreshold(threshold=0.01).fit(X)
print("variances:", selector.variances_.round(4))
print("kept columns:", selector.get_support(indices=True))
variances: [1.25   0.0019 0.0125 0.    ]
kept columns: [0 2]

Filter: univariate statistics

SelectKBest scores every feature with a statistical test and keeps the top k. For classification, f_classif (ANOVA F-test) measures how much a feature's mean differs between classes; mutual_info_classif also catches non-linear relationships:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, f_classif

X, y = make_classification(n_samples=300, n_features=25, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1,
                           shuffle=False, random_state=1)

selector = SelectKBest(score_func=f_classif, k=4).fit(X, y)
print("selected columns:", selector.get_support(indices=True))
top = selector.scores_.argsort()[::-1][:6]
print("top-6 F scores:", [(int(i), round(float(selector.scores_[i]), 1)) for i in top])
selected columns: [ 0  1  2 21]
top-6 F scores: [(1, 271.9), (0, 192.4), (2, 178.3), (21, 3.9), (13, 2.6), (17, 2.5)]

Wrapper: recursive feature elimination

RFE trains a model, removes the weakest feature (smallest coefficient or importance), and repeats until the requested number remains:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=300, n_features=25, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1,
                           shuffle=False, random_state=1)

rfe = RFE(LogisticRegression(max_iter=1000), n_features_to_select=4).fit(X, y)
print("selected columns:", rfe.get_support(indices=True))
print("ranking of the first 10 columns:", rfe.ranking_[:10])
selected columns: [0 1 2 3]
ranking of the first 10 columns: [ 1  1  1  1  9 15  2 18  6  4]

Rank 1 means "selected"; higher ranks were eliminated earlier. RFE found exactly the four informative columns, while the F-test above picked three of them plus one noise column: testing features one at a time is cheaper but cruder than refitting a model.

Embedded: importance from a model

SelectFromModel keeps features whose importance (or absolute coefficient) is above a threshold, here the mean importance of a random forest:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=300, n_features=25, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1,
                           shuffle=False, random_state=1)

forest = RandomForestClassifier(n_estimators=100, random_state=0)
selector = SelectFromModel(forest, threshold="mean").fit(X, y)
print("selected columns:", selector.get_support(indices=True))
print("X shrinks from", X.shape, "to", selector.transform(X).shape)
selected columns: [0 1 2 3]
X shrinks from (300, 25) to (300, 4)

Selection inside a pipeline

Selection must be learned on training data only — selecting features using all rows and then cross-validating leaks information and gives over-optimistic scores. Put the selector in a pipeline so it is refit within every fold:

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.neighbors import KNeighborsClassifier

X, y = make_classification(n_samples=300, n_features=25, n_informative=4,
                           n_redundant=0, n_clusters_per_class=1,
                           shuffle=False, random_state=1)

for k in [2, 4, 8, 25]:
    pipe = make_pipeline(StandardScaler(), SelectKBest(f_classif, k=k), KNeighborsClassifier())
    print(f"k={k:2}: CV accuracy {cross_val_score(pipe, X, y, cv=5).mean():.3f}")
k= 2: CV accuracy 0.880
k= 4: CV accuracy 0.913
k= 8: CV accuracy 0.890
k=25: CV accuracy 0.847

Test yourself

Which method trains a model repeatedly, removing the weakest feature each round?

  1. VarianceThreshold
  2. SelectKBest
  3. Recursive feature elimination (RFE)
  4. PCA

How does feature selection differ from PCA?

  1. It creates new mixed features
  2. It keeps a subset of the original features
  3. It only works for regression
  4. It requires no data

Why should feature selection happen inside a pipeline during cross validation?

  1. It runs faster
  2. Otherwise the selection sees the validation folds and scores become over-optimistic
  3. Pipelines are required by SelectKBest
  4. To scale the target