Target encoding, also called mean encoding, is a machine learning technique that replaces each category of a categorical feature with a statistic of the target variable computed for that category, most often the smoothed mean target value. It turns text labels such as city, product code or merchant into informative numbers that models can use directly.
Target encoding is especially valuable for high-cardinality features with hundreds or millions of distinct values, where one-hot encoding would create an impractically wide and sparse matrix. Its power comes with a serious risk: because it uses the target, a careless implementation causes data leakage and overly optimistic validation scores.
How target encoding computes category values
Target encoding maps each category to an estimate of the expected target given that category. For binary classification, the value is the observed positive rate in the category; for regression, it is the mean target; for multi-class problems, one encoded column is created per class with the class probability for each category.
Raw category means are unreliable for rare categories. A category seen twice with one positive outcome would receive 0.5, which is mostly noise. Smoothing solves this by blending the category mean with the global mean according to how many observations support the category. A common formula is: encoded value = (n × category mean + m × global mean) / (n + m), where n is the category count and m is a smoothing strength chosen by validation.
With this formula, a category with thousands of rows keeps almost its own mean, while a category with a handful of rows is pulled strongly toward the prior. Unseen categories at prediction time simply receive the global mean. The table below shows the effect with a global positive rate of 0.10 and m equal to 20.
| Category count | Raw category mean | Smoothed value |
|---|---|---|
| 2 | 0.50 | 0.136 |
| 20 | 0.30 | 0.200 |
| 200 | 0.30 | 0.282 |
| 2,000 | 0.30 | 0.298 |
| Unseen | Not available | 0.100 |
Preventing leakage with out-of-fold encoding
The defining risk of target encoding is target leakage: if a row’s own target contributes to its encoded value, the model learns a shortcut that does not exist at prediction time. Rare categories suffer most, because their encoded value is almost the row’s own label.
The standard remedy is out-of-fold encoding. The training data is split into k folds, typically five to ten, and each fold is encoded using statistics computed only from the other folds. The final model is trained on these encodings, while the test set and production data are encoded with statistics from the full training set.
Other schemes serve the same goal. Leave-one-out encoding excludes only the current row, which can still leak through the row count. Ordered target statistics, used by CatBoost, process rows in a random order and encode each row using only the preceding rows, mimicking an online setting. For time series, encodings must use only past data to respect causality.
| Scheme | How statistics are computed | Leakage risk |
|---|---|---|
| Naive encoding | All training rows including the current one | High |
| Leave-one-out | All rows except the current one | Moderate |
| Out-of-fold (k-fold) | Rows from other folds only | Low |
| Ordered statistics | Rows preceding in a random permutation | Low |
| Time-based | Only rows earlier in time | Low for temporal data |
Target encoding compared with other categorical encodings
Target encoding is one of several ways to represent categorical variables, and it is the only common method that injects target information directly into the feature. That makes it the most informative and also the most dangerous option.
| Method | Output size | Uses target | Best suited for |
|---|---|---|---|
| One-hot encoding | One column per category | No | Few categories, linear models |
| Label encoding | One integer column | No | Tree models, ordinal data |
| Feature hashing | Fixed number of columns | No | Huge or streaming vocabularies |
| Frequency encoding | One count column | No | When popularity is predictive |
| Target encoding | One column per target class | Yes | High-cardinality predictive features |
| Learned embeddings | Dense vector per category | Indirectly | Neural networks with large data |
In practice, target encoding pairs well with gradient boosting and other tree ensembles, which can split on the encoded value efficiently. Linear models also benefit, since the encoded column has a roughly monotonic relationship with the target by construction.
Practical guidelines for using target encoding
Target encoding works best as part of a reproducible preprocessing pipeline that is fitted inside cross-validation, never on the full dataset before splitting. Libraries such as scikit-learn provide a TargetEncoder with built-in cross-fitting, which reduces the chance of manual mistakes.
- Tune the smoothing strength as a hyperparameter instead of fixing it arbitrarily.
- Add Gaussian noise to training encodings only when out-of-fold schemes are not available.
- Keep a frequency feature alongside the encoding so the model knows how reliable each value is.
- Encode interactions such as city and product jointly only when there is enough data per pair.
- Store the fitted mapping and global mean so production scoring uses identical statistics.
| Situation | Recommended approach | Reason |
|---|---|---|
| Under 15 categories | One-hot encoding | Simple and leakage-free |
| Thousands of categories | Smoothed out-of-fold target encoding | Compact and informative |
| Strong temporal order | Time-based expanding mean | Avoids using future labels |
| Shifting category behavior | Periodic refit with monitoring | Encodings go stale under drift |
Limitations and common mistakes
The most common mistake is fitting the encoder before cross-validation, which produces impressive validation scores that collapse in production. A second mistake is applying no smoothing, so that rare categories dominate tree splits with noisy values.
Target encoding also compresses a category into one number, which discards information about the variance of outcomes inside the category. When the relationship between category and target changes over time, a form of concept drift, stale encodings silently degrade accuracy. Finally, encoding sensitive attributes such as postal codes can act as a proxy for protected characteristics, so fairness reviews should include encoded features.
Explained without jargon
Computers work with numbers, not names. Target encoding gives each name a useful number. The number is the average outcome seen for that name in past data. If customers from one city bought often, that city gets a high number.
There is a catch. A city with only two customers tells little, so its number is pulled toward the overall average. The model must also never peek at the answer it is trying to predict. Otherwise it looks clever in testing but fails on new data.
A typical use case
An online retailer builds a model that predicts whether an order will be returned. The data contains a merchant identifier with 40,000 distinct values, and the overall return rate is 8 percent. One-hot encoding would add 40,000 sparse columns, so the data science team applies five-fold out-of-fold target encoding with a smoothing strength of 50.
Large merchants keep encodings close to their real return rates, while a new merchant with three orders receives a value near the 8 percent global rate. A gradient boosting model trained with the encoded feature improves validation AUC from 0.71 to 0.76, and the gain holds on the next month of production orders. The outcome is that the warehouse can flag high-risk orders for extra quality checks before shipment.