Sub topic 6
Fit on Training Data Only
This chapter assumes you know the scikit-learn estimator pattern (fit, transform, predict), can use NumPy arrays and pandas DataFrames, and understand why data is split into training and test sets. It also assumes you have used SimpleImputer with the mean and median strategies.
What leakage is
Data leakage happens when information from outside the training data influences how a model is built. The test set exists to simulate new data the model has never seen. If preprocessing uses test values, the test score becomes too optimistic.
Imputation is a common source of leakage. The mean or median is a statistic computed from data. If you compute it on the full dataset before splitting, the test rows contribute to the fill values that the training rows receive.
The rule: fit once, transform many times
fit learns the fill values and stores them in statistics_. transform only applies those stored values. So the rule is:
- Call
fiton the training data only. - Call
transformon the training data and again on the test data. - Never call
fitorfit_transformon the test data.
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0], [2.0], [np.nan], [100.0]])
X_test = np.array([[np.nan], [5.0]])
imputer = SimpleImputer(strategy="median")
imputer.fit(X_train) # learns the median of the training data only
print(imputer.statistics_) # [2.]
print(imputer.transform(X_test))
# [[2.]
# [5.]]The imputer ignores NaN when it computes the median, so the training median is 2. The test NaN becomes 2, even though the test set contains a 5. The test set had no influence on that value. The median also stays at 2 despite the outlier 100. A mean would be pulled up to about 34.3.
The common mistakes
The leaky version looks harmless:
# Wrong: the imputer sees the test data
imputer = SimpleImputer(strategy="median")
X_train_filled = imputer.fit_transform(X_train)
X_test_filled = imputer.fit_transform(X_test) # refits on the test setThis has two problems. The test set is filled with its own median, which is a different value from the one the model was trained with. The model then receives inputs that follow a different convention than the training inputs. At prediction time on a single new row, there may be no sensible statistic to compute at all.
The second mistake is subtler: imputing the whole dataset before calling train_test_split.
# Wrong: statistics computed from every row, including future test rows
X_all_filled = SimpleImputer().fit_transform(X_all)
X_train, X_test = train_test_split(X_all_filled)Here the test rows shape the training fill values. The effect is usually small for a mean over many rows. It becomes large with small datasets, with rare categories for most_frequent, and when the statistic is used inside cross-validation.
Leakage inside cross-validation
Cross-validation repeats the train and test split several times. If you impute the full dataset first and then cross-validate, every validation fold has already contributed to the fill values. The scores come out inflated and are not reliable.
The fix is to make the imputer part of the model, so that each fold refits it on that fold's training portion only. A Pipeline does this:
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 3))
y = (X[:, 0] + X[:, 1] > 0).astype(int)
X[rng.random(X.shape) < 0.15] = np.nan # about 15% missing
model = Pipeline([
("impute", SimpleImputer(strategy="median")),
("clf", LogisticRegression()),
])
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())Within each of the five folds, cross_val_score calls fit on the training portion, which refits the imputer and the classifier together. It then calls predict on the validation portion, which runs transform on the imputer and never refits it. The next chapter builds on this with ColumnTransformer.
Checking what was learned
You can confirm that the test set had no influence by changing the test data and watching the fill values stay put:
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0], [3.0], [np.nan]])
imputer = SimpleImputer(strategy="mean").fit(X_train)
print(imputer.statistics_) # [2.]
print(imputer.transform(np.array([[np.nan]]))) # [[2.]]
print(imputer.transform(np.array([[np.nan], [1000.0]])))
# [[2.]
# [1000.]]The fill value is 2 in every case, whatever the new data contains. Printing statistics_ right after fitting is a quick sanity check in your own projects.
Exercise
A colleague writes X_all = imputer.fit_transform(X) and then calls train_test_split(X_all, y). Name the problem and give the corrected order of steps.
Show answer
The fill values are computed from all rows, so the test rows influence the training data (leakage). Split first with train_test_split(X, y). Then call imputer.fit(X_train) (or fit_transform(X_train)), and call imputer.transform(X_test). Better still, put the imputer in a Pipeline with the model, so cross-validation refits it on each training fold.
Exercise
Given X_train = [[2.0], [4.0], [np.nan]] and a mean imputer fitted on it, what does transform return for the test data [[np.nan], [100.0]]?
Show answer
statistics_ is [3.], since the mean of 2 and 4 is 3 and the NaN is ignored. The result is [[3.], [100.]]. The test value 100 does not change the fill value.