Target encoding

Also known as: mean encoding

On this page 7

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 countRaw category meanSmoothed value
20.500.136
200.300.200
2000.300.282
2,0000.300.298
UnseenNot available0.100
Effect of smoothing on encoded values

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.

SchemeHow statistics are computedLeakage risk
Naive encodingAll training rows including the current oneHigh
Leave-one-outAll rows except the current oneModerate
Out-of-fold (k-fold)Rows from other folds onlyLow
Ordered statisticsRows preceding in a random permutationLow
Time-basedOnly rows earlier in timeLow for temporal data
Target encoding schemes and their leakage risk

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.

MethodOutput sizeUses targetBest suited for
One-hot encodingOne column per categoryNoFew categories, linear models
Label encodingOne integer columnNoTree models, ordinal data
Feature hashingFixed number of columnsNoHuge or streaming vocabularies
Frequency encodingOne count columnNoWhen popularity is predictive
Target encodingOne column per target classYesHigh-cardinality predictive features
Learned embeddingsDense vector per categoryIndirectlyNeural networks with large data
Comparison of categorical encoding methods

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.
SituationRecommended approachReason
Under 15 categoriesOne-hot encodingSimple and leakage-free
Thousands of categoriesSmoothed out-of-fold target encodingCompact and informative
Strong temporal orderTime-based expanding meanAvoids using future labels
Shifting category behaviorPeriodic refit with monitoringEncodings go stale under drift
Decision guide for target encoding

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.