Sub topic 6
Fit on training data only to avoid leakage
This chapter assumes you can use NumPy arrays and know what a mean and a standard deviation are. It also assumes you know why data is split into training and test sets, and that you have used a scikit-learn estimator with fit and predict. The earlier chapters of this tutorial introduced StandardScaler, MinMaxScaler, and the fit / transform / fit_transform methods. Here you learn which data each method call may see, and why the answer matters.
What leakage means
Data leakage happens when information from data the model should not have seen influences the model or its preprocessing. The usual consequence is that your evaluation score looks better than the model's real performance on new data.
A test set exists to imitate the future. In production, you will not have the future data when you train the model or choose preprocessing parameters. If you compute a mean from the test set and use it to scale the training data, the test set has affected your pipeline. The test score is no longer an honest estimate.
Scaling is a mild source of leakage compared with something like target leakage. It is still worth getting right, because the habit carries over to every preprocessing step that learns from data: imputation, PCA, feature selection, and encoders.
What a scaler learns
A scaler is an estimator that learns numbers during fit, then applies them during transform.
| Scaler | Learned in `fit` | Applied in `transform` |
|---|---|---|
| `StandardScaler` | `mean_`, `scale_` (standard deviation, `ddof=0`) | `(x - mean_) / scale_` |
| `MinMaxScaler` | `data_min_`, `data_max_` | `(x - data_min_) / (data_max_ - data_min_)`, then mapped to `feature_range` |
These learned statistics are parameters, just like the coefficients of a linear model. The rule follows directly: parameters are learned from training data only. The test set is only ever passed through transform, using the numbers the scaler already learned.
The correct pattern
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(loc=[50, 1000], scale=[5, 300], size=(100, 2))
y = (X[:, 0] > 50).astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
scaler = StandardScaler().fit(X_train) # learn statistics from training data only
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # reuse the training statisticsThree details matter here:
- The split happens first. Nothing is scaled before
train_test_split. fitreceivesX_trainand nothing else.transformis called on both sets, and it never changes the learned statistics.
After this code, the scaled training columns have mean 0 and standard deviation 1. The scaled test columns will be close to that but not exactly equal, and that is correct. The difference tells you the test sample differs slightly from the training sample, just as new data will in production.
In the diagram, the test set has an arrow into the transform step but no arrow into the fit step. That is the whole rule.
A visible demonstration of the wrong way
The mistake that is easiest to make is calling fit_transform on the test set. The code runs without error and gives plausible-looking numbers, so nothing warns you. This example uses a test set that has drifted far from the training data, which is a situation your evaluation should reveal.
import numpy as np
from sklearn.preprocessing import StandardScaler
train = np.array([[10.0], [20.0], [30.0]])
test = np.array([[100.0], [110.0], [120.0]]) # much larger than anything in training
# Correct: statistics come from the training data
scaler = StandardScaler().fit(train)
print(scaler.transform(test).ravel()) # about [ 9.80 11.02 12.25 ]
# Wrong: a new scaler is fitted on the test data
wrong = StandardScaler().fit_transform(test)
print(wrong.ravel()) # about [-1.22 0.00 1.22 ]The correct version reports that the test values are roughly 10 to 12 training standard deviations above the training mean. The model will see inputs far outside what it learned from, and its performance will reflect that. The wrong version rescales the test set to mean 0 and standard deviation 1 by construction, so the shift disappears. The model receives inputs that look normal and your evaluation hides the problem.
This shows two separate failures of fitting on test data:
- Information leaks: the test set determines how its own values are represented.
- The test set stops being a stress test. Any difference in distribution between training and test data is erased.
Leakage before the split
A subtler version scales the whole dataset first and splits afterward:
# Leaky: the scaler has seen every row, including future test rows
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test = train_test_split(X_scaled, test_size=0.2, random_state=0)The test rows contributed to mean_ and scale_, so the training features already carry a small amount of information about them. With a plain scaler and a large dataset, the numerical effect is usually small. It is still a violation of the rule, and the same shortcut applied to a step like target-aware feature selection can inflate scores dramatically. Build the habit of splitting before any step that calls fit.
Leakage inside cross-validation
Cross-validation repeats the train/test logic several times. In each fold, one slice acts as the test data and the remaining slices are the training data. The scaler must therefore be refitted for every fold, using only that fold's training slice.
This does not work if you scale the full dataset first and then call cross_val_score. Every validation slice would already have contributed to the scaler's statistics. Doing the fold loop by hand is possible but easy to get wrong. The reliable fix is to put the scaler and the model in a single Pipeline, which the next chapter covers in depth. A short preview:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())For each of the five folds, cross_val_score clones the pipeline, calls fit on the training slices (which fits the scaler and then the classifier), and calls predict on the held-out slice (which only transforms). The scaler never sees the held-out slice during fitting.
Which split should the scaler see?
The rule is the same in every setup: the scaler sees only the data the model is allowed to learn from at that moment.
| Situation | Fit the scaler on | Only transform |
|---|---|---|
| Train/test split | Training set | Test set |
| Train/validation/test split | Training set | Validation set, test set |
| k-fold cross-validation | Training folds of each iteration | Held-out fold of each iteration |
| Final model after tuning | All data used to train the final model (for example train plus validation) | Future data, including the untouched test set if you report a final score |
| Time series | Past observations up to the forecast point | Observations after that point |
| Production inference | Nothing: load the saved scaler | Each incoming batch or row |
For time series, a random split is already a leakage risk, because future rows end up in the training set. Split by time first, then fit the scaler on the earlier part.
When you retrain the final model on train plus validation data, refit the scaler on that combined set too. The scaler is part of the model, so it is retrained with it.
Keeping the fitted scaler for deployment
At prediction time you receive new rows, often one at a time. Scaling a single row with its own statistics is meaningless, since its standard deviation is 0. You must reuse the scaler that was fitted during training. Save it together with the model:
import joblib
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 200.0], [2.0, 400.0], [3.0, 600.0]])
scaler = StandardScaler().fit(X_train)
joblib.dump(scaler, "scaler.joblib")
loaded = joblib.load("scaler.joblib")
new_row = np.array([[2.5, 500.0]])
print(loaded.transform(new_row))If the scaler and the model are in one Pipeline, saving the pipeline saves both together, which prevents the common error of deploying a model with a mismatched or missing scaler.
Checking your work
You can inspect a fitted scaler to confirm which data it learned from:
scaler.n_samples_seen_reports how many rows were used infit. If it equals the size of the full dataset instead of the training set, you fitted too early.scaler.mean_andscaler.data_min_can be compared againstX_train.mean(axis=0)andX_train.min(axis=0). They should match exactly.- The scaled test set should not have mean exactly 0 and standard deviation exactly 1. If it does, check whether the test set was passed to
fit_transform.
MinMaxScaler has a related symptom. Test values scaled with training statistics can fall outside the range [0, 1] when they exceed the training minimum or maximum. That is correct behavior and tells you something about the data. Do not "fix" it by refitting on the test set. The edge-case chapter covers clipping as an explicit choice.
Common errors
- Calling
fit_transformon bothX_trainandX_testin two separate lines. Each call fits a separate scaler, so the two sets are scaled on different scales. - Scaling the full dataset before
train_test_splitor beforecross_val_score. - Fitting the scaler on training plus test data "to get better statistics".
- Fitting a new scaler on each batch of production data.
- Forgetting to save the scaler, then recomputing statistics from a different sample at inference.
- Scaling the target
ywith the same scaler as the features. Use a separate scaler for the target if you need one, fitted on the training target only.
Summary
The scaler's statistics are learned parameters. Learn them from the training data, apply them to everything else, and let a Pipeline do the bookkeeping inside cross-validation.
Exercise
A colleague writes X_s = StandardScaler().fit_transform(X) and then calls cross_val_score(LogisticRegression(), X_s, y, cv=5). What is wrong, and how would you fix it?
Show answer
The scaler is fitted on the whole dataset before cross-validation, so every validation fold has contributed to the mean and standard deviation used to scale the training folds. This is leakage. Put the scaler and the classifier in one pipeline, for example make_pipeline(StandardScaler(), LogisticRegression()), and pass the raw X to cross_val_score. The pipeline refits the scaler on the training folds of each iteration.
Exercise
You fit a MinMaxScaler on training data where a feature ranges from 10 to 50. A test row has the value 70 for that feature. What does transform return for it, and should you refit the scaler on the test data to bring it back into [0, 1]?
Show answer
It returns (70 - 10) / (50 - 10) = 1.5. You should not refit on the test data. The value outside [0, 1] is correct information that the test row lies beyond the training range. If you want to bound it, apply clipping as a separate, deliberate step, or choose a scaler suited to the data.
Exercise
After scaling, your test features have mean exactly 0.000 and standard deviation exactly 1.000 in every column. What does this suggest about your code, and why is it a warning sign?
Show answer
It suggests the scaler was fitted on the test set, for example with fit_transform(X_test). A scaler fitted on training data produces test statistics that are close to, but not exactly, 0 and 1. Exact values mean the test set was normalized on its own statistics, which leaks information and hides any distribution shift between training and test data.