Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 102/ 160
06. Feature Engineering & Model Evaluation

Categorical Encoding (One-Hot, Ordinal, Target)

Encode categories safely with one-hot, ordinal maps, and careful target encoding.

BeginnerOne-Hot · Ordinal3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Encoding turns words like city names into numbers a model can use, and each way of doing it has different strengths and risks.

Think of it like…

Labelling shelves in a warehouse: separate bins for each product (one-hot) are clear but need lots of space; numbering shelves by size works only if size is meaningful (ordinal); writing each product's average sales on its bin (target encoding) is compact but dangerous if you peek at the sales you're trying to predict.

Where you’ve seen it

A churn model has plan (3 levels), size (S/M/L/XL) and zip_code (30,000 levels). plan is one-hot encoded (3 columns, drop one level for a linear model's intercept), size is ordinal with explicit order [S, M, L, XL], and zip_code would explode to 30,000 columns, so the team uses smoothed target encoding computed with 5-fold out-of-fold statistics: encoding = (n × category mean + m × global mean) / (n + m) with m = 10 and a global churn rate of 0.20. A ZIP with 3 customers who all churned (mean 1.0) gets (3 × 1.0 + 10 × 0.2) / 13 = 0.385, not 1.0; a ZIP with 300 customers and mean 0.35 gets (300 × 0.35 + 10 × 0.2) / 310 = 0.345, barely shrunk. Naive full-data target encoding scored AUC 0.91 in validation but 0.76 on new data because each row's own label influenced its encoding; out-of-fold encoding gives an honest 0.78. Rare ZIPs under 20 rows are grouped into "other", and OneHotEncoder(handle_unknown="ignore") guards against unseen plans at prediction time.

Words you’ll hear

One-hot encoding
Binary indicator column per category.
Ordinal encoding
Integer codes preserving an order.
Target encoding
Replacing categories by a smoothed target statistic.
Out-of-fold encoding
Computing the target statistic for each row from other folds only.

Visual diagram

Loading interactive diagram

Theory & deep dive

One-hot, ordinal and frequency encoding

One-hot (OneHotEncoder) is the safe default for nominal categories and linear or neural models: it adds no artificial ordering. For linear models with an intercept, drop one column (drop="first") to avoid perfect collinearity (the dummy-variable trap). Its weakness is width: a feature with 30,000 levels yields 30,000 sparse columns, high memory and slow, overfit-prone models. Mitigate by grouping rare categories (min_frequency=20, handle_unknown="infrequent_if_exist"), using sparse matrices or choosing another encoding. Always set handling for unseen categories at prediction time (handle_unknown="ignore" produces all zeros).

Ordinal encoding (OrdinalEncoder with explicit categories=[["S", "M", "L", "XL"]]) is appropriate when order is meaningful (education level, size, rating), or for tree-based models that can split an integer code at any threshold regardless of order (though the arbitrary order can still hurt efficiency). Using ordinal codes for nominal categories in linear models imposes false distances. Frequency or count encoding replaces each category by how often it appears, which is leak-free and compact, but categories with equal counts become indistinguishable. Binary encoding (log₂(k) columns) and hashing (fixed number of buckets, collisions allowed) handle high cardinality with controlled width, at the cost of interpretability.

Width of each encoding

ZIP with 30,000 levels: one-hot = 30,000 columns; binary = ⌈log₂ 30,000⌉ = 15 columns; hashing to 1,024 buckets = 1,024 columns with collisions; target or frequency encoding = 1 column.

Key takeaway: Use one-hot for nominal features of modest cardinality, ordinal only when order is real and group rare levels or compress when cardinality is high.

Target encoding without leakage

Target encoding replaces a category by the mean target for that category. It's powerful for high-cardinality features (it can capture ZIP-level churn in one column) but dangerous: a row's own label is part of its category mean, so the model learns a shortcut and validation scores inflate. Two safeguards are essential. Smoothing shrinks small categories toward the global mean: encoding = (n × category mean + m × global mean) / (n + m). With m = 10 and a global rate of 0.20, a category with 3 rows all positive becomes (3 + 2) / 13 = 0.385 instead of 1.0, and a category with 300 rows and mean 0.35 becomes 0.345. Out-of-fold (cross-fitted) encoding computes each row's value from the other folds only, so a row never sees its own label; at prediction time use encodings fitted on all training data.

Implement with sklearn.preprocessing.TargetEncoder (v1.3+, which cross-fits internally during fit_transform), category_encoders, or CatBoost's ordered target statistics. Put the encoder inside the pipeline and cross-validation loop; encoding before splitting is leakage, and in the example it produced AUC 0.91 in validation versus 0.76 on new data. Handle unseen categories by falling back to the global mean, and for regression or multiclass targets use the corresponding statistics. Add noise or regularisation if the model still overfits, and monitor drift: category-target relationships change over time. Remember target encoding creates a feature derived from the label, so evaluation must be strictly out-of-sample.

Smoothing arithmetic

m = 10, global mean 0.20. n = 3, mean 1.0 → (3×1.0 + 10×0.2)/13 = 5/13 = 0.385. n = 300, mean 0.35 → (105 + 2)/310 = 0.345. Small groups are pulled strongly to 0.20, large ones stay near their own mean.

Key takeaway: Smooth small categories and cross-fit encodings inside the pipeline; otherwise validation scores are inflated.

How it works, step by step

Step 1 of 4
Analyst

1. Classify categorical features

Label each as nominal or ordinal and note cardinality, rare levels and whether unseen values can appear.

plan 3 · size ordered · zip 30,000
Key numbers at this step
Group
rare levels < 20 rows

When to use it & trade-offs

What it is

Models need numbers, so categorical encoding converts categories into numeric features. One-hot encoding creates one binary column per category (no false order, but wide for high-cardinality features). Ordinal encoding maps categories to integers and is correct only when there's a real order (small < medium < large) or when using tree models that can split on arbitrary integer codes. Target encoding replaces a category with a (smoothed) statistic of the target for that category, which compresses high-cardinality features into one column but leaks the label unless it's computed out-of-fold. Other options include frequency encoding, hashing and binary encoding, and native categorical support in CatBoost and LightGBM.

Why it matters: The encoding choice affects model accuracy, memory and, above all, leakage. One-hot encoding a 30,000-level ZIP code creates 30,000 columns; ordinal encoding "red, green, blue" as 0, 1, 2 tells a linear model that blue is twice green; naive target encoding gives a rare category with 3 positive rows a perfect predictive value that is pure noise. Understanding each method's bias, size and leakage risks lets you choose safely.

When to reach for it

  • Preparing categorical features for linear, neural and tree models
  • High-cardinality IDs such as ZIP, product or merchant
  • Production pipelines with unseen categories

When to avoid or be careful

  • Ordinal codes for nominal variables in linear models
  • Target encoding before the train-test split
  • One-hot encoding 30,000 levels without grouping

Encoding methods

One-hot
Best for: Nominal features with modest cardinality

Strengths: No false order; works with any model.

Watch out: Wide for high cardinality.

Ordinal
Best for: Truly ordered categories and tree models

Strengths: One compact column.

Watch out: Imposes distances in linear models.

Target (out-of-fold, smoothed)
Best for: High-cardinality categories with signal

Strengths: Compact and powerful.

Watch out: Leakage risk; needs careful validation.

Interview signals & numbers to know

When this topic comes up

  • “zip code has thousands of values”
  • Dummy variable trap
  • Target encoding leakage
  • Unseen categories in production
  • Hashing trick

Benchmarks & rules of thumb

(n·mean + m·global)/(n + m) -
smoothed target encoding
0.385 vs 0.345 -
encodings for a 3-row and a 300-row category
30,000 → 15 -
columns for one-hot versus binary encoding

Common mistakes & follow-ups

Common interview mistakes

  • Encoding categories on the whole dataset before cross-validation.
  • Forgetting to handle categories that appear only at prediction time.
  • Using category order from alphabetical sorting.

Likely interviewer follow-ups

  • When would you use ordinal versus one-hot encoding?
  • How does target encoding leak and how do you prevent it?
  • How do you handle a feature with 50,000 categories?
Interview tip: Show the smoothing arithmetic (0.385 versus 1.0). It proves you can prevent noisy rare categories from fooling the model.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Categorical Encoding (One-Hot, Ordinal, Target) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Missing Value Imputation Strategies
Next topic
Feature Scaling (StandardScaler, MinMax, Robust)