Feature Engineering
After this lesson, you will be able to:
- Rescale numbers using min-max normalization, standard scaling, and robust scaling so big and small features play fair in distance-based and gradient-based models
- Encode categorical variables with one-hot, ordinal, and target encoding, and know which to use based on cardinality and the risk of data leakage
- Create interaction features by multiplying, dividing, and combining existing columns to surface relationships that linear models cannot discover on their own
- Build polynomial features for nonlinear relationships, apply cyclical sin/cos encoding for time-based features, and select the most predictive features to reduce overfitting
Before you start
Don't worry if "feature engineering" sounds intimidating — it is really just creating new columns from your existing data. Once you see a few examples, you will wonder why it has such a fancy name!
#Raw Ingredients vs. Mise en Place
Feature engineering is widely considered one of the most valuable skills in applied machine learning. A saying often attributed to Andrew Ng goes: "Applied machine learning is basically feature engineering." Treat it as a saying, not a measurement. Competition write-ups often credit new features as much as the choice of model.
#Before and After: Feature Engineering in Action
Tests: Verify the DataFrame has more columns after engineering. Verify revenue equals price times quantity. Verify is_weekend is binary.
Try it! Open the Python REPL and type these lines yourself. Create a quick DataFrame and engineer one feature:import pandas as pd; df = pd.DataFrame({'date': pd.date_range('2024-01-01', periods=7)}); df['day_of_week'] = df['date'].dt.day_name(); print(df)— you just did feature engineering!
#Numeric Feature Scaling
Models that compute distances (KNN, SVM) or use gradient-based optimization (linear regression, neural networks) are sensitive to feature scales. A feature ranging from 0 to 1,000,000 will dominate a feature ranging from 0 to 1. Scaling fixes this.
#Min-Max Normalization
Scales features to a fixed range, typically [0, 1].
#Standard Scaling (Z-score Normalization)
Centers data at 0 with unit standard deviation.
Why standard scaling gives mean 0 and variance 1, and why min-max scaling fills [0, 1], is derived in Feature Engineering: The 80% of ML, in the Classical ML track.
#Robust Scaling
Uses median and IQR instead of mean and standard deviation.
Why does the median land on 0 and the IQR on 1, and why does one billionaire squeeze min-max but not this? Open the derivation.
You have a feature 'annual_income' with values ranging from $15,000 to $50,000,000 (a few billionaires in the dataset). Which scaling method should you use?
With extreme outliers, min-max would compress 99.9% of the data into a tiny range near 0, and standard scaling would be distorted by the extreme mean and standard deviation. Robust scaling uses the median and IQR, which are barely affected by billionaire outliers.
#Categorical Feature Encoding
Models need numbers, not strings. Encoding converts categorical variables into numeric representations.
This section is a quick recap. For the full treatment — target encoding with K-fold to prevent leakage, frequency/hashing for high-cardinality, and learned embeddings — see the dedicated Categorical EncodingCategorical EncodingTurning category labels into numbers so a model can use them, without implying an order or leaking the target.Learn more lesson, which is now a prerequisite to this one.
#One-Hot Encoding
Creates a binary column for each category.
color -> color_red color_blue color_green
"red" -> 1 0 0
"blue" -> 0 1 0
"green" -> 0 0 1
#Ordinal Encoding
Maps ordered categories to integers.
size -> size_encoded
"small" -> 0
"medium" -> 1
"large" -> 2
#Target Encoding (Mean Encoding)
Replaces each category with the mean of the target variable for that category.
The smoothing idea for rare categories is derived in Feature Engineering: The 80% of ML, in the Classical ML track.
#Creating New Features
The most powerful feature engineering goes beyond scaling and encoding — it creates entirely new features that capture domain knowledge.
#Polynomial Features
Capture nonlinear relationships by raising features to powers.
How fast does this table of columns grow? Open the derivation to count the columns for any number of features and any degree.
#Interaction Terms
Capture how features modify each other's effect.
price_per_sqft = price / square_feet
bmi = weight_kg / (height_m ** 2)
click_through_rate = clicks / impressions
#Feature Interactions: Where the Real Signal Hides
Sometimes the signal is not in individual features but in their COMBINATION. Price alone does not predict sales. Quantity alone does not predict sales. But price x quantity = revenue, and THAT predicts profit. Always ask: do any features multiply, divide, or combine to create a stronger signal?
Common interaction patterns:
- Multiplication: revenue = price x quantity, area = length x width
- Division: price_per_sqft = price / sqft, efficiency = output / input
- Ratios: click_through_rate = clicks / impressions, conversion_rate = purchases / visits
- Differences: profit = revenue - cost, net_change = current - previous
- Conditional: high_value_weekend = (is_weekend) x (order_value > 100)
#Domain-Specific Features
The most valuable features come from understanding the domain:
- E-commerce: Days since last purchase, average order value, number of returns
- Healthcare: BMI from height/weight, age at diagnosis, time between visits
- NLP: Text length, sentence count, average word length, sentiment score
- Time series: Rolling averages, lag features, day-of-week, is_holiday
- Geospatial: Distance to nearest store, population density, elevation
#Date/Time Features
A timestamp contains multiple signals:
"2024-03-15 14:30:00" ->
year: 2024
month: 3
day_of_week: 4 (Friday)
hour: 14
is_weekend: false
is_business_hours: true
quarter: 1
days_since_epoch: 19797
sin_hour: sin(2*pi*14/24) # cyclical encoding
cos_hour: cos(2*pi*14/24) # cyclical encoding
The cyclical encoding (sin/cos) is important: it tells the model that hour 23 and hour 0 are close together, which simple integer encoding does not.
Why the sine and cosine pair keeps hour 23 next to hour 0 is derived in Feature Engineering: The 80% of ML, in the Classical ML track.
#The End-to-End Feature Engineering Pipeline
Before diving into feature selection, let us see the complete journey from raw features to a final feature matrix ready for modeling:
#Step 1: Raw Features
You start with the raw columns from your dataset — dates as strings, categorical columns as text, numerical values at wildly different scales, and missing values scattered throughout. These raw features are what your data pipeline produced, but they are not yet suitable for most models.
#Step 2: Handle Missing Values
Before any transformation, decide how to handle nulls. Impute numerical columns with the median (robust to outliers), categorical columns with the mode, or create "is_missing" indicator columns for MNAR data. Imputation statistics must come from the training set only.
#Step 3: Scale Numerical Features
Apply min-max normalization for bounded outputs, standard scaling (z-score) for roughly normal data, or robust scaling (median/IQR) when outliers are present. Tree-based models skip this step, but linear models and neural networks require it.
#Step 4: Encode Categorical Features
Convert strings to numbers. Use one-hot encoding for low-cardinality unordered categories, ordinal encoding for ordered categories (small/medium/large), or target encoding with regularization for high-cardinality features like zip codes.
#Step 5: Create Interaction Features
Engineer new features that capture domain knowledge: price_per_sqft from price and area, BMI from height and weight, days_since_last_purchase from timestamps. Polynomial features and cyclical sin/cos encoding for time features go here too.
#Step 6: Select Top Features
Not all features help. Remove zero-variance features, drop one of any highly correlated pair (r > 0.95), and use tree-based importance or mutual information to rank the rest. Validate with cross-validation that removing features does not degrade performance.
#Step 7: Final Feature Matrix
The output is a clean, scaled, encoded, and selected feature matrix — ready for model training. Every transformation is encapsulated in a reproducible pipeline that applies identically during training and inference, preventing train-serve skew.
#Feature Selection: Less Is More
Not all features help. Some are redundant, some are noisy, and some are correlated with the target only by coincidence.
#Try It Yourself
Tests: Verify pricePerSqft is computed correctly. Verify standard scaling produces mean ~0. Verify one-hot encoding sums to 1 per row. Verify cyclical month encoding.
#Feature Engineering for Different Model Types
Not all models need the same features:
- Do NOT need scaling (splits are scale-invariant)
- Do NOT need one-hot encoding (can split on categorical values)
- DO benefit from interaction terms and derived features
- Handle missing values natively (some implementations)
- NEED scaling (coefficients are meaningless otherwise)
- NEED encoding (cannot handle strings)
- Benefit greatly from polynomial features (capture nonlinearity)
- Sensitive to multicollinearity (correlated features)
- NEED scaling (gradient descent converges poorly without it)
- Can learn features automatically from raw inputs (for images, text)
- For tabular data, manual feature engineering still helps significantly
- Embedding layers replace one-hot encoding for high-cardinality categories
The ratio in the box is a score between 0 and 1. Open the derivation to see why, and what a score of 1 means.
#Key Takeaways
- Feature engineering is the most impactful skill in applied ML. Domain knowledge translated into features accounts for more performance gain than model selection or hyperparameter tuning, especially for tabular data
- Different model families need different preprocessing. Tree-based models need no scaling and handle categoricals natively, while linear models and neural networks require scaling and encoding; always match your preprocessing to your model
- Cyclical features need sin/cos encoding. Integer encoding treats December (12) and January (1) as distant when they are adjacent; sin/cos encoding preserves the circular structure that time-based patterns require
- Domain-specific derived features unlock hidden signal. Raw timestamps, prices, and measurements are rarely useful directly; features like price-per-square-foot, days-since-last-purchase, and rolling averages capture the relationships models need
- Feature selection reduces overfitting. Too many features cause the model to memorize noise; remove zero-variance, highly correlated, and low-importance features, then validate with cross-validation
#Quick Check
Why do tree-based models (Random Forest, XGBoost) NOT need feature scaling?