Feature Selection in Machine Learning: Complete Guide

Adding more features to a dataset does not automatically improve machine learning performance. In fact, including hundreds of irrelevant, redundant, or noisy columns can increase training time, consume more memory, make models harder to interpret, and increase the risk of overfitting.

This problem is closely related to the Curse of Dimensionality, where learning meaningful patterns becomes increasingly difficult as the number of dimensions grows.

Feature Selection is the process of identifying and retaining the most useful input variables while removing irrelevant, redundant, or less informative features.

Unlike dimensionality reduction techniques such as Principal Component Analysis (PCA), which transform original features into new representations, feature selection retains the original columns.

For example, suppose a customer dataset contains 100 features, including age, income, account balance, transaction frequency, customer ID, and several redundant financial fields.

Feature selection might identify 15 useful features and remove the remaining 85.

The resulting model can become simpler, faster, easier to interpret, and potentially more effective.

In this guide, we will explore the three major feature selection approaches—Filter Methods, Wrapper Methods, and Embedded Methods—with statistical techniques, Python implementations, Scikit-learn examples, advantages, limitations, and best practices.


1. Why Does Feature Selection Matter?

Feature selection is an important part of machine learning preprocessing because not every available feature contributes useful predictive information.

1.1 Reduces Overfitting

A dataset may contain irrelevant or noisy variables that capture random fluctuations rather than meaningful patterns.

When a model learns from too many unnecessary features, it may memorize training-specific relationships that do not generalize to unseen data.

Removing unhelpful features can reduce this risk.

1.2 Improves Model Interpretability

Consider two credit-scoring models:

  • Model A uses 450 input features.
  • Model B uses 12 meaningful financial indicators.

Model B may be easier to explain, audit, maintain, and debug.

This is especially valuable in industries such as banking, healthcare, and insurance, where understanding model decisions can be important.

1.3 Reduces Training and Inference Costs

Fewer input features can reduce:

  • Memory consumption.
  • Data storage requirements.
  • Model training time.
  • Hyperparameter tuning time.
  • Feature extraction overhead.
  • Inference latency.

The actual speed improvement depends on the algorithm and the cost of computing each feature.

1.4 Reduces Redundancy and Multicollinearity

A dataset may contain highly correlated features that provide overlapping information.

For example:

Annual Income
Monthly Income
Annual Salary

These columns may represent nearly the same underlying information.

Including strongly correlated predictors can make coefficient estimates unstable in linear and logistic regression models.

Feature selection can help reduce this redundancy.

However, correlated predictors are not automatically useless. Each may contain additional information in certain situations.

1.5 Improves Generalization

A carefully selected feature subset can help a model focus on meaningful relationships rather than unnecessary variables.

However, feature selection does not guarantee better performance. Removing useful features can also reduce predictive accuracy.

The selected subset should always be evaluated using validation data or cross-validation.


2. Feature Selection vs. Feature Extraction

Feature selection and feature extraction are related but different concepts.

ParameterFeature SelectionFeature Extraction
Main purposeSelects useful original featuresCreates new transformed features
Original columnsPreservedCombined or transformed
InterpretabilityUsually easierMay be more difficult
ExampleSelecting age, income, and balanceCreating principal components using PCA
Common techniquesRFE, Chi-Square, LassoPCA, LDA, Autoencoders

Example

Suppose your original dataset contains:

Age
Income
Account Balance
Transaction Frequency
Credit Score

Feature Selection might retain:

Income
Account Balance
Credit Score

The selected features remain unchanged.

Feature Extraction using PCA might instead create:

Principal Component 1
Principal Component 2

These components are combinations of the original features.

Key difference: Feature selection chooses existing variables; feature extraction creates new representations.


3. The Three Families of Feature Selection

Feature selection methods generally fall into three major categories.

<escape>

  1. Filter Methods: All Features → Statistical Evaluation → Selected Features → Model
  1. Wrapper Methods: All Features → Feature Subset Search ↔ Model Evaluation → Selected Features
  1. Embedded Methods: All Features → Model Training with Built-in Selection → Selected Features

</escape>

MethodHow it worksModel involvementComputational cost
FilterUses statistical properties of featuresIndependent of the final predictive modelUsually low
WrapperEvaluates different feature subsets using a modelRepeatedly trains modelsUsually high
EmbeddedSelects features during model trainingBuilt into the learning algorithmUsually moderate

Let's explore each approach.


4. Filter Methods: Statistical Feature Selection

Filter Methods evaluate features using statistical measures before training the final machine learning model.

They do not repeatedly train the final model for every possible feature combination.

Instead, they calculate a score for each feature and select the most informative ones.

Common filter techniques include:

  1. Variance Threshold
  2. Correlation Analysis
  3. Chi-Square Test
  4. ANOVA F-Test
  5. Mutual Information

4.1 Variance Threshold

Variance Threshold removes features that have very little variation.

A feature containing nearly identical values across all observations may provide limited information.

For example:

CustomerAgeCountry CodeAnnual Income
A229125000
B259130000
C309145000
D359160000

The Country Code feature has the same value for every observation.

It cannot distinguish between these customers and is a candidate for removal.

Formula

For a feature \(X\), variance is:

\[ Var(X)=\frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2 \]

Where:

  • \(N\) = Number of observations.
  • \(x_i\) = Individual feature value.
  • \(\mu\) = Mean of the feature.

A feature with zero variance contains no variation.

Python Implementation

import pandas as pd

from sklearn.feature_selection import VarianceThreshold

# Sample dataset
data = {
    "age": [22, 25, 30, 35, 40],
    "income": [25000, 30000, 45000, 60000, 80000],
    "constant": [1, 1, 1, 1, 1]
}

df = pd.DataFrame(data)

# Create selector
selector = VarianceThreshold(threshold=0)

# Select features
X_selected = selector.fit_transform(df)

# Get selected column names
selected_features = df.columns[selector.get_support()]

print("Selected Features:")
print(list(selected_features))

Output:

Selected Features:
['age', 'income']

When Should You Use It?

  • Removing constant features.
  • Removing near-constant features.
  • Cleaning high-dimensional datasets.
  • Reducing unnecessary input columns before model training.

Limitation: A low-variance feature is not necessarily useless. A feature with little variation may still be highly predictive, particularly in certain medical or fraud-detection problems.


4.2 Correlation-Based Feature Selection

Correlation measures the strength and direction of the relationship between two numerical variables.

Pearson correlation ranges from -1 to +1.

  • +1 indicates a perfect positive linear relationship.
  • -1 indicates a perfect negative linear relationship.
  • 0 indicates no linear correlation.

<LearningViz type_id="CORRELATION" initial_values={{"pattern":"positive"}} />

Pearson Correlation Formula

\[ r=\frac{\sum_{i=1}^{N}(x_i-\bar{x})(y_i-\bar{y})} {\sqrt{\sum_{i=1}^{N}(x_i-\bar{x})^2} \sqrt{\sum_{i=1}^{N}(y_i-\bar{y})^2}} \]

Example

Suppose a dataset contains:

Monthly Income
Annual Income
Age
Credit Score

Monthly Income and Annual Income may have a very strong positive correlation because one is derived from the other.

Keeping both features may introduce unnecessary redundancy.

Python Implementation

import pandas as pd
import numpy as np

data = {
    "monthly_income": [20000, 25000, 30000, 35000, 40000],
    "annual_income": [240000, 300000, 360000, 420000, 480000],
    "age": [22, 25, 30, 35, 40],
    "credit_score": [600, 620, 650, 700, 750]
}

df = pd.DataFrame(data)

# Calculate correlation matrix
correlation_matrix = df.corr()

print(correlation_matrix)

# Identify highly correlated feature pairs
threshold = 0.90

correlated_pairs = []

for i in range(len(correlation_matrix.columns)):
    for j in range(i + 1, len(correlation_matrix.columns)):

        correlation = correlation_matrix.iloc[i, j]

        if abs(correlation) > threshold:
            correlated_pairs.append((
                correlation_matrix.columns[i],
                correlation_matrix.columns[j],
                correlation
            ))

print("Highly Correlated Features:")
print(correlated_pairs)

When Should You Use It?

  • Identifying redundant numerical features.
  • Reducing multicollinearity.
  • Simplifying regression models.
  • Exploring relationships between numerical predictors.

Important: Correlation does not imply causation. Also, Pearson correlation detects linear relationships and may miss nonlinear dependencies.

Two highly correlated features are not always interchangeable. Consider domain knowledge and predictive performance before removing either one.


4.3 Chi-Square Test

The Chi-Square test evaluates whether two categorical variables are statistically associated.

In feature selection, it can help identify categorical or non-negative numerical features associated with a categorical target.

It is commonly used for classification problems.

Formula

\[ \chi^2=\sum\frac{(O-E)^2}{E} \]

Where:

  • \(O\) = Observed frequency.
  • \(E\) = Expected frequency under independence.

A higher Chi-Square score indicates stronger evidence of an association between the feature and target, subject to the test's assumptions.

Python Implementation

from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.preprocessing import MinMaxScaler

# Load dataset
iris = load_iris()

X = iris.data
y = iris.target

# Chi-square requires non-negative feature values
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

# Select top 2 features
selector = SelectKBest(
    score_func=chi2,
    k=2
)

X_selected = selector.fit_transform(X_scaled, y)

print("Original Shape:", X.shape)
print("Selected Shape:", X_selected.shape)

print("Selected Feature Names:")
print(iris.feature_names)
print(selector.get_support())

When Should You Use It?

  • Text classification with non-negative count features.
  • Categorical feature screening.
  • Classification datasets.
  • High-dimensional datasets with many candidate predictors.

Limitation: The standard Scikit-learn chi2 selector requires non-negative feature values. It is not appropriate for arbitrary negative-valued numerical features.


4.4 ANOVA F-Test

ANOVA (Analysis of Variance) can evaluate whether the mean values of a numerical feature differ across target classes.

The ANOVA F-statistic compares between-group variation with within-group variation.

\[ F=\frac{\text{Between-group variance}} {\text{Within-group variance}} \]

A larger F-statistic generally indicates greater separation between class means.

Python Implementation

from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest, f_classif

# Load dataset
iris = load_iris()

X = iris.data
y = iris.target

# Select top 2 features
selector = SelectKBest(
    score_func=f_classif,
    k=2
)

X_selected = selector.fit_transform(X, y)

print("Selected Features:")

for feature, selected in zip(
    iris.feature_names,
    selector.get_support()
):
    if selected:
        print(feature)

When Should You Use It?

  • Numerical features with categorical targets.
  • Classification problems.
  • Initial feature screening.
  • Identifying features with differences across target groups.

Limitation: ANOVA evaluates differences in group means. A feature may have useful nonlinear or interaction-based predictive information that a simple ANOVA test does not capture.


4.5 Mutual Information

Mutual Information measures how much information one variable provides about another.

Unlike Pearson correlation, it can identify certain nonlinear relationships.

The general formula is:

\[ I(X;Y)=\sum_{x,y}p(x,y) \log\left(\frac{p(x,y)}{p(x)p(y)}\right) \]

For continuous variables, mutual information is estimated using statistical methods rather than this simple discrete summation.

A higher mutual information score indicates a stronger statistical dependency between the feature and target.

Python Implementation

from sklearn.datasets import make_classification
from sklearn.feature_selection import mutual_info_classif
import pandas as pd

# Generate dataset
X, y = make_classification(
    n_samples=1000,
    n_features=10,
    n_informative=4,
    n_redundant=2,
    random_state=42
)

# Calculate mutual information
scores = mutual_info_classif(
    X,
    y,
    random_state=42
)

# Display scores
feature_scores = pd.DataFrame({
    "Feature": [f"Feature_{i}" for i in range(X.shape[1])],
    "MI Score": scores
})

print(feature_scores.sort_values(
    by="MI Score",
    ascending=False
))

When Should You Use It?

  • Detecting nonlinear dependencies.
  • Classification and regression feature screening.
  • High-dimensional datasets.
  • Identifying informative features without assuming a linear relationship.

Limitation: Mutual Information measures dependency, not causation. Its estimates can be noisy, especially with small datasets or poorly chosen estimation settings.


5. Wrapper Methods: Feature Selection Through Model Evaluation

Wrapper Methods select features by repeatedly training and evaluating a machine learning model on different feature subsets.

Unlike filter methods, they directly consider the performance of a chosen predictive algorithm.

Common wrapper techniques include:

  1. Forward Feature Selection.
  2. Backward Feature Elimination.
  3. Recursive Feature Elimination (RFE).
  4. Recursive Feature Elimination with Cross-Validation (RFECV).

5.1 Forward Feature Selection

Forward Selection begins with an empty feature set.

It repeatedly adds the feature that provides the greatest improvement in validation performance.

Workflow

Start with No Features
        |
        v
Evaluate Each Available Feature
        |
        v
Select the Best Feature
        |
        v
Add Another Feature
        |
        v
Evaluate Again
        |
        v
Stop When the Criterion Is Met

Example

Suppose a dataset contains:

Age
Income
Credit Score
Transaction Frequency
Account Balance

Forward Selection might choose:

Step 1: Credit Score
Step 2: Add Income
Step 3: Add Account Balance
Step 4: Add Transaction Frequency

It stops when adding another feature no longer improves the selected evaluation metric sufficiently.

Python Implementation

from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Create model pipeline
model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=5000)
)

# Forward selection
selector = SequentialFeatureSelector(
    estimator=model,
    n_features_to_select=5,
    direction="forward",
    scoring="accuracy",
    cv=5
)

selector.fit(X, y)

print("Selected Features:")

for feature, selected in zip(
    data.feature_names,
    selector.get_support()
):
    if selected:
        print(feature)

5.2 Backward Feature Elimination

Backward Elimination starts with all available features.

It repeatedly removes the feature whose removal produces the least deterioration—or the greatest improvement—in model performance.

Workflow

Start with All Features
        |
        v
Evaluate Model
        |
        v
Remove One Feature
        |
        v
Evaluate Again
        |
        v
Repeat Until Desired Feature Count

When Should You Use It?

  • When the dataset contains a manageable number of features.
  • When you want to remove unnecessary predictors systematically.
  • When model evaluation is affordable.

Forward and backward selection are greedy search methods. They do not guarantee that the globally optimal feature subset will be found.


5.3 Recursive Feature Elimination (RFE)

RFE repeatedly trains a model, ranks features using the model's importance or coefficients, and removes the least important features.

The process continues until the required number of features remains.

Workflow

Original Features: 20
        |
        v
Train Model and Rank Features
        |
        v
Remove Least Important Feature(s)
        |
        v
Train Model Again
        |
        v
Repeat
        |
        v
Selected Features: 5

Python Implementation

from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Create estimator
model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=5000)
)

# RFE
selector = RFE(
    estimator=model,
    n_features_to_select=5,
    step=1
)

selector.fit(X, y)

print("Selected Features:")

for feature, selected in zip(
    data.feature_names,
    selector.get_support()
):
    if selected:
        print(feature)

RFE works with estimators that expose suitable feature importance or coefficient information. Scikit-learn pipelines can expose the required information through supported feature-selection interfaces.

5.4 RFECV: Recursive Feature Elimination with Cross-Validation

RFECV extends RFE by using cross-validation to identify a suitable number of features.

Instead of choosing the number of features entirely in advance, it evaluates different subset sizes and selects the number that performs best according to the chosen scoring method.

Python Implementation

from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import RFECV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

data = load_breast_cancer()

X = data.data
y = data.target

model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=5000)
)

selector = RFECV(
    estimator=model,
    step=1,
    cv=StratifiedKFold(
        n_splits=5,
        shuffle=True,
        random_state=42
    ),
    scoring="accuracy",
    min_features_to_select=1
)

selector.fit(X, y)

print("Optimal Number of Features:")
print(selector.n_features_)

print("Selected Features:")

for feature, selected in zip(
    data.feature_names,
    selector.support_
):
    if selected:
        print(feature)

Advantages of Wrapper Methods

  • Evaluate features in the context of a predictive model.
  • Can capture interactions between selected features.
  • Often provide useful subsets for a specific algorithm.
  • RFECV helps choose the number of features using cross-validation.

Limitations of Wrapper Methods

  • Computationally expensive.
  • May require many model-training iterations.
  • Can overfit if feature selection and model evaluation are not properly separated.
  • Selected features can vary across datasets and validation splits.

Wrapper methods are especially useful when the number of features is manageable and computational resources are available.


6. Embedded Methods: Feature Selection During Model Training

Embedded Methods perform feature selection as part of the model-training process.

Unlike filter methods, they use the predictive model's learning mechanism. Unlike wrapper methods, they do not need to evaluate every candidate feature subset separately.

Common embedded approaches include:

  1. L1 Regularization (Lasso).
  2. Elastic Net Regularization.
  3. Tree-Based Feature Importance.
  4. Model-Based Feature Selection.

6.1 L1 Regularization (Lasso)

L1 regularization adds a penalty based on the absolute values of model coefficients.

\[ L=L_{original}+\lambda\sum_{j=1}^{p}|w_j| \]

Where:

  • \(L_{original}\) = Original model loss.
  • \(\lambda\) = Regularization strength.
  • \(w_j\) = Coefficient of feature \(j\).
  • \(p\) = Number of features.

L1 regularization can force some coefficients to become exactly zero.

A feature with a zero coefficient does not contribute directly to the fitted linear model.

Python Implementation

from sklearn.datasets import load_diabetes
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import pandas as pd

# Load dataset
data = load_diabetes()

X = data.data
y = data.target

# Create pipeline
model = make_pipeline(
    StandardScaler(),
    Lasso(alpha=0.1, max_iter=10000)
)

# Train model
model.fit(X, y)

# Get coefficients
lasso = model.named_steps["lasso"]

feature_importance = pd.DataFrame({
    "Feature": data.feature_names,
    "Coefficient": lasso.coef_
})

# Identify nonzero coefficients
selected_features = feature_importance[
    feature_importance["Coefficient"] != 0
]

print("Selected Features:")
print(selected_features)

The value of alpha controls regularization strength.

  • Smaller alpha generally retains more features.
  • Larger alpha generally shrinks more coefficients toward zero.

Feature scaling is important when using L1 regularization because coefficient penalties are sensitive to feature scales.

6.2 Elastic Net Regularization

Elastic Net combines L1 and L2 regularization.

\[ L=L_{original} +\lambda_1\sum_{j=1}^{p}|w_j| +\lambda_2\sum_{j=1}^{p}w_j^2 \]

It combines:

  • L1's ability to produce sparse models.
  • L2's tendency to shrink correlated coefficients together.

Elastic Net can be useful when many predictors are correlated.

Python Implementation

from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNet
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

data = load_diabetes()

X = data.data
y = data.target

model = make_pipeline(
    StandardScaler(),
    ElasticNet(
        alpha=0.1,
        l1_ratio=0.5,
        max_iter=10000
    )
)

model.fit(X, y)

elastic_net = model.named_steps["elasticnet"]

for feature, coefficient in zip(
    data.feature_names,
    elastic_net.coef_
):
    print(feature, coefficient)

Features with zero coefficients are excluded from the fitted linear prediction.

6.3 Tree-Based Feature Importance

Tree-based algorithms such as Decision Trees, Random Forests, and Gradient Boosting can provide feature importance scores.

For example, a Random Forest can calculate impurity-based importance based on how much each feature contributes to reducing split impurity across its trees.

Features with larger importance scores have contributed more to the model's impurity reduction.

Python Implementation

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
import pandas as pd

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Train Random Forest
model = RandomForestClassifier(
    n_estimators=200,
    random_state=42
)

model.fit(X, y)

# Get feature importance
importance = pd.DataFrame({
    "Feature": data.feature_names,
    "Importance": model.feature_importances_
})

importance = importance.sort_values(
    by="Importance",
    ascending=False
)

print(importance.head(10))

Advantages of Embedded Methods

  • Feature selection occurs during model training.
  • Usually more efficient than exhaustive wrapper approaches.
  • Can produce compact models.
  • Often work well with high-dimensional datasets.
  • Can integrate feature selection with regularization.

Limitations of Embedded Methods

  • Selection depends on the chosen model.
  • Some importance measures can be biased.
  • Correlated features may divide importance among themselves.
  • Selected features may not generalize equally well to other algorithms.

Important: Tree-based impurity importance can favor features with many possible split points or high cardinality. Permutation importance on held-out data can provide a useful complementary assessment.


7. Permutation Feature Importance

Permutation Importance measures how much a model's performance changes when the values of one feature are randomly shuffled.

The idea is straightforward:

  1. Train a model.
  2. Measure its baseline performance.
  3. Randomly shuffle one feature.
  4. Measure performance again.
  5. Calculate the performance decrease.

If shuffling a feature significantly reduces performance, that feature may contain useful predictive information for the fitted model.

Concept

\[ Importance_j=Score_{baseline}-Score_{permuted,j} \]

Where:

  • \(Score_{baseline}\) = Model performance before shuffling.
  • \(Score_{permuted,j}\) = Performance after shuffling feature \(j\).

Python Implementation

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

data = load_breast_cancer()

X = data.data
y = data.target

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    stratify=y,
    random_state=42
)

model = RandomForestClassifier(
    n_estimators=200,
    random_state=42
)

model.fit(X_train, y_train)

result = permutation_importance(
    model,
    X_test,
    y_test,
    n_repeats=10,
    random_state=42,
    scoring="accuracy"
)

for index in result.importances_mean.argsort()[::-1]:
    print(
        data.feature_names[index],
        result.importances_mean[index]
    )

Permutation importance can be useful for evaluating a trained model on held-out data.

However, it is not automatically a causal explanation. When features are strongly correlated, shuffling one feature may have little effect because another feature provides similar information.


8. Comparing Filter, Wrapper, and Embedded Methods

ParameterFilter MethodsWrapper MethodsEmbedded Methods
Selection basisStatistical scoresModel evaluationModel training mechanism
Requires final model training for every subset?NoYesNo
Computational costLowHighUsually moderate
Captures feature interactionsUsually limitedCan capture themDepends on model
Model dependencyLowHighHigh
ExamplesChi-Square, ANOVA, Mutual InformationRFE, Forward Selection, RFECVLasso, Elastic Net, Random Forest
Best suited forInitial screeningSmaller or moderate feature setsModel-specific selection

Which Method Should You Choose?

There is no universally best feature selection technique.

A practical starting strategy is:

SituationSuggested technique
Thousands of candidate featuresFilter methods
Many constant or redundant featuresVariance and correlation screening
Numerical features with categorical targetANOVA F-test or Mutual Information
Non-negative count featuresChi-Square
Manageable number of featuresRFE or Sequential Feature Selection
Linear model with many predictorsL1 or Elastic Net
Tree-based classificationModel importance and permutation importance
Need to choose the number of featuresRFECV or validation-based selection

Combining methods can also be useful. For example, a filter method can first remove obviously uninformative features, followed by RFE or L1 regularization.


9. Complete Feature Selection Workflow Using Python

Let's build a practical classification workflow using the Breast Cancer dataset from Scikit-learn.

We will:

  1. Load the dataset.
  2. Separate features and target.
  3. Split training and testing data.
  4. Standardize numerical features.
  5. Select features using a statistical method.
  6. Train Logistic Regression.
  7. Evaluate the model.

Step 1: Import Libraries

import pandas as pd

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

Step 2: Load Dataset

data = load_breast_cancer()

X = pd.DataFrame(
    data.data,
    columns=data.feature_names
)

y = data.target

print("Original Shape:", X.shape)

Step 3: Split Dataset

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    stratify=y,
    random_state=42
)

The split occurs before feature selection so the test data does not influence which features are selected.

Step 4: Create Pipeline

pipeline = Pipeline([
    ("scaler", StandardScaler()),

    ("feature_selection", SelectKBest(
        score_func=f_classif,
        k=10
    )),

    ("model", LogisticRegression(
        max_iter=5000
    ))
])

The pipeline performs three operations:

  • Standardizes numerical features.
  • Selects the 10 highest-scoring features.
  • Trains Logistic Regression.

Step 5: Train Model

pipeline.fit(X_train, y_train)

Step 6: Predict

y_pred = pipeline.predict(X_test)

Step 7: Evaluate

print("Accuracy:", accuracy_score(y_test, y_pred))

print("\nClassification Report:")
print(classification_report(y_test, y_pred))

Step 8: Display Selected Features

selector = pipeline.named_steps["feature_selection"]

selected_features = X.columns[
    selector.get_support()
]

print("Selected Features:")
print(list(selected_features))

This example demonstrates how feature selection can be incorporated into a machine learning pipeline.

The number of selected features (k=10) is illustrative. In a real project, evaluate different values of k using cross-validation rather than assuming 10 is optimal.


10. Feature Selection and Data Leakage

One of the most important rules in feature selection is avoiding data leakage.

Suppose you calculate feature scores using the complete dataset before splitting it into training and test sets.

Even though the test labels are not directly used to train the final classifier, they influence which features are selected.

This makes the test evaluation less independent.

Incorrect Approach

# Do not select features using the entire dataset first

selector = SelectKBest(
    score_func=f_classif,
    k=10
)

X_selected = selector.fit_transform(X, y)

X_train, X_test, y_train, y_test = train_test_split(
    X_selected,
    y,
    test_size=0.2,
    random_state=42
)

Correct Approach

# Split first

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    stratify=y,
    random_state=42
)

# Fit selection only on training data
selector = SelectKBest(
    score_func=f_classif,
    k=10
)

X_train_selected = selector.fit_transform(
    X_train,
    y_train
)

# Apply the same selection to test data
X_test_selected = selector.transform(X_test)

An even safer approach is to include feature selection inside a Scikit-learn Pipeline.

During cross-validation, the pipeline will fit the feature selector independently within each training fold.

If you are tuning the number of features or comparing many selection strategies, use nested cross-validation or an independent validation set to reduce selection bias.


11. Common Mistakes in Feature Selection

Mistake 1: Selecting Features Only by Correlation

A feature with low Pearson correlation may still contain useful nonlinear information.

Use other methods, such as Mutual Information, when appropriate.

Mistake 2: Removing Every Highly Correlated Feature

Two correlated features may still contain complementary information.

Use domain knowledge, model performance, and validation results before removing them.

Mistake 3: Ignoring Feature Interactions

Two features may be weak individually but highly informative together.

For example, income and existing debt may jointly help predict credit risk.

Some filter methods evaluate features individually and may miss such interactions.

Mistake 4: Selecting Features Before Train-Test Splitting

This introduces information leakage and can produce overly optimistic evaluation results.

Perform supervised feature selection using training data only.

Mistake 5: Choosing Too Few Features

A smaller feature set is not automatically better.

Removing useful predictors can cause underfitting and reduce model performance.

Mistake 6: Treating Feature Importance as Causation

A highly important feature is not necessarily the cause of the target outcome.

Feature importance describes predictive relationships within a particular model and dataset.

Mistake 7: Ignoring Correlated Features in Importance Analysis

When two features contain similar information, model importance may be divided between them.

Permutation importance can also underestimate the importance of an individual feature when a correlated alternative remains available.

Mistake 8: Ignoring One-Hot Encoded Feature Groups

A categorical variable can expand into many one-hot encoded columns.

Selecting individual encoded columns may retain only some categories from the original feature.

In such cases, consider grouped feature selection when the goal is to retain or remove the original categorical variable as a whole.


12. Best Practices for Feature Selection

  1. Understand the dataset: Inspect feature names, types, distributions, and relationships.
  2. Remove constant features: Use Variance Threshold as an initial screening step.
  3. Check redundancy: Examine correlation and domain-level duplication.
  4. Choose an appropriate selection method: Match the technique to the data and predictive model.
  5. Use domain knowledge: Statistical scores alone do not establish business or scientific relevance.
  6. Avoid data leakage: Fit supervised selectors using training data only.
  7. Use cross-validation: Evaluate feature subsets across multiple training and validation folds.
  8. Compare against a baseline: Check whether feature selection actually improves performance.
  9. Consider model complexity: Balance predictive performance, interpretability, and operational cost.
  10. Check feature stability: Investigate whether the selected variables remain consistent across different data splits.
  11. Retain important interactions: Do not automatically discard individually weak features.
  12. Document selected features: Record the selection method, parameters, and fitted preprocessing steps for production use.

13. Real-World Applications of Feature Selection

IndustryExample FeaturesWhy Feature Selection Helps
BankingIncome, debt ratio, repayment history, credit utilizationReduces redundant financial predictors
HealthcareBlood pressure, glucose, test results, patient measurementsIdentifies useful diagnostic predictors
TelecomCall frequency, data usage, billing history, support requestsSimplifies churn prediction
E-commercePurchase frequency, average order value, browsing activityIdentifies useful customer behavior
ManufacturingTemperature, pressure, vibration, production measurementsRemoves noisy or redundant sensor variables
CybersecurityNetwork traffic statistics, connection duration, packet countsReduces high-dimensional input data

Feature selection is particularly useful when datasets contain hundreds or thousands of candidate variables.


14. Final Conclusion

Feature Selection is an important machine learning technique that identifies useful input variables while removing irrelevant, redundant, or noisy features.

It can improve model simplicity, reduce computational requirements, support interpretability, and sometimes improve generalization.

The three major approaches are:

  • Filter Methods: Use statistical measures such as Variance Threshold, Correlation, Chi-Square, ANOVA, and Mutual Information.
  • Wrapper Methods: Evaluate different feature subsets using model performance, with techniques such as Forward Selection, Backward Elimination, RFE, and RFECV.
  • Embedded Methods: Select features during model training using techniques such as L1 Regularization, Elastic Net, and tree-based importance.

Each approach has different advantages and limitations.

Filter methods are generally fast, wrapper methods directly evaluate predictive performance but can be expensive, and embedded methods combine selection with model training.

The most important principle is that feature selection should be judged by how well the resulting model performs on unseen data—not simply by how many features it removes.

A smaller feature set is valuable only when it retains the information needed to solve the prediction problem.