Skip to main content
LearnMLAcademy
Intermediate10 min read

Feature Selection & Extraction

Select optimal feature subsets using variance thresholds and elimination, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Feature Selection and Feature Extraction in Machine Learning

Feature selection keeps the most useful original input features, while feature extraction transforms the original inputs into a smaller set of new features. Both approaches can reduce dimensionality, simplify models, lower computation, and sometimes improve generalization.

In simple terms, feature selection asks “which original features should I keep?” while feature extraction asks “how can I represent the same information with fewer new features?” This guide explains both approaches, when to use each one, and the most common methods used in Machine Learning.

Feature Selection & Extraction in Simple Words

Imagine your dataset has many columns, but not every column is equally useful. You have two simple choices: keep only useful original columns, or combine information into a smaller set of new columns.

Feature Selection

Age · Study Hours · Attendance · Student ID
↓ Keep useful columns
Study Hours · Attendance

The surviving columns keep their original meaning.

Feature Extraction

Maths · Physics · Chemistry · Biology
↓ Combine information
Component 1 · Component 2

The new columns are compact mathematical summaries.

QuestionSelectionExtraction
Do original column names remain?YesUsually no
Simple exampleKeep Age, Salary4 columns → 2 PCA components
Best when...Interpretability mattersCompression is important

What is a Feature?

A feature is an input variable used by a Machine Learning model. Features help models discover patterns.

DatasetFeatures
House Price PredictionArea, Bedrooms, Location
Student PerformanceStudy Hours, Attendance
HealthcareBlood Pressure, Sugar Level
E-CommerceProduct Price, Ratings

Why Feature Optimization Matters

Real-world datasets often contain problems that reduce model performance:

  • Irrelevant Features: E.g., Random IDs
  • Duplicate Features: E.g., Same information repeated
  • Noisy Features: E.g., Corrupted sensor data
  • High-Dimensional Data: E.g., Thousands of columns

What is Feature Selection?

Feature Selection is the process of selecting the most useful features and removing unnecessary ones. Instead of creating new features, it chooses the best subset from existing columns.

Original Features
  • Age
  • Salary
  • Phone Number
  • Random ID
  • Experience
Selected Features
  • Age
  • Salary
  • Experience

In this example, Phone Number and Random ID are treated as identifiers rather than useful predictive features, so they are removed.

Possible Benefits of Feature Selection: ✅ Reduce unnecessary inputs ✅ Shorten training time ✅ Simplify models ✅ Improve interpretability ✅ Sometimes improve generalization by reducing noise

Types of Feature Selection Techniques

Feature SelectionFilter MethodsStatistical Selectione.g. CorrelationWrapper MethodsModel Evaluatione.g. RFEEmbedded MethodsDuring Traininge.g. Lasso

1. Filter Methods

Filter methods score or remove features using statistical properties before fitting the final predictive model. They are often fast and scalable, but a simple one-feature-at-a-time test may miss useful interactions between features.

  • Correlation: Highly correlated input features can carry very similar information. For some models, you may consider keeping one of them after checking domain meaning and validation performance.
  • Chi-Square Test: For classification, it can test whether non-negative input features are related to the class label.
  • ANOVA F-test: In supervised feature selection, it can score how strongly a numerical feature differs across target classes.
  • Mutual Information: Scores how much knowing a feature reduces uncertainty about the target. It can capture some non-linear relationships that simple correlation may miss.
  • Variance Threshold: Remove low-variance features.
select_k_best.py
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, mutual_info_classif

X, y = make_classification(
    n_samples=200,
    n_features=10,
    n_informative=5,
    random_state=42
)

selector = SelectKBest(score_func=mutual_info_classif, k=5)
X_selected = selector.fit_transform(X, y)

print("Original shape:", X.shape)
print("Selected shape:", X_selected.shape)
print("Selected columns:", selector.get_support(indices=True))
Output
Original shape: (200, 10)
Selected shape: (200, 5)
Selected columns: [0 2 4 6 9]

# The exact selected indexes can vary because mutual information is estimated.
variance_threshold.py
from sklearn.feature_selection import VarianceThreshold
import pandas as pd

# Creating a dataset where feature 'B' has very low variance (mostly 1s)
data = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [1, 1, 1, 1, 0],
    'C': [5, 4, 3, 2, 1]
})

selector = VarianceThreshold(threshold=0.2)
X_new = selector.fit_transform(data)

print(X_new)
Output
[[1 5]
 [2 4]
 [3 3]
 [4 2]
 [5 1]]
# Column B is removed because its variance is below 0.2.

A tiny variance example

Feature B contains [1, 1, 1, 1, 0]. It changes very little, so its population variance is only 0.16. With a threshold of 0.20, it is removed.

Low variance does not automatically mean a feature is useless. Treat this as a simple filter and validate the choice for your problem.

2. Wrapper Methods

Wrapper methods evaluate multiple feature combinations using actual ML model performance. Examples include Forward Selection, Backward Selection, and Recursive Feature Elimination (RFE).

Recursive Feature Elimination (RFE) repeatedly trains a estimator and recursively removes the least important features until the requested number remains. Because it repeatedly fits a model, it can be more computationally expensive than simple filters.

rfe_example.py
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=100, n_features=10, random_state=42)

model = LogisticRegression(max_iter=1000)
# Select top 5 features out of 10
rfe = RFE(model, n_features_to_select=5)
X_rfe = rfe.fit_transform(X, y)

print("Original shape:", X.shape)
print("New shape:", X_rfe.shape)
print("Which columns were selected?", rfe.support_)
Output
Original shape: (100, 10)
New shape: (100, 5)
Which columns were selected? [ True  True  True  True False False  True False False False]

3. Embedded Methods

Embedded methods use information learned while fitting a model to decide which features matter. Examples include Lasso-based selection and importance-based selection with suitable tree models.

Lasso Regression uses an L1 penalty and can drive some coefficients exactly to zero. Those zero-coefficient features can then be treated as unselected. Ridge, by contrast, usually shrinks coefficients but does not normally create sparse zero-coefficient feature sets, so it is not usually used as a direct selector.

Simplified idea: Error + λ × ∑|βᵢ|
Prediction error + L1 penalty

Simple Lasso penalty calculation

Suppose:

  • RSS = 8
  • λ = 2
  • Coefficients = 3, -1, 0.5
Step 1 — Add absolute coefficient values
|3| + |-1| + |0.5| = 4.5
Step 2 — Apply the penalty strength
2 × 4.5 = 9
Step 3 — Add it to the original error
8 + 9 = 17

This tiny calculation only explains the objective. During training, Lasso searches for coefficients that balance prediction error and the L1 penalty.

What is Feature Extraction?

Feature Extraction transforms the original variables into a new representation. Unlike selection, which keeps a subset of original columns, extraction creates new features that can summarize important patterns in the original data.

Why Feature Extraction Matters: It can reduce dimensionality, make some datasets easier to visualize, and sometimes reduce computation. The trade-off is that the new components may be harder to interpret and some information can be lost.

Raw Features (e.g., Image Pixels):
Pixel1, Pixel2, Pixel3, Pixel4, Pixel_N...
Extracted Meaning:
Edge Mapping, Texture Pattern, Geometric Shape

A simple way to picture extraction

Maths
Physics
Chemistry
Biology
→
Extraction method
→
Component 1
Component 2

Four original columns become two new summary columns. The new components no longer have simple names like “Maths” or “Physics.”

Core Techniques in Feature Extraction

1. Dimensionality Reduction Methods

These algorithms find mathematical ways to squish numerous columns into a few elite "components" while retaining the dataset's core characteristics.

  • Principal Component Analysis (PCA): The most popular unsupervised dimensionality-reduction technique. It finds new directions that capture as much variance in the data as possible, then projects the observations onto those directions.
  • Linear Discriminant Analysis (LDA): A supervised supervised dimensionality-reduction method that uses class labels and seeks directions that separate classes relative to variation within each class.
  • t-SNE & UMAP: Non-linear dimensionality-reduction techniques commonly used to explore or visualize high-dimensional data in 2D or 3D. Their plots should be interpreted carefully.
Z = X_centered × W (Conceptually: centered data projected onto component directions)
pca_example.py
from sklearn.decomposition import PCA
import numpy as np

# A small fixed dataset with 4 numeric features
X = np.array([
    [1, 2, 1, 4],
    [2, 4, 2, 3],
    [3, 5, 3, 5],
    [4, 7, 4, 6],
    [5, 8, 6, 7],
    [6, 10, 5, 9],
    [7, 11, 7, 8],
    [8, 13, 9, 11]
], dtype=float)

# Reduce 4 original features to 2 new components
pca = PCA(n_components=2)
X_compressed = pca.fit_transform(X)

print("Original Data Shape:", X.shape)
print("Compressed Shape:", X_compressed.shape)
print("Variance Captured (%):", np.round(pca.explained_variance_ratio_ * 100, 2))
print("Total captured (%):", round(pca.explained_variance_ratio_.sum() * 100, 2))
Output
Original Data Shape: (8, 4)
Compressed Shape: (8, 2)
Variance Captured (%): [97.31  1.76]
Total captured (%): 99.06
Scaling note: PCA centers features, but it does not automatically scale every feature to the same variance. If features use very different units (for example rupees and years), scaling is often useful before PCA so one large-scale feature does not dominate the variance.

2. Extracting Information from Text (NLP)

Most standard machine-learning algorithms ultimately work with numeric representations. Text therefore needs to be converted into useful numeric features or embeddings before those models can use it.

  • Bag of Words (BoW): Represents documents using counts (or presence) of words from a vocabulary.
  • TF-IDF (Term Frequency - Inverse Document Frequency): Gives a word more weight when it is frequent in one document but less common across the full collection of documents.
  • Embeddings: Methods such as Word2Vec and GloVe create dense word vectors, while transformer models such as BERT can produce context-dependent representations. Similar meanings can often have related vector representations.

3. Image and Signal Extraction

Images and audio can contain many raw values such as pixels or waveform samples. Feature extraction can turn those raw values into representations that are easier for a model to use.

  • Computer Vision: Historically, classical techniques such as HOG (Histogram of Oriented Gradients) describe local edge directions. Convolutional Neural Networks (CNNs) can learn hierarchical visual features automatically during training.
  • Audio Processing: Sound tracks are converted into spectrograms or summarized using features such as MFCCs (Mel-Frequency Cepstral Coefficients), which describe useful aspects of the frequency spectrum.

Pros and Cons of Extraction

Advantages ✅
  • Resource Efficiency: Fewer dimensions can reduce memory use and training time for some workflows.
  • May Reduce Noise: A compact representation can sometimes improve generalization, but this is not guaranteed.
  • Data Visualization: Extracting from 1,000 hidden mathematical dimensions down to 2 or 3 allows human scientists to visually graph trends.
Challenges ⚠️
  • Loss of Direct Meaning: Highly compressed mathematical components lose their real-world 'labels'. A feature named `Component 1` is harder to explain than `Age`.
  • Information Loss: Compression can discard information that may matter for prediction.
  • Computation Cost: Some extraction methods are cheap, while training large representation-learning models can be expensive.

Feature Selection vs Feature Extraction in Machine Learning

Since Feature Selection and Feature Extraction are related but serve distinctly different purposes, let’s quickly contrast them across key aspects for a better understanding:

Comparison AspectFeature SelectionFeature Extraction
Core DefinitionIdentifies and retains a relevant subset of the original dataset columns.Mathematically transforms existing columns into an entirely new set of condensed variables.
Primary GoalTo specifically reduce dimensionality by dropping redundant or irrelevant data.To compress raw, complex high-dimensional information into a smaller, dense, and more informative representation.
Underlying ProcessRelies on statistical filters, wrapper algorithms (like RFE), and embedded model penalties.Utilizes linear algebra, signal processing, and transformation algorithms (like PCA or neural nets).
Resulting OutputA strict, smaller subset consisting solely of the original features.A completely new, abstract array of engineered components that replace the original data.
Computational CostGenerally lightweight and incurs a lower computational cost.Varies by method: PCA can be moderate, while deep representation learning can be much more computationally expensive.
Human InterpretabilityHigh (Retains the original interpretability of variables, e.g., "Age" still means "Age").Low (The final variables are abstract mathematical combinations, e.g., "Principal Component 2").

When to use Selection: Need interpretability, want faster models, features are redundant, working with tabular data.
When to use Extraction: High-dimensional data exists, need compression, working with images/text/audio, visualization is needed.

The Curse of Dimensionality

As dimensionality grows, data can become sparse and distance-based patterns may become harder to estimate reliably. More features can also increase computation and overfitting risk. Feature selection or extraction can help, but they should be validated rather than applied automatically.

Mistakes to Avoid ❌
  • Removing useful features accidentally.
  • Letting very different feature scales dominate PCA without first deciding whether scaling is appropriate.
  • Ignoring interpretability when choosing extraction.
  • Data leakage during feature selection (Select based on entire dataset instead of just training set).
Best Practices ✅
  • Consider scaling before PCA when feature units/scales differ greatly.
  • Use Cross-Validation with wrapper methods.
  • Balance interpretability and accuracy.
  • Use domain knowledge to validate feature subset selection.

Common Questions

What is the difference between feature selection and feature extraction?

Feature selection keeps a subset of the original features, so their names and meanings remain unchanged. Feature extraction creates new features by transforming or combining the originals, as PCA does with principal components.

Does feature selection always improve accuracy?

No. It can reduce noise and simplify a model, but removing a useful feature can make performance worse. Compare alternatives using validation or cross-validation.

Is PCA feature selection?

No. PCA is feature extraction: it creates new principal components from combinations of the original numeric features.

Should feature selection use the test set?

No. Learn the selection rule using training data (and validation/CV as appropriate), then evaluate the final pipeline on untouched test data. Otherwise information can leak into model development.

Interview Knowledge Test

Quiz

Q: Difference between PCA and RFE?

PCA extracts entirely new components from linear combinations of the data. RFE recursively evaluates and removes original features using importance information from an estimator.

Q: Which is more interpretable?

Feature Selection. You keep columns with exact, real-world meanings (like "Age" or "Salary"), rather than PCA's mathematically abstract "Component 1".

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Feature Selection & Extraction"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Feature selection keeps original variables; extraction creates new compressed variables.
  • Filter, wrapper, and embedded methods use different selection evidence.
  • Regularized models and trees can select features while fitting.
  • PCA creates variance-preserving components that may be less interpretable.
  • Selection must occur inside cross-validation to prevent leakage.
  • Judge the result by quality, stability, latency, and interpretability.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
You have 300 features and 400 training examples. Why is feature selection particularly critical here?
Question 2 of 4
What is the difference between filter methods and wrapper methods for feature selection?
Question 3 of 4
Why is Lasso regularisation described as 'embedded' feature selection?
Question 4 of 4
Permutation importance reports that feature X has an importance of 0.002. What does this mean practically?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1You have 300 features and 400 training examples. Why is feature selection particularly critical here?▼

Correct Answer: With more features than training examples, any model with enough capacity can find a hyperplane that perfectly separates training examples even when labels are random. Feature selection forces the model to find signals that are robust across different data samples

This is the p >> n (more features than samples) regime where models will overfit to noise. With 300 features and 400 examples, a model has more parameters than data points and can easily fit random patterns.

2What is the difference between filter methods and wrapper methods for feature selection?▼

Correct Answer: Filter methods assess feature relevance using statistics independent of any model (e.g., correlation, mutual information) — fast but ignores feature interactions. Wrapper methods iteratively train the actual model on different feature subsets — more accurate but orders of magnitude slower

Mutual information filter (fast, model-agnostic) vs. Recursive Feature Elimination (trains the model multiple times to find the most impactful subset). For an initial baseline, filter is practical; for a production pipeline, wrapper methods give better results if you can afford the compute.

3Why is Lasso regularisation described as 'embedded' feature selection?▼

Correct Answer: Feature selection is embedded into the training process itself — Lasso's L1 penalty directly drives some coefficients to exactly zero during training. There is no separate preprocessing step; the model selects and fits simultaneously

Filter and wrapper methods are separate preprocessing steps. Lasso integrates selection into the loss function — the penalty for nonzero weights naturally eliminates uninformative features as part of finding the minimum loss.

4Permutation importance reports that feature X has an importance of 0.002. What does this mean practically?▼

Correct Answer: When feature X's values are randomly shuffled (destroying its relationship with the target), model accuracy drops by only 0.002 — meaning X contributes almost nothing to the model's predictive power

Permutation importance answers: 'How much worse does the model perform when it can no longer use this feature?' Near-zero importance means the model performs just as well without this feature — a strong case for removing it and simplifying the model.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next