How do you encode categorical features? Compare one-hot, target encoding, and embeddings.
Written by the mlprep team · Updated
You have a categorical feature with high cardinality — say, 10,000 unique zip codes. How do you encode it? Walk me through the trade-offs of different approaches.
One-hot encoding#
Convert each category to a binary vector with a single 1. For 10,000 zip codes: 10,000 binary columns.
Problems at high cardinality:
- Memory: 10k sparse columns, though most models use sparse matrices
- Dimensionality: many columns with very few 1s — lots of noise features
- Unseen categories: a zip code at inference time that wasn't in training has no representation
- No ordinal information: doesn't capture that nearby zip codes share characteristics
Best for: low cardinality (under ~50 categories), tree models where it works fine, linear models where you need explicit feature control.
Label / ordinal encoding#
Map each category to an integer (0 to n-1). Compact, handles high cardinality. But it imposes a false ordering — "Chicago" = 5 > "Atlanta" = 2 is meaningless.
Works for: tree models (XGBoost, LightGBM), which split on thresholds and aren't misled by arbitrary orderings. Never for linear models or distance-based methods.
Target encoding (mean encoding)#
Replace each category with the mean target value for that category:
encoding(zip) = mean(target | zip)
Example: if users in zip code 94103 convert at 8%, encode that zip as 0.08.
Why it's powerful: captures the relationship between category and target directly. Works for high cardinality. Keeps dimensionality at 1.
The leakage problem: if you compute the target mean on the full training set and use it as a feature, you've leaked label information. The model sees the answer encoded in the feature.
Solution: out-of-fold encoding. Compute each row's encoding using only the other folds, not its own data. Equivalent to k-fold for encoding.
Add smoothing for rare categories:
encoding = (n_c * mean_c + m * global_mean) / (n_c + m)
where n_c = count in category, m = smoothing parameter. Rare zip codes blend toward the global mean rather than overfitting to 2 examples.
Learned embeddings#
Map each category to a dense low-dimensional vector (e.g., 10,000 zip codes → 32-dimensional embeddings) trained end-to-end with the model.
Advantages:
- Learned representations capture semantic similarity (nearby zip codes learn similar embeddings)
- Handles high cardinality without explosion in dimensions
- Natural in neural network architectures (categorical inputs as
nn.Embedding) - Can initialize from pretrained embeddings (entity2vec, etc.)
Disadvantages: requires enough data per category to learn a good embedding. Sparse categories underfit.
For new categories at inference: use the global mean embedding or a dedicated "UNKNOWN" embedding trained explicitly.
Practical decision tree#
| Cardinality | Model type | Encoding | |-------------|-----------|---------| | < 20 | Any | One-hot | | 20 – 5k | Tree | Label or target (OOF) | | 20 – 5k | Linear/NN | Target (OOF) or embedding | | > 5k | Tree | Target (OOF) with smoothing | | > 5k | NN | Learned embedding |
Hashing trick#
For very high cardinality or streaming: hash each category into m buckets. Collisions trade accuracy for fixed memory. Used in production recommendation systems, feature hashing in vowpal wabbit.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Low cardinality → one-hot. High cardinality + tree models → target encoding with out-of-fold to prevent leakage + smoothing for rare categories. High cardinality + neural nets → learned embeddings (nn.Embedding). Label encoding works for trees but never linear/distance-based models. Hashing trick for streaming/very high cardinality. Always handle unseen categories at inference (UNKNOWN bucket or global mean).
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you implement out-of-fold target encoding correctly in a sklearn pipeline without leakage?
- Your model is deployed. A new product category appears in production that wasn't in training. How do you handle it?
- How do entity embeddings (like those used in FastAI's tabular model) compare to standard target encoding on structured data?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Walk me through feature engineering for tabular data
When do feature crosses matter, and how do you control their complexity?
How do you handle missing data without introducing bias?
How would you design a feature store for a large ML platform?