TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Min-Max, Z-Score, Robust and Max-Abs Scaling

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, x′=(x−a)/bx' = (x - a)/b, with a different choice of aa and bb. 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:

0.00.20.40.60.81.0050100150200x₁ salary ($k)x₂ debt ratioOriginal units−5005050100150200Distances as kNN sees themEqual axes: x₂ spans just 1 unit,so salary decides the distances.class Aclass B

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 k=5k = 5. 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 kk: the gap stays.

The four linear scalers

Scaler Formula Result Sensitive to outliers?
Min-max x′=x−min⁡max⁡−min⁡x' = \dfrac{x - \min}{\max - \min} training range mapped to [0,1][0, 1] very: one extreme value squeezes all others
Z-score (standardisation) z=x−μσz = \dfrac{x - \mu}{\sigma} mean 0, standard deviation 1 yes: μ\mu and σ\sigma are pulled by outliers
Robust x′=x−median⁡Q3−Q1x' = \dfrac{x - \operatorname{median}}{Q_3 - Q_1} median 0, interquartile range 1 no: median and quartiles ignore the extremes
Max-abs x′=xmax⁡∣x∣x' = \dfrac{x}{\max \lvert x \rvert} values in [−1,1][-1, 1], zero stays zero very

Here μ\mu and σ\sigma are the training mean and standard deviation (scikit-learn uses the population formula, dividing by nn), and Q1,Q3Q_1, Q_3 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 [0,1][0, 1] 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

python · try it yourself
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 σ\sigma 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:

python · try it yourself
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: StandardScaler for 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: MaxAbsScaler or StandardScaler(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 [0,1][0, 1] after min-max scaling: values beyond the training range map outside it. Use clip=True only if you understand what clipping does to new extremes.

Practice

  1. 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: (12−2)/8=1.25(12 - 2)/8 = 1.25. Z-score: μ=6\mu = 6, σ=8≈2.83\sigma = \sqrt{8} \approx 2.83, so z=6/2.83≈2.12z = 6/2.83 \approx 2.12. Robust: median 6, Q1=4Q_1 = 4, Q3=8Q_3 = 8 (NumPy's linear interpolation), IQR 4, so (12−6)/4=1.5(12 - 6)/4 = 1.5.

  1. 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?

  1. Min-max
  2. Z-score
  3. Robust (median and IQR)
  4. Max-abs

After MinMaxScaler is fitted on training data, a test value is larger than the training maximum. What is its scaled value?

  1. Exactly 1
  2. Greater than 1
  3. 0
  4. An error is raised

Which scaler keeps a sparse matrix sparse?

  1. StandardScaler with default settings
  2. MaxAbsScaler
  3. MinMaxScaler
  4. RobustScaler with centring

In the scaling lab, why does kNN on raw salary and debt ratio reach only about 60% accuracy?

  1. kNN cannot use two features
  2. Salary differences dominate the Euclidean distance, so the debt ratio is ignored
  3. The data has missing values
  4. k is too small