Sub topic 6
Fit on Training Data Only
This chapter assumes you can split data with train_test_split, know the scikit-learn fit/transform/predict pattern, and have used SimpleImputer on a small array. The chapter covers where fit must run, the mistakes that break that rule, and how a Pipeline enforces it.
What the imputer learns
SimpleImputer is a stateful transformer. Calling fit computes one statistic per column (mean, median, most frequent value, or the constant you supplied) and stores them in statistics_. Calling transform only reads those stored values and writes them into the missing cells. It never recomputes anything.
This split is the whole basis of leakage control. The statistics are learned parameters, in the same sense that a regression coefficient is. If the test rows influence them, the test rows have influenced the model.
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 median comes from 1, 2, 100 and is 2. The test set contributes nothing to it. The missing test value is filled with the training median, and the known test value 5.0 passes through unchanged. The outlier 100 would have pulled a mean up to about 34.3, but it does not move the median.
What leakage means here
Data leakage is any path by which information from data you will not have at prediction time (or that you are meant to be evaluating on) reaches the training process. Evaluation scores then look better than real-world performance will be.
Imputation statistics are a mild but real leak path. Suppose you compute the median over the full dataset and then split:
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]])
X_all = np.vstack([X_train, X_test])
leaky = SimpleImputer(strategy="median").fit(X_all)
clean = SimpleImputer(strategy="median").fit(X_train)
print(leaky.statistics_) # [3.5] uses 1, 2, 5, 100
print(clean.statistics_) # [2.] uses 1, 2, 100The leaky imputer has seen the test value 5.0. The fill value for the training rows now depends on test data. A single median rarely changes a model's score by much. The cost grows when:
- the dataset is small, so each row has more influence on the statistic;
- many columns are imputed, so many small leaks add up;
- you tune hyperparameters on the leaked score, which can make you pick the wrong model;
- later preprocessing steps (scaling, encoding) build on the leaked values.
Treating "fit on training data only" as a rule with no exceptions is cheaper than judging each case.
The rule
fit(orfit_transform) runs on training data only.transformruns on everything else: validation rows, test rows, and new production rows.- The fitted object is kept and reused. It is not refitted.
Three common mistakes
Mistake 1: fitting before splitting
This is the version shown above. It often looks harmless because it is a single line near the top of a notebook:
# Wrong: statistics computed from every row, including future test rows
X_imputed = SimpleImputer(strategy="median").fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_imputed, y)The fix is to split first, then fit on the training part.
Mistake 2: calling `fit_transform` on the test set
This one is not leakage from the test set into training. It is a different failure: the test set is imputed with its own statistics, so train and test rows are filled by different rules.
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").fit(X_train)
wrong = SimpleImputer(strategy="median").fit_transform(X_test)
right = imputer.transform(X_test)
print(wrong) # [[5.] [5.]] median of the single known test value
print(right) # [[2.] [5.]] training medianThe model was trained with missing values replaced by 2.0. With the wrong approach it receives 5.0 for the same situation. That is a silent shift in the input distribution.
It also fails in a worse way for single-row predictions. With one production row containing a NaN, there is no known value to take a median from, so the row has nothing to be filled with. A fitted imputer handles that row without trouble.
Mistake 3: refitting inside a loop
If you build the imputer inside a loop or helper function that is called once per dataset, you will refit it on whatever data arrives. This commonly happens when a "prepare features" function is reused for training and for serving. Fit once, keep the object, and call transform afterwards.
Cross-validation makes the problem harder to see
A single train/test split gives you one imputer. Cross-validation gives you one per fold, and the rule applies inside each fold: the imputer must be fitted only on that fold's training part.
If you impute the whole of X_train first and then run cross_val_score, every validation fold has contributed to the statistics used to fill its own missing cells. The leak is small but real, and it inflates every fold's score.
The reliable fix is to put the imputer in a Pipeline. Cross-validation tools clone the whole pipeline for each fold and call fit on the training portion only.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
rng = np.random.default_rng(0)
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
X[rng.random(X.shape) < 0.1] = np.nan # blank out about 10% of the cells
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("clf", LogisticRegression()),
])
# Each fold fits its own imputer on that fold's training rows only.
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.mean())
# The final fit uses all training rows; the test rows are only transformed.
pipe.fit(X_train, y_train)
print(pipe.named_steps["impute"].statistics_) # five training medians
print(pipe.score(X_test, y_test))Notice what the code never does. It never calls fit or fit_transform on X_test. pipe.score(X_test, y_test) calls transform on the imputer step and predict on the classifier. The imputer's medians stay those of X_train.
How the pipeline enforces the rule
| Pipeline method | What happens to the imputer step |
|---|---|
| `pipe.fit(X, y)` | Calls `fit_transform` on the imputer with `X`, passes the result to the next step |
| `pipe.predict(X)` / `pipe.score(X, y)` | Calls only `transform` on the imputer |
| `cross_val_score(pipe, ...)` | Clones the pipeline per fold, fits on the training part, scores on the held-out part |
| `GridSearchCV(pipe, ...)` | Same as above, once per parameter combination and fold |
Because the pipeline is the unit you pass around, you cannot forget to apply the imputer. You also cannot apply it with the wrong statistics.
Statistics follow the data you fit on
A few consequences are worth knowing before you hit them.
- Different folds give different
statistics_. That is expected. Each fold's imputer only knows its own training rows. - Refitting on more data changes the fill values. If you retrain a model on a larger dataset, the medians will move. Do not reuse old statistics with a new model.
- Serving uses the stored statistics. Save the whole fitted pipeline (for example with
joblib.dump(pipe, "model.joblib")), not just the classifier. The imputer'sstatistics_travel with it. - Grouped statistics need the same discipline. If you compute something like "median income per city" with pandas
groupbybefore splitting, it is the same leak, and a larger one, because small groups let single rows dominate. Compute it after splitting, from training rows only, or build it into a custom transformer that learns infit.
The imputer also checks its input shape. A fitted imputer expects the same number of columns on transform as it saw in fit, and raises a ValueError otherwise. In a pipeline, that check protects you from feeding columns in a different order or count.
When fitting on all data is acceptable
There is one situation where people legitimately use all available data to learn imputation statistics: after model selection is finished, when you train the final model on every labeled row before deployment. At that point the "training data" is all labeled data, and there is no held-out score left to protect. You still do not include data from the future, or unlabeled rows you will predict later, in the fit.
Another gray area is unsupervised preprocessing with a lot of unlabeled data (transductive setups). If you do this, document it, and keep the evaluation rows out of the fit anyway.
Verifying your own workflow
You can check that an imputer was fitted only on the training rows by comparing its statistics with ones computed directly:
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({"x": [1.0, 2.0, np.nan, 100.0, 5.0, np.nan]})
train, test = df.iloc[:4], df.iloc[4:]
imputer = SimpleImputer(strategy="median").fit(train)
print(imputer.statistics_) # [2.]
print(train["x"].median()) # 2.0 (pandas skips NaN)
print(imputer.statistics_[0] == train["x"].median()) # TrueIf this comparison is False with the training rows and True with all rows, you fitted on the wrong data.
Summary
fitlearns the statistics,transformapplies them. Onlyfitmay see training data.- Fitting before the split leaks test information into the fill values.
- Calling
fit_transformon test data replaces the training rule with a different one and breaks consistency. - In cross-validation, the imputer must be refitted inside each fold. A
Pipelinedoes this automatically. - Save the fitted pipeline, so the same
statistics_are used in production.
Exercise
A colleague writes X_imp = SimpleImputer(strategy="mean").fit_transform(X), then train_test_split(X_imp, y), then trains and evaluates a model. Name the problem and give the corrected structure.
Show answer
The mean was computed from all rows, including those that end up in the test set, so test information influences the training data (leakage). Split first, then call fit (or fit_transform) on X_train only, and call transform on X_test. Better still, put the imputer and the model in a Pipeline and fit the pipeline on X_train.
Exercise
You fit SimpleImputer(strategy="median") on X_train = [[1.0], [2.0], [np.nan], [100.0]]. A test row arrives as [[np.nan]]. What value does imputer.transform return, and what would SimpleImputer(strategy="median").fit_transform([[np.nan]]) do instead?
Show answer
transform returns [[2.]], the median of 1, 2 and 100 learned during fit. A fresh imputer fitted on a column with no known values has no statistic to learn. It drops that column by default (keep_empty_features=False), so the result has zero columns rather than a filled value. This is why test data must be transformed with the already fitted imputer.
Exercise
Why does passing a Pipeline containing the imputer to cross_val_score avoid leakage, while imputing X_train first and then passing the imputed array to cross_val_score does not?
Show answer
cross_val_score clones the pipeline for each fold and calls fit on that fold's training rows only, so the imputer's statistics_ never include the validation rows. If you impute X_train beforehand, the statistics already include every row, and each validation fold has contributed to the values that fill its own missing cells.