Feature Engineering: Categorical Encoding, Scalers & Transformers

"Coming up with features is difficult, time-consuming, and requires expert knowledge. Applied machine learning is basically feature engineering." — Prof. Andrew Ng. In this class, we master Categorical Encodings, Feature Scaling, and ColumnTransformers.

1. Categorical Encoding Strategy Matrix

Encoding Method Best For Dimensionality Impact Key Pitfall
One-Hot Encoding (OHE) Nominal categories with low cardinality (< 15 unique values). Expands to \(k\) or \(k-1\) binary columns. Causes sparse matrix explosion on high cardinality columns.
Ordinal Encoding Categories with inherent ranked order (e.g., Low, Medium, High). Maintains 1 single numeric column. Imposing arbitrary numeric orders on unordered nominal data.
Target / WoE Encoding High cardinality categories (e.g., 500 city names, 1,000 product SKUs). Maintains 1 single numeric column. Extreme risk of target leakage without m-estimate smoothing.

2. Feature Scaling Formulas & Selection

  • StandardScaler (Z-Score Normalization): Centers at \(\mu = 0\), scales to \(\sigma = 1\): \[ x_{\text{scaled}} = \frac{x - \mu}{\sigma} \] Required for Linear/Logistic Regression, Neural Networks, and PCA.
  • MinMaxScaler: Binds features into a strict fixed interval \([0, 1]\): \[ x_{\text{scaled}} = \frac{x - x_{\min}}{x_{\max} - x_{\min}} \] Essential for image pixel processing and algorithms requiring strictly positive numbers.
  • RobustScaler: Uses median and Interquartile Range: \[ x_{\text{scaled}} = \frac{x - \text{Median}}{Q_3 - Q_1} \] The gold standard when numeric features contain stubborn real-world outliers.

Production Pipeline with ColumnTransformer

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# Sample feature dataset
df = pd.DataFrame({
    'age': [25, 45, 35, 52, 23, 40, 60, 48],
    'income': [50000, 110000, 75000, 130000, 42000, 85000, 160000, 95000],
    'education': ['Bachelors', 'PhD', 'Masters', 'Masters', 'HighSchool', 'Bachelors', 'PhD', 'Masters'],
    'country': ['US', 'UK', 'CA', 'US', 'US', 'UK', 'CA', 'US'],
    'purchased': [0, 1, 1, 1, 0, 0, 1, 1]
})

X = df.drop(columns=['purchased'])
y = df['purchased']

# Define feature subsets
numeric_cols = ['age', 'income']
categorical_cols = ['education', 'country']

# Build ColumnTransformer (Zero Data Leakage Pipeline)
preprocessor = ColumnTransformer(transformers=[
    ('num', StandardScaler(), numeric_cols),
    ('cat', OneHotEncoder(drop='first', sparse_output=False), categorical_cols)
])

# Full scikit-learn pipeline
clf_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', LogisticRegression())
])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf_pipeline.fit(X_train, y_train)

print(f"Test Accuracy: {clf_pipeline.score(X_test, y_test) * 100:.1f}%")

Complete Protection Against Data Leakage

By wrapping feature preprocessing and estimator fitting inside a Scikit-Learn Pipeline, cross-validation automatically re-fits the scalers and encoders only on the training folds, preventing statistical contamination of validation sets.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between One-Hot Encoding and Target Encoding?

One-Hot Encoding converts each category into a new binary (0/1) column; it causes severe dimensionality explosion on high-cardinality features (like 5,000 ZIP codes). Target (Mean) Encoding replaces categories with the average target value for that category, retaining a single compact column (must use smoothing to prevent target leakage).

Q2. When should I use StandardScaler vs. RobustScaler?

StandardScaler transforms data to mean=0 and variance=1; it is highly sensitive to extreme outliers. RobustScaler removes the median and scales data according to the Interquartile Range (IQR), making it immune to outliers.

Q3. Why do tree-based models (Random Forests, XGBoost) not require feature scaling?

Decision trees make orthogonal splitting decisions on individual features independently (e.g., 'Is Age > 35?'). The monotonic scale or unit magnitude of a feature does not alter split points, unlike distance-based models (KNN, SVM, K-Means) and gradient-based neural networks.

Q4. What is data leakage in feature scaling?

Data leakage occurs when you fit a scaler on the entire dataset BEFORE splitting into train and test sets. The scaler learns the global mean and variance of the test set, contaminating test evaluation. Always fit on X_train only and call .transform() on X_test.

Q5. What does Scikit-Learn's ColumnTransformer achieve?

ColumnTransformer bundles disparate feature transformations (applying OneHotEncoder to categories and StandardScaler to numerics) into a unified, leak-proof pipeline that executes seamlessly during inference.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Data Cleaning & Outlier Removal

Clean and sanitize raw attributes prior to feature transformations.

Eigenvalues, SVD & PCA

Dimensionality reduction using Principal Component Analysis.

Predictive Modeling & Leakage Prevention

Assemble ColumnTransformers inside scikit-learn Pipeline objects.

Customer Churn Prediction Modeling

Engineer interaction terms and behavioural aggregations for churn prediction.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!