Sub topic 8
Handling categories not seen in training
This chapter assumes you can fit and transform with a scikit-learn OneHotEncoder and that you split data into training and test sets. It covers what happens when the data you predict on contains a category the encoder never saw.
Why unseen categories happen
OneHotEncoder learns its list of categories during fit. That list defines the output columns. If a later row contains a value outside the list, the encoder has no column for it.
This happens in practice for several reasons:
- A rare category lands only in the test split.
- A new product, city, or device type appears after the model is deployed.
- A typo or a change in spelling appears in incoming data.
The default: fail loudly
By default, handle_unknown="error". The encoder raises a ValueError when it sees an unknown value.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "purple"]})
strict = OneHotEncoder(sparse_output=False)
strict.fit(train)
try:
strict.transform(test)
except ValueError as err:
print(type(err).__name__)This prints ValueError. Failing is a reasonable choice when an unknown value means the data is broken. In a production service, though, one odd value would reject the whole batch.
Ignoring unknown values
Setting handle_unknown="ignore" encodes an unknown value as a row of zeros.
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.get_feature_names_out())
print(enc.transform(test))The output is:
['color_blue' 'color_green' 'color_red']
[[0. 1. 0.]
[0. 0. 0.]]The first row is green. The second row is purple, and all three indicators are zero. The model treats it as "none of the known colors". For a linear model, this means the color contributes nothing beyond the intercept.
Why not just use get_dummies?
pd.get_dummies builds columns from whatever values are in the DataFrame you pass it. Called separately on training and test data, it produces different column sets. The test matrix then has a different shape than the one the model was trained on. An encoder object remembers the training categories, so the output columns stay the same every time.
Choosing a policy
| Situation | Suggested setting |
|---|---|
| Exploration or a fixed dataset where new values signal a bug | `handle_unknown="error"` |
| Cross-validation, where a rare value may be absent from a training fold | `handle_unknown="ignore"` |
| A deployed model that receives live data | `handle_unknown="ignore"`, plus monitoring |
| Many rare categories you also want to group | `handle_unknown="infrequent_if_exist"` with `min_frequency`, covered in a later chapter |
Ignoring unknowns should not mean never noticing them. If the share of unseen values grows, the model is predicting on data that differs from what it learned. Log the count of unknown values, for example by comparing incoming values against enc.categories_, and retrain when it rises.
Common errors
- Passing
handle_unknown="ignore"toget_dummies. It has no such option. - Calling
fiton the test data to avoid the error. This leaks test information and breaks the fit-on-training-only rule from the previous chapter. - Forgetting that an unknown value becomes zeros, then reading the model's prediction as if the category were known.
Exercise
You train a model with OneHotEncoder(drop="first", handle_unknown="ignore") on a "size" column with values small, medium and large. At prediction time a row arrives with the value "extra large". What does the encoder output for that row, and why can this mislead you?
Show answer
It outputs all zeros for the size columns. Because drop="first" removes the column for "large", all zeros is also how "large" is encoded. The model cannot tell an unknown value from "large", so it predicts as if the size were "large". Use drop=None, or monitor for unknown values, if this matters.