TExcelTAD

Target Encoding Inside Folds

A column like store_id with 3,000 stores, or product with 50,000 products, carries real signal: some stores sell more, some products are returned more often. One-hot would need thousands of sparse columns, and frequency or hashing throw the category's own effect away. Target encoding replaces each category with a single number: the average target of that category's training rows. It is compact and powerful, and it is the encoder most likely to leak, because it is computed from the label. This lesson shows the formula, the leak, and the fix: fitting it inside folds only.

The idea and the smoothing formula

For a binary or numeric target yy, let ncn_c be the number of training rows of category cc, yˉc\bar{y}_c their mean target and yˉ\bar{y} the global mean. The raw encoding yˉc\bar{y}_c is unreliable for small ncn_c: a store with one sale that happened to be returned would get a return rate of 1. Smoothing pulls small categories towards the global mean:

enc(c)=nc yˉc+m yˉnc+m\text{enc}(c) = \frac{n_c \, \bar{y}_c + m \, \bar{y}}{n_c + m}

The smoothing strength mm acts like mm imaginary rows at the global mean. With nc≫mn_c \gg m the encoding is close to yˉc\bar{y}_c; with nc=0n_c = 0 (an unseen category) it is exactly yˉ\bar{y}. This is a shrinkage estimate, the same idea as a Bayesian prior (see MAP and regularisation). scikit-learn's TargetEncoder(smooth="auto") picks the strength per category from the variance of the target inside the category versus overall (an empirical Bayes estimate); smooth=m with a number uses the formula above.

The leak

Encode the training rows with means that include their own label, and every row carries a piece of its answer. For a category with 2 rows, the encoding is half made of the row's own label. A flexible model learns "high encoding means positive" and looks brilliant on training data and in any cross-validation that reuses those encodings, then collapses on new data. The problem is worst for high-cardinality, ID-like columns, where most categories have few rows.

The example below has no signal at all: the label is a coin flip, and customer_id has 400 values with about 3 rows each.

python · try it yourself
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(0)
n = 1200
cust = rng.integers(0, 400, n)          # ID-like, about 3 rows per customer
y = rng.integers(0, 2, n)               # pure noise: nothing to learn

def mean_encode(train_c, train_y, apply_c, m=1.0):
    g = train_y.mean()
    sums = np.bincount(train_c, weights=train_y, minlength=400)
    cnts = np.bincount(train_c, minlength=400)
    return ((sums + m * g) / (cnts + m))[apply_c]

# Naive: encode with ALL rows (including each row's own label), then cross-validate.
X_naive = mean_encode(cust, y, cust).reshape(-1, 1)
model = RandomForestClassifier(n_estimators=100, min_samples_leaf=5, random_state=0)
print("naive 5-fold CV accuracy:", round(cross_val_score(model, X_naive, y, cv=5).mean(), 3))

# New data from the same source: fresh labels for the same customers.
cust_new = rng.integers(0, 400, 2000)
y_new = rng.integers(0, 2, 2000)
model.fit(X_naive, y)
X_new = mean_encode(cust, y, cust_new).reshape(-1, 1)
print("accuracy on new data:   ", round(model.score(X_new, y_new), 3))
naive 5-fold CV accuracy: 0.695
accuracy on new data:    0.495

The cross-validated accuracy is 0.695 on a coin flip, and on new data the same model scores 0.495, chance. Cross-validation did not protect us, because the encodings were computed before the split: the held-out rows' labels were already baked into the feature.

The fix from scratch: out-of-fold encodings

The rule is the same as for every fitted transformer: the encoding a row receives must be computed without that row's label. For the training data, split it into KK folds, and encode each fold with means computed on the other K−1K - 1 folds ("cross fitting"). For validation, test and production data, use means computed on the whole training set.

python · try it yourself
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold, cross_val_score

rng = np.random.default_rng(0)
n = 1200
cust = rng.integers(0, 400, n)
y = rng.integers(0, 2, n)

def mean_encode(train_c, train_y, apply_c, m=1.0):
    g = train_y.mean()
    sums = np.bincount(train_c, weights=train_y, minlength=400)
    cnts = np.bincount(train_c, minlength=400)
    return ((sums + m * g) / (cnts + m))[apply_c]

def out_of_fold(c, y, k=5):
    enc = np.empty(len(c))
    for fit_idx, enc_idx in KFold(k, shuffle=True, random_state=0).split(c):
        enc[enc_idx] = mean_encode(c[fit_idx], y[fit_idx], c[enc_idx])
    return enc

X_oof = out_of_fold(cust, y).reshape(-1, 1)
model = RandomForestClassifier(n_estimators=100, min_samples_leaf=5, random_state=0)
print("out-of-fold 5-fold CV accuracy:", round(cross_val_score(model, X_oof, y, cv=5).mean(), 3))
naive = mean_encode(cust, y, cust)
for name, enc in [("naive", naive), ("out-of-fold", X_oof[:, 0])]:
    print(f"{name:12s} mean encoding: label-1 rows {enc[y == 1].mean():.3f}, label-0 rows {enc[y == 0].mean():.3f}")
out-of-fold 5-fold CV accuracy: 0.526
naive        mean encoding: label-1 rows 0.625, label-0 rows 0.396
out-of-fold  mean encoding: label-1 rows 0.510, label-0 rows 0.515

With out-of-fold encodings, cross-validation now reports 0.526, close to the 0.5 that pure noise deserves. The last two lines show why: with naive encodings, rows labelled 1 have a mean encoding of 0.625 and rows labelled 0 only 0.396, a gap made entirely of the rows' own labels. Out of fold the gap disappears (0.510 against 0.515).

Note: strictly, the outer cross-validation should also recompute the out-of-fold encoding inside each of its training folds. That is exactly what putting the encoder in a pipeline does, next.

The library version: TargetEncoder in a pipeline

scikit-learn 1.3+ ships TargetEncoder, which does the cross fitting for you. Its fit_transform(X, y) returns out-of-fold encodings for the training rows (internal cv=5), while transform(X) uses the full-training means for new data. Inside a Pipeline, cross_val_score calls fit_transform on each training fold and transform on the held-out fold, so nothing leaks. Here it is on data that does have signal: the return rate truly depends on the product.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.preprocessing import TargetEncoder, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(1)
n, k = 3000, 300
product = rng.integers(0, k, n)
true_rate = rng.beta(1, 4, k)                      # each product has its own return rate
y = (rng.random(n) < true_rate[product]).astype(int)
X = pd.DataFrame({"product": product.astype(str)})

te = make_pipeline(TargetEncoder(target_type="binary", random_state=0), LogisticRegression())
oh = make_pipeline(OneHotEncoder(handle_unknown="ignore"), LogisticRegression())
for name, pipe in [("target encoding", te), ("one-hot", oh)]:
    auc = cross_val_score(pipe, X, y, cv=5, scoring="roc_auc").mean()
    print(f"{name:16s} 5-fold ROC AUC: {auc:.3f}")

enc = TargetEncoder(target_type="binary", random_state=0)
train_codes = enc.fit_transform(X, y)              # out-of-fold for training rows
full_codes = enc.transform(X)                      # full-data means: only for NEW rows
print("columns: 1 vs", X["product"].nunique())
print("row 0, fit_transform:", round(float(train_codes[0, 0]), 3), " transform:", round(float(full_codes[0, 0]), 3))
target encoding  5-fold ROC AUC: 0.655
one-hot          5-fold ROC AUC: 0.663
columns: 1 vs 300
row 0, fit_transform: 0.095  transform: 0.087

With one column instead of 300, target encoding reaches a ROC AUC of 0.655, about the same as one-hot's 0.663 (on 3,000 rows a linear model on one-hot columns is also fine; target encoding pays off when the categories number in the tens of thousands or when the model is a tree ensemble). For row 0, fit_transform gives 0.095 and transform 0.087: the first excludes the row's own fold, the second does not.

The last line shows the trap that remains even with the library: enc.fit(X, y).transform(X) on the training rows gives the leaky full-data encodings. Always use fit_transform on training data, which pipelines do automatically.

Multiclass and regression targets

For a numeric target, the encoding is the smoothed mean of yy (target_type="continuous"). For KK classes, TargetEncoder produces KK columns per feature, one smoothed class share P(y=j∣c)P(y = j \mid c) each. The leak and the cure are the same.

Pitfalls

  • Encoding before splitting or before cross-validation: the scores are inflated, most on ID-like columns. Fit inside folds.
  • fit(...).transform(...) on training data: the library's cross fitting only happens in fit_transform.
  • No smoothing: categories with one or two rows get extreme encodings; keep smooth="auto" or a sensible mm.
  • Time order ignored: for temporal data, encode with past rows only (an expanding mean), otherwise the encoding contains the future.
  • Using it on a true identifier: if a column identifies the row (a ticket number), no encoding makes it a feature.

Practice

  1. A category has nc=4n_c = 4 rows with mean target 1.0; the global mean is 0.2 and m=4m = 4. What is the smoothed encoding? And for nc=400n_c = 400 with the same mean?
Answer

4⋅1.0+4⋅0.24+4=4.88=0.6\frac{4 \cdot 1.0 + 4 \cdot 0.2}{4 + 4} = \frac{4.8}{8} = 0.6. With nc=400n_c = 400: 400+0.8404≈0.992\frac{400 + 0.8}{404} \approx 0.992. Small categories are pulled strongly towards the global mean, large ones hardly at all.

  1. A teammate computes df["city_te"] = df.groupby("city")["churn"].transform("mean") on the whole table, then runs GridSearchCV. What is wrong, and how do you fix it?
Answer

Every row's encoding includes its own label and the labels of the validation folds, so the grid search optimises an inflated score. Remove the column, put TargetEncoder() for city into a ColumnTransformer inside the pipeline, and grid-search the pipeline.

Test yourself

Why does naive target encoding leak?

  1. It uses too many columns
  2. Each training row's encoding is computed from a mean that includes its own label
  3. It ignores the global mean
  4. It only works for regression

In the formula (ncyˉc+myˉ)/(nc+m)(n_c \bar{y}_c + m \bar{y}) / (n_c + m), what does an unseen category (nc=0n_c = 0) get?

  1. 0
  2. 1
  3. The global mean yˉ\bar{y}
  4. An error

With scikit-learn's TargetEncoder, which call gives cross-fitted (out-of-fold) encodings for the training rows?

  1. fit(X, y) then transform(X)
  2. fit_transform(X, y)
  3. transform(X) alone
  4. get_feature_names_out()

On which kind of column is the target-encoding leak worst?

  1. Binary columns
  2. Columns with a few large categories
  3. High-cardinality, ID-like columns with few rows per category
  4. Numeric columns