Module 3 · Beginner · Data preparation and EDA

Standardisation vs normalisation explained

Feature scaling for machine learning: standardisation vs min-max normalisation, robust scaling, which models need scaling, and scaling without leakage.

By theprogrammers team · · 6 min read

Imagine predicting a house's price from its area (500 to 5,000 square feet) and its number of bedrooms (1 to 5). The area numbers are a thousand times bigger than the bedroom numbers. Many machine learning models measure distances or add up weighted features, and to them, a difference of 1,000 square feet looks a thousand times more important than a difference of one bedroom, just because of the units.

Feature scaling puts all numeric features on a similar range so that no feature dominates because of its units. This lesson explains the two main methods, standardisation and normalisation, plus robust scaling for data with outliers, which models need scaling and which don't, and the leakage mistake almost every beginner makes.

The example data

import numpy as np
import pandas as pd

houses = pd.DataFrame({
    "area_sqft": [650, 900, 1200, 1500, 2400, 3200],
    "bedrooms": [1, 2, 2, 3, 4, 5],
    "age_years": [30, 12, 8, 15, 5, 2],
})
print(houses.describe().loc[["mean", "std", "min", "max"]].round(1))
      area_sqft  bedrooms  age_years
mean     1641.7       2.8       12.0
std       974.9       1.5       10.0
min       650.0       1.0        2.0
max      3200.0       5.0       30.0

Three features, three very different ranges.

Why scale? A distance example

Many models, such as k-nearest neighbours, k-means clustering and support vector machines, compare items by distance. Which house is closer to house 0: house 1 or house 2?

def distance(a, b):
    return np.sqrt(((a - b) ** 2).sum())

h = houses.to_numpy(dtype=float)
print(round(distance(h[0], h[1]), 1), round(distance(h[0], h[2]), 1))
250.6 550.4

The distance is almost entirely the area difference. A one-bedroom, 30-year-old flat and a 12-year-old two-bedroom flat differ a lot, but bedrooms and age barely count. Scaling fixes this.

Standardisation (z-scores)

Standardisation rescales each feature to have a mean of 0 and a standard deviation of 1:

z = (value − mean) / standard deviation

Each value then says "how many standard deviations above or below average", the same idea as z-scores in statistics for machine learning.

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
standardised = scaler.fit_transform(houses)
print(pd.DataFrame(standardised, columns=houses.columns).round(2))
print(standardised.mean(axis=0).round(2), standardised.std(axis=0).round(2))
   area_sqft  bedrooms  age_years
0      -1.11     -1.36       1.98
1      -0.83     -0.62       0.00
2      -0.50     -0.62      -0.44
3      -0.16      0.12       0.33
4       0.85      0.87      -0.77
5       1.75      1.61      -1.10
[-0. -0. -0.] [1. 1. 1.]

Now every column is on the same footing: house 0 is 1.11 standard deviations smaller than average and 1.98 older. (Scikit-learn uses the population standard deviation, so these differ slightly from pandas' std(). -0. is just a tiny negative number rounded to zero.)

The picture puts the six houses on number lines. On one shared ruler, only area spreads out. After standardisation, all three features spread over the same range, so a distance would count each of them.

Six houses on number lines. Before scaling, on one ruler from 0 to 3,200, the area values spread out while bedrooms and age bunch up at zero. After standardisation, all three features spread between about −1.4 and 2.

Normalisation (min-max scaling)

Min-max normalisation squeezes each feature into the range 0 to 1:

x' = (value − min) / (max − min)

from sklearn.preprocessing import MinMaxScaler

normalised = MinMaxScaler().fit_transform(houses)
print(pd.DataFrame(normalised, columns=houses.columns).round(2))
   area_sqft  bedrooms  age_years
0       0.00      0.00       1.00
1       0.10      0.25       0.36
2       0.22      0.25       0.21
3       0.33      0.50       0.46
4       0.69      0.75       0.11
5       1.00      1.00       0.00

The smallest value becomes 0 and the largest 1. It's easy to understand and keeps every value positive, which suits image pixels (0–255 becomes 0–1) and neural networks.

Now the distances are fair:

print(round(distance(normalised[0], normalised[1]), 2),
      round(distance(normalised[0], normalised[2]), 2))
0.7 0.85

All three features now contribute.

Robust scaling for outliers

Both methods are sensitive to outliers. One mansion of 50,000 square feet would make it the max, squashing every normal house into 0.00 to 0.06 with min-max scaling. Robust scaling uses the median and the interquartile range instead, which outliers barely affect:

from sklearn.preprocessing import RobustScaler

area = pd.DataFrame({"area_sqft": [650, 900, 1200, 1500, 2400, 50000]})
print(pd.DataFrame({
    "min-max": MinMaxScaler().fit_transform(area).ravel(),
    "robust": RobustScaler().fit_transform(area).ravel(),
}).round(2))
   min-max  robust
0     0.00   -0.58
1     0.01   -0.38
2     0.01   -0.12
3     0.02    0.12
4     0.04    0.88
5     1.00   40.54

With min-max, the normal houses are crushed together near 0. With robust scaling, they stay well spread, and only the outlier gets a huge value. You may still want to treat the outlier separately.

Which one to use?

MethodResultUse when
StandardScalerMean 0, std 1The default for most models: linear and logistic regression, SVM, PCA, neural networks
MinMaxScalerRange 0 to 1You need bounded values: images, some neural networks, KNN with no big outliers
RobustScalerMedian 0, scaled by IQRFeatures with outliers
Log transform firstPulls in a long tailStrongly right-skewed features such as income or prices

When unsure, standardise. The differences between scalers usually matter far less than whether you scale at all.

Which models need scaling?

Needs scalingDoesn't need scaling
K-nearest neighbours, k-means (distances)Decision trees
Support vector machinesRandom forests
Linear and logistic regression with regularisation (Ridge, Lasso)Gradient boosting (XGBoost, LightGBM)
PCANaive Bayes, mostly
Neural networks, and anything trained with gradient descent, which converges much faster on scaled features

Trees split one feature at a time on thresholds like "area > 1,350", so the scale doesn't change their splits. Scaling them does no harm, though, so in a mixed pipeline it's fine to scale everything.

Don't scale one-hot encoded columns or the target in most cases; they're already 0/1 or in their natural units. See encoding categorical data.

The leakage mistake: fit on training data only

A scaler learns numbers from the data: the mean and standard deviation, or the min and max. If you fit it on all your data before splitting, the test set's statistics leak into training, and test scores become slightly too optimistic. The correct pattern:

from sklearn.model_selection import train_test_split

X_train, X_test = train_test_split(houses, test_size=2, random_state=0)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)   # learn from training data
X_test_scaled = scaler.transform(X_test)         # apply the same numbers

print(scaler.mean_.round(1))
[1362.5    2.5   15.5]
  • fit_transform on training data: learn the means and standard deviations, and scale.
  • transform on test data (and on any future data): reuse the training numbers. Never call fit on test data.

test_size=2 keeps two of the six rows for testing. The learnt means come from the four training houses only. Scikit-learn pipelines do this fit-on-train, transform-on-test pattern for you automatically, which is the safest way. More on splitting in train, validation and test sets.

Practice

  1. Standardise the values [10, 20, 30] by hand. Check with StandardScaler.
Show the answer

The mean is 20 and the population standard deviation is about 8.165, so the results are about −1.22, 0 and 1.22.

print(StandardScaler().fit_transform([[10], [20], [30]]).ravel().round(2))
  1. Which scaler would you choose for a salary column with a few very high earners?
Show the answer

RobustScaler, or a log transform followed by StandardScaler. Min-max scaling would squash almost everyone near 0.

  1. Your random forest's accuracy doesn't change after scaling. Is something wrong?
Show the answer

No. Tree-based models split on thresholds of one feature at a time, so their results don't depend on the features' scale.

Interview questions

What is the difference between standardisation and normalisation?

Standardisation subtracts the mean and divides by the standard deviation, giving mean 0 and standard deviation 1 with no fixed range. Min-max normalisation rescales to a fixed range, usually 0 to 1, using the minimum and maximum, which makes it more sensitive to outliers.

Why must a scaler be fitted only on the training data?

Fitting on all data lets statistics from the test set influence training, which is data leakage and makes evaluation optimistic. Fit on training data, then transform training, validation and test data with the same fitted scaler.

Which algorithms require feature scaling?

Distance-based and gradient-based methods: KNN, k-means, SVM, PCA, regularised linear models and neural networks. Tree-based models generally don't.

What to learn next

  1. Combine scaling and encoding safely in scikit-learn pipelines and ColumnTransformer.
  2. Revisit one-hot vs label encoding.