Encoding categorical variables

Turn categories into numbers a model can use, without inventing order or leaking the target.

Lesson 14 of 6610 minBeginner

You will learn to

  • Choose an encoding by cardinality and model type
  • Avoid target-encoding leakage
  • Handle categories that were not seen in training

Before this lesson

Intuition

Most models do arithmetic, so they need numbers. A column with values such as "Lima", "Madrid" and "Quito" has to be turned into numbers first. How you do it decides what the model believes about the categories.

The main danger is inventing structure. If you code Lima = 0, Madrid = 1, Quito = 2, a linear model reads "Quito is twice Madrid" and "Madrid is between the other two". For cities that is nonsense. The main alternatives are:

  • One-hot: one new 0/1 column per category. No fake order; many columns when there are many categories.
  • Ordinal: one integer per category. Compact, and right when the categories really have an order (small, medium, large). Tree models tolerate it well for unordered categories too.
  • Frequency: replace each category by how often it appears. One column; categories with the same frequency become indistinguishable.
  • Binary: write the integer code in binary and keep one column per bit. About log2 of the number of categories in columns; the bits have no meaning.
  • Target: replace each category by a (smoothed) average of the target for that category. One column, often strong, but it uses the label, so it can leak.

Picture it

CityOne-hot (3 columns)OrdinalFrequencyLima10000.3Madrid01010.6Quito00120.1
A City column with three categories (Lima on 3 rows, Madrid on 6, Quito on 1, out of 10) under three encodings.

One-hot spends three columns and invents nothing. Ordinal spends one column and invents an order. Frequency spends one column and says that Madrid is common and Quito is rare, which may or may not be useful.

The math

For a categorical column with CC categories, one-hot creates CC columns, binary encoding creates ⌈log⁡2C⌉\lceil \log_2 C \rceil, and the others create one. With 100 cities, that is 100 columns versus 7.

Smoothed target encoding. For category cc with ncn_c training rows and target mean yˉc\bar{y}_c, and an overall target mean yˉ\bar{y}:

enc(c)=nc yˉc+m yˉnc+m\text{enc}(c) = \frac{n_c\,\bar{y}_c + m\,\bar{y}}{n_c + m}

where mm is the smoothing strength. A category with many rows (nc≫mn_c \gg m) keeps its own mean. A category with few rows is pulled towards the overall mean yˉ\bar{y}, because a mean of one or two rows is unreliable.

Unseen categories. A new category appears at prediction time that training never saw. Each encoding must say what to do. One-hot can set all columns to 0; ordinal can use a reserved code such as -1; frequency can use 0; target encoding can use the overall mean yˉ\bar{y}.

Worked example

Suppose the overall share of positives is yˉ=0.30\bar{y} = 0.30 and the smoothing is m=10m = 10.

  • Common category: 200 rows, target mean 0.25. Encoded value: (200 x 0.25 + 10 x 0.30) / 210 = 53 / 210 = 0.252. Barely changed.
  • Rare category: 2 rows, both positive (mean 1.0). Encoded value: (2 x 1 + 3) / 12 = 0.417. Pulled strongly towards 0.30, because two rows are weak evidence. Without smoothing it would be 1.0, which would look like a certain win.

Now see the leak. A column holds a near-unique identifier, so each category has one row. If you fit target encoding on those same rows, a positive row has nc=1n_c = 1 and mean 1, so with m=10m = 10 it becomes (1 + 3) / 11 = 0.364, while a negative row becomes 3 / 11 = 0.273. Even smoothed, the encoded value now separates the classes perfectly: it is the label in disguise. A model trained on it will look brilliant on the training rows and fail on new ones. The remedy is to fit the encoding on the training rows of each fold, and score the other rows with it. Better still, do not target-encode near-unique columns at all.

Choosing, in short: low cardinality and no order, use one-hot; a true order, ordinal; very many categories, frequency or binary, or target encoding inside the folds; and a tree-based model forgives most choices.

How mlflow does it

In Pipeline Studio, the Turn categories into numbers group of the Choose... list on a category column has One-hot, Number the categories, Label encoding, How common it is, Average result per category (setting smoothing, default 10) and Binary code. A category column that no step encodes does not stop a run: the engine ordinal-encodes it automatically, and unseen or missing categories map to -1, so choose an encoding yourself when the order of those codes would mislead the model.

  • One-hot ignores unseen categories (all zeros for that column). Ordinal and Label encoding give unseen categories the code -1. Frequency encoding gives them 0. Target encoding gives them the overall target mean.
  • Order of codes. Ordinal and Label encoding number the categories in sorted (alphabetical) order, not in the order they appear. If your categories have a real order, such as small, medium, large, rename them or add a column so that the codes follow it.
  • Recommendations. For categorical columns with at most 10 distinct values the recommender suggests One-hot; above 20 distinct values it suggests How common it is. The suggestion shows as Suggested: in the column row, with Apply. Columns in between get no suggestion.
  • No leakage. Steps are fitted on the training rows of each fold. Target encoding also needs the target, which a time series forecasting pipeline does not have, so that step is not available for exogenous columns there.

Common mistakes

  • Ordinal codes on unordered categories with a linear model. The model reads the codes as quantities. Use one-hot, or accept the risk with trees.
  • One-hot on a column with thousands of values. It creates a very wide, sparse table, slows training and invites overfitting. Use frequency, binary or target encoding.
  • Target encoding without smoothing or without folds. Both let the label leak into the feature. Keep the smoothing, and let the pipeline fit it per fold.
  • Encoding the target itself with a feature encoder. The target is encoded by the task (classes become labels); do not add an encoding step for it.
  • Forgetting new categories. Production data will contain values you never saw. Check what each encoding does with them, and monitor for them.
  • Encoding identifiers. An ID column usually carries no pattern; drop it instead of encoding it.

Try it in mlflow

Add an encoding step

  1. Open Pipelines and pick a pipeline whose dataset has a text or category column.
  2. In the Columns part, find the category column, press Choose... and, under Turn categories into numbers, pick One-hot. Press the new chip to see Before and after.
  3. Choose the categorical columns in the step settings and train.
  4. Try Frequency Encoding on a column with many categories and compare.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A City column has 3 values: Lima, Madrid, Quito. Why is coding them 0, 1, 2 risky for a linear model?
  2. 2. A column has 5,000 distinct values among 20,000 rows. Which encoding avoids creating thousands of columns?
  3. 3. Why must a target encoding be fitted on training rows only, inside each fold?