Quant Memo
Core

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.

encode(c)=ncyˉc+myˉnc+m\text{encode}(c) = \frac{n_c \cdot \bar{y}_c + m \cdot \bar{y}}{n_c + m}

In words: the category's own average outcome, blended toward the overall (global) average by a smoothing weight mm — categories with lots of observations (ncn_c 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 m=20m=20 and a global fraud rate of 0.02: encode=3(1.0)+20(0.02)3+20=3.4230.148\text{encode} = \frac{3(1.0) + 20(0.02)}{3+20} = \frac{3.4}{23} \approx 0.148 — pulled far back toward the base rate, reflecting how little evidence 3 observations really provide.

Related concepts

Further reading

  • Micci-Barreca, 'A Preprocessing Scheme for High-Cardinality Categorical Attributes' (2001)
ShareTwitterLinkedIn