Skip to content

Encoding categories for models

Choose among one-hot, ordinal, frequency, target, weight-of-evidence and hash encoding, and avoid the leak in target encoding.

Applied ~11 min8 steps

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

01

Models need numbers

Read

Most models accept only numbers. Encoding is how a category becomes one, and each method tells the model something different.

Step in PrepareReplaces a category withFits
One-hot encodea 0/1 column per levelfew unordered levels
Ordinal encode1, 2, 3 in the order you giveordered levels
Frequency encodeits count or sharemany levels, when commonness matters
Target encodea smoothed mean of the targetmany levels, in supervised models
Weight-of-evidence encodea log ratio of event sharesyes/no targets, credit-style models
Hash encodeone of N fixed bucketshuge vocabularies, new values welcome
02

What does a code imply?

Predict

Predict first

You code cities alphabetically: Austin = 1, Boston = 2, Chicago = 3, and fit a linear model. What does the model assume about the cities?

Nothing, codes are labelsBoston sits between Austin and ChicagoChicago counts three times as much as Austin
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.

03

Cardinality decides a lot

Reflect

One-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?

04

The target encoding trap

Read

Target 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.

05

See the leak

Explore

Target 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?

How sure?

The pipeline

200
60
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

In code

Read
Python
import pandas as pd

df = pd.DataFrame({"plan": ["basic", "pro", "basic", "enterprise"]})
encoded = pd.get_dummies(df, columns=["plan"])
print(encoded.columns.tolist())
R
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.

07

Check your understanding

Checkpoint

Check 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.

08

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