Min-Max, Z-Score, Robust and Max-Abs Scaling
A salary in dollars ranges over tens of thousands; a debt ratio lies between 0 and 1. To a person both columns matter. To a k-nearest-neighbour model, which compares rows by Euclidean distance, a salary difference of 1,000 outweighs the largest possible debt-ratio difference a thousand times over, so the debt ratio is simply ignored. Gradient descent has a related problem: features on very different scales make the loss surface a long, narrow valley that takes many small steps to cross. Regularisation penalises all coefficients with one strength, which is only fair when the features are on comparable scales.
Scaling puts the features on comparable scales. This lesson covers the four linear scalers among the eight methods: each one shifts and stretches a column, , with a different choice of and . The next lesson covers the other four, which change the shape of a distribution or work per row. For a first introduction, see ML Scale.
See the effect
In the lab, two classes depend on both salary and debt ratio. Switch the scaling and watch the right-hand plot, which draws the training points in the space where kNN measures distance, with equal units on both axes:
On raw values the points form a flat line: debt ratio spans 1 unit, salary about 180, so neighbours are chosen by salary alone and the regions are vertical stripes. Test accuracy on 400 new points is 60.5 % with . Standardising or min-max scaling (both fitted on the 60 training points only) lets both features count, and accuracy rises to 88.8 % for both. Try other values of : the gap stays.
The four linear scalers
| Scaler | Formula | Result | Sensitive to outliers? |
|---|---|---|---|
| Min-max | training range mapped to | very: one extreme value squeezes all others | |
| Z-score (standardisation) | mean 0, standard deviation 1 | yes: and are pulled by outliers | |
| Robust | median 0, interquartile range 1 | no: median and quartiles ignore the extremes | |
| Max-abs | values in , zero stays zero | very |
Here and are the training mean and standard deviation (scikit-learn uses the population formula, dividing by ), and the 25th and 75th percentiles of the training data. Every statistic comes from the training data; validation and test data are transformed with the same numbers, so their values may fall outside after min-max scaling, and that is correct.
Max-abs has a special use: it does not shift the data, so a sparse matrix (mostly zeros, like word counts) stays sparse. Subtracting a mean would turn every zero into a non-zero value and blow up memory. StandardScaler(with_mean=False) is the other sparse-safe option.
From scratch
import numpy as np
rng = np.random.default_rng(0)
train = np.round(rng.normal(50, 10, 9), 1)
train = np.append(train, 400.0) # one extreme value (data error or rare case)
test = np.array([45.0, 60.0, 80.0])
stats = {
"min-max": (train.min(), train.max() - train.min()),
"z-score": (train.mean(), train.std()),
"robust": (np.median(train), np.subtract(*np.percentile(train, [75, 25]))),
"max-abs": (0.0, np.abs(train).max()),
}
print("train:", train.tolist())
for name, (a, b) in stats.items():
tr = (train - a) / b
te = (test - a) / b
print(f"{name:8s} a={a:7.2f} b={b:7.2f} train 1st..9th: {tr[:9].min():6.2f}..{tr[:9].max():5.2f}"
f" outlier: {tr[9]:6.2f} test: {np.round(te, 2).tolist()}")train: [51.3, 48.7, 56.4, 51.0, 44.6, 53.6, 63.0, 59.5, 43.0, 400.0]
min-max a= 43.00 b= 357.00 train 1st..9th: 0.00.. 0.06 outlier: 1.00 test: [0.01, 0.05, 0.1]
z-score a= 87.11 b= 104.46 train 1st..9th: -0.42..-0.23 outlier: 3.00 test: [-0.4, -0.26, -0.07]
robust a= 52.45 b= 9.45 train 1st..9th: -1.00.. 1.12 outlier: 36.78 test: [-0.79, 0.8, 2.92]
max-abs a= 0.00 b= 400.00 train 1st..9th: 0.11.. 0.16 outlier: 1.00 test: [0.11, 0.15, 0.2]
The nine ordinary values span about 30 units. With min-max and max-abs scaling, the one extreme value takes over the whole range: the nine ordinary training values are squeezed into a band of width 0.06 (min-max) or 0.05 (max-abs), so they become almost indistinguishable. The z-score is affected too: the outlier inflates to 104, and the nine values end up between -0.42 and -0.23, while the robust scaler keeps the ordinary values well spread (-1.00 to 1.12) and simply leaves the outlier far out at 36.78. If a column has outliers you want to keep, use RobustScaler; if the extreme value is an error, fix it in cleaning first.
In scikit-learn
The four classes are MinMaxScaler, StandardScaler, RobustScaler and MaxAbsScaler. All follow the same fit / transform contract and store what they learned (data_min_, mean_, scale_, center_, max_abs_). As always, put them in a pipeline so cross-validation fits them per fold:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MaxAbsScaler, MinMaxScaler, RobustScaler, StandardScaler
X, y = load_wine(return_X_y=True)
print("feature ranges from", round(float(np.ptp(X, axis=0).min()), 2), "to", round(float(np.ptp(X, axis=0).max()), 1))
cv = StratifiedKFold(5, shuffle=True, random_state=0)
for scaler in [None, MinMaxScaler(), StandardScaler(), RobustScaler(), MaxAbsScaler()]:
pipe = make_pipeline(scaler, KNeighborsClassifier(n_neighbors=5)) if scaler else KNeighborsClassifier(n_neighbors=5)
acc = cross_val_score(pipe, X, y, cv=cv)
name = type(scaler).__name__ if scaler else "no scaling"
print(f"{name:15s} accuracy {acc.mean():.3f}")feature ranges from 0.53 to 1402.0
no scaling accuracy 0.663
MinMaxScaler accuracy 0.972
StandardScaler accuracy 0.961
RobustScaler accuracy 0.955
MaxAbsScaler accuracy 0.955
The wine data (178 wines, 13 chemical measurements, 3 cultivars) has features whose ranges differ by a factor of more than 2,000 (from 0.53 to 1402) (one column, proline, is in the hundreds to over a thousand). Without scaling, kNN reaches 0.663 accuracy in 5-fold stratified cross-validation; any of the four scalers lifts it to 0.955 or more. The differences between the scalers are small here because the wine data has few extreme values.
Which one?
- Default:
StandardScalerfor linear models, SVMs, kNN, PCA and neural networks. - Bounded inputs wanted (some neural-network inputs, image pixels):
MinMaxScaler, after removing errors. - Outliers you keep:
RobustScaler. - Sparse data:
MaxAbsScalerorStandardScaler(with_mean=False). - Tree models: none needed; see Which Models Need Scaling.
Pitfalls
- Fitting the scaler on all data before splitting: the test set's mean and range leak into training. The effect on the score is often small, but the procedure is wrong and the leakage lab shows cases where it is not small.
- Scaling the target by accident together with the features, then reporting errors in scaled units. Scale targets only on purpose (
TransformedTargetRegressor), and report errors in original units. - Scaling one-hot columns with z-scores: usually harmless, but it destroys sparsity and the 0/1 meaning; scale numeric columns only, with a
ColumnTransformer. - Expecting test values in after min-max scaling: values beyond the training range map outside it. Use
clip=Trueonly if you understand what clipping does to new extremes.
Practice
- A training column has values 2, 4, 6, 8, 10. What do min-max, z-score and robust scaling give for a new value 12? (Use the population standard deviation.)
Answer
Min-max: . Z-score: , , so . Robust: median 6, , (NumPy's linear interpolation), IQR 4, so .
- Why does subtracting the mean ruin a sparse bag-of-words matrix?
Answer
Most entries are 0. After subtracting a column mean that is not zero, almost every entry becomes non-zero, so the sparse matrix must be stored densely: a matrix of 100,000 documents by 50,000 words would need 5 billion numbers.
Test yourself
Which scaler is least affected by a few extreme values?
- Min-max
- Z-score
- Robust (median and IQR)
- Max-abs
After MinMaxScaler is fitted on training data, a test value is larger than the training maximum. What is its scaled value?
- Exactly 1
- Greater than 1
- 0
- An error is raised
Which scaler keeps a sparse matrix sparse?
- StandardScaler with default settings
- MaxAbsScaler
- MinMaxScaler
- RobustScaler with centring
In the scaling lab, why does kNN on raw salary and debt ratio reach only about 60% accuracy?
- kNN cannot use two features
- Salary differences dominate the Euclidean distance, so the debt ratio is ignored
- The data has missing values
- k is too small