Home Knowledge Base Target Encoding (Mean Encoding)

Target Encoding (Mean Encoding) is a supervised categorical encoding technique that replaces each category with the mean of the target variable for that category — transforming "New York" into 0.82 (82% of New York customers bought) and "Paris" into 0.23 (23% of Paris customers bought), providing a single numeric column that captures predictive signal for high-cardinality features (1000+ categories) where one-hot encoding would create an impractically wide matrix, but requiring careful regularization to prevent severe overfitting.

What Is Target Encoding?

How Target Encoding Works

CityTarget (Bought?)CountMean TargetEncoded Value
New York1,1,1,0,150.800.80
Paris0,0,1,0,050.200.20
Tokyo1,1,0,1,150.800.80
Berlin111.00⚠️ Overfitting!

The Overfitting Problem and Solutions

ProblemExampleSolution
Small categoryBerlin has 1 sample → mean = 1.0 (perfect but fake)Smoothing with global mean
Target leakageEncoding uses the same data the model trains onCompute encoding inside cross-validation folds
Rare categoriesA new city in test data has no encodingFall back to global mean

Smoothing Formula

$ ext{Encoded} = frac{n imes ext{category\_mean} + m imes ext{global\_mean}}{n + m}$

Where n = category count, m = smoothing parameter. For Berlin (n=1, global_mean=0.5, m=10): $(1 × 1.0 + 10 × 0.5) / (1 + 10) = 0.545$ — pulled toward the global mean instead of the unreliable 1.0.

Cross-Validation Encoding (K-Fold)

FoldTraining DataEncoding SourceTest Data
Fold 1 as testCompute means from Folds 2-5Means from Folds 2-5Apply to Fold 1
Fold 2 as testCompute means from Folds 1,3-5Means from Folds 1,3-5Apply to Fold 2

This ensures no data point's own target value contributes to its encoding — preventing leakage.

When to Use Target Encoding

ScenarioUse Target Encoding?Reason
High-cardinality (1000+ categories)Yes ✓One-hot creates too many columns
Low-cardinality (3-10 categories)Usually noOne-hot works fine and is simpler
Tree-based models (XGBoost, LightGBM)Yes ✓Trees benefit from continuous signal
Linear modelsCarefullyMust ensure proper smoothing

Target Encoding is the most powerful encoding for high-cardinality categorical features — converting thousands of categories into a single informative numeric column that captures predictive signal, with the critical requirement that smoothing and cross-validation encoding must be used to prevent the data leakage that makes naive target encoding notoriously prone to overfitting.

target encodingmeancategory

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.