StandardScaler in Python with scikit-learn
Rescale every feature to mean 0 and standard deviation 1, learning the numbers from the training set only.
- fit_transform on the training set
- transform on the test set
- Reading mean_ and scale_
- alcohol: mean 13.0, std 0.8
- proline: mean 749.81, std 302.18
- alcohol: mean 0.0, std 1.0
- proline: mean 0.0, std 1.0
Putting features on the same scale
The problem
Features often come in very different units: alcohol around 13, proline around 750. Models that use distances or gradients (KNN, SVM, logistic regression, PCA) then pay attention to the big numbers and ignore the small ones.
Think of it like this
Standardizing is like comparing a score out of 10 with a score out of 1000 by asking "how far above or below average is it?" instead of looking at the raw number. Every column is measured in the same unit: standard deviations from its mean.
scaler.fit(X_train)📊 Work out each column's average and spreadscaler.mean_🎯 The average of each column(x - mean) / std📏 How many spreads above or below averagescaler.transform(X_test)🔁 Use the same average and spread on new dataStandardScaler subtracts each column's mean and divides by its standard deviation, so every feature ends up with mean 0 and standard deviation 1.
Key points
fit_transform(X_train)learns the mean and standard deviation of each column and rescales the training set.transform(X_test)reuses the training numbers, so the test set is scaled the same way.- The test means are near 0 (0.01 and -0.04), not exactly 0, because they use the training statistics.
scaler.mean_andscaler.scale_store what was learned.
When should you use it?
- Before KNN, SVM, logistic regression, neural networks and PCA.
- When features are measured in different units.
- Inside a pipeline, so cross-validation scales each fold correctly.
When not to use it
- Tree models (decision trees, random forests) do not need scaling.
- Data with big outliers: RobustScaler is less affected by them.
Example code
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# Two columns on very different scales: alcohol and proline
print("Before mean:", np.round(X_train[:, [0, 12]].mean(axis=0), 2).tolist())
print("Before std: ", np.round(X_train[:, [0, 12]].std(axis=0), 2).tolist())
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # learn mean and std from the training set only
X_test_scaled = scaler.transform(X_test) # reuse them for the test set
print("Train mean:", (np.round(X_train_scaled[:, [0, 12]].mean(axis=0), 2) + 0.0).tolist()) # + 0.0 turns -0.0 into 0.0
print("Train std: ", np.round(X_train_scaled[:, [0, 12]].std(axis=0), 2).tolist())
print("Test mean:", np.round(X_test_scaled[:, [0, 12]].mean(axis=0), 2).tolist())
print("Learned mean:", np.round(scaler.mean_[[0, 12]], 2).tolist())
Result of running the code
Before mean: [13.0, 749.81]
Before std: [0.8, 302.18]
Train mean: [0.0, 0.0]
Train std: [1.0, 1.0]
Test mean: [0.01, -0.04]
Learned mean: [13.0, 749.81]
Code explanation
In the wine data, alcohol has a standard deviation of 0.8 while proline has 302.18. fit_transform on X_train learns each column's mean and standard deviation (stored in scaler.mean_ and scaler.scale_) and rescales the training set, so both columns end with mean 0.0 and standard deviation 1.0. transform on X_test reuses the training numbers instead of learning new ones, which is why the test means are close to 0 (0.01 and -0.04) but not exactly 0.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Fitting the scaler on all the data before splitting
The test set then leaks into the training statistics and the score is too optimistic.
X_scaled = StandardScaler().fit_transform(X) # then split
scaler.fit_transform(X_train); scaler.transform(X_test)
Calling fit_transform on the test set
The test set must be scaled with the training mean and standard deviation.
X_test_scaled = scaler.fit_transform(X_test)
X_test_scaled = scaler.transform(X_test)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Z-Score Standardization Center a feature at 0 and scale it to a standard deviation of 1. Easy
- Min-Max Normalization Rescale a feature so its smallest value becomes 0 and its largest becomes 1. Easy
Tools for this lesson
- Data Preparation for Machine Learning in PythonScale features with min-max normalization and z-score standardization, and multiply matrices by hand.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.