Sub topic 7
Fit on training data, transform everywhere
This chapter assumes you can split data into training and test sets and that you have used OneHotEncoder or get_dummies once. It covers how an encoder should learn its categories, and why that matters.
What "fit" means for an encoder
An encoder learns something from data, just as a model does. OneHotEncoder learns the list of categories in each column and their order. That list decides which output columns exist and what each column means.
scikit-learn separates this into two steps:
fitlearns the categories from the data you pass in.transformapplies the learned categories to any data, without changing them.
fit_transform runs both in one call. Use it only on training data.
Why get_dummies breaks this rule
pd.get_dummies has no memory. It builds columns from whatever frame you give it, so the training and test matrices can end up with different columns.
import pandas as pd
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "red"]})
print(pd.get_dummies(train, dtype=int).columns.tolist())
print(pd.get_dummies(test, dtype=int).columns.tolist())The output is:
['color_blue', 'color_green', 'color_red']
['color_green', 'color_red']The test matrix has two columns and the training matrix has three. A model trained on three columns cannot score a two-column matrix. Even when the shapes happen to match, the column order can differ, and the model would then read the wrong columns without raising an error.
Fitting OneHotEncoder correctly
OneHotEncoder stores the categories after fit, so every later call produces the same columns in the same order.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
test = pd.DataFrame({"color": ["green", "red"]})
enc = OneHotEncoder(sparse_output=False)
X_train = enc.fit_transform(train)
X_test = enc.transform(test)
print(enc.categories_)
print(X_train.shape, X_test.shape)
print(X_test)The output is:
[array(['blue', 'green', 'red'], dtype=object)]
(4, 3) (2, 3)
[[0. 1. 0.]
[0. 0. 1.]]Both matrices have three columns. In the test matrix, the first row ("green") has its 1 in the middle column, and the second row ("red") has its 1 in the last column. The unused "blue" column is all zeros.
Why test data must not be used for fitting
Fitting on the test set, or on the full dataset before splitting, is a form of data leakage. Leakage means information from data the model should not have seen influences how it is built.
For one-hot encoding the leak is mild. The encoder learns only category names, not target values. The habit still causes real problems:
- Your evaluation stops matching production. A deployed model never gets to learn categories from future data.
- The encoder's column list changes whenever the data changes, so saved models and encoders fall out of sync.
- The same habit with scalers or target-based encoders leaks real information and inflates your scores.
The safe rule is to split first, then fit every preprocessing step on the training portion only.
A common error: refitting on new data
A frequent mistake is to create a new encoder for each dataset:
# Wrong: each call learns a different set of categories
X_train = OneHotEncoder().fit_transform(train)
X_test = OneHotEncoder().fit_transform(test)This reproduces the get_dummies problem. Reuse one fitted encoder object instead. When you save a model for later use, save the fitted encoder with it. A Pipeline does this for you, as a later chapter shows.
Exercise
You fit a OneHotEncoder on a training set whose column "city" contains Paris, Berlin and Rome. You then call enc.transform on a test set that contains only Rome. How many output columns does the test matrix have, and why?
Show answer
Three. The categories were learned during fit on the training data, so transform always produces one column per learned category (Berlin, Paris, Rome). The Berlin and Paris columns are all zeros in the test matrix.