Target Encoding for Categorical Features
Target encoding replaces a categorical value with the average outcome seen for that category in the training data, which handles high-cardinality categories far better than one-hot encoding but leaks label information if done carelessly.
One-hot encoding a categorical feature with hundreds of distinct values — a ZIP code, a stock ticker, a merchant ID — produces hundreds of new sparse columns, which slows training and can overwhelm the actual signal. Target encoding takes a different approach: replace each category with a single number, the average value of the target variable among rows sharing that category in the training data.
In words: the category's own average outcome, blended toward the overall (global) average by a smoothing weight — categories with lots of observations ( large) rely mostly on their own average, while rare categories lean more on the global average, which prevents a category seen only twice from getting an extreme, unreliable encoding.
Target encoding directly uses the label you're trying to predict to build a feature, so computing it on the same rows you'll train on leaks information — it must be computed out-of-fold (as in cross-validation) or it will make the model look far better on training data than it will ever perform on new data.
Worked example. A "merchant" feature has a category seen in only 3 training rows, all fraudulent (target average 1.0). Raw target encoding would assign that merchant a 1.0 — an overconfident signal from 3 data points. With smoothing weight and a global fraud rate of 0.02: — pulled far back toward the base rate, reflecting how little evidence 3 observations really provide.
Further reading
- Micci-Barreca, 'A Preprocessing Scheme for High-Cardinality Categorical Attributes' (2001)