Skip to main content

Feature Engineering

Feature Engineering Pipeline

Data Scientists Spend 80% of Time Here

Raw data is messy. Models need clean, meaningful numbers. Feature engineering is the art of transforming raw data into features that help models learn. It’s the difference between feeding a model β€œMarch 15, 1995” (a string it can’t use) and feeding it β€œ30 years old, built pre-2000, winter construction” (numbers that carry meaning). Here’s a truth that surprises beginners: a simple model with great features almost always beats a complex model with raw features. Feature engineering is where domain knowledge meets data science, and it’s the single highest-leverage activity in most ML projects.
E-commerce Feature Extraction

The House Price Example

Raw data:
What a model needs:

Handling Missing Values

Strategy 1: Drop Missing Values

Only use when you have lots of data and missingness is truly random (called MCAR β€” Missing Completely At Random). If high-income people tend to skip the income question, dropping those rows biases your model toward low-income profiles. Check this by comparing the distributions of other features between β€œhas missing” and β€œno missing” groups.

Strategy 2: Imputation

Strategy 3: Indicator Variables

Which imputation strategy should you use? Use median for numeric features with outliers (median is robust to extreme values). Use mean for normally distributed features. Use mode (most frequent) for categorical features. And always create a missingness indicator β€” it’s free information and tree-based models will use it if it’s predictive.

Encoding Categorical Variables

Label Encoding (for ordinal categories)

Use this when categories have a natural order β€” like education levels, satisfaction ratings, or T-shirt sizes. The numbers you assign should reflect the ranking.

One-Hot Encoding (for nominal categories)

Use this when categories have no natural order β€” like colors, countries, or product types. Each category becomes its own binary column.
Before:
After:

Target Encoding (for high-cardinality categories)

When a categorical feature has hundreds or thousands of unique values (like zip codes or product IDs), one-hot encoding creates an explosion of columns. Target encoding replaces each category with the average target value for that category β€” essentially asking β€œwhat’s the typical outcome for this group?”
Data leakage warning: Target encoding uses the target variable to create features, which can leak future information into training. Always compute means on training data only, and consider using smoothed target encoding (blending category mean with global mean) to reduce overfitting on rare categories. Libraries like category_encoders handle this correctly.

Scaling Numerical Features

Why Scale?

Many algorithms (SVM, KNN, neural networks) are sensitive to scale:
  • Age: 0-100
  • Income: 0-1,000,000
Without scaling, income would dominate!

StandardScaler (Z-score normalization)

xscaled=xβˆ’ΞΌΟƒx_{scaled} = \frac{x - \mu}{\sigma} Centers each feature at 0, scales to unit variance. The most common choice for algorithms that assume normally distributed features (logistic regression, SVM, neural networks).

MinMaxScaler (0-1 normalization)

xscaled=xβˆ’xminxmaxβˆ’xminx_{scaled} = \frac{x - x_{min}}{x_{max} - x_{min}} Maps every feature to [0, 1]. Best when you need bounded values (e.g., neural network inputs, or when features are already uniformly distributed). Sensitive to outliers β€” one extreme value can squash everything else into a narrow range.

RobustScaler (for outliers)

Uses median and IQR instead of mean and std. If your data has outliers that you don’t want to remove, this is your best bet β€” the median and IQR are not affected by extreme values.
Quick decision guide for scaling:

Creating New Features

Mathematical Transformations

Interaction Features

These capture relationships between features that the model might not discover on its own. They encode domain knowledge: β€œthe combination of these two things matters, not just each one individually.”

Date Features

Text Features


Binning Continuous Variables


Handling Outliers


Feature Selection

More features is not always better. Think of it like packing for a trip: bringing everything β€œjust in case” makes your suitcase impossibly heavy and you can never find what you need. Feature selection is choosing to pack only what you’ll actually wear. Irrelevant features add noise, slow training, and can even hurt accuracy by diluting the signal.

Correlation Analysis

Model-Based Selection

Recursive Feature Elimination

RFE works like a talent show elimination: train a model, eliminate the weakest feature, retrain, repeat. It’s slower but catches feature interactions that univariate tests miss.

Feature Engineering Pipeline


Common Mistakes

Data Leakage

Problem: Using test data info during trainingFix: Always fit transformers on train data only

Scaling After Split

Problem: Scaling before train-test splitFix: Split first, then scale

πŸš€ Mini Projects

Project 1: E-commerce Feature Engineer

Transform raw transaction data into predictive features

Project 2: Date-Time Feature Factory

Extract powerful temporal features from timestamps

Project 3: Text Feature Extractor

Convert text data into numerical features

Project 4: Automated Feature Pipeline

Build an end-to-end feature engineering pipeline

Project 1: E-commerce Feature Engineer

Transform raw e-commerce transaction data into features that predict customer churn.

Project 2: Date-Time Feature Factory

Extract powerful temporal features from timestamp data.

Project 3: Text Feature Extractor

Convert text data into numerical features for machine learning.

Project 4: Automated Feature Pipeline

Build an end-to-end feature engineering pipeline that handles multiple data types.

Key Takeaways

Handle Missing Data

Impute or create indicator variables

Encode Categories

One-hot for nominal, ordinal for ordered

Scale Features

StandardScaler or MinMaxScaler for most algorithms

Create Features

Domain knowledge creates the best features

🧹 Real-World Messy Data: Complete Guide

Missing Values Decision Tree

Outlier Detection & Treatment

Handling Skewed Distributions


πŸ”— Math β†’ ML Connection

Feature engineering connects to these mathematical concepts:The Linear Algebra course covers why these transformations work geometrically.

πŸš€ Going Deeper (Optional)

Target Encoding (for High-Cardinality Categoricals)

When a categorical has 1000+ unique values, one-hot encoding creates too many features:

Time-Based Features

Automated Feature Engineering


What’s Next?

Now you know how to prepare data. But how do you find the best hyperparameters?

Continue to Module 9: Hyperparameter Tuning

Learn Grid Search, Random Search, and Bayesian Optimization