Categorical Encoding

Most models take numbers, and a column holding “red”, “green”, “blue” is not one. Encoding is the translation, and which translation you pick changes what the model can learn.

  • One-hot โ€” one binary column per category. No ordering is implied, and the width grows with the number of categories.
  • Ordinal โ€” an integer per category. Correct when the categories really are ordered (low < medium < high), and an invented claim when they are not.
  • Target (mean) encoding โ€” replace the category with the average outcome for that category. Compact regardless of how many categories there are.
  • Frequency โ€” replace the category with how often it occurs. Cheap, and useful when rarity itself is informative.
  • Embeddings โ€” a learned dense vector per category, standard for identifiers with very many values.

The third one deserves more than a caveat. It is the usual answer to high cardinality, and it is the one that quietly breaks evaluations.

Target encoding manufactures signal

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import KFold, train_test_split

rng = np.random.default_rng(0)
n, levels = 20_000, 4_000
category = rng.integers(0, levels, size=n)
y = rng.integers(0, 2, size=n)
"""The category is assigned at random and so is the label. There is nothing to
   learn here: an honest AUROC is 0.5."""

xtr, xte, ytr, yte = train_test_split(category, y, test_size=0.3, random_state=0)
prior = ytr.mean()

def means(cats, labels):
    total = np.bincount(cats, weights=labels, minlength=levels)
    count = np.bincount(cats, minlength=levels)
    return np.where(count > 0, total / np.maximum(count, 1), labels.mean())

naive_table = means(xtr, ytr)
naive_train = naive_table[xtr]

oof_train = np.full(len(xtr), prior)
for fit, held in KFold(5, shuffle=True, random_state=0).split(xtr):
    oof_train[held] = means(xtr[fit], ytr[fit])[xtr[held]]

for name, encoded in (("encoded on all the training rows", naive_train), ("encoded out of fold", oof_train)):
    model = LogisticRegression(max_iter=1000).fit(encoded.reshape(-1, 1), ytr)
    on_train = roc_auc_score(ytr, model.predict_proba(encoded.reshape(-1, 1))[:, 1])
    on_test = roc_auc_score(yte, model.predict_proba(naive_table[xte].reshape(-1, 1))[:, 1])
    print(f"  {name:<33} AUROC on the training rows {on_train:.4f}   on held-out rows {on_test:.4f}")
print(f"\n  rows per category in training: {len(xtr) / levels:.2f}")
#   encoded on all the training rows  AUROC on the training rows 0.7950   on held-out rows 0.4881
#   encoded out of fold               AUROC on the training rows 0.5043   on held-out rows 0.5119
#
#   rows per category in training: 3.50

The category is random. The label is random. There is nothing in this data, and an honest AUROC is 0.5.

Encoding each category by its mean outcome over all the training rows produces a training AUROC of 0.7950. The encoded value of a row’s category was computed using that row’s own label, so the feature partly is the label. With 3.50 rows per category, each encoded value is essentially the average of three coin flips โ€” including the one you are about to predict.

On held-out rows it reads 0.4881, which is the truth. So the failure is not subtle in its effect; it is subtle in that everything looks fine until deployment, and the gap is largest exactly where target encoding is most tempting โ€” on columns with thousands of levels and few rows each.

Computing the encoding out of fold โ€” for each row, use only the other folds’ rows to build the mapping โ€” gives 0.5043 on the training rows. It reports no signal, because there is none. scikit-learn’s TargetEncoder does this internally when you call fit_transform on the training rows, which is the reason to prefer it to a hand-rolled group-by. Calling fit and then transform on those same rows does not cross-fit and reproduces the leak; new rows are encoded with transform, which applies the mapping learned from the full training set.

Two further defenses are standard. Smooth each category’s mean toward the overall mean in proportion to how few rows it has, so a category seen twice barely moves from the prior. And fit the encoder inside each cross-validation fold rather than once on the full training set โ€” the same rule that applies to every learned transformation, and the same leakage when it is broken.

Two API details that bite

  • OneHotEncoder(sparse=False) no longer works. The argument was renamed in scikit-learn 1.2 and removed in 1.4; it is sparse_output now, and the old form raises a TypeError. Tutorial code written before 2023 fails on contact.
  • LabelEncoder is for targets, not features. Its documentation says so directly โ€” it should encode \(y\), not \(X\). It accepts only one column and assigns integers in alphabetical order, which is an arbitrary ordering imposed on unordered data. OrdinalEncoder is the one for features, and it lets you state the order you mean.

Choosing between them

Choose the representation from the category structure, row count and learner. One-hot is a common choice for nominal categories; sparse storage can make far more than a few dozen levels practical, as categorical explosions illustrates. Ordinal encoding represents a meaningful order. With an arbitrary integer encoding, threshold trees can isolate categories through multiple splits, but their greedy choices and depth limits can still depend on the numbering.

Target and frequency encoding earn their place at high cardinality, target encoding with the discipline above. Embeddings are the answer when the identifiers are numerous, reappear often, and the model is already a network.

And whichever you choose, decide in advance what happens to a category that appears only at prediction time. One-hot can ignore it, target encoding can fall back to the overall mean, and hashing maps it to a bucket regardless โ€” but a pipeline with no answer will raise an exception in production.

This is one form of sensitivity in feature engineering: the representation can alter what a restricted model can learn.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.