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
The surviving columns keep their original meaning.
Feature Extraction
The new columns are compact mathematical summaries.
| Question | Selection | Extraction |
|---|---|---|
| Do original column names remain? | Yes | Usually no |
| Simple example | Keep Age, Salary | 4 columns → 2 PCA components |
| Best when... | Interpretability matters | Compression is important |
What is a Feature?
A feature is an input variable used by a Machine Learning model. Features help models discover patterns.
| Dataset | Features |
|---|---|
| House Price Prediction | Area, Bedrooms, Location |
| Student Performance | Study Hours, Attendance |
| Healthcare | Blood Pressure, Sugar Level |
| E-Commerce | Product 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.
- Age
- Salary
- Phone Number
- Random ID
- Experience
- Age
- Salary
- Experience
In this example, Phone Number and Random ID are treated as identifiers rather than useful predictive features, so they are removed.
Types of Feature Selection Techniques
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.
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))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.
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)[[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.
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_)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.
Simple Lasso penalty calculation
Suppose:
- RSS = 8
- λ = 2
- Coefficients = 3, -1, 0.5
|3| + |-1| + |0.5| = 4.52 × 4.5 = 98 + 9 = 17This 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.
Pixel1, Pixel2, Pixel3, Pixel4, Pixel_N...
Edge Mapping, Texture Pattern, Geometric Shape
A simple way to picture extraction
Physics
Chemistry
Biology
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.
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))Original Data Shape: (8, 4) Compressed Shape: (8, 2) Variance Captured (%): [97.31 1.76] Total captured (%): 99.06
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
- 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.
- 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 Aspect | Feature Selection | Feature Extraction |
|---|---|---|
| Core Definition | Identifies and retains a relevant subset of the original dataset columns. | Mathematically transforms existing columns into an entirely new set of condensed variables. |
| Primary Goal | To 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 Process | Relies 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 Output | A strict, smaller subset consisting solely of the original features. | A completely new, abstract array of engineered components that replace the original data. |
| Computational Cost | Generally 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 Interpretability | High (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.
- 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).
- 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.
Continue learning
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".