Sub topic 13
Rare categories and high-cardinality features
One-hot encoding creates one column per category. That is fine for a column like color with three values. It becomes a problem for a column like zip_code or user_id with thousands of values. This chapter covers what goes wrong with many categories and how to limit the damage inside scikit-learn.
It assumes you can already use OneHotEncoder, know why it is fitted on training data only, and have seen handle_unknown="ignore". It also assumes you know what a ColumnTransformer does.
Two related problems
Cardinality is the number of distinct values in a column. Two separate problems come from it, and they call for different fixes.
- High cardinality means a column has many distinct values. The feature matrix gets wide, memory use grows, and training slows down.
- Rare categories are values that occur in only a few rows. A column for a category seen twice gives the model almost nothing to learn from. The model can still fit those two rows exactly, which is overfitting.
A column can have one problem without the other. A column with 5,000 categories that each appear 20 times is high-cardinality but not rare. A column with 6 categories, one of them seen in a single row, has a rare category but is not high-cardinality.
What high cardinality costs
Suppose a column has 5,000 distinct ids and the data has 100,000 rows. A dense one-hot matrix would hold 500 million cells. At 8 bytes per float, that is about 4 GB for one column. Almost every cell is zero, because each row has exactly one 1.
OneHotEncoder returns a sparse matrix by default, which stores only the nonzero entries.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
rng = np.random.default_rng(0)
ids = rng.integers(0, 5000, size=100_000).astype(str).reshape(-1, 1)
enc = OneHotEncoder(handle_unknown="ignore")
X = enc.fit_transform(ids)
print(type(X).__name__)
print(X.shape)
print(X.nnz)The output is csr_matrix, a shape of about (100000, 5000), and nnz equal to 100000. There is one stored value per row, so memory use is proportional to the number of rows, not rows times columns.
Sparse output solves the memory problem but not the modeling problem. Many linear models and some tree implementations accept sparse input. Others convert it to dense internally, and you lose the savings. Check the documentation of the estimator you plan to use.
Grouping infrequent categories
OneHotEncoder can merge rare categories into one shared column. Two parameters control this.
| Parameter | Meaning |
|---|---|
| `min_frequency` | An integer is a minimum count. A float between 0 and 1 is a minimum fraction of the training rows. Categories below it are grouped. |
| `max_categories` | The maximum number of output columns per feature, counting the infrequent group. The most frequent categories are kept and the rest are grouped. |
Here is the min_frequency example. The categories c and d each appear fewer than two times.
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())The result has three columns: x0_a, x0_b and x0_infrequent_sklearn. The rows for c and d both have a 1 in the last column.
With max_categories you set a column budget instead of a threshold. The next example keeps at most three columns for the city feature.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
cities = ["a"] * 5 + ["b"] * 3 + ["c"] * 2 + ["d"]
df = pd.DataFrame({"city": cities})
enc = OneHotEncoder(max_categories=3, sparse_output=False)
out = enc.fit_transform(df)
print(enc.get_feature_names_out())
print(out.shape)The budget of three covers two kept categories plus one infrequent column. So a and b stay, and c and d are merged into city_infrequent_sklearn. The output shape is (11, 3).
If you set both parameters, a category is grouped when either rule applies.
Choosing a threshold
There is no universal value. These rules of thumb work as a starting point.
- Use a count threshold (such as 10 or 20 rows) when the data size is fixed and you want a clear rule.
- Use a fraction (such as
0.01) when the data grows over time and you want the rule to scale. - Use
max_categorieswhen the column budget is the real constraint, for example a downstream model with a width limit. - Treat the threshold as a hyperparameter. Tune it with cross-validation, as you would any other setting.
Rare categories at prediction time
Grouping interacts with handle_unknown, and the combinations behave differently.
| `handle_unknown` | Category seen in training but rare | Category never seen in training |
|---|---|---|
| `"error"` | Goes to the infrequent column | Raises an error |
| `"ignore"` | Goes to the infrequent column | All zeros |
| `"infrequent_if_exist"` | Goes to the infrequent column | Goes to the infrequent column, or all zeros if no infrequent column exists |
"infrequent_if_exist" is usually the best choice when you group rare values. A brand-new category is statistically similar to a rare one, so it makes sense to treat them the same way. The model has seen the infrequent column during training, so its weight for that column carries over.
The counts used to decide what is "infrequent" come from the data passed to fit. This is the same rule you saw for leakage. If you compute frequencies on the full dataset before splitting, test-set information shapes your features. Fit the encoder on the training split, or put it in a Pipeline so cross-validation refits it on each fold.
Using grouping in a pipeline
Put the grouping options on the encoder inside the ColumnTransformer. Nothing else in the pipeline changes.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = pd.DataFrame({
"city": ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome",
"Paris", "Berlin", "Oslo", "Paris"],
"age": [25, 32, 47, 51, 38, 29, 41, 36, 44, 30],
})
y = [0, 1, 0, 1, 1, 0, 0, 1, 1, 0]
preprocess = ColumnTransformer([
("cat", OneHotEncoder(min_frequency=2,
handle_unknown="infrequent_if_exist"), ["city"]),
("num", StandardScaler(), ["age"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)
new = pd.DataFrame({"city": ["Madrid"], "age": [33]})
print(model.predict(new))
print(model.named_steps["prep"].get_feature_names_out())Oslo appears once, so it is grouped. Madrid was never seen, and it also lands in the infrequent column. The feature names show cat__city_infrequent_sklearn alongside the kept cities.
When grouping is not enough
Grouping reduces width, but it throws information away. If a column such as user_id has 50,000 values that each occur a handful of times, grouping leaves you with a few columns and little signal. Other encodings may fit better.
- Target encoding replaces each category with a statistic of the target, such as its mean. scikit-learn provides
TargetEncoderfrom version 1.3. It uses cross-fitting insidefit_transformto limit leakage, sofit_transform(X, y)gives different values thanfit(X, y).transform(X). Use it inside a pipeline. - Hashing maps categories into a fixed number of columns with a hash function. Width is fixed in advance, but different categories can collide in the same column.
- Ordinal encoding uses one integer column. It suits tree-based models, which can split on the integer, but it is risky for linear models for the reasons covered earlier in the tutorial.
The final chapter of this part compares these options in more detail.
Common mistakes
- Computing frequencies on all the data. Counting category frequencies before the train/test split leaks test information. Fit the encoder on training data only.
- Using
handle_unknown="error"with grouping and expecting new values to be grouped. Only"infrequent_if_exist"sends unseen categories to the infrequent column. - Forcing dense output.
sparse_output=Falseon a wide column wastes memory. - Setting
max_categoriestoo low. The count includes the infrequent column, somax_categories=3keeps only two named categories. - Reading feature names as original categories. A column named
infrequent_sklearnstands for several categories. Do not interpret its weight as the effect of one value.
Exercise
A training column store has 400 distinct values. A new store appears in the test data. You want the encoder to group stores with fewer than 25 training rows, and to send the new store to that same group instead of raising an error or producing all zeros. Which OneHotEncoder arguments do you use, and why does it matter that the frequencies come from the training split only?
Show answer
Use OneHotEncoder(min_frequency=25, handle_unknown="infrequent_if_exist"), and keep the default sparse output. min_frequency=25 groups every store with fewer than 25 training rows into one infrequent_sklearn column. handle_unknown="infrequent_if_exist" sends the unseen store to that column, which the model already learned a weight for. The counts must come from the training split because counting on the full dataset lets test rows decide which categories are kept. That leaks test information into the features and makes validation scores look better than they will be in practice. Putting the encoder in a Pipeline means each cross-validation fold recomputes the counts on its own training part.