Sub topic 8
Handling categories not seen in training
This chapter assumes you can fit and transform with scikit-learn's OneHotEncoder, and that you know why an encoder is fitted on training data only. Here you will see what happens when new data contains a category the encoder never saw. You will also learn how to choose the behavior that fits your project.
Why unseen categories happen
An encoder learns its list of categories during fit. After that, the list is frozen. The number of output columns is fixed, and the trained model expects exactly that many inputs.
Unseen categories show up in ordinary work:
- A new product, city, or browser version appears after the model is deployed.
- A rare category lands only in the test split, or only in one cross-validation fold.
- A typo or a different spelling reaches the model, such as
"Paris "with a trailing space.
You cannot add a column for the new value at prediction time. The model has no weight for it. The encoder has to do something else, and its handle_unknown parameter decides what.
The default: fail loudly
The default is handle_unknown="error". The encoder raises a ValueError the first time it meets a value it did not learn.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
enc = OneHotEncoder(sparse_output=False)
enc.fit(train)
try:
enc.transform(test)
except ValueError as err:
print("Transform failed:", err)The error message names the unknown value and the column position. Failing is a reasonable default for batch jobs where a new category means the data pipeline has changed. In that case you want a human to look.
For a live prediction service, one new city should not take down every request. That is where the other options come in.
handle_unknown="ignore": an all-zeros row
With handle_unknown="ignore", an unknown value is encoded as zeros in every column of that feature.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
enc.fit(train)
print(enc.categories_[0])
encoded = enc.transform(test)
print(encoded)
print(enc.inverse_transform(encoded))The categories are blue, green, red. green becomes [0, 1, 0]. purple becomes [0, 0, 0]. Calling inverse_transform on the second row returns None, because no category matches an all-zeros row.
Read the all-zeros row as "none of the known categories". For a linear model, the feature then contributes only the intercept and the other features. For a tree model, every split on a color column goes the "not this color" way. The prediction is not meaningless, but it is not informed about the new value either.
A silent behavior to know about
Because ignore never raises, a broken upstream process can feed your model all-zeros rows indefinitely. Nothing will tell you. If you use ignore in production, count the unseen values yourself. You can compare against categories_:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
new_data = pd.DataFrame({"color": ["green", "purple", "teal"]})
enc = OneHotEncoder(handle_unknown="ignore").fit(train)
known = set(enc.categories_[0])
unseen = set(new_data["color"]) - known
share = new_data["color"].isin(unseen).mean()
print("Unseen values:", sorted(unseen))
print(f"Share of rows affected: {share:.0%}")Log that share, or alert when it passes a threshold. A rising share tells you the model needs retraining.
The interaction with drop
Chapter material on the drop option showed that drop="first" removes one column per feature. Combine that with handle_unknown="ignore" and a problem appears. The dropped category is itself represented by all zeros. An unknown category is also all zeros. The model cannot tell them apart, so unknown values are treated exactly like the dropped category.
That may be acceptable for a regularized model, where redundancy was not a problem to begin with. For an unregularized linear model, think about it before combining the two. If you need the model to distinguish "unknown" from a specific category, either keep all columns or send unknowns to an explicit infrequent bucket (next section).
handle_unknown="infrequent_if_exist": an explicit bucket
Zeros are an implicit answer. A better one is often to say "this is some category we have not seen often." Scikit-learn supports that by grouping rare categories into one column. With handle_unknown="infrequent_if_exist", unknown values go into that same column.
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,
)
enc.fit(X)
print(enc.get_feature_names_out())
print(enc.transform(np.array([["a"], ["c"], ["z"]])))The categories c and d appear fewer than two times, so they merge into a column named x0_infrequent_sklearn. The output has three columns: x0_a, x0_b, and x0_infrequent_sklearn. The row for a is [1, 0, 0]. The rows for c and the never-seen z are both [0, 0, 1].
This option has a useful side effect. The model learns a weight for the infrequent column during training, from real examples of rare categories. When a new category arrives, it receives that learned weight. Compare that with the all-zeros row, which gets no category-specific signal.
The fallback matters: if the feature has no infrequent categories after fitting, there is no infrequent column. Unknown values then become all zeros, as with ignore. If you want the bucket guaranteed to exist, set min_frequency or max_categories so that some grouping actually happens on your training data.
Choosing a strategy
| Setting | Unknown value becomes | Raises an error | Best for |
|---|---|---|---|
| `handle_unknown="error"` | Not allowed | Yes | Batch jobs where new values signal a data problem |
| `handle_unknown="ignore"` | All zeros for that feature | No | Services that must keep running, with monitoring |
| `handle_unknown="infrequent_if_exist"` | The infrequent column if one exists, otherwise all zeros | No | Features with a long tail of rare values |
The pandas get_dummies trap
pd.get_dummies has no memory. It builds columns from whatever values are in the DataFrame you give it. Apply it to the training and test sets separately, and the two outputs can have different columns.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
train_enc = pd.get_dummies(train, columns=["color"], dtype=int)
test_enc = pd.get_dummies(test, columns=["color"], dtype=int)
print(list(train_enc.columns))
print(list(test_enc.columns))
aligned = test_enc.reindex(columns=train_enc.columns, fill_value=0)
print(aligned)The training columns are color_blue, color_green, color_red. The test columns are color_green, color_purple. Feeding the second set to a model trained on the first fails or, worse, silently puts values in the wrong positions when the column counts happen to match.
reindex with fill_value=0 repairs this. It keeps the training columns, adds missing ones as zeros, and drops color_purple. That behavior matches handle_unknown="ignore". But you must remember to do it at every call site, and you must save the training column list. This is why OneHotEncoder inside a pipeline is the safer choice for anything beyond exploration.
Unseen categories inside a pipeline
Put the option on the encoder, and the whole pipeline inherits it. The model below was trained without Madrid, and it still predicts.
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"],
"age": [25, 32, 47, 51, 38, 29],
})
y = [0, 1, 0, 1, 1, 0]
preprocess = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
("num", StandardScaler(), ["age"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)
new = pd.DataFrame({"city": ["Madrid", "Paris"], "age": [40, 30]})
print(model.predict(new))
print(model.predict_proba(new).shape)Without handle_unknown="ignore", the call to predict would raise the ValueError from earlier. Note that the scaler is unaffected: only the categorical branch has this issue.
Common mistakes
- Using
ignoreduring development and never checking it. Evaluation scores look fine while the model quietly sees zero rows. Count unseen values on your validation data. - Expecting
inverse_transformto recover the original value. For unknown categories it returnsNone. - Cross-validating with the default error setting on rare categories. A category that appears once can land entirely in a validation fold, and the fold fails. Set
ignoreorinfrequent_if_existon the encoder inside the pipeline. - Assuming that
infrequent_if_existalways creates a bucket. It does so only when some training categories fall below your threshold. - Mixing up unknown and missing. A missing value such as
NaNis a different problem from an unseen string. The next chapters on missing values cover it.
Exercise
You fit OneHotEncoder(drop="first", handle_unknown="ignore") on a "size" column with the values small, medium, and large. At prediction time a row contains "huge". What does the encoder output for that row, and why is that a problem?
Show answer
The encoder outputs all zeros for the size feature. With drop="first", the dropped category "large" is also represented by all zeros, so the model cannot tell the unseen value "huge" from "large" and treats it as "large". If that distinction matters, keep all columns, or use minfrequency with handleunknown="infrequentifexist" so unknown values go to an explicit infrequent column.
Exercise
A fraud model is trained with minfrequency=5 and handleunknown="infrequentifexist" on a "merchant" column. In the training data every merchant appears at least 5 times. A new merchant arrives in production. What is the encoded row, and what would you change to get a dedicated bucket for unknown values?
Show answer
No category falls below the threshold, so no infrequent column exists, and the unknown merchant becomes all zeros, the same as with handleunknown="ignore". To get a bucket you can raise minfrequency so that some real categories are grouped on the training data, or set max_categories so the least common merchants are merged. The model then learns a weight for the infrequent column, and unknown merchants receive it.