Fit feature scaling without leaking test data
Feature scaling learns information from data. Treat fitting a scaler as part of model training, even though it does not use target labels. Split the data first, fit on training rows, and reuse the learned transformation for validation, test and production inputs.
Inspect what the scaler learns
Use Python 3.14 and scikit-learn 1.9.1. Install scikit-learn==1.9.1 in an isolated environment. NumPy is installed as a dependency. This example uses small literal arrays and needs no network or external dataset.
With its defaults, StandardScaler subtracts each feature's training mean and divides by its training standard deviation. It treats columns separately. This changes location and scale, but it does not make an arbitrary distribution Gaussian or constrain values to a fixed range.
StandardScaler reference
.
import numpy as np
from sklearn.preprocessing import StandardScaler
x_train = np.array([[10.0, 100.0], [20.0, 200.0], [30.0, 300.0]])
x_new = np.array([[40.0, 400.0]])
scaler = StandardScaler()
scaled_train = scaler.fit_transform(x_train)
scaled_new = scaler.transform(x_new)
np.testing.assert_allclose(scaler.mean_, [20.0, 200.0])
np.testing.assert_allclose(scaled_train.mean(axis=0), [0.0, 0.0], atol=1e-12)
np.testing.assert_allclose(scaled_train.var(axis=0), [1.0, 1.0])
np.testing.assert_allclose(scaled_new, [[2.44948974, 2.44948974]])
print("Training mean:", scaler.mean_.tolist())
print("New row:", scaled_new.round(4).tolist())
Expect a training mean of [20.0, 200.0] and a new row of approximately [[2.4495, 2.4495]]. The new row sits beyond the training observations, so its scaled values exceed one. That is expected. Fitting a fresh scaler on this single row would erase that relationship and produce zeros instead.
Keep preprocessing inside model selection
For a real model, combine preprocessing and estimation in one pipeline. Cross-validation then fits a fresh scaler within each training fold. Scaling the entire dataset before cross-validation would allow the held-out fold to influence that transformation. Data leakage guidance .
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
data = load_iris()
pipeline = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=23)
scores = cross_val_score(pipeline, data.data, data.target, cv=folds)
assert scores.shape == (3,)
assert np.all((scores >= 0) & (scores <= 1))
print("Fold count:", len(scores))
Run this block after the first block in the same script. It prints Fold count: 3. The fold scores describe this small demonstration, not a guaranteed performance target. cross_val_score evaluates clones, so the original pipeline is not the fitted deployment artifact. After selecting the design, fit it on the intended training data and evaluate once against a separate final test set.
Pipeline reference
,
Cross-validation guide
.
Handle data characteristics deliberately
A constant training column has no variance to normalize. The scaler uses a scale of one for that column, and default centering makes its training values zero. This does not mean the column will remain constant in future data.
Centering a sparse matrix would usually destroy its sparse representation. Use with_mean=False when preserving sparsity is required, and check whether the resulting preprocessing suits the estimator. Large outliers also affect means and standard deviations. Compare appropriate alternatives using the same validation discipline rather than picking a scaler from a training score alone.
Preserve feature names, units and order at inference. A stored scaler cannot detect that two unnamed numeric columns have been swapped. The numerical example and three-fold pipeline evaluation were executed locally with scikit-learn 1.9.1.
Question provenance
This article addresses Can anyone explain me StandardScaler? , asked by nitinvijay23 on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.
Author: Herman Schoenfeld