Overview
Columns arrive in different units. An income in dollars runs to tens of thousands, an age to less than a hundred. Many models treat a large number as an important number: a distance is dominated by the column with the widest range, and gradient descent takes awkward steps when one weight needs to be thousands of times smaller than another. Scaling removes the units. Each column gets one offset to subtract and one scale to divide by. The four methods differ only in which offset and scale they choose.
A short history
Standard scores, values expressed in standard deviations from the mean, have been used in statistics since the late 1800s to compare measurements in different units. Scaling became a routine preprocessing step in machine learning because gradient descent, distance-based methods and regularised models all behave badly when columns differ by orders of magnitude. It is a shared practice with no single inventor.
How it works
- Choose a method: minmax, standard, robust or maxabs.
- Call fit on the training data. For each column it computes an offset and a scale, ignoring NaN, and stores them in offset_ and scale_.
- A constant column gets a scale of 1, so it maps to a constant and is not divided by zero.
- Call transform: subtract the offset and divide by the scale. For minmax the result is then mapped to feature_range.
- Apply the same fitted scaler to validation, test and live data. Their values may fall outside the training range.
- Call inverse_transform to return scaled values, such as model predictions, to the original units.
Watch out for
- Fitting the scaler on all the data before splitting lets the test rows shape the mean and range. Fit on the training split and only transform the rest.
- Min-max scaling depends on the two most extreme values. One outlier squeezes every other value into a narrow band. Use robust scaling or treat the outliers first.
- New data can fall outside the range seen in training, so min-max output can be below 0 or above 1 unless clip is on.
- Scaling changes the range, not the shape. A skewed column stays skewed after standardising. That needs a transformation such as a logarithm.
- Subtracting an offset turns the zeros of a sparse column into non-zero values. Use maxabs when zeros must stay zero.
Use cases
When to use it
Before any model that uses distances or gradients: k-nearest neighbours, support vector machines, linear models with a penalty, and neural networks. Tree models do not need it.
In industry
- Customer segmentation
- Marketing teams standardise spend, visit counts and tenure before k-means clustering, so no one column dominates the distances.
- Neural network training
- Inputs such as pixel intensities or sensor readings are scaled to a small common range so that gradient descent converges.
- Risk modelling
- Regularised logistic regression needs standardised inputs so that the penalty treats every coefficient alike.
Choosing it: what must hold
- Numeric columns, with the offset and scale fitted on the training data only.
- A model that is sensitive to scale: gradient-based, distance-based, kernel-based or regularised.
- A method matched to the data: standard for bell-shaped columns, robust when outliers are present, min-max for a fixed range, max-abs for sparse data.
When to choose something else
| If | Use instead |
|---|---|
| The model is tree-based, such as Random Forest or XGBoost | No scaling, since trees depend only on the order of values |
| A column is strongly skewed | A log, power or quantile transformation first |
| Outliers are extreme enough to squeeze min-max output into a narrow band | Robust scaling, or outlier treatment first |
| The column is categorical | Categorical encoding |
Math foundations
The general form
Every method subtracts an offset and divides by a scale , both computed per column on the training data.
Min-max
The smallest training value maps to and the largest to , by default 0 and 1. Everything else lands in between, in proportion.
Standardisation (z-score)
The result has mean 0 and standard deviation 1 on the training data. It says how many standard deviations a value lies from the mean. The setting ddof is , 0 or 1.
Robust scaling
The median and the interquartile range replace the mean and the standard deviation. Outliers barely move them, so the bulk of the data is scaled sensibly.
Max-abs
No offset is subtracted, so zero stays zero. The result lies between and 1 on the training data.
The inverse
Scaling is a linear map, so it can be undone exactly. This is how predictions made in scaled units are reported in real units.
Symbols
- a value before and after scaling
- the offset and scale of a column (offset_ and scale_)
- the smallest and largest training value of the column
- the low and high ends of feature_range
- the mean and standard deviation of the column on the training data
- the ddof setting (0 or 1)
- the median of the column
- the 25th and 75th percentiles of the column
- the number of training rows
Worked by hand
A training column holds 2, 4, 6 and 8. Scale the value 4 with minmax to the range 0 to 1, and the value 8 with standard scaling and ddof 0.
Under min-max the value 4 sits one third of the way up the range. Under standard scaling the value 8 is 1.342 standard deviations above the mean. A new value of 11 would map to 1.5 under min-max, outside the range.
Visual example
Loading the example.
Try this
- Step through the four methods and watch where the same cloud lands: inside the unit square, around zero, or around the median.
- Choose minmax and drag the largest income up to 600,000: every other income is squashed toward 0. Then choose robust.
- Change the row you inspect and compare its nearest neighbour in raw units with its nearest neighbour after scaling.
Code sample
import numpy as np
from impl import Scaler
from config import ScalerConfig
X_train = np.array([[1.0, 10.0], [2.0, 20.0], [3.0, 60.0]])
scaler = Scaler(ScalerConfig(method="minmax")).fit(X_train)
Z = scaler.transform(X_train) # every column now spans [0, 1]
X_back = scaler.inverse_transform(Z) # equals X_trainRead the implementation (91 lines)
"""Feature scaling: min-max, z-score, robust and max-abs, fitted per column.
NumPy only. `fit` learns one offset and one scale per column from the training data, `transform` applies them
to any data with the same columns, and `inverse_transform` undoes it. NaN values are ignored when fitting and
stay NaN when transforming.
"""
from __future__ import annotations
import numpy as np
try:
from .config import ScalerConfig
except ImportError: # run from the template's own folder
from config import ScalerConfig
def _as_2d(X) -> np.ndarray:
"""Return X as a float array of shape (n_samples, n_features); a 1-D input becomes one column."""
X = np.asarray(X, dtype=float)
if X.ndim == 1:
X = X[:, None]
if X.ndim != 2:
raise ValueError(f"X must be 1-D or 2-D, got {X.ndim} dimensions")
return X
class Scaler:
"""Column-wise scaler: transform(X) = (X - offset_) / scale_, then mapped to the range for "minmax".
After `fit`: `offset_` and `scale_` have shape (n_features,). Constant columns get scale 1 so they map
to a constant instead of dividing by zero.
"""
def __init__(self, config: ScalerConfig | None = None) -> None:
self.config = config or ScalerConfig()
self.offset_: np.ndarray | None = None
self.scale_: np.ndarray | None = None
def fit(self, X) -> "Scaler":
"""Learn the per-column offset and scale from X, shape (n_samples, n_features)."""
X = _as_2d(X)
if X.shape[0] == 0:
raise ValueError("cannot fit a scaler on zero rows")
method = self.config.method
if method == "minmax":
offset = np.nanmin(X, axis=0)
scale = np.nanmax(X, axis=0) - offset
elif method == "standard":
offset = np.nanmean(X, axis=0)
scale = np.nanstd(X, axis=0, ddof=self.config.ddof) if X.shape[0] > self.config.ddof else np.ones(X.shape[1])
elif method == "robust":
offset = np.nanmedian(X, axis=0)
q75, q25 = np.nanpercentile(X, [75, 25], axis=0)
scale = q75 - q25
else: # maxabs
offset = np.zeros(X.shape[1])
scale = np.nanmax(np.abs(X), axis=0)
scale = np.where(np.isfinite(scale) & (scale > 0), scale, 1.0)
self.offset_, self.scale_ = offset, scale
return self
def _check(self, X) -> np.ndarray:
if self.offset_ is None:
raise RuntimeError("call fit before transform")
X = _as_2d(X)
if X.shape[1] != self.offset_.shape[0]:
raise ValueError(f"X has {X.shape[1]} columns, the scaler was fitted on {self.offset_.shape[0]}")
return X
def transform(self, X) -> np.ndarray:
"""Scale X, shape (n_samples, n_features), with the statistics learned in `fit`."""
X = self._check(X)
out = (X - self.offset_) / self.scale_
if self.config.method == "minmax":
low, high = self.config.feature_range
out = low + out * (high - low)
if self.config.clip:
out = np.clip(out, low, high)
return out
def inverse_transform(self, X) -> np.ndarray:
"""Map scaled values back to the original units (exact unless `clip` changed a value)."""
X = self._check(X)
if self.config.method == "minmax":
low, high = self.config.feature_range
X = (X - low) / (high - low)
return X * self.scale_ + self.offset_
def fit_transform(self, X) -> np.ndarray:
"""Fit on X and return the scaled X."""
return self.fit(X).transform(X)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 10, run with
python3 -m unittest -v
Practice
Create a table with one column in the thousands, one between 0 and 1, and one with a single huge outlier. Fit a Scaler for each of the four methods through ScalerConfig and print offset_, scale_ and the minimum, mean and maximum of each transformed column. Check that inverse_transform returns the original table. Then transform a new row that lies outside the training range.
Check on learning
- A k-nearest-neighbours model uses age in years and income in dollars, unscaled. Which column decides who the neighbours are, and why?
A way to think about it
Write the squared distance between two people as a sum of two terms and compare typical sizes of each term.
- A column has 999 values between 0 and 10 and one value of 10000. Compare where the 999 values end up under minmax and under robust scaling.
A way to think about it
Work out the scale each method divides by. See how much of the output range is left for the ordinary values.
- Decision trees give the same splits whether or not the columns are scaled. Why is that, and why is the same not true for a penalised linear model?
A way to think about it
A tree asks only whether a value is above a threshold, which survives any increasing rescaling. A penalty compares the sizes of the weights across columns.
- You scale the whole dataset, then split it and report test accuracy. A reviewer objects. How large is the harm likely to be, and why is it still wrong in principle?
A way to think about it
Estimate how much a mean changes when a share of rows is added. Then separate the size of the effect from the rule that test data must not influence training.