A categorical feature such as a ZIP code can have thousands of levels, far too many to one-hot encode. Target encoding replaces each level with a smoothed average of the target, and computes the training values out of fold so a row never sees its own label.
Implement target_encode(train_cats, y, m, folds=None, test_cats=None).
train_cats: list of hashable category values; y: list of numeric targets.m: smoothing strength .folds: optional list of fold ids.test_cats: optional list of categories to encode for new data.Given a set of reference rows with prior mean (the mean of their targets), a category with reference rows and target sum is encoded as
A category with gets .
folds is None, the reference rows are all training rows. Otherwise row is encoded using only the rows whose fold id differs from folds[i] (both the category statistics and come from those rows). If folds has fewer than 2 distinct ids, raise ValueError.Return {"train": [...], "test": [...]} with values rounded to 4 decimals ("test" is [] when test_cats is None).