Fold-safe target encoding
Quick answer
Target encoding replaces a category with a statistic of training targets associated with that category. For a regression task, this can be a smoothed category mean. Because it uses labels, the training representation must avoid giving each row access to its own outcome.
Smoothed category mean
total, count, mean, alpha = 6, 2, 4, 2print((total + alpha*mean)/(count+alpha))Expected output:
3.5Two pseudo-observations at the global mean shrink the raw mean of 3 toward 4.
How it works
For category c, a simple smoothing formula is (sum_c + alpha*global_mean)/(count_c + alpha), alpha >= 0. For unseen categories use the training global mean. With small category counts, smoothing shrinks estimates toward that mean; it does not remove self-label leakage. For training rows, split into inner folds, fit on the other folds, and encode the held-out fold. Then fit a final encoder on the entire outer training set for inference on outer validation or test. In scikit-learn 1.8 TargetEncoder.fit_transform uses internal cross-fitting, while fit followed by transform on the same training rows does not. Specify target_type and smoothing intentionally. Random inner folds are inappropriate for some grouped or temporal problems: use a splitter compatible with entity or time boundaries, verify actual library support or implement a manual past-only encoder. The outer evaluation must never participate in encoder fitting. Store category policy, target availability, smoothing and training cutoff; high cardinality still warrants comparison against one-hot or simpler models.
Unique categories and cross-fitting
from sklearn.preprocessing import TargetEncoderX = [['a'],['b'],['c'],['d']]y = [1.,3.,5.,7.]e = TargetEncoder(target_type='continuous', smooth=0., cv=2, shuffle=False)print(e.fit_transform(X,y).ravel().tolist())print(e.transform([['unknown']]).ravel().tolist())Expected output:
[6.0, 6.0, 2.0, 2.0][4.0]Each held-out category is unseen in its inner training fold, so it receives that fold mean; inference fallback is the full training mean.
Common mistakes
Encoding a unique ID using its own target can create a nearly perfect training representation with no generalization. Do not call fit_transform on the full dataset before cross-validation; inner cross-fitting cannot protect an outer validation boundary that has already been crossed.
Practice
For category A with sum 6 and count 2, global mean 4 and alpha 2, calculate the smoothed value. Then encode a held-out A using only the other fold and explain why its own target is excluded. Complete the chapter exercise and knowledge check. Scientific examples are local scikit-learn 1.8.0 static snippets; ByteMind execution support is not verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fold-safe target encoding — knowledge check
Apply feature engineering and leakage controls to synthetic scenarios.
What data may encode a held-out training row during cross-fitting?
What is the smoothed value when sum=6,count=2,global mean=4,alpha=2?
What does an unseen category receive in the demonstrated encoder?
Why is smoothing insufficient to prevent leakage?
Which split is appropriate for repeated entities?