Target Encoding and Advanced Categorical Handling
Target encoding, frequency encoding, binary encoding, embeddings for high-cardinality columns.
Target Encoding and Advanced Categorical Handling is a free Learn AI with Python lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Categorical Encoding Problem
Models need numbers, but categories are text. One-hot encoding works for few categories, but high-cardinality features (thousands of cities, products) create too many columns.
Limits of One-Hot and Label Encoding
One-hot explodes dimensionality. Plain label encoding invents a false ordering (city 5 is not greater than city 2). For high-cardinality data we need smarter encodings.
What Is Target Encoding
Target encoding replaces each category with the mean of the target for that category. A city becomes the average churn rate of customers in that city, a single informative number.
import pandas as pd
means = df.groupby("city")["target"].mean()
df["city_encoded"] = df["city"].map(means)The Overfitting Danger
Rare categories with few rows get extreme means that leak the target and overfit. A category seen once would copy that single label exactly. We fix this with smoothing.
Smoothing the Estimate
Smoothing blends the category mean with the global mean, weighted by how many samples the category has. Rare categories lean toward the global average, reducing variance.
import pandas as pd
global_mean = df["target"].mean()
agg = df.groupby("city")["target"].agg(["mean", "count"])
smoothing = 10
agg["enc"] = (agg["count"] * agg["mean"] + smoothing * global_mean) / (agg["count"] + smoothing)
df["city_enc"] = df["city"].map(agg["enc"])The category_encoders Library
The category_encoders package implements these encoders with a scikit-learn API, so they slot into pipelines and apply consistently to train and test sets.
import category_encoders as ce
encoder = ce.TargetEncoder(cols=["city", "product"], smoothing=10)
X_enc = encoder.fit_transform(X_train, y_train)
X_test_enc = encoder.transform(X_test)Avoiding Leakage in Practice
Always fit the encoder on training data only, then transform validation/test. Better still, use cross-validation or out-of-fold encoding so each row is encoded by data that excludes it.
import category_encoders as ce
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(
ce.TargetEncoder(cols=["city"]),
LogisticRegression(),
)
# fit inside CV to encode without leakageBinary Encoding
BinaryEncoder converts categories to binary digits, using only log2(N) columns instead of N. It is a compact middle ground between one-hot and target encoding.
import category_encoders as ce
encoder = ce.BinaryEncoder(cols=["product_id"])
X_enc = encoder.fit_transform(X_train)
# 256 categories -> 8 binary columnsOther Useful Encoders
category_encoders also offers CountEncoder (frequency of each category), LeaveOneOutEncoder (target mean excluding the current row), and CatBoostEncoder (ordered target stats).
import category_encoders as ce
count_enc = ce.CountEncoder(cols=["city"])
loo_enc = ce.LeaveOneOutEncoder(cols=["city"])Handling High Cardinality
For very high cardinality: target/count encoding compresses to one column, binary encoding stays compact, and grouping rare categories into an "other" bucket reduces noise. Pick based on cardinality and leakage risk.
import pandas as pd
freq = df["product"].value_counts()
rare = freq[freq < 20].index
df["product"] = df["product"].replace(rare, "other")Choosing an Encoder
Few categories: one-hot. Tree models with many categories: target or CatBoost encoding. Need compactness: binary. Always guard against leakage by fitting on train only and using smoothing or out-of-fold schemes.
Quick Check
Test your categorical encoding knowledge.
Recap
Recap: Target encoding replaces a category with its target mean, using smoothing to tame rare categories. Use category_encoders (TargetEncoder, BinaryEncoder, CatBoost/LeaveOneOut) and fit on train only or out-of-fold to avoid leakage. Compact encoders handle high-cardinality features one-hot cannot.
Frequently asked questions
Is the “Target Encoding and Advanced Categorical Handling” lesson free?
Yes — the full text of “Target Encoding and Advanced Categorical Handling” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.
What will I learn in “Target Encoding and Advanced Categorical Handling”?
Target encoding, frequency encoding, binary encoding, embeddings for high-cardinality columns. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn AI with Python?
No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Target Encoding and Advanced Categorical Handling” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn AI with Python lesson?
Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Feature Selection Methods
- Creating Interaction and Polynomial Features
- Target Encoding and Advanced Categorical Handling
- Automated Feature Engineering with Featuretools