30 Mins

6. Feature Selection Techniques

Filter Methods: Variance Thresholds and Correlation

Filter methods evaluate the relevance of features by looking at the intrinsic properties of the features themselves, independent of any machine learning algorithm. The simplest filter method is the Variance Threshold, which removes features that do not meet a certain variance cutoff. If a feature is constant or has very low variance, it contains very little information for the model.

Correlation analysis is another powerful filter technique. Highly correlated features provide redundant information. By calculating the Pearson correlation matrix, we can identify pairs of features that are nearly identical and remove one of them to reduce the dimensionality of the dataset without significant information loss.

MethodMechanism
Variance ThresholdRemoves features with low variance (constant features).
CorrelationRemoves one feature from pairs with high collinearity.
Operator Note: Always normalize your data before performing correlation analysis, as it is based on the relationship between feature scales.
Python 3
import pandas as pd
import numpy as np
from sklearn.feature_selection import VarianceThreshold

# Create dummy data
df = pd.DataFrame({'f1': [1, 2, 3, 4], 'f2': [1, 1, 1, 1], 'f3': [1, 2, 3, 5]})
# Remove constant features
selector = VarianceThreshold(threshold=0.1)
filtered = selector.fit_transform(df)
print(f'Original shape: {df.shape}, New shape: {filtered.shape}')

Wrapper Methods: Recursive Feature Elimination (RFE)

Wrapper methods treat feature selection as a search problem where different subsets of features are prepared and evaluated. Recursive Feature Elimination (RFE) is a popular greedy optimization algorithm.

RFE works by fitting a model (typically a linear model or SVM) on the full set of features and ranking them by importance. The least important feature is removed, and the process repeats until the desired number of features is reached. This is computationally expensive but often yields highly effective feature sets because it accounts for interactions between features and the specific model used.

Operator Note: RFE can be slow on very large datasets; use a linear model with lower complexity to speed up the selection process.
Python 3
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression

X, y = make_regression(n_samples=50, n_features=5, n_informative=2)
est = LinearRegression()
selector = RFE(est, n_features_to_select=2)
selector.fit(X, y)
print(f'Selected feature indices: {selector.support_}')

Embedded Methods: Lasso L1 Regularization

Embedded methods perform feature selection during the training phase. Lasso (Least Absolute Shrinkage and Selection Operator) regression adds an L1 penalty to the loss function. The L1 penalty forces the coefficients of less important features to become exactly zero.

This inherent property makes Lasso a built-in feature selection tool. When you use a Lasso model, any feature with a coefficient of zero is effectively removed from the model, making it a highly efficient way to select features while training the model simultaneously.

Operator Note: Adjust the alpha parameter in Lasso; higher alpha values increase the number of features that get set to zero.
Python 3
from sklearn.linear_model import Lasso
import numpy as np

X = np.random.rand(100, 5)
y = X[:, 0] * 2 + np.random.randn(100) * 0.1
model = Lasso(alpha=0.1)
model.fit(X, y)
selected = np.where(model.coef_ != 0)[0]
print(f'Features with non-zero coefficients: {selected}')

Evaluating Performance Improvements

After stripping redundant or noise-inducing features, the critical final step is evaluating your model's performance on a validation set. Removing features should theoretically lead to better generalization and lower risk of overfitting.

Compare the metrics (e.g., RMSE, Accuracy, F1-Score) of your model before and after feature selection. If performance remains similar but the model is significantly smaller and faster to train, you have successfully optimized your pipeline.

Operator Note: Always cross-validate during the evaluation phase to ensure your performance improvements are not just luck of the draw on a specific test split.
Text
from sklearn.metrics import mean_squared_error
# Imagine comparing scores before and after
original_rmse = 0.45
optimized_rmse = 0.42
print(f'Improvement: {original_rmse - optimized_rmse:.3f}')

Knowledge Check

Ready to test your understanding of 6. Feature Selection Techniques?

Back