Concept guide · Data and features
How do you encode categorical variables?
A slower explanation for when the short interview answer is not enough. Start with the intuition, then connect it to the technical idea and the way an interviewer expects you to reason about it.
ML area
Data and features → Core interview concept
Interview format
Core
Question
ML-014
Start with the idea
In simple terms
This question is asking you to explain How do you encode categorical variables in a way that connects the idea to a real machine-learning decision. Start with the role this concept plays, then explain what changes when the data, target, or deployment situation changes.
Build the answer
How to reason about it
- 1Define the concept before naming algorithms or implementation details.
- 2Connect it to the data, target, decision, or failure mode in the question.
- 3State the assumption or evaluation check that would make the explanation trustworthy.
Go one level deeper
The technical explanation
The choice depends on cardinality, ordering, model family, unknown categories, and serving constraints. One-hot encoding is a strong simple default for low-cardinality nominal features. Ordinal encoding is only appropriate when the order is meaningful. For high-cardinality features, hashing, learned embeddings, or carefully cross-fitted target encoding may be useful, but target-derived encodings must be fitted inside each training fold to avoid leakage. The safest way to understand this topic is to connect the definition to assumptions, data available at prediction time, the decision it supports, and how you would evaluate whether the result is useful.
Common mistake
Using integer IDs for nominal categories and accidentally telling the model that category 9 is larger than category 2.
Say this in the interview
The choice depends on cardinality, ordering, model family, unknown categories, and serving constraints. One-hot encoding is a strong simple default for low-cardinality nominal features. Ordinal encoding is only appropriate when the order is meaningful. For high-cardinality features, hashing, learned embeddings, or carefully cross-fitted target encoding may be useful, but target-derived encodings must be fitted inside each training fold to avoid leakage.
Keep preparing