Learn
Mini widget·

Scaling & Standardization

A $2,000 pay gap outweighed eight years of service 250 to 1

You run kNN over an employee table to find whoever most resembles a given person. Two candidates come up. A differs only in salary, by $2,000, with identical service. B differs only in service, by 8 years, on identical pay.

Obviously A is the closer match. But compute a Euclidean distance on the raw numbers and this is what comes back.

CandidateSalary gapService gapDistance on the raw numbers
A — the one a person would pick$2,000none2,000
Bnone8 years8

A is scored 250 times further away. The algorithm returns whichever is closer, so it returns B. Salary is only bigger because it is counted in dollars — and on that basis alone, years of service stopped counting at all.

Scaling exists to deal with this. But describing it as "preprocessing that makes the units match" only gets you halfway. What it actually does is decide how much each variable counts — and different scalers decide differently.

The key question

Does this model compute distances? If so, which variable is currently dominating them?

1

Concept

Removing the units exposes the weights

Four scalers

All of them have the same shape: subtract something, divide by something. Only the two somethings differ.

Standardisation

(x − μ) / σ
0

Centre 0, SD 1. Unbounded, keeps the shape.

Min-Max

(x − min) / (max − min)
01

Exactly 0 to 1. One outlier sets the whole range.

Robust scaling

(x − median) / IQR

Uses quartiles, so outliers do not set the scale.

Unit norm

x / ‖x‖

Scales each row, not each column. Direction only.

x=xcd(c=centre,  d=scale)x' = \frac{x - c}{d} \qquad (c = \text{centre}, \; d = \text{scale})
  • Standardisation — centre on the mean, divide by the SD. Result has mean 0 and SD 1, with no bound on the range.
  • Min-max — centre on the minimum, divide by the range. Result lands exactly between 0 and 1.
  • Robust scaling — centre on the median, divide by the IQR. Stops outliers from setting the scale.
  • Unit norm — the only one that works across a row rather than down a column. Discards magnitude, keeps direction.
ScalerOutput rangeGood forWeak against
StandardisationUnbounded, centred on 0Most models; the default choiceOutliers inflate σ
Min-MaxExactly 0 to 1Neural nets, images, bounded inputsOne outlier compresses everything else
Robust scalingUnbounded, centred on the medianData with known outliersNeeds a meaningful IQR
MaxAbs−1 to 1, zero stays zeroSparse matricesStill driven by the largest value
Unit normEach row has length 1Text vectors, cosine similarityDiscards magnitude entirely
Quantile / rankUniform or normal by constructionBadly behaved distributionsDistorts distances between values

Scaling is not normalising

The most persistent confusion in the area. Standardisation shifts and stretchesa distribution and leaves its shape untouched. Standardise data with a skewness of 3 and the skewness is still 3.

What you wantWhat to useWhat changes
Put variables on comparable footingScalingCentre and width
Straighten a skewed distributionLog or square-root transformThe shape
Force everything into 0–1Min-maxThe range (shape unchanged)
Make it closer to normalBox–Cox or quantile transformThe whole distribution
Reduce the pull of extremesWinsorise or robust scalingThe weight given to outliers

When you need both

Feeding skewed data into a distance-based model calls for the transform first and the scaler second. Reverse them and the transform is applied to values that have already been shifted, which gives a different result.

2

Why It Matters

Anything that measures distance depends on this

Everything distance-based is affected

Euclidean distance squares each axis's difference and adds them up. When the axes carry different units, that sum is essentially the largest-unit axis and nothing else. The other axes may as well not exist.

d=(x1y1)2+(x2y2)2+d = \sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \cdots}
MethodScalingWhy
k-means, kNN, SVM, DBSCANRequiredDistance is computed in raw units
PCARequiredComponents chase whichever variable has the largest variance
Ridge, Lasso, Elastic NetRequiredThe penalty applies to coefficient size
Neural networksRequiredGradients behave badly on mismatched scales
Linear regression, unpenalisedNot neededCoefficients absorb the units
Decision trees, random forest, boostingNot neededSplits depend only on order
Naive Bayes, chi-squareNot neededNo distance is involved

The bottom three rows matter as much as the top four. Trees do not need scaling, because a split of the form "salary > 50,000" uses order only — apply any monotonic transform and you get exactly the same split.

Penalised regression fails especially quietly

Ridge and Lasso penalise the size of the coefficients — and coefficient size depends on the variable's units. Measure salary in dollars rather than thousands and the coefficient becomes tiny, so the penalty barely touches it.

Same variable, different units

Salary in dollars: coefficient 0.0031 → effectively unpenalised

Salary in thousands: coefficient 3.1 → properly penalised

The model has not changed, yet units decide which variables survive. An unscaled Lasso drops large-unit variables first.

PCA simply follows the largest variance

Principal components find the direction of maximum variance. If salary has a variance a million times larger than years of service, the first component is the salary axis, and nothing else contributes.

This is why PCA distinguishes between running on the correlation matrix and on the covariance matrix. Correlation-based PCA is precisely PCA after standardising.

There is a PCA that should not be scaled

When every variable shares a unit and the differences in variance are themselves the signal, leave them alone. Thirty-two channels from the same sensor array are the classic case: which channel moves most is the information.

3

How It Works

Pick one of four, and fit it on training rows only

1. Choosing one

SituationUseWhy
No particular reason to do otherwiseStandardisationThe most reliable default
Neural network inputsMin-max or standardisationMatches the working range of activations
Known outliers in the dataRobust scalingKeeps outliers from setting the scale
Sparse matrices (mostly zeros)MaxAbsZero stays zero, so sparsity survives
Text embeddings, cosine similarityUnit normOnly the direction is being compared
A badly misbehaved distributionQuantile transformKeeps the ranks, forces the shape

2. Fit on training rows only

A scaler learns parameters. The mean, the SD, the minimum, the maximum, the median — every one of them is a number extracted from data. The moment those numbers have seen the test set, you have leakage.

Table 1 The correct order for applying a scaler, and the usual mistakes
StepCorrectLeaky
Compute μ and σFrom the training rows onlyFrom the whole dataset
Transform the training setfit_transformfit_transform
Transform the test settransformfit_transform
Inside cross-validationRefit on each foldFit once, outside the loop
At serving timeReuse the stored training μ and σRecompute on the incoming batch

Row three is the one that goes wrong most often. The test set should get transform alone; call fit_transform and it is standardised against its own mean, which flatters the score.

3. Categorical and binary columns

Column typeTreatmentNote
One-hot dummiesUsually leave aloneAlready 0/1, so no scale problem
Ordinal integers (1, 2, 3)Standardising is defensibleOnly if equal spacing is acceptable
Binary 0/1Leave aloneScaling only makes it harder to read
CountsTransform, then scaleLog or square root comes first
Already a proportion (0–1)Usually leave aloneUnnecessary if the other variables are comparable

4. Where this breaks in production

  • Store the training μ and σ — recompute them on each incoming batch and the same input maps to different values from batch to batch.
  • Values outside the training range — min-max stops guaranteeing 0 to 1. Decide up front whether to clip or allow it.
  • Drift — a stored μ goes stale as the population moves. Schedule refits or monitor for drift.
  • Bundle it in a pipeline — persist the scaler and the model together and the order cannot be got wrong.
  • After missing-value handling — leftover blanks corrupt the μ and σ before anything else happens.
4

Example

One scaler, completely different clusters

In practice: one scaler, completely different clusters

Customers clustered with k-means on age, annual spend and purchase frequency. Changing nothing but the scaler produced entirely different segments.

ScalerWhat separates the clustersLargest clusterRead
NoneSpend, and nothing else78%Effectively a three-way split on spend
Min-maxMostly spend61%One top spender sets the scale
StandardisationAll three fairly evenly41%Segments you can actually describe
Robust scalingAll three fairly evenly38%Similar to standardisation, better balanced

Same algorithm, same data, same k. One line of preprocessing changed — and the answer to "how do our customers divide up" changed with it.

The lesson here

Any report of a clustering result has to state which scaler produced it. A scaler is not invisible plumbing; it is the modelling decision that defines what counts as similar.

In practice: the 3-point gap between validation and production

A classifier cross-validated at 91.2% accuracy and ran at roughly 88% once deployed. The code turned out to be scaling outside the cross-validation loop.

Same data, same model

Scaler fitted outside the loop: CV accuracy 91.2%

Refitted on every fold: CV accuracy 88.4%

Actual production accuracy: 88.1%

The second figure predicted production almost exactly. The first was a three-point illusion created by letting each held-out fold contribute to the mean it was standardised against.

Even something as innocuous as standardisation leaks. The effect is small, but the direction is always optimistic, so it always shows up as a drop after deployment.

Common misunderstandings

Misconception 1

❌ Scaling makes the data normal.

It changes the centre and the width and leaves the shape alone. Skewness and kurtosis come through untouched. Changing the shape requires a transform — a log, a Box–Cox.

Misconception 2

❌ Min-max is safest because it bounds everything to 0–1.

A single outlier sets that range. One person on $150,000 compresses everybody else below 0.2. And in production, values outside the training range break the 0–1 guarantee anyway.

Misconception 3

❌ It is only preprocessing, so the full dataset is fine.

A scaler learns numbers from data. Fit it on everything and the test set's mean and variance flow into training, which makes the score optimistic.

Misconception 4

❌ Scaling everything costs nothing.

On tree models it changes no result and destroys interpretability. A rule reading "salary > 50,000" becomes "salary > 0.37", which nobody can act on.

Misconception 5

❌ Which scaler you use is a matter of taste.

The scaler sets the weight of every variable. Your clusters, your kNN neighbours and the features Lasso discards all depend on it. It belongs in the writeup next to the result.

5

Interactive

Change the scaler and watch the neighbour change

Change the scaler and watch the neighbour change

One query employee and two candidates. A differs by $2,000 in salary alone; B by 8 years of service alone. Which one is nearer is decided by the scaler.

One query employee and two candidate neighbours. Which one is "closer" is decided by the scaler, not the data.

No scaling — raw units

CandidateSalaryYearsDistance from Q
Q$52,0006
A$2,000 more in salary, same years$54,00062.00e+3
B8 more years, same salary$52,000148.00e+0

Nearest neighbour

B

How much further B is

4.0e-3×

In raw units a salary gap of $2,000 and a service gap of 8 years get added together as if they were the same kind of number. A — who differs from Q by one modest raise and nothing else — scores as 250 times more distant than B, and kNN picks B.

Choosing a scaler is choosing how much each variable counts.

What to look for

  • Without scaling, why does B come back as the nearer one?
  • After standardising, how many SDs separate A from Q?
  • Why does min-max push B furthest away of the three?
  • Why is the multiple smallest under robust scaling?
  • All three scalers pick A — so why do the multiples differ?

Learning points

Without scaling, the largest-unit variable becomes the entire distance.

Different scalers can agree on the ranking and still assign very different weights.

With an outlier present, min-max under-weights, standardisation lands between, and robust scaling is unaffected.

Key takeaways

It sets the weights

Scaling decides what counts as far

  • Unscaled, the largest unit wins
  • Distance models need it, trees do not
  • Choosing a scaler is a modelling choice

Scaling is not normalising

The distribution keeps its shape

  • Skew survives standardisation untouched
  • Use a transform to change shape
  • Min-max bounds the range, not the shape

Fit on training only

A scaler learns parameters

  • transform the test set, never fit it
  • Refit inside every CV fold
  • Store μ and σ for serving

The question is not "should I scale?"

It is "how much weight does this scaler give each variable?" A scaler looks like invisible preprocessing and is really the step that defines what counts as similar.

How does this apply to real data?

Scaling is the first step after the train/test split, and bundling it into a pipeline makes the ordering impossible to get wrong. In SKARI you can check the following alongside.

Scalers

Standard, Min-Max, Robust, MaxAbs, Quantile

Distance-based analysis

k-means, kNN, DBSCAN, Hierarchical

Dimension reduction

PCA, t-SNE, UMAP, Factor Analysis

Leakage checks

Pipeline, CV Fold Isolation, Leakage Check

Once this clicks, you can answer questions like these.

  • Does this model compute distances at all?
  • Unscaled, which variable is driving the result right now?
  • Is an outlier setting the scale for everyone else?
  • Were μ and σ fitted on the training rows only?
  • Have the production μ and σ been stored anywhere?
Now try it on real dataOpen in Lab

Go Deeper

Categorical Encoding