Sub topic 14
When not to use one-hot encoding
This chapter assumes you can fit a scikit-learn Pipeline with a ColumnTransformer, and that you know how OneHotEncoder handles unseen categories. One-hot encoding is a good default for nominal features with few values, but it has costs. This chapter covers when to choose something else.
Where one-hot encoding fails
One-hot encoding adds one column per category. That causes three problems:
- High cardinality. A feature such as zip code or user ID can add thousands of columns. The result is a wide, sparse matrix that is slow to train on and easy to overfit.
- Lost order. If the categories are ordered, such as
small < medium < large, the indicator columns discard that information. - Tree models. Trees split on one column at a time. Spreading one feature over many indicators forces the tree to ask many yes/no questions to isolate a group of categories, and each indicator is individually weak.
Choosing an alternative
Ordinal encoding for ordered categories
For an ordinal feature, a single integer column keeps the order. Pass the order explicitly. Without it, OrdinalEncoder sorts the labels alphabetically, which gives large < medium < small.
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
df = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
enc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print(enc.fit_transform(df))The output is 0, 2, 1, 0 as a column of floats. A linear model now treats the gap between small and medium as equal to the gap between medium and large. If that assumption is wrong for your data, one-hot encoding may still be the better choice.
Native categorical support
Some models accept categories directly, so no encoding step is needed. HistGradientBoostingClassifier does this for columns with pandas category dtype. The example below needs scikit-learn 1.4 or later.
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
X = pd.DataFrame({
"city": pd.Categorical(["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome"] * 5),
"age": [25, 32, 47, 51, 38, 29] * 5,
})
y = [0, 1, 0, 1, 1, 0] * 5
model = HistGradientBoostingClassifier(categorical_features="from_dtype")
model.fit(X, y)
print(model.predict(X.head(3)))The model searches for good groupings of categories itself. This works best with high-cardinality columns, where one-hot encoding would be wide.
Target encoding
TargetEncoder (scikit-learn 1.3 or later) replaces each category with a smoothed average of the target for that category. It produces one column no matter how many categories exist.
Its main risk is leakage, because the encoding is computed from the labels. fit_transform therefore uses internal cross-fitting, so each row is encoded using statistics from other folds. Calling fit(X, y).transform(X) on the training data does not do this and gives over-optimistic features. Always put TargetEncoder inside a Pipeline, so cross-validation refits it on each training fold.
Comparison
| Approach | Columns added | Keeps order | Main risk |
|---|---|---|---|
| One-hot | One per category | No | Wide matrices with many categories |
| Ordinal | One | Yes | Implies equal spacing between levels |
| Native categorical | None | No | Only some models support it |
| Target encoding | One | No | Leakage if used outside a pipeline |
Exercise
A dataset has a product_id column with 40,000 distinct values and a rating column with values "poor", "fair", "good", "excellent". You are training a logistic regression. Which encoding would you consider for each column, and what must you do for rating?
Show answer
For rating, use OrdinalEncoder with categories=[["poor", "fair", "good", "excellent"]], so the integers follow the real order. For product_id, one-hot encoding would add about 40,000 columns. Consider TargetEncoder inside a Pipeline to avoid leakage, or group rare IDs with min_frequency before one-hot encoding.