Feature Engineering, Scaling, Encoding & Pipelines
Part I · Chapter 3: Standard vs. MinMax vs. Robust scaling, One-Hot vs. Target encoding, missing values, cyclical features & ColumnTransformer
'Applied Machine Learning is basically Feature Engineering.' — Andrew Ng. Better features beat fancier models almost every time!
Unscaled features crash gradient descent convergence, while missing `handle_unknown='ignore'` crashes production APIs the first time a brand-new category arrives!
Crafting domain ratios (spend_per_visit), log-transforms for skewed revenue, and MissingIndicator flags routinely unlocks +5–15% AUC lift on tabular datasets.
'Which models need feature scaling and why?', 'How do you encode a 50,000-level ZIP code column?', and 'Why does missingness itself carry signal?' are asked in almost every DS interview!
You multiply the 'Salary' feature by 1,000 (converting $k to $). Which model's predictions stay 100% IDENTICAL without needing feature scaling?
- Know instantly WHICH models require feature scaling (Linear/Logistic, SVM, KNN, Neural Nets, PCA, K-Means) and which DON'T (Decision Trees, Random Forest, XGBoost!).
- Choose accurately between StandardScaler, MinMaxScaler, RobustScaler (IQR), and Log Transforms when outliers or skewness appear.
- Encode categorical features cleanly (One-Hot, Ordinal, Out-of-Fold Target Encoding) and handle unseen production categories safely.
- Build leakage-free scikit-learn `ColumnTransformer` + `Pipeline` workflows.
Raw real-world data is messy: salaries range from $30,000 to $10,000,000, ages range from 18 to 80, cities are strings ('NYC', 'Tokyo'), and 12% of cells are NaN! Feature Engineering & Preprocessing translates that raw mess into clean, well-scaled numbers that models can learn from effortlessly.
1. Scaling Showdown: Standard vs. MinMax vs. Robust IQR
Suppose 4 normal employees earn [40k, 60k, 80k, 100k] and the CEO walks into the table earning $1,000k. Watch what happens when you run MinMaxScaler: the CEO becomes 1.00, and ALL FOUR normal employees get crushed into a microscopic [0.00, 0.06] sliver! Now watch RobustScaler (using Median & IQR) completely ignore the CEO below!
Quick Cheat Sheet: Who Needs Scaling?
- MUST Scale: Linear/Logistic Regression (with L1/L2 or GD), SVM, KNN, K-Means, PCA, Neural Networks.
- Scale-Invariant (No scaling needed!): Decision Trees, Random Forests, XGBoost, LightGBM, CatBoost, Naive Bayes.
Raw salaries ($k): [40, 60, 80, 100, 1000]. Look at what happens to the 4 normal employees [40, 60, 80, 100]:
CRUSHED into [0.00, 0.06]!
All 4 normal people look negative!
100% UNCHANGED by the outlier!
A feature column on Train has values [10, 20, 30] (mean=20, std=8.165, min=10, max=30). Compute the StandardScaler and MinMaxScaler value for a NEW test point x = 40.
2. Categorical Encoding, Missingness & Cyclical Features
Models only understand numbers — so how do you turn 'City = Paris' into a number? If you naively assign NYC=1, Paris=2, Tokyo=3, a linear model thinks Tokyo is 3× bigger than NYC and NYC + Paris = Tokyo! That's why we match the encoding to the category type:
The 4 Essential Feature Engineering Moves
- One-Hot Encoding (low-cardinality unordered categories like Color, Country): creates binary
0/1columns. Always sethandle_unknown="ignore"for production! - Ordinal Encoding (true ordered ranks like
Small=0, Med=1, Large=2). - Out-of-Fold Target Encoding (high-cardinality IDs like 40,000 ZIP codes): replace each ZIP with its smoothed average target
ycomputed strictly out-of-fold to avoid target leakage! - Missingness as a Feature (
MissingIndicator) + Cyclical Time: Never blindly dropNaN— someone leavingincomeblank is often a HUGE predictive signal! Add a binaryincome_is_missingflag BEFORE imputing with Train median. And encodehour ∈ [0..23]as(sin(2π·h/24), cos(2π·h/24))so11 PMsits right next to1 AM!
Pause & Check: You have a 'hour_of_day' feature (0 to 23). Why is encoding it with sin/cos better for a neural net or KNN than raw integers 0..23?
3. Production `ColumnTransformer` Pipelines
In real tables, numeric columns and text/category columns live side-by-side. Scikit-learn's ColumnTransformer routes numeric columns to (MedianImputer → StandardScaler) and categorical columns to (ModeImputer → OneHotEncoder) inside ONE single leak-free object that you can pickle and deploy directly to production!
Look at how clean and bug-proof a real production preprocessing pipeline is in the Python code below — AND test why scaling speeds up Gradient Descent 10× in the Contour Race Deep Lab!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Naive (x − μ) / σ divides by ZERO and explodes your entire matrix into NaNs! That's why production scalers (and our AIMLCode ml-standard-scaler-scratch coding problem!) replace std == 0 with 1.0 so constant columns safely scale to 0.0!
Unscaled Ravine (Zigzag!) vs. Scaled Circle (Straight Shot!)
Credit Scoring & Missingness Signals
Missing credit-bureau fields carry strong default signal — pairing Median Imputation with MissingIndicator flags lifts AUC significantly.
Ad-Tech High-Cardinality Features
Publisher IDs and App IDs have 100K+ unique values — Out-of-Fold Target Encoding or learned Embeddings handle them without 100K sparse columns.
Ride-Share Demand & Cyclical Time
Uber/Lyft encode hour-of-day and day-of-week with sin/cos pairs so midnight and Sunday→Monday transitions stay continuous.
Train/Serve Parity Pipelines
Bundling `ColumnTransformer` + model into one artifact prevents 'training-serving skew' where production scales features differently from training.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, RobustScaler
num_cols = ["sqft", "income", "age"]
cat_cols = ["city", "plan_tier"]
pre = ColumnTransformer([
("num", Pipeline([
("imp", SimpleImputer(strategy="median", add_indicator=True)),
("scl", RobustScaler()),
]), num_cols),
("cat", Pipeline([
("imp", SimpleImputer(strategy="most_frequent")),
("ohe", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
]), cat_cols),
])
model = Pipeline([("pre", pre), ("reg", Ridge(alpha=1.0))])
# model.fit(X_train, y_train) -> 100% leak-free in CV & production!