Machine Learning with scikit-learn

StandardScaler in Python with scikit-learn

Rescale every feature to mean 0 and standard deviation 1, learning the numbers from the training set only.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • fit_transform on the training set
  • transform on the test set
  • Reading mean_ and scale_
Two wine features in the training set
Before
  • alcohol: mean 13.0, std 0.8
  • proline: mean 749.81, std 302.18
After
  • 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.

From exam scores to code
scaler.fit(X_train)📊 Work out each column's average and spread
scaler.mean_🎯 The average of each column
(x - mean) / std📏 How many spreads above or below average
scaler.transform(X_test)🔁 Use the same average and spread on new data
Each value becomes its distance from the average.
In one sentence

StandardScaler 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

  1. fit_transform(X_train) learns the mean and standard deviation of each column and rescales the training set.
  2. transform(X_test) reuses the training numbers, so the test set is scaled the same way.
  3. The test means are near 0 (0.01 and -0.04), not exactly 0, because they use the training statistics.
  4. scaler.mean_ and scaler.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

Open in editor →
main.py
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())
Get a Run button for this example

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.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

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.

Problem
X_scaled = StandardScaler().fit_transform(X)  # then split
Fix
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.

Problem
X_test_scaled = scaler.fit_transform(X_test)
Fix
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.

All challenges

Tools for this lesson