Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 2 of 9
Categorical Encoding: One-Hot, Ordinal, Target & Weight of Evidence
Machine learning algorithms require numerical input matrices. Encoding categoricals properly requires matching the encoding technique to category cardinality and semantic ordering: Ordinal Encoding (natural rank order: Low, Medium, High), One-Hot Encoding (low-cardinality nominals), and Target Encoding with Empirical Bayes Smoothing (high-cardinality categoricals: zip codes, merchant IDs).
High-Cardinality Target Encoding with Smoothing
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, TargetEncoder
# Synthetic multi-categorical dataset
np.random.seed(42)
n = 1000
cities = np.random.choice(['New York', 'London', 'Tokyo', 'Paris', 'Berlin', 'Sydney'], size=n)
education = np.random.choice(['High School', 'Bachelors', 'Masters', 'PhD'], size=n)
# High-cardinality feature (100 zip codes)
zip_codes = np.random.choice([f"ZIP_{i:03d}" for i in range(100)], size=n)
# Binary target with city dependence
city_risk = {'New York': 0.25, 'London': 0.18, 'Tokyo': 0.05, 'Paris': 0.12, 'Berlin': 0.08, 'Sydney': 0.10}
y = np.array([np.random.uniform(0, 1) < city_risk[c] for c in cities]).astype(int)
df = pd.DataFrame({'city': cities, 'education': education, 'zip_code': zip_codes})
# 1. ORDINAL ENCODING (Natural hierarchical rank)
edu_order = [['High School', 'Bachelors', 'Masters', 'PhD']]
ord_enc = OrdinalEncoder(categories=edu_order)
df['education_encoded'] = ord_enc.fit_transform(df[['education']])
# 2. ONE-HOT ENCODING (Low-cardinality nominal)
# drop='first' avoids the dummy variable trap in linear models
ohe = OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore')
city_ohe = ohe.fit_transform(df[['city']])
print(f"One-Hot encoded city matrix shape: {city_ohe.shape} (added {city_ohe.shape[1]} columns)")
# 3. SMOOTHED TARGET ENCODING (High-cardinality zip codes)
# Uses Empirical Bayes smoothing: S_i = (n_i * y_bar_i + m * y_global) / (n_i + m)
# Prevents overfitting on rare categories with 1 or 2 samples
target_enc = TargetEncoder(smooth='auto', cv=5, random_state=42)
df['zip_code_target_enc'] = target_enc.fit_transform(df[['zip_code']], y)
print("\nSample of Encoded Multi-Categorical Features:")
print(df[['city', 'education', 'education_encoded', 'zip_code', 'zip_code_target_enc']].head(5))Pro Tip: Prevent Target Leakage with Cross-Validation Encoding
Target Encoding replaces category c with the mean of target y for that category. If computed on the full dataset, the feature leaks the target directly into the predictor. Always use out-of-fold target encoding (`TargetEncoder(cv=5)`) so that a sample's own label never influences its encoded value.
MlCategoricalEncoding Visual Representation
Hands-On Challenge: Build a Weight of Evidence (WoE) Transformer
Write a custom Scikit-Learn transformer that implements Weight of Evidence encoding: `WoE_i = ln(P(Positive | Category_i) / P(Negative | Category_i))`. Verify that it linearizes logistic regression log-odds relationships.
Quick Quiz & Key Concept Checks
Common Pitfall: Unseen Categories at Inference Time
If a new category appears in production that was never present in training data, `OneHotEncoder` will throw a `ValueError` unless configured with `handle_unknown='ignore'`. Always configure encoders to handle unknown categories gracefully.