Machine LearningFeature Engineering and Dimensionality Reduction

Feature Selection vs Feature Extraction

Question 307 of 307 · Updated

On this page

Feature selection keeps a subset of the original input features. Feature extraction transforms the original inputs into a new representation. Both can reduce dimensionality, remove noise, and improve a machine-learning pipeline, but they do so differently.

Choose feature selection when retaining the meaning and identity of original columns matters. Choose feature extraction when combining information into a compact representation is more useful than keeping each original variable separate. Neither method is automatically better; compare them using leakage-safe validation and the needs of the application.

1. Why do we need them?#

A dataset may contain hundreds or thousands of columns. Some features are irrelevant, some repeat information already present elsewhere, and some are useful only in combination with other variables.

A large feature space can increase memory use, training time, and model complexity. It can also make interpretation and generalization harder, especially when the number of observations is small compared with the number of features.

Both approaches attempt to create a more useful input representation:

LaTeX

Here, (n) is the number of observations, (d) is the original number of features, and (k) is the reduced number of features.

The difference is what the columns of (Z) represent.

2. What is feature selection?#

Feature selection chooses a subset of existing columns and discards the rest. The selected features retain their original definitions and values.

Suppose a loan-risk dataset has these columns:

  • Annual income
  • Monthly income
  • Credit score
  • Employment duration
  • Customer ID
  • Random tracking code

A selection method might retain income, credit score, debt, and employment duration while removing identifiers that do not generalize and provide no legitimate predictive value.

Mathematically, feature selection can be represented by a binary mask:

LaTeX

where (S) is a subset of column indices. Equivalently, a selection matrix (M) chooses columns:

LaTeX

Each output column is one of the original columns; its meaning is not rewritten by the selection operation.

For a supervised predictive task, an idealized objective is:

LaTeX

The model () is trained using subset (S), and (lambda) represents a penalty for keeping more features. Real algorithms use practical approximations because searching every possible subset is expensive.

3. What is feature extraction?#

Feature extraction creates new features by transforming, combining, or representing the original data. The output columns are not necessarily original columns.

For example, height and weight can be combined into a new feature such as body mass index (BMI). More generally, a transformation maps the input vector to a new representation:

LaTeX

For a linear extraction method:

LaTeX

where (W) is a learned projection matrix. Each extracted feature can be a weighted combination of many original features.

Examples include:

  • PCA: combines correlated numerical variables into principal components that capture high variance.
  • Truncated SVD: creates lower-dimensional representations and is useful with sparse matrices such as term-document data.
  • Linear Discriminant Analysis (LDA): learns projections that aim to separate known classes, subject to its assumptions and dimensionality limits.
  • Autoencoders: learn nonlinear compressed representations through a neural-network encoder and decoder.
  • Text representations: convert tokens or documents into numerical features such as TF-IDF vectors or learned embeddings.
  • Signal and image features: transform raw measurements into frequency, shape, texture, or learned representations.

Feature extraction can reduce dimensions, keep the same number of dimensions, or even create more features. Its defining property is transformation—not necessarily compression.

4. Numerical example: selecting columns vs combining them#

Imagine a small dataset with four standardized input features:

  • (): annual income
  • (): monthly income
  • (): credit score
  • (): random customer reference number

Assume income and monthly income are strongly correlated, credit score is useful for predicting repayment, and the reference number has no legitimate predictive relationship.

Feature selection#

A selection method might retain:

LaTeX

The resulting two columns are still annual income and credit score. A business user can inspect them directly.

Feature extraction using PCA#

Suppose, for illustration, PCA is applied to the first three standardized variables and learns these two components:

LaTeX
LaTeX

The first component captures the shared movement of the two income measurements; the second captures their difference. The output features are new combinations, not the original annual-income and monthly-income columns.

This is only an illustrative projection, not a fitted model or claim about real financial data. PCA chooses directions using variance, not the repayment target. It may retain a high-variance direction that is not the most predictive one.

The central distinction#

  • Selection: keep () and (); remove () and ().
  • Extraction: construct () and () by transforming the original variables.

Both outputs have two columns, but only the selection output preserves the original column identities.

5. Main feature-selection methods#

Feature selection methods are commonly grouped into filter, wrapper, and embedded approaches.

A. Filter methods#

Filter methods score features using statistical properties, generally before fitting the final predictive model. They are usually fast and relatively model-independent.

Examples:

  • Variance threshold: removes features with little or no variation.
  • Correlation: identifies features strongly associated with a target or highly redundant with other features.
  • Chi-square test: scores non-negative features against a categorical target.
  • ANOVA F-test: measures evidence of association between a numerical feature and a categorical target under the test's assumptions.
  • Mutual information: measures statistical dependence and can detect some nonlinear relationships.

Example: a text-classification dataset has 20,000 word-frequency columns. A univariate filter can rank words by their association with the training labels and retain the top 500.

Limitations: a univariate score may miss a feature that is useful only through interaction with another feature. Correlated features can also make rankings unstable. Statistical significance is not the same as practical predictive value.

B. Wrapper methods#

Wrapper methods evaluate candidate feature subsets by training and validating a model. They use model performance to decide which subset is useful.

Examples:

  • Forward selection: start with no features and add the feature that most improves validation performance at each step.
  • Backward elimination: start with all features and remove the least useful one at each step.
  • Recursive Feature Elimination (RFE): fit an estimator, rank features using its coefficients or importance values, remove the least important, and repeat.
  • RFECV: use cross-validation to help choose how many features to retain.

Wrapper methods can account for interactions and the behavior of a particular estimator, but they can be computationally expensive because they fit many models. They can also overfit the validation process if the search is too broad or repeatedly tuned against the same holdout set.

C. Embedded methods#

Embedded methods perform feature selection as part of model training.

Examples:

  • Lasso (L1 regularization): penalizes the absolute values of coefficients and can drive some coefficients to exactly zero.
  • L1-regularized logistic regression: can produce sparse coefficients for classification.
  • Tree-based models: can provide feature-importance scores that can be used to select columns, though impurity-based importance has known biases and should not be treated as proof of causal or unique relevance.

Embedded methods often provide a practical balance between filter speed and wrapper search cost. Their selected features depend on the estimator, regularization strength, data, and fitting procedure.

6. Main feature-extraction methods#

Feature extraction methods learn or construct a new representation from the input.

A. Unsupervised extraction#

These methods do not require target labels to learn the representation.

  • PCA: finds orthogonal linear directions that maximize variance.
  • Truncated SVD: factorizes a matrix into a lower-rank representation; commonly used for sparse text matrices.
  • Autoencoders: learn a compressed latent representation by training a neural network to reconstruct its input.
  • Independent Component Analysis (ICA): seeks statistically independent components under its assumptions.

For example, PCA can turn 100 correlated sensor measurements into 15 components. Those components are weighted combinations of the original sensors.

B. Supervised extraction#

These methods use labels or target information to learn a representation that is useful for separating or predicting classes.

  • Linear Discriminant Analysis (LDA): finds directions that increase between-class separation relative to within-class variation.
  • Supervised embeddings: learn vector representations using labels or a task-specific objective.
  • Neural-network hidden representations: intermediate activations can act as learned features for a downstream task.

A key distinction: PCA is unsupervised because it does not use (y) when fitting its components. LDA is supervised because class labels influence the projection.

Supervised extraction can improve task relevance, but it also needs careful validation to avoid target leakage.

7. Mathematical intuition: what are the methods optimizing?#

Feature selection and extraction can both be framed as representation-learning problems, but their constraints differ.

Selection objective#

A selection method searches for a subset that works well for a task while controlling complexity:

LaTeX

Here, (L) is a task loss. The subset is restricted to original columns.

PCA extraction objective#

PCA seeks a low-dimensional linear projection that preserves as much total variance as possible:

LaTeX

where (S) is the covariance matrix and (W) contains the retained directions.

PCA does not look at the target labels. Its objective is reconstruction/variance oriented, not directly predictive.

LDA extraction objective#

For class-labeled data, LDA seeks directions with large between-class scatter relative to within-class scatter. A common formulation maximizes:

LaTeX

where () is between-class scatter and () is within-class scatter. This makes the learned representation supervised and class-oriented.

These objectives explain why a method that preserves variance may not select the best features for prediction, and why a supervised projection may be useful for classification but less suitable when labels are unavailable.

8. Supervised vs unsupervised: an important nuance#

Do not assume feature selection is always supervised or feature extraction is always unsupervised.

  • Supervised selection: uses the target, such as SelectKBest with an F-test or mutual information against class labels.
  • Unsupervised selection: uses properties of (X) alone, such as removing constant or near-constant columns.
  • Unsupervised extraction: PCA, Truncated SVD, and many autoencoders trained without labels.
  • Supervised extraction: LDA and task-trained neural embeddings.

The right method depends on whether labels exist, whether they are reliable, and what the final model must achieve.

9. Interpretability and practical trade-offs#

Feature selection is usually easier to explain. If a model uses income, account age, and payment history, the input columns retain their business definitions. This can help with audits, debugging, data collection, and explaining model behavior.

Feature extraction can be harder to interpret. A component such as (0.31x_1-0.18x_2+0.74x_3) is a combination of original measurements. It may capture useful structure, but it does not have a simple business meaning.

Other trade-offs:

  • Information: selection discards columns; extraction transforms information and may compress or discard detail.
  • Correlated inputs: selection may choose one among correlated variables; extraction can combine them into fewer components.
  • Interactions: univariate filters can miss interactions; wrappers and some extraction models can capture richer relationships.
  • Computation: simple filters are usually cheap; wrappers and neural extraction can be expensive.
  • New data: both require a fitted, versioned transformation or selection mask to be reused consistently.
  • Model compatibility: sparse feature selection can work well for linear models and high-dimensional text. Dense extracted components may suit other estimators but can increase serving cost.
  • Regulatory or business needs: retaining named original variables may be essential even when a compressed representation gives slightly better validation performance.

10. Python example: compare both approaches safely#

This example uses the breast-cancer classification dataset from scikit-learn. It compares a pipeline that selects the 10 highest-scoring original features with one that extracts 10 PCA components. Both use the same classifier and cross-validation folds.

The feature selector and PCA transformation are inside their respective pipelines. Therefore, each is fitted only on the training fold during cross-validation.

PYTHON
from sklearn.datasets import load_breast_cancer from sklearn.feature_selection import SelectKBest, f_classif from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold, cross_val_score X, y = load_breast_cancer(return_X_y=True) cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # Selection: retain 10 original columns. selection_pipeline = Pipeline([ ("scale", StandardScaler()), ("select", SelectKBest(score_func=f_classif, k=10)), ("model", LogisticRegression(max_iter=5000)) ]) # Extraction: replace the original columns with 10 PCA components. extraction_pipeline = Pipeline([ ("scale", StandardScaler()), ("extract", PCA(n_components=10)), ("model", LogisticRegression(max_iter=5000)) ]) selection_scores = cross_val_score( selection_pipeline, X, y, cv=cv, scoring="accuracy" ) extraction_scores = cross_val_score( extraction_pipeline, X, y, cv=cv, scoring="accuracy" ) print("Feature selection accuracy:", selection_scores.mean(), "+/-", selection_scores.std()) print("PCA extraction accuracy:", extraction_scores.mean(), "+/-", extraction_scores.std()) # Fit the selection pipeline on all available data only for # inspecting the selected column names after the comparison. selection_pipeline.fit(X, y) selected_mask = selection_pipeline.named_steps["select"].get_support() feature_names = load_breast_cancer().feature_names print("Selected original features:") print(feature_names[selected_mask])

How to interpret this experiment:

  • Both pipelines produce 10 input columns for the classifier.
  • The selection pipeline retains 10 original measurements, so their names remain available.
  • The PCA pipeline creates 10 new components, each potentially combining many original measurements.
  • Cross-validation scores can differ; neither approach is guaranteed to win.
  • The selected feature list printed after the comparison is for illustration. For an unbiased final estimate, keep a separate untouched test set and do not use it to choose between approaches.

11. Data leakage: the mistake to avoid#

Feature selection and feature extraction are preprocessing steps. If they learn from data, they must be fitted only on the training portion of each evaluation split.

An incorrect workflow is:

  1. Run feature selection or PCA on the entire dataset.
  2. Split the transformed dataset into training and test sets.
  3. Report test performance.

This leaks information from the test set into the representation. In supervised selection, labels from test observations can directly influence which features are retained. Even unsupervised PCA can leak information because its means, scales, and component directions are learned from the full dataset.

A safer workflow is:

  1. Split data into training, validation, and test sets.
  2. Fit imputers, scalers, selectors, and extractors on training data only.
  3. Apply the learned transformations to validation and test data using transform.
  4. During cross-validation, place the transformations inside a pipeline so each fold learns its own representation from that fold's training partition.
  5. Keep the final test set untouched until model and preprocessing choices are complete.

Also check for target leakage in the source columns themselves. A feature created after the outcome occurs is not safe merely because a selector or extractor chooses it.

12. Which one should you choose?#

Choose feature selection when:

  • You need the original column names and business meanings.
  • Data collection or inference cost is high and you want to stop collecting unnecessary measurements.
  • You need a compact, sparse, or auditable input set.
  • You suspect irrelevant columns are adding noise.
  • You want a simpler model that stakeholders can inspect.

Choose feature extraction when:

  • Many original features are correlated or redundant.
  • The raw input is unstructured, such as text, images, or audio.
  • You need a compact representation for a downstream model.
  • The predictive signal is distributed across combinations of variables.
  • You can accept less direct interpretability in exchange for a useful representation.

A practical approach is to build a baseline with the original features, compare a filter or embedded selector with an extraction method such as PCA, and evaluate them using the same leakage-safe cross-validation and untouched test set. Measure not only predictive performance but also latency, memory, stability, interpretability, and the cost of collecting inputs.

13. Production guidance#

For feature selection:

  • Persist the selected column names, order, data types, and selector configuration with the model.
  • Validate that incoming data contains the expected columns and compatible meanings.
  • Monitor missingness, feature distributions, and changes in selected-feature availability.
  • Re-evaluate selection when the data-generating process or business definition changes.

For feature extraction:

  • Persist the fitted transformation, including scaling, component weights, encoder version, and feature ordering.
  • Apply exactly the same transformation at training and inference time.
  • Monitor input drift and the distribution of extracted representations.
  • Version the extractor with the downstream model; changing an embedding model or PCA basis can change the meaning of every downstream coordinate.
  • Test latency, memory, and numerical consistency when deploying the transformation.

In either case, do not assume fewer dimensions automatically means better performance. Validate the full pipeline under realistic data and serving conditions.

14. Final takeaway#

Feature selection chooses which original features to keep. Feature extraction creates a new representation from the original features.

Selection usually offers better interpretability and simpler data requirements. Extraction can capture combinations and structure that individual columns cannot represent conveniently. Both can reduce dimensionality, and both can be supervised or unsupervised.

The best choice is the one that improves the complete model pipeline while meeting its interpretability, data, validation, and production constraints.

Related questions

Explore other topics:Forward Deployed EngineeringDeep LearningMLOps