Train-only preprocessing
Quick answer
A transformer learns preprocessing parameters during fit and applies the stored parameters during transform. For example, StandardScaler subtracts each feature’s training mean and divides by its training standard deviation (population convention, ddof=0). Apply the same transformation to validation and test features without fitting on them. This keeps evaluation closer to the information available in deployment. Examples use local Python 3.13.5 and scikit-learn 1.8.0 where imported. All fixtures are synthetic; ByteMind library execution is unverified.
Learn scaling from training data
Four input sizes have training mean 2.5. The validation input sizes are 2 and 5.
from sklearn.preprocessing import StandardScalerscaler = StandardScaler().fit([[1],[2],[3],[4]])print(scaler.mean_.tolist())print(scaler.transform([[2],[5]]).round(6).ravel().tolist())Expected output:
[2.5][-0.447214, 2.236068]Both validation values use the training mean and scale. A transformed value need not lie within the training range.
Keep a constant feature safe
A constant feature has zero variance; StandardScaler uses a scale factor of one for that feature. A later different value is still transformed with stored training parameters.
from sklearn.preprocessing import StandardScalers = StandardScaler().fit([[4],[4]])print(s.scale_.tolist())print(s.transform([[4],[7]]).ravel().tolist())Expected output:
[1.0][0.0, 3.0]The constant training feature becomes zero; an unseen value of 7 becomes 3, not zero. This behavior does not establish that the feature is useful.
Common mistakes
Never fit a scaler, imputer or feature selector on validation/test data. Calling fit_transform separately on validation yields incompatible feature coordinates and leaks distribution information. A pipeline makes correct ordering easier but cannot repair a feature that already contains future information. A scaler is not required for every estimator; here it demonstrates the workflow.
Practice and next steps
Calculate the training mean for sizes 1, 2, 3, 4, then center a validation value of 5 by hand. Explain why the validation mean is irrelevant. The exercise isolates centering, not full standardization. The separate pure-Python exercise assesses the underlying calculation, not library execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Train-only preprocessing — knowledge check
Apply experiment design and evaluation reasoning to synthetic examples.
Which data should determine the scaler mean?
Which method applies existing scaler parameters?
Training mean is 4; center value 9. Result?
What is StandardScaler scale_ for a constant feature?
Can a pipeline repair an input feature that reveals the target?