Encoding categories for models
Choose among one-hot, ordinal, frequency, target, weight-of-evidence and hash encoding, and avoid the leak in target encoding.
You will be able to
- Choose an encoding from a category's order and cardinality
- Explain why ordinal codes mislead for unordered categories
- Explain how target encoding leaks, and how to prevent it
Read first
Models need numbers
ReadMost models accept only numbers. Encoding is how a category becomes one, and each method tells the model something different.
| Step in Prepare | Replaces a category with | Fits |
|---|---|---|
| One-hot encode | a 0/1 column per level | few unordered levels |
| Ordinal encode | 1, 2, 3 in the order you give | ordered levels |
| Frequency encode | its count or share | many levels, when commonness matters |
| Target encode | a smoothed mean of the target | many levels, in supervised models |
| Weight-of-evidence encode | a log ratio of event shares | yes/no targets, credit-style models |
| Hash encode | one of N fixed buckets | huge vocabularies, new values welcome |
What does a code imply?
PredictPredict first
You code cities alphabetically: Austin = 1, Boston = 2, Chicago = 3, and fit a linear model. What does the model assume about the cities?
Reveal
The answer: Boston sits between Austin and Chicago
It assumes they sit in that order, equally spaced, with the outcome changing steadily along the line. For cities that is nonsense. One-hot encoding avoids it by giving each city its own coefficient.
Cardinality decides a lot
ReflectOne-hot encoding adds one column per level, so a zip-code column with thousands of levels adds thousands of columns. Trees and linear models then spend most of their effort on levels seen a handful of times.
Options: Group rare categories first, or use frequency, target or hash encoding.
Look at a high-cardinality column of your own. Which levels carry enough rows to learn anything?
The target encoding trap
ReadTarget encoding replaces each category with the mean outcome for that category. Fit on all rows, it lets each row's own outcome leak into its own feature.
A level seen once becomes a perfect copy of that row's outcome, and the model looks excellent until it meets new data.
Two guards help: Cross-fit in Target encode encodes each row from the other folds only, and an Assign split step lets the recipe learn from training rows only.
See the leak
ExploreTarget encoding on all rows leaks the same way as picking features on all rows. Choose that pipeline and compare cross-validated accuracy with accuracy on new data, then choose the one that learns inside each fold.
DExplorable · Leakage detective
Why does a model that scores brilliantly in testing fail on real data?
Read the pipeline on the left. Will its cross-validation score overstate real-world accuracy by more than 6 points?
The pipeline
Commit your prediction above to see the result
Make your prediction to see the result.
In code
Readimport pandas as pd
df = pd.DataFrame({"plan": ["basic", "pro", "basic", "enterprise"]})
encoded = pd.get_dummies(df, columns=["plan"])
print(encoded.columns.tolist())df <- data.frame(plan = c("basic", "pro", "basic", "enterprise"))
encoded <- model.matrix(~ plan - 1, df)
colnames(encoded)Dropping one level as a baseline is standard for linear models with an intercept, because the columns would otherwise add up to the intercept.
Check your understanding
CheckpointCheck yourself
Which column is the best fit for Ordinal encode?
Show the answer
Answer: a
Satisfaction has a real order. Country has none, and email identifies a person, so it shouldn't be a feature at all.
Check yourself
A clean plan column has the levels basic, pro and enterprise. How many 0/1 columns does one-hot encoding create if it keeps every level?
Show the answer
Answer: 3
One per level.
Check yourself
A model with a target-encoded customer_id scores nearly perfectly in validation. What is the most likely explanation?
Show the answer
Answer: b
An identifier has as many levels as rows, so its target encoding nearly equals the target. Treat any near-perfect score as a bug until shown otherwise.
Recap
Recap- An encoding tells the model what a category means: order, identity, frequency or outcome.
- Use ordinal codes only for categories with a real order.
- Target encoding must be learned on training rows, with rare levels smoothed.
Concepts in this lesson