Should I normalize data before or after the train/test split?
par Équipe NextData
I scale my features before training a model. Should the scaler be fitted on the full dataset before splitting into training and test sets, or after the split?
Signaler
1 réponse
Split first, then fit the scaler on the training set only. Apply that fitted scaler to the test set.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # learns mean and standard deviation
X_test_scaled = scaler.transform(X_test) # reuses them, learns nothing
Why: fitting on the full dataset lets information from the test set (its mean, its range) leak into training. This is called data leakage.
The same rule applies to every step that learns from data: imputing missing values, encoding categories, selecting features, reducing dimensions. How much the leak distorts the test score depends on the step. Measured with scikit-learn 1.7:
| Step fitted on the full dataset | Score with leakage | Score without |
|---|---|---|
| Scaling, 60 rows, logistic regression (average of 1,000 datasets) | 0.717 | 0.719 |
| Scaling, 2,000 rows, logistic regression (average of 200 datasets) | 0.810 | 0.810 |
| Selecting 20 features out of 5,000 on data with no signal, 100 rows (average of 50 datasets) | 0.88 | 0.51 |
For scaling alone, the difference stayed within noise in these tests. For feature selection, the leak turned purely random data into an apparent 88% accuracy, when the honest score is 50%. Apply the rule to every step rather than guessing where it is safe to skip.
The safest way to respect it, especially with cross-validation, is a pipeline. The scaler is refitted inside each fold automatically:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
model = make_pipeline(StandardScaler(), LogisticRegression())
scores = cross_val_score(model, X_train, y_train, cv=5)
In production, save the fitted pipeline and apply it unchanged to incoming data. Never refit the scaler on the data you are predicting.
Note that tree-based models (random forests, gradient boosting) do not need scaling at all.
Réponse rédigée par l'équipe NextData et relue par un expert.
