Stop 06 · Data Preparation & Feature EngineeringTopics · 5/10

Target Encoding & High-Cardinality Features

Part of the Machine Learning Roadmap

In short

India has around 19,000 pincodes. One-hot encode them and your table grows 19,000 columns wide, mostly zeros. Target encoding squeezes each category into one useful number, as long as you do it carefully.

When a categorical column has thousands of values, like pincodes or product IDs, one-hot encoding becomes huge. Target encoding replaces each category with a smoothed average of the target, but it must be computed out-of-fold to avoid leaking the answer.

The jaadu stands at a wall of hundreds of small numbered pigeonhole slots in a courier office, sticking a coloured dot on each slot.

Think of it like this

The courier's area reputation

A courier manager doesn't memorise every street. He remembers each area's track record: 'parcels to this pincode get returned 30% of the time'. That track record is target encoding. But for an area he has delivered to only twice, he leans on the city-wide average instead of trusting two parcels. That caution is smoothing.

Watch it happen

Return rate by pincode, smoothed towards the overall 10%

400001: 200 orders
0
560034: 50 orders
1
110001: 2 orders
2
700019: 0 seen
3

1/5Overall return rate is 10%. We use smoothing strength m = 10 (like 10 imaginary average orders).

The big ideas

What you need to know

High cardinality

Columns like pincode, product_id or merchant name have thousands of values. One-hot encoding explodes, label encoding invents a fake order.

Replace with the target mean

Each category becomes the average label for that category: return rate, default rate or mean price.

Smooth rare categories

Blend each category's mean with the global mean, weighted by how many rows it has, so tiny groups don't get extreme values.

Encode out-of-fold

If a row's own label goes into its encoding, the model sees the answer. Compute training encodings with cross-fitting on other folds.

See it in code

Walk through the code

python
1import pandas as pd2from sklearn.preprocessing import TargetEncoder3from sklearn.model_selection import train_test_split4 5df = pd.read_csv("orders.csv", dtype={"pincode": str, "product_id": str})6X = df[["pincode", "product_id"]]7y = df["returned"]                       # 1 if the order came back8 9X_train, X_test, y_train, y_test = train_test_split(10    X, y, test_size=0.2, random_state=0, stratify=y11)12 13enc = TargetEncoder(smooth="auto", cv=5, random_state=0)14X_train_enc = enc.fit_transform(X_train, y_train)   # out-of-fold values15X_test_enc = enc.transform(X_test)                  # uses the full training fit16 17print(X_train.nunique())     # thousands of categories...18print(X_train_enc.shape)     # ...now just 2 numeric columns

1/4Two high-cardinality text columns and a binary label.

scikit-learn's TargetEncoder (version 1.3 and later) smooths and cross-fits for you.

Save yourself the pain

Common mistakes

Oops

Computing category means on the full dataset, then splitting.

Do this instead

That leaks test labels into training. Split first, then encode inside cross-validation or with TargetEncoder.

Oops

Calling enc.fit(X_train, y_train) and then enc.transform(X_train).

Do this instead

Use fit_transform on training data. Only fit_transform does the out-of-fold cross-fitting.

Oops

Target encoding a column with only 5 categories.

Do this instead

Plain one-hot encoding is simpler and safer for low-cardinality columns.

Your mission

One-hot vs target encoding

~30 min

Quick check

Why does target encoding need smoothing?

Go deeper

  1. 1Try scikit-learn's TargetEncoder, which uses cross-fitting internally, on a high-cardinality column.
  2. 2Compare it with frequency encoding and grouping rare categories into 'other'.
  3. 3Check validation scores to make sure target encoding is not leaking.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge