Categorical Encoding Explained: Label, One-Hot, Ordinal & Target Encoding
How to turn text categories ('NYC', 'London', 'Tokyo') into numbers without creating fake ordering, feature explosions, or target leakage
Categorical Encoding converts text or discrete category columns (like city, color, or subscription tier) into numeric representations that mathematical ML models can compute on.
ML equations only multiply and add numbers—you cannot multiply a weight by 'Tokyo'—and naïve numbering (NYC=1, London=2, Tokyo=3) tricks linear models into thinking Tokyo is 3× larger than NYC.
Almost every business table is half categorical (country, merchant_id, device_type) — how you encode them makes or breaks tabular accuracy.
Production models crash daily when a brand-new category (e.g., a new iPhone model) arrives at inference time without handle_unknown='ignore'.
Encoding a 50,000-level zip_code column with One-Hot creates 50,000 sparse columns and kills training speed; Target or Frequency encoding solves it cleanly.
Favorite interview question: 'How would you encode a categorical feature with 10,000 unique values for Logistic Regression vs. LightGBM?'
You have a city column with 5 unique cities and you are training Logistic Regression. Which encoding is best?
- Choose between One-Hot Encoding (nominal, low cardinality), Ordinal Encoding (ordered categories), and Target/Frequency Encoding (high cardinality).
- Explain why Label Encoding (
Red=0, Green=1, Blue=2) breaks Linear Regression and KNN, yet works reasonably in tree models. - Avoid the Dummy Variable Trap (
drop_first=Truefor unregularized linear models) and Target Encoding leakage (out-of-fold smoothing). - Handle unseen categories gracefully at inference time (
handle_unknown='ignore').
Every categorical encoding choice boils down to two questions: (1) Do the categories have a natural order? (if yes → Ordinal Encoding), and (2) How many unique values exist? (if small like → One-Hot Encoding; if huge like → Out-of-Fold Smoothed Target Encoding, Frequency Encoding, or Embeddings).
1. The 4 Essential Encoders Compared
Imagine encoding T-shirt sizes (S, M, L) versus favorite colors (Red, Green, Blue) versus 50,000 product SKUs. One size does NOT fit all!
| Encoder | Best For | Pros | Watch Out For |
|---|---|---|---|
Ordinal (S=0, M=1, L=2) | Ordered categories | Compact (1 column), preserves rank | Never use on unordered categories for linear models |
One-Hot ([1,0,0]) | Unordered, low () | Zero fake ordering; great for Linear/KNN/NN | Column explosion when is huge; Dummy Variable Trap |
Frequency (count(c)/N) | High cardinality () | Fast, 1 column, zero target leakage | Collisions if two categories have identical counts |
| Target (Smoothed) | High cardinality + strong signal | Compresses 10,000 levels into 1 rich feature | Must be computed out-of-fold with smoothing to avoid leakage! |
2. The Dummy Variable Trap & Unseen Categories
If a pet column only has Cat and Dog, and you already know is_cat = 0, you 100% know is_dog = 1 — that redundant column causes perfect multicollinearity!
- Dummy Variable Trap: In unregularized OLS Linear Regression, One-Hot columns sum to (identical to the intercept column!), making non-invertible. Fix: drop 1 reference column (
drop='first') for unregularized linear models, or use Ridge/Lasso/Trees. - Unseen Production Categories: Always configure
OneHotEncoder(handle_unknown="ignore")so a brand-new category in production maps cleanly to all zeros instead of crashing your API.
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Linear Regression computes , so encoding Tokyo=3 literally multiplies the weight by 3. A Decision Tree can isolate city == 2 using two threshold splits (city > 1.5 and city <= 2.5), though One-Hot or native CatBoost/LightGBM splits are still cleaner.
Activate All 5 Pillars of a Ship-Ready ML Project
handle_unknown='ignore') for low-cardinality nominal features, and Out-of-Fold Smoothed Target/Frequency Encoding for high-cardinality columns.import numpy as np
# 1. One-Hot Encoding with safe unseen-category handling
categories = ["NYC", "London", "Tokyo"]
cat_to_idx = {c: i for i, c in enumerate(categories)}
def one_hot_encode(values: list[str]) -> np.ndarray:
mat = np.zeros((len(values), len(categories)), dtype=float)
for row, val in enumerate(values):
if val in cat_to_idx: # unseen categories safely stay all-zeros
mat[row, cat_to_idx[val]] = 1.0
return mat
# 2. Smoothed Target Encoding (prevents overfitting on rare categories)
def smoothed_target_encode(cats: list[str], y: np.ndarray, m: float = 5.0) -> dict[str, float]:
global_mean = float(y.mean())
encoding = {}
for c in set(cats):
mask = np.array([x == c for x in cats])
n_c = mask.sum()
encoding[c] = float((n_c * y[mask].mean() + m * global_mean) / (n_c + m))
return encoding
print("One-Hot (with unseen 'Paris'):\n", one_hot_encode(["NYC", "Tokyo", "Paris"]))
print("Smoothed Target Encoding:", smoothed_target_encode(["A", "A", "A", "B"], np.array([1, 1, 0, 1]), m=5.0))
user_id or zip_code column with 50,000 unique levels.country column with 4 countries and you are training KNN. Why is Label Encoding (0, 1, 2, 3) a bad idea?