Sub topic 7
Fit on training data, transform everywhere
This chapter assumes you can use pandas DataFrames, know what a train/test split is, and have seen OneHotEncoder produce indicator columns. The question here is a different one: when the encoder learns its categories, and what goes wrong if it learns them at the wrong moment.
Encoders have state
Scikit-learn objects that prepare data follow a two-step contract:
fit(X_train)learns something from the data and stores it on the object.transform(X)applies what was learned to any data, without learning anything new.
For OneHotEncoder, the learned state is the list of categories in each column. The encoder stores it in the categories_ attribute. The order of that list fixes which output column means which category. A model trained on those columns depends on that mapping staying the same.
Attributes that end in an underscore, such as categories_, exist only after fitting.
The failure with get_dummies
pd.get_dummies has no stored state. Every call looks only at the DataFrame you give it. That is convenient for exploration, but it breaks when the training and test sets contain different categories:
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "red"]})
print(list(pd.get_dummies(train, dtype=int).columns))
print(list(pd.get_dummies(test, dtype=int).columns))The output is:
['color_blue', 'color_green', 'color_red']
['color_green', 'color_red']The training matrix has three columns and the test matrix has two. A model fitted on three features cannot score a two-column matrix. The failure can also be quieter. If the test set had a different set of categories but the same number of them, the shapes would match and the columns would mean different things. You can patch this with reindex(columns=train_columns, fill_value=0), but that rebuilds by hand what a fitted encoder already does.
Fitting OneHotEncoder correctly
Fit the encoder once on the training data. Then reuse the same fitted object everywhere else.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["red", "green"]})
enc = OneHotEncoder(sparse_output=False)
enc.fit(train)
print(enc.categories_)
print(enc.get_feature_names_out())
print(enc.transform(test))The output is:
[array(['blue', 'green', 'red'], dtype=object)]
['color_blue' 'color_green' 'color_red']
[[0. 0. 1.]
[0. 1. 0.]]The test data has no "blue" row, but the output still has a color_blue column, filled with zeros. The shape and the column meanings come from the training data, not from the data being transformed.
The same rule applies to validation data, to new rows at prediction time, and to any later batch. fit happens once, and transform happens many times.
The common mistake: fit_transform on the test set
fit_transform(X) is shorthand for fit(X) followed by transform(X). Use it on training data only. If you call it on the test set, you throw away the training categories and learn new ones:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
test = pd.DataFrame({"color": ["red", "green"]})
wrong = OneHotEncoder(sparse_output=False)
print(wrong.fit_transform(test))The output is:
[[0. 1.]
[1. 0.]]The result has two columns, not three. Column 0 now means "green", where it meant "blue" during training. The code raises no error, and a model that accepts two features would produce confident but wrong predictions.
Why this is called leakage
Data leakage means information from outside the training set influences how the model is built. For one-hot encoding the leak is small. The encoder would learn the names of categories that exist only in the test data. Other transformers leak more. A StandardScaler fitted on all the data uses test-set means and variances. The rule is the same for every transformer, so it is better to follow it everywhere than to judge each case.
Leakage matters most during cross-validation. In each fold, the encoder must be fitted on that fold's training portion only. Doing this by hand is tedious and easy to get wrong. A Pipeline does it for you.
Letting a Pipeline enforce the rule
Putting the encoder inside a Pipeline removes the choice about where to call fit. Calling pipeline.fit(X_train, y_train) fits every step on the training data. Calling pipeline.predict(X_new) only transforms.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"city": ["Paris", "Berlin", "Rome"] * 4})
y = [0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0]
model = Pipeline([
("prep", ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])),
("clf", LogisticRegression()),
])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
print(cross_val_score(model, X, y, cv=3))Two things happen here without extra code:
model.fitfits the encoder onX_trainonly.model.scorethen transformsX_testwith the stored categories.cross_val_scoreclones the whole pipeline for each fold and fits it on that fold's training rows. The encoder is never fitted on a fold's held-out rows.
The handle_unknown="ignore" option is there because a small split can leave a city out of the training portion. The next chapter covers it in detail.
Inspecting and reusing a fitted encoder
After fitting, you can look inside the pipeline to check what the encoder learned:
encoder = model.named_steps["prep"].named_transformers_["cat"]
print(encoder.categories_)Note the trailing underscore on named_transformers_. The fitted copies live there. The unfitted transformers list you passed in is not changed.
To use the model in another process, save the whole pipeline, not only the classifier. The learned categories are part of the model:
import joblib
joblib.dump(model, "model.joblib")
loaded = joblib.load("model.joblib")
print(loaded.predict(X.head(3)))If you saved only the classifier, you would need to rebuild the encoder later, and a rebuilt encoder could end up with different categories or a different column order.
Edge cases to know
| Situation | What happens |
|---|---|
| `transform` before `fit` | Raises `NotFittedError`. |
| Calling `fit` a second time | Replaces the old categories completely. Nothing accumulates. |
| Test DataFrame is missing a fitted column name | Raises an error about feature names, because the encoder records column names when fitted on a DataFrame. |
| Category in the test data that was not in training | Raises `ValueError` by default. `handle_unknown="ignore"` gives all zeros instead. |
| Training set lacks a category that exists in reality | The model never learned a weight for it. Treat it as unknown at prediction time. |
You can see the first row of that table directly:
import pandas as pd
from sklearn.exceptions import NotFittedError
from sklearn.preprocessing import OneHotEncoder
try:
OneHotEncoder().transform(pd.DataFrame({"color": ["red"]}))
except NotFittedError as err:
print(type(err).__name__)It prints NotFittedError.
Choosing between the two tools
| Row | `pd.get_dummies` | `OneHotEncoder` |
|---|---|---|
| Remembers categories | No | Yes, in `categories_` |
| Safe on new data | Only if you realign columns by hand | Yes, through `transform` |
| Works in a `Pipeline` | No | Yes |
| Best use | Quick exploration of a single table | Any model you will evaluate or deploy |
Use get_dummies to look at data. Use OneHotEncoder once the encoded features feed a model.
Exercise
A colleague writes X_test_enc = OneHotEncoder().fit_transform(X_test) and then calls model.predict(X_test_enc) on a model trained with three encoded columns. The test data contains only two distinct categories. What happens, and what is the fix?
Show answer
The new encoder learns only the two categories in the test data, so the output has two columns instead of three and the prediction call fails with a shape error. If the test data had the same number of categories as the training data but a different set, the shapes would match and the columns would silently mean the wrong things. The fix is to fit the encoder on the training data only, then call transform on the test data with that same fitted encoder. Better still, put the encoder in a Pipeline so pipeline.predict(X_test) does this automatically.
Exercise
Why does cross_val_score(model, X, y) with an encoder inside the pipeline give a more honest score than encoding all of X first and cross-validating only the classifier?
Show answer
With the encoder inside the pipeline, each fold fits the encoder on that fold's training rows only, so the held-out rows never influence the learned categories (or the scaling statistics of any other step). Encoding all of X first lets every fold's encoder state come from data that includes the held-out rows, which is a form of leakage and can make the score look slightly better than real-world performance.