Sub topic 13
Rare categories and high-cardinality features
This chapter assumes you can use OneHotEncoder inside a ColumnTransformer, and that you know why the encoder is fitted on training data only. Here we look at what happens when a column has many distinct values, and how to keep the number of columns under control.
Why many categories cause trouble
One-hot encoding creates one column per category. A column such as country has about 200 values, which is manageable. A column such as zip_code or user_id can have tens of thousands. This is called a high-cardinality feature, meaning a feature with a very large number of distinct values.
Two problems follow:
- The feature matrix becomes very wide, which costs memory and training time.
- Many categories appear only once or twice. A model cannot learn a reliable pattern from so few rows, so those columns mostly add noise and invite overfitting.
Grouping infrequent categories
OneHotEncoder can merge rare categories into one shared column. You control this with min_frequency or max_categories.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
X = np.array([["a"], ["a"], ["a"], ["b"], ["b"], ["c"], ["d"]])
enc = OneHotEncoder(
min_frequency=2,
handle_unknown="infrequent_if_exist",
sparse_output=False,
)
print(enc.fit_transform(X))
print(enc.get_feature_names_out())Categories c and d each appear once, which is fewer than two times. They share one column named x0_infrequent_sklearn. The output has three columns: x0_a, x0_b and x0_infrequent_sklearn.
The two options work differently:
| Option | Meaning | Example |
|---|---|---|
| `min_frequency=2` | Categories seen fewer than 2 times are infrequent. | Integer: a count. |
| `min_frequency=0.05` | Categories seen in under 5% of rows are infrequent. | Float: a fraction. |
| `max_categories=10` | Keep at most 10 output columns, including the infrequent one. | The most frequent categories survive. |
You can set both. The encoder applies each rule and groups whatever either one marks as infrequent.
Unknown values and the infrequent column
The setting handle_unknown="infrequent_if_exist" sends categories unseen during fit to the infrequent column, if one exists. If no infrequent column was created, they become all zeros, like handle_unknown="ignore". This is useful because new rare values at prediction time are, in effect, rare categories too.
Choosing a threshold
There is no universal cutoff. Use these guidelines:
- Start with a fraction such as
min_frequency=0.01so the rule scales with dataset size. - Use
max_categorieswhen you need a hard upper limit on width. - Treat the threshold as a hyperparameter. Compare cross-validation scores for a few values.
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
prep = ColumnTransformer([
("cat", OneHotEncoder(
min_frequency=0.01,
handle_unknown="infrequent_if_exist",
), ["city"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression())])You can then pass prep__cat__min_frequency to GridSearchCV to tune the value.
Sparse output helps with width
Wide one-hot matrices are mostly zeros. The default sparse output stores only the non-zero entries, so a 50,000-column matrix stays practical. Keep sparse_output=True (the default) for high-cardinality data, and use sparse_output=False only for small demonstrations.
When grouping is not enough
Grouping reduces width, but a feature with thousands of common categories stays wide. Then consider other encodings, covered in the next chapter's neighbors in the plan: target encoding, hashing, or letting a model such as gradient boosting handle categories natively.
Exercise
A column has 40,000 distinct values, and most appear fewer than 5 times. Which OneHotEncoder settings reduce the width and still accept new, unseen values at prediction time?
Show answer
Set min_frequency=5 (or a small fraction) so rare values merge into one infrequent column, and set handle_unknown="infrequent_if_exist" so unseen values go to that column instead of raising an error. Keep the output sparse.