Sign in

Scaling

Feature scaling

A scaler that puts features on a common scale by standard, min-max, robust or max-abs scaling per column, or unit length per row.

Overview

One column may hold ages from 0 to 100 and another incomes in the tens of thousands. Many models read size as importance, so the income column would dominate for no good reason. Scaling removes the units. Each column is shifted and stretched so that all columns cover a similar range, and the model can weigh them by what they say instead of how large their numbers are. The shift and stretch are learned once from the training data and reused everywhere.

A short history

Scaling comes from statistics, where the standard score has long been used to compare measurements on different units. It has no single inventor. In machine learning it matters because distance and gradient methods are sensitive to units. Yann LeCun and colleagues set out the argument for neural networks in the 1998 chapter Efficient BackProp, showing that centred, equally scaled inputs make gradient descent converge faster. Robust variants based on the median and percentiles come from robust statistics.

How it works

  1. In fit, compute one offset and one scale per column from the training data, according to method.
  2. Standard uses the mean and standard deviation, minmax the minimum and the range, robust the median and the distance between two percentiles, maxabs the largest absolute value.
  3. A constant column would give a scale of zero, so its scale is set to 1 and the column stays constant.
  4. In transform, subtract the offset and divide by the scale. For minmax, then map the result onto the range from range_min to range_max.
  5. The l2 method works differently: it learns nothing and divides each row by its Euclidean length.
  6. inverse_transform undoes every column method exactly, and state with from_state carries the fitted numbers through JSON.

Watch out for

  • Fitting the scaler on all the data lets the validation and test rows influence the mean and scale, which leaks information and flatters the score. Fit on the training split only.
  • Min-max scaling is set by the two most extreme training values, so one outlier squeezes every other value into a narrow band.
  • New data can fall outside the training range, so min-max outputs below range_min or above range_max are possible at serving time.
  • Standard scaling subtracts the mean, which turns the zeros of a sparse column into non-zeros. Use maxabs when zeros must stay zeros.
  • The l2 method throws away each row's length, so it cannot be inverted and the template raises an error if you try.

Use cases

When to use it

Before any model that is sensitive to feature scale: gradient descent, k-nearest neighbours, support vector machines, PCA and regularised linear models. Tree models do not need it.

In industry

Banking
A credit model mixes income in tens of thousands with ratios below one. Standard scaling lets a regularised logistic regression penalise all coefficients fairly.
Customer segmentation
Clustering and nearest neighbour methods measure distance. Without scaling, the column with the largest units decides every distance.
Manufacturing
Sensor channels have very different ranges and occasional spikes. Robust scaling by median and percentile range keeps the spikes from squeezing the normal readings.

Choosing it: what must hold

  • Numeric features on different units or ranges.
  • A model sensitive to scale: gradient descent, k-nearest neighbours, support vector machines, PCA or regularised linear models.
  • Offsets and scales learned on the training split only and reused unchanged on validation and serving data.

When to choose something else

IfUse instead
The model is a decision tree or a tree ensembleNo scaling. Random Forest, XGBoost and LightGBM split on order and ignore scale
A column is heavily skewed, not just on a different scaleA log transform from the feature engineering lesson, then scaling
The column has strong outliersThe robust method of this lesson, or clip the outliers first with the cleaning lesson

Math foundations

  1. Standard scaling

    z=x−μσz = \frac{x - \mu}{\sigma}

    Subtract the column mean and divide by its standard deviation. The training column ends with mean 0 and standard deviation 1. The template uses the population standard deviation.

  2. Min-max scaling

    x′=a+x−xmin⁡xmax⁡−xmin⁡ (b−a)x' = a + \frac{x - x_{\min}}{x_{\max} - x_{\min}}\,(b - a)

    Maps the training minimum to aa and the training maximum to bb, by default 0 and 1. Everything in between keeps its relative position.

  3. Robust scaling

    x′=x−median⁡Qhigh−Qlowx' = \frac{x - \operatorname{median}}{Q_{\text{high}} - Q_{\text{low}}}

    Uses the median and the distance between two percentiles, by default the 25th and 75th. Outliers hardly move either, so the bulk of the data is scaled sensibly.

  4. Max-abs scaling

    x′=xmax⁡i∣xi∣x' = \frac{x}{\max_i |x_i|}

    Divides by the largest absolute value without shifting. The result lies between −1-1 and 1 and zeros stay zeros.

  5. Unit length per row

    x′=x∥x∥2,∥x∥2=∑jxj2\mathbf{x}' = \frac{\mathbf{x}}{\lVert \mathbf{x} \rVert_2}, \qquad \lVert \mathbf{x} \rVert_2 = \sqrt{\sum_j x_j^{2}}

    Each row is divided by its own length. After this, the dot product of two rows is the cosine of the angle between them.

  6. Undoing the scaling

    x=z σ+μx = z\,\sigma + \mu

    The inverse of standard scaling. It is how a prediction made on the scaled target is turned back into real units.

Symbols

xx
one value of a column
z,  x′z,\; x'
the scaled value
μ, σ\mu,\, \sigma
mean and population standard deviation of the training column
xmin⁡, xmax⁡x_{\min},\, x_{\max}
smallest and largest training value of the column
a, ba,\, b
range_min and range_max
Qlow, QhighQ_{\text{low}},\, Q_{\text{high}}
the two percentiles of the robust scale
x\mathbf{x}
one row as a vector
∥x∥2\lVert \mathbf{x} \rVert_2
Euclidean length of a row

Worked by hand

A training column holds 1, 2 and 3. Scale it with the standard method, then with min-max onto 0 to 1.

μ=1+2+33=2,σ=(1−2)2+(2−2)2+(3−2)23=23=0.8165\mu = \frac{1 + 2 + 3}{3} = 2, \qquad \sigma = \sqrt{\frac{(1-2)^2 + (2-2)^2 + (3-2)^2}{3}} = \sqrt{\frac{2}{3}} = 0.8165
z=(1−20.8165,  2−20.8165,  3−20.8165)=(−1.2247,  0,  1.2247)z = \left(\frac{1 - 2}{0.8165},\; \frac{2 - 2}{0.8165},\; \frac{3 - 2}{0.8165}\right) = (-1.2247,\; 0,\; 1.2247)
x′=(1−13−1,  2−13−1,  3−13−1)=(0,  0.5,  1)x' = \left(\frac{1 - 1}{3 - 1},\; \frac{2 - 1}{3 - 1},\; \frac{3 - 1}{3 - 1}\right) = (0,\; 0.5,\; 1)

Standard scaling centres the column at 0 with spread 1. Min-max pins the ends to 0 and 1. A new value of 5 would become 3.674 and 2, outside the range seen in training.

Visual example

Loading the example.

Try this

  • Drag the largest training value out to 60 with the standard method and watch the other points squeeze together.
  • Switch to robust with the same wild value: the bulk keeps its spread and only the wild value moves away.
  • With minmax, move the new value above the largest training value. It lands outside 0 to 1.

Code sample

import numpy as np
from impl import Scaler
from config import ScalingConfig

X_train = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
scaler = Scaler(ScalingConfig(method="standard")).fit(X_train)
Z = scaler.transform(X_train)             # every column: mean 0, std 1
back = scaler.inverse_transform(Z)        # equals X_train
print(Z.mean(axis=0), Z.std(axis=0), np.allclose(back, X_train))
Read the implementation (104 lines)
"""Feature scaling: standard, min-max, robust, max-abs (per column) and L2 (per row).

NumPy only. Every column method is the same affine map `(x - offset_) / scale_ * gain + shift`, with the
offset and scale learned in `fit`, so `transform` and `inverse_transform` are exact inverses.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import ScalingConfig
except ImportError:  # run from the template's own folder
    from config import ScalingConfig


def _as_table(X) -> np.ndarray:
    """Return X as a float array of shape (n_rows, n_columns)."""
    X = np.asarray(X, dtype=float)
    if X.ndim != 2:
        raise ValueError(f"expected shape (n_rows, n_columns), got {X.shape}")
    return X


class Scaler:
    """Scale the columns (or, for "l2", the rows) of a table.

    After `fit` (column methods):
        offset_  shape (n_columns,), subtracted from each column
        scale_   shape (n_columns,), each column is divided by it. A column with zero spread gets scale 1,
                 so a constant column maps to a constant instead of dividing by zero.
    """

    def __init__(self, config: ScalingConfig | None = None) -> None:
        self.config = config or ScalingConfig()
        self.offset_: np.ndarray | None = None
        self.scale_: np.ndarray | None = None

    def fit(self, X) -> "Scaler":
        """Learn offset_ and scale_ from X, shape (n_rows, n_columns)."""
        X = _as_table(X)
        cfg = self.config
        zeros = np.zeros(X.shape[1])
        if cfg.method == "standard":
            offset, scale = X.mean(axis=0), X.std(axis=0)
        elif cfg.method == "minmax":
            offset, scale = X.min(axis=0), X.max(axis=0) - X.min(axis=0)
        elif cfg.method == "robust":
            low, high = np.percentile(X, [cfg.quantile_low, cfg.quantile_high], axis=0)
            offset, scale = np.median(X, axis=0), high - low
        elif cfg.method == "maxabs":
            offset, scale = zeros, np.abs(X).max(axis=0)
        else:  # l2 works row by row and has nothing to learn
            offset, scale = zeros, np.ones(X.shape[1])
        self.offset_ = offset
        self.scale_ = np.where(scale == 0.0, 1.0, scale)
        return self

    def _check(self, X) -> np.ndarray:
        if self.offset_ is None:
            raise RuntimeError("call fit before transform")
        X = _as_table(X)
        if X.shape[1] != self.offset_.shape[0]:
            raise ValueError(f"fitted on {self.offset_.shape[0]} columns, got {X.shape[1]}")
        return X

    def transform(self, X) -> np.ndarray:
        """Scale X, shape (n_rows, n_columns), with the numbers learned in fit. Same shape out."""
        X = self._check(X)
        cfg = self.config
        if cfg.method == "l2":
            norms = np.linalg.norm(X, axis=1, keepdims=True)
            return X / np.where(norms == 0.0, 1.0, norms)
        Z = (X - self.offset_) / self.scale_
        if cfg.method == "minmax":
            Z = Z * (cfg.range_max - cfg.range_min) + cfg.range_min
        return Z

    def inverse_transform(self, Z) -> np.ndarray:
        """Undo `transform`. Not defined for "l2", which throws the row lengths away."""
        Z = self._check(Z)
        cfg = self.config
        if cfg.method == "l2":
            raise ValueError("l2 scaling cannot be inverted: the row lengths are not kept")
        if cfg.method == "minmax":
            Z = (Z - cfg.range_min) / (cfg.range_max - cfg.range_min)
        return Z * self.scale_ + self.offset_

    def fit_transform(self, X) -> np.ndarray:
        """`fit(X)` then `transform(X)`."""
        return self.fit(X).transform(X)

    def state(self) -> dict:
        """The fitted numbers as plain lists, ready for json.dump, so serving can rebuild the same scaler."""
        if self.offset_ is None:
            raise RuntimeError("call fit before state")
        return {"config": self.config.to_dict(), "offset": self.offset_.tolist(), "scale": self.scale_.tolist()}

    @classmethod
    def from_state(cls, state: dict) -> "Scaler":
        """Rebuild a fitted scaler from the dict returned by `state`."""
        scaler = cls(ScalingConfig.from_dict(state["config"]))
        scaler.offset_ = np.asarray(state["offset"], dtype=float)
        scaler.scale_ = np.asarray(state["scale"], dtype=float)
        return scaler
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Take a column with the values 1, 2, 3, 4 and 1,000. Fit Scaler(ScalingConfig(method=m)) for standard, minmax and robust, and print the transformed first four values each time. Say which method keeps them usefully spread out, then check that inverse_transform returns the original column.

Check on learning

  1. Why must the scaler be fitted on the training split only, even though using all the data would give a more accurate mean?
    A way to think about it

    Ask what the validation score is supposed to measure, and what the model would know about validation rows if their values shaped the scaling.

  2. Gradient descent on two features, one ranging over 0 to 1 and one over 0 to 100,000, is slow. Explain why, in terms of the shape of the loss surface.
    A way to think about it

    Picture the contour lines of the loss: a long narrow valley. Think about which direction a single learning rate can serve well.

  3. With the column 1, 2, 3, 4, 1,000, where do the first four values land under min-max scaling, and why does robust scaling behave differently?
    A way to think about it

    Compute the min-max values. Then ask which statistics the 1,000 can move: the maximum, the mean, the median, the quartiles.

  4. A decision tree splits on thresholds. Would standard scaling change its predictions? What does that say about which models need scaling?
    A way to think about it

    A split asks whether a value is above a threshold. Check whether that ordering changes when the column is shifted and stretched.

  5. At serving time a feature arrives in different units than in training (metres instead of centimetres). The scaler runs without error. What does the model see, and how could the pipeline catch it?
    A way to think about it

    Push a typical value through (x−μ)/σ(x - \mu)/\sigma with the training numbers. Then consider a range check on the inputs before scaling.