Feature Engineering

Feature engineering is the process of transforming raw data into meaningful features that improve the performance of machine learning models.

The goal is to make the data more useful and relevant for the problem we’re solving.

This Lesson Will Cover
  • ⚙️ Feature Engineering Fundamentals
  • 🏗️ Creating New Features
  • 🎯 Feature Selection Methods
  • 📉 Dimensionality Reduction Techniques
  • 🔄 Data Transformation Strategies

When to do Feature Engineering?

A good rule of thumb for feature engineering is:

If we can’t clearly explain why the feature will help predict the target, then it’s not a good feature.

“Good” Feature Engineering Examples:

Feature Description Goal Explanation
Monthly transaction amount divided by 6-month average Fraud Detection Unusually high ratios might indicate suspicious activity
Percentage decrease in weekly logins over 3 months Customer Churn Prediction Decreased engagement often precedes customer departure
Heat index (combining temperature and relative humidity) Weather Forecasting Better represents human comfort levels than individual measures

“Bad” Feature Engineering Examples:

Feature Description Goal Explanation
Birth month number multiplied by shoe size General Business No logical connection to any business outcome
Binary encoding of first letter in street name (A=1, B=2, etc.) House Price Prediction Street name initials don’t meaningfully impact property values
Count of a,e,i,o,u letters in sender’s email name Email Spam Detection Spelling pattern of names isn’t logically related to spam behavior
Feature Engineering Pipeline
Overview of the feature engineering pipeline for ML.

Creating New Features

As seen above, creating new features involves extracting or combining existing data.

This step should be informed by domain expertise, through discussions with SMEs (Subject Matter Experts).

Techniques for Creating New Features

Mathematical Transformations

Create ratios, differences, or products of existing features.

import pandas as pd

# Sample DataFrame
data = {'Height': [170, 165, 180], 'Weight': [70, 60, 80]}
df = pd.DataFrame(data)

# Create a new feature: BMI (Body Mass Index)
df['BMI'] = df['Weight'] / (df['Height'] / 100) ** 2
print(df)

# Outputs:
#     Height  Weight        BMI
# 0     170      70  24.221453
# 1     165      60  22.038567
# 2     180      80  24.691358

Date and Time Features:

Extract insights like the day of the week, month, or time of day.

df['Date'] = pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03'])
df['Day_of_Week'] = df['Date'].dt.day_name()
print(df)

# Outputs:
#    Height  Weight        BMI       Date Day_of_Week
# 0     170      70  24.221453 2024-01-01      Monday
# 1     165      60  22.038567 2024-01-02     Tuesday
# 2     180      80  24.691358 2024-01-03   Wednesday

Text Features:

Use text length, word counts, or sentiment scores.

df['Review'] = ['Great product!', 'Not bad', 'Terrible experience.']
df['Review_Length'] = df['Review'].apply(len)
print(df)

# Outputs:
#    Height  Weight        BMI       Date Day_of_Week                Review  \
# 0     170      70  24.221453 2024-01-01      Monday        Great product!
# 1     165      60  22.038567 2024-01-02     Tuesday               Not bad
# 2     180      80  24.691358 2024-01-03   Wednesday  Terrible experience.
#
#    Review_Length
# 0             14
# 1              7
# 2             20

Feature Selection

Selecting the most relevant features can simplify our model, reduce overfitting, and improve performance.

Feature Selection Methods

Embedded Methods

Algorithms like decision trees and LASSO automatically select features during training by assigning importance weights.

# Random Forests provide feature importance scores based on how much
# each feature contributes to decreasing impurity across all trees
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris

# Load sample iris dataset
X, y = load_iris(return_X_y=True)

# Initialize and train the random forest
model = RandomForestClassifier()
model.fit(X, y)

# Get feature importance scores - higher scores mean more important features
print(model.feature_importances_)

# Outputs:
# [0.12609839 0.03224898 0.38591743 0.4557352 ]
Random-Forest Feature Importance Bar Chart - Identifying the Most Predictive Iris Measurements via Embedded Selection
Random-Forest feature importances for the Iris dataset.

Wrapper Methods

Use model performance as the criteria (e.g., recursive feature elimination).

# Recursive Feature Elimination (RFE) iteratively removes features
# by training the model multiple times and eliminating the weakest feature
# until the desired number of features is reached
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression

# Initialize the model
model = LogisticRegression()

# Create RFE selector that will select 2 best features
rfe = RFE(model, n_features_to_select=2)

# Fit RFE - this will iteratively eliminate features
rfe = rfe.fit(X, y)

# Print boolean mask of selected features (True = selected)
print(rfe.support_)

# Outputs: [False False  True  True]
Recursive Feature Elimination Results - Visual Mask Showing Retained vs. Discarded Features After Logistic Regression Wrapping
RFE-selected features: 1 = retained, 0 = eliminated.

Filter Methods

Use statistical tests or correlation to rank features.

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

# Load the iris dataset as an example
X, y = load_iris(return_X_y=True)

# Create a selector that will keep the 2 best features
# f_classif measures the relationship between each feature and the target variable
selector = SelectKBest(score_func=f_classif, k=2)

# Fit the selector and transform the data
X_selected = selector.fit_transform(X, y)

print("Original features shape:", X.shape)
print("Selected features shape:", X_selected.shape)
print("Feature scores:", selector.scores_)
print("Selected features:", selector.get_support())

# Outputs:
# Original features shape: (150, 4)
# Selected features shape: (150, 2)
# Feature scores: [ 119.26450218   49.16004009 1180.16118225  960.0071468 ]
# Selected features: [False False  True  True]
ANOVA F-Test Scores for Iris Attributes - Filter-Based Ranking with Selected Features Highlighted
F-scores for each Iris feature using SelectKBest.

Dimensionality Reduction

Dimensionality reduction techniques combine information from multiple features into a smaller set of new features.

This differs from feature selection because, instead of choosing existing features, it creates new features that capture the most important patterns in the data while reducing the overall complexity.

It’s typically used when dealing with high-dimensional data, e.g., when:

  • The number of features is very large (hundreds or thousands)
  • Features are highly correlated with each other
  • Computational resources are limited, or model training time needs to be reduced
  • Visualization of high-dimensional data is needed

Techniques for Dimensionality Reduction

PCA (Principal Component Analysis)

Projects data into a lower-dimensional space while retaining maximum variance: reducing dimensionality while preserving the most important patterns in the data.

Like we discussed in the linear algebra section of this course, PCA finds orthogonal directions (principal components) that capture the most variation in the data.

from sklearn.decomposition import PCA

pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
print(X_pca[:5])
print("Explained variance ratio:", pca.explained_variance_ratio_)

# Outputs:
# [[-2.68412563  0.31939725]
#  [-2.71414169 -0.17700123]
#  [-2.88899057 -0.14494943]
#  [-2.74534286 -0.31829898]
#  [-2.72871654  0.32675451]]
# Explained variance ratio: [0.92461872 0.05306648]
PCA 2-D Projection of Iris Dataset
PCA projection of Iris dataset (2 components).

SVD (Singular Value Decomposition)

A generalized version of PCA that is commonly used in recommendation systems and text analysis.

SVD can handle sparse matrices efficiently and works well with high-dimensional data, making it particularly useful for large-scale applications like collaborative filtering and document analysis.

from sklearn.decomposition import TruncatedSVD

svd = TruncatedSVD(n_components=2, random_state=42)
X_svd = svd.fit_transform(X)
print(X_svd[:5])
print("Explained variance ratio:", svd.explained_variance_ratio_)

# Outputs:
# [[ 5.91274714 -2.30203322]
#  [ 5.57248242 -1.97182599]
#  [ 5.44697714 -2.09520636]
#  [ 5.43645948 -1.87038151]
#  [ 5.87564494 -2.32829018]]
# Explained variance ratio: [0.52875361 0.44845576]
Truncated SVD Projection of Iris Dataset
SVD projection of Iris dataset (2 components).

t-SNE (t-Distributed Stochastic Neighbor Embedding)

A non-linear dimensionality reduction technique that is particularly effective for visualizing high-dimensional data. t-SNE preserves local relationships between points, making it excellent for revealing clusters and patterns that linear methods might miss.

from sklearn.manifold import TSNE

tsne = TSNE(n_components=2, perplexity=30, random_state=42)
X_tsne = tsne.fit_transform(X)
print(X_tsne[:5])

# Outputs:
# [[-26.62385    -2.969567 ]
#  [-29.334204   -2.056246 ]
#  [-29.084578   -3.2681649]
#  [-29.577831   -2.9022093]
#  [-26.578043   -3.3951583]]
t-SNE Non-Linear Embedding of Iris Data
t-SNE embedding of Iris dataset (2 components).

In addition to visualization, t-SNE can be a helpful tool for doing exploratory data analysis of complex datasets. For example:

  • Customer Segmentation: Exploring high-dimensional customer behavior data (purchases, clicks, demographics) to discover natural groupings
  • Image Classification: Analyzing how different images cluster together based on their pixel features, helping identify potential subgroups or misclassified samples
  • Text Document Analysis: Visualizing relationships between documents based on their word embeddings, useful for topic discovery or content organization

Conclusion

Feature engineering is a fun and creative part of machine learning. It’s also a really important step in building models that learn more effectively.

Key Takeaways

🛠️ Feature engineering requires domain expertise and understanding of the problem.

🎯 Good features should have a clear, logical connection to the target variable.

📊 Common techniques include mathematical transformations, date/time features, and text analysis.

✂️ Feature selection helps reduce model complexity.

🔽 Dimensionality reduction techniques like PCA, SVD, and t-SNE help manage high-dimensional data.

Next: Data Splitting Strategies

Next, let’s continue through the full ML pipeline and look at strategies to splitting data into training, test and eval sets.

Comments (0)

No comments yet.