Lesson 3 of 9
High-Cardinality Target Encoding with K-Fold Smoothing & M-Estimate
When categorical features have hundreds or thousands of levels (postal zip codes, merchant IDs, device models), One-Hot Encoding inflates dimensionality and destroys tree performance. Target Encoding replaces each category with the average target value for that category. However, naive target encoding causes catastrophic target leakage and memorization. Implementing Out-of-Fold K-Fold splitting and Empirical Bayes smoothing (m-estimate) is mandatory.
Smoothed Target Encoding with Out-of-Fold Cross-Validation
import pandas as pd
import numpy as np
from sklearn.preprocessing import TargetEncoder
# Synthetic dataset with a high-cardinality categorical feature (100 merchant categories)
np.random.seed(42)
n_samples = 2000
categories = [f"CAT_{i:03d}" for i in range(100)]
# Heavily skewed category distribution (some categories have 200 samples, some have 1 sample)
cat_weights = np.random.dirichlet(np.ones(100))
cat_column = np.random.choice(categories, size=n_samples, p=cat_weights)
# Ground truth probability of fraud per category
cat_fraud_rates = {c: np.random.beta(1, 10) for c in categories}
y = np.array([np.random.uniform(0, 1) < cat_fraud_rates[c] for c in cat_column]).astype(int)
df = pd.DataFrame({'merchant_category': cat_column})
# 1. SCIKIT-LEARN TARGET ENCODER WITH SMOOTHING & OUT-OF-FOLD CV
# Formula: S_i = (n_i * y_bar_i + m * y_prior) / (n_i + m)
# When sample count n_i is small, S_i shrinks to the global prior y_prior
target_encoder = TargetEncoder(
smooth='auto', # Empirical Bayes shrinkage parameter estimation
cv=5, # Out-of-fold internal 5-fold cross-validation
random_state=42
)
# Fit on feature and target
encoded_feature = target_encoder.fit_transform(df[['merchant_category']], y)
df['encoded_target'] = encoded_feature
global_prior = y.mean()
print("=== SMOOTHED TARGET ENCODING REPORT ===")
print(f"Global Target Prior Mean: {global_prior:.4f}")
# Inspect rare category with 1 sample vs frequent category with 150 samples
rare_cat = df['merchant_category'].value_counts().index[-1]
freq_cat = df['merchant_category'].value_counts().index[0]
print(f"\nRare Category '{rare_cat}' (Count: {np.sum(df['merchant_category'] == rare_cat)}):")
print(f" Encoded Value: {df[df['merchant_category'] == rare_cat]['encoded_target'].iloc[0]:.4f} (Shrunk toward prior {global_prior:.4f}!)")
print(f"\nFrequent Category '{freq_cat}' (Count: {np.sum(df['merchant_category'] == freq_cat)}):")
print(f" Encoded Value: {df[df['merchant_category'] == freq_cat]['encoded_target'].iloc[0]:.4f} (Reflects empirical category mean)")Pro Tip: The M-Estimate Smoothing Formula
In production, the m-estimate formula `S_i = (n_i * mean_i + m * prior) / (n_i + m)` provides direct business control. Setting `m=10` means a category requires at least 10 observations before its empirical mean is weighted equally with the global baseline prior.
MlTargetEncoding Visual Representation
Hands-On Challenge: Write Out-of-Fold Target Encoding from Scratch
Implement an out-of-fold target encoding loop in pure Pandas using `KFold(n_splits=5)`. Ensure that each training fold's encoded values are computed strictly from the remaining 4 folds.
Quick Quiz & Key Concept Checks
Common Pitfall: Fitting TargetEncoder on the Entire Dataset
Calling `target_encoder.fit(X, y)` on the entire dataset before train-test splitting leaks test set target values into feature representations. Always place `TargetEncoder` inside an atomic `Pipeline`.