Sign in

Transformation

Data transformation (power, quantile and unit-norm)

Changes the shape of a column's distribution, by a logarithm, a fitted power transform or a quantile map, or rescales each row to length 1.

Overview

Scaling moves and stretches a column but keeps its shape. A column with a long right tail, such as income, keeps the tail after scaling. A transformation bends the axis instead. A logarithm compresses large values much more than small ones, so the tail is pulled in and the column looks more symmetric. Power transforms are a family of such bends with one dial, the exponent, which is tuned so the result looks as close to a bell curve as possible. Many models behave better on roughly symmetric inputs.

A short history

Taking logarithms to tame skewed data is a long-standing habit in statistics. George Box and David Cox made the choice systematic in 1964 with a family of power transforms whose exponent is fitted to the data. In-Kwon Yeo and Richard Johnson extended it in 2000 to data with zeros and negative values. Quantile mapping to a normal shape comes from rank-based statistics, and unit-length rows from information retrieval.

How it works

  1. Choose a method: log, boxcox (positive data only), yeojohnson (any sign), quantile_normal, or the row-wise unit_l1 and unit_l2.
  2. Call fit on the training data. For the power transforms it finds one exponent per column by trying a grid of values and refining the best, and stores them in lambdas_.
  3. For quantile_normal, fit stores the sorted training values of each column as reference quantiles.
  4. If standardize is on, fit also records the mean and standard deviation of the transformed training column.
  5. Call transform: apply the fitted bend to each column, then subtract that mean and divide by that standard deviation.
  6. For unit_l1 and unit_l2, transform divides each row by its own norm. Nothing is learned from the training data.
  7. Call inverse_transform to map values back to the original scale. The row-norm methods cannot be inverted.

Watch out for

  • The logarithm and Box-Cox are undefined at zero and below. Use a shift of 1 for counts with zeros, or Yeo-Johnson for data with negative values.
  • If you train on a transformed target and invert the predictions, the result estimates the median of the target, not its mean. Averages of back-transformed predictions run low for a log transform.
  • The quantile map flattens every column to the same bell shape. It discards the distances between values, and new values beyond the training range are pinned at the ends.
  • The exponent is estimated from data. On a small sample it is noisy, and fitting it on all rows before splitting leaks the test distribution.
  • Unit-norm scaling works on rows, not columns. It removes the size of each row, which is harmful when the size is the signal.

Use cases

When to use it

For strongly skewed positive quantities such as prices, counts and durations, before linear models or neural networks. Use the unit-norm methods when only the direction of a row matters, as with text count vectors.

In industry

Finance and economics
Analysts work with log prices and log incomes, which turn multiplicative changes into additive ones and reduce skew.
Biology
Gene expression and concentration measurements are log-transformed before statistical tests that assume roughly normal data.
Text retrieval
Document vectors are scaled to unit length so that similarity depends on direction, the cosine, and not on document length.

Choosing it: what must hold

  • A numeric column whose skew or heavy tail harms the model, typically a linear, distance-based or neural model.
  • Positive values for a logarithm or Box-Cox. Yeo-Johnson accepts zeros and negatives.
  • Fitted exponents or reference quantiles learned from the training data only.
  • For the quantile map, enough rows to estimate quantiles well, and acceptance that distances between values are distorted.

When to choose something else

IfUse instead
The column is already roughly symmetric and only differs in unitsFeature scaling
The model is tree-basedNo transformation of inputs, since trees depend only on order
The skew comes from a few erroneous valuesOutlier detection and treatment

Math foundations

  1. Logarithm

    y=ln⁡(x+c)y = \ln(x + c)

    It turns ratios into differences: multiplying xx by 10 always adds the same amount to yy. The shift cc is 0 by default. Setting it to 1 lets the transform accept zeros.

  2. Box-Cox

    y={xλ−1λλ≠0ln⁡xλ=0(x>0)y = \begin{cases} \dfrac{x^{\lambda} - 1}{\lambda} & \lambda \ne 0 \\[2mm] \ln x & \lambda = 0 \end{cases} \qquad (x > 0)

    A family of power curves. λ=1\lambda = 1 leaves the shape alone, λ=0.5\lambda = 0.5 is a square root, and λ=0\lambda = 0 is the logarithm, which is also the limit of the first line as λ\lambda goes to 0.

  3. Yeo-Johnson

    y={(x+1)λ−1λx≥0−(1−x)2−λ−12−λx<0y = \begin{cases} \dfrac{(x + 1)^{\lambda} - 1}{\lambda} & x \ge 0 \\[2mm] -\dfrac{(1 - x)^{2 - \lambda} - 1}{2 - \lambda} & x < 0 \end{cases}

    Box-Cox applied to x+1x + 1 for non-negative values, and a mirrored version with exponent 2−λ2 - \lambda for negative ones. When λ=0\lambda = 0 or λ=2\lambda = 2 the matching line is replaced by its logarithm limit.

  4. Choosing the exponent

    ℓ(λ)=−n2ln⁡σ^2(λ)+(λ−1)∑i=1nln⁡xi\ell(\lambda) = -\frac{n}{2} \ln \hat{\sigma}^2(\lambda) + (\lambda - 1) \sum_{i=1}^{n} \ln x_i

    The Box-Cox log-likelihood of λ\lambda, assuming the transformed data is normal. The first term rewards a tight result, and the second corrects for how the transform stretches the axis. fit_lambda picks the λ\lambda in [−5,5][-5, 5] that makes it largest.

  5. Quantile map to a normal

    y=Φ−1(F^(x))y = \Phi^{-1}\big(\hat{F}(x)\big)

    First find what share of training values lies below xx, then find the point of the standard normal with the same share below it. The output is bell-shaped whatever the input looked like.

  6. Unit-norm rows

    x′=x∥x∥p,∥x∥1=∑j∣xj∣,∥x∥2=∑jxj2x' = \frac{x}{\lVert x \rVert_p}, \qquad \lVert x \rVert_1 = \sum_j \lvert x_j \rvert, \quad \lVert x \rVert_2 = \sqrt{\sum_j x_j^2}

    Each row is divided by its own length, so every row ends with norm 1. Only the proportions between the entries of a row remain.

Symbols

x, yx,\ y
a value before and after the transform
cc
the shift setting of the log method
λ\lambda
the exponent of a power transform (one entry of lambdas_)
ℓ(λ)\ell(\lambda)
the log-likelihood used to choose the exponent
σ^2(λ)\hat{\sigma}^2(\lambda)
the variance of the column after transforming with exponent lambda
nn
the number of training rows
F^\hat{F}
the empirical distribution function: the share of training values at or below x
Φ−1\Phi^{-1}
the inverse of the standard normal cumulative distribution function
∥x∥p\lVert x \rVert_p
the L1 or L2 norm of a row

Worked by hand

Apply Box-Cox with λ=0.5\lambda = 0.5 to the values 1, 4 and 100. Then scale the row (3,4)(3, 4) to unit L2 norm.

y(1)=10.5−10.5=0,y(4)=2−10.5=2y(1) = \frac{1^{0.5} - 1}{0.5} = 0, \qquad y(4) = \frac{2 - 1}{0.5} = 2
y(100)=10−10.5=18y(100) = \frac{10 - 1}{0.5} = 18
∥(3,4)∥2=9+16=5,x′=(0.6, 0.8)\lVert (3, 4) \rVert_2 = \sqrt{9 + 16} = 5, \qquad x' = (0.6,\ 0.8)

The gap from 4 to 100 was 32 times the gap from 1 to 4. After the transform it is 8 times. The tail is pulled in while the order is kept. The row (3,4)(3, 4) becomes (0.6,0.8)(0.6, 0.8), which has length 1.

Visual example

Loading the example.

Try this

  • Drag λ from 1 down toward 0 and watch the long right tail fold in. At λ = 1 the shape does not change at all.
  • Press the button to use the fitted λ, then make the tail heavier and press it again: the best exponent changes with the data.
  • Choose quantile_normal: the result is a bell curve whatever the column looked like.

Code sample

import numpy as np
from impl import Transformer
from config import TransformerConfig

rng = np.random.default_rng(0)
X = rng.lognormal(mean=1.0, sigma=0.8, size=(500, 2))      # right-skewed
t = Transformer(TransformerConfig(method="boxcox")).fit(X)
Z = t.transform(X)                  # close to normal, mean 0, std 1
X_back = t.inverse_transform(Z)     # equals X
print(t.lambdas_)                   # near 0: Box-Cox found the log transform
Read the implementation (188 lines)
"""Distribution transforms: log, Box-Cox, Yeo-Johnson, quantile-to-normal, and unit-norm rows.

NumPy only. The power transforms pick their exponent per column by maximising the Gaussian log-likelihood of
the transformed data (a grid search refined by golden-section search). Every column transform has an inverse.
"""
from __future__ import annotations

import math
from statistics import NormalDist

import numpy as np

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

_NORMAL = NormalDist()
_ppf = np.vectorize(_NORMAL.inv_cdf, otypes=[float])
_cdf = np.vectorize(_NORMAL.cdf, otypes=[float])
_GOLD = (math.sqrt(5.0) - 1.0) / 2.0


def boxcox(x: np.ndarray, lmbda: float) -> np.ndarray:
    """Box-Cox transform of positive x: (x^lmbda - 1) / lmbda, or log(x) when lmbda is 0."""
    return np.log(x) if abs(lmbda) < 1e-12 else (np.power(x, lmbda) - 1.0) / lmbda


def boxcox_inverse(y: np.ndarray, lmbda: float) -> np.ndarray:
    """Inverse of `boxcox`."""
    return np.exp(y) if abs(lmbda) < 1e-12 else np.power(lmbda * y + 1.0, 1.0 / lmbda)


def yeojohnson(x: np.ndarray, lmbda: float) -> np.ndarray:
    """Yeo-Johnson transform: Box-Cox of (x + 1) for x >= 0, a mirrored version with 2 - lmbda for x < 0."""
    out = np.empty_like(x, dtype=float)
    pos = x >= 0
    out[pos] = np.log1p(x[pos]) if abs(lmbda) < 1e-12 else (np.power(x[pos] + 1.0, lmbda) - 1.0) / lmbda
    two = 2.0 - lmbda
    out[~pos] = -np.log1p(-x[~pos]) if abs(two) < 1e-12 else -(np.power(1.0 - x[~pos], two) - 1.0) / two
    return out


def yeojohnson_inverse(y: np.ndarray, lmbda: float) -> np.ndarray:
    """Inverse of `yeojohnson`."""
    out = np.empty_like(y, dtype=float)
    pos = y >= 0
    out[pos] = np.expm1(y[pos]) if abs(lmbda) < 1e-12 else np.power(lmbda * y[pos] + 1.0, 1.0 / lmbda) - 1.0
    two = 2.0 - lmbda
    out[~pos] = -np.expm1(-y[~pos]) if abs(two) < 1e-12 else 1.0 - np.power(1.0 - two * y[~pos], 1.0 / two)
    return out


def _log_likelihood(x: np.ndarray, lmbda: float, kind: str) -> float:
    """Gaussian profile log-likelihood of lmbda for one column x, shape (n,)."""
    if kind == "boxcox":
        y, jacobian = boxcox(x, lmbda), np.log(x).sum()
    else:
        y, jacobian = yeojohnson(x, lmbda), (np.sign(x) * np.log1p(np.abs(x))).sum()
    var = y.var()
    if not np.isfinite(var) or var <= 0:
        return -np.inf
    return -0.5 * len(x) * math.log(var) + (lmbda - 1.0) * jacobian


def fit_lambda(x: np.ndarray, kind: str) -> float:
    """Maximum-likelihood exponent in [-5, 5] for one column: coarse grid, then golden-section search."""
    grid = np.linspace(-5.0, 5.0, 41)
    best = int(np.argmax([_log_likelihood(x, g, kind) for g in grid]))
    a, b = grid[max(best - 1, 0)], grid[min(best + 1, len(grid) - 1)]
    c, d = b - _GOLD * (b - a), a + _GOLD * (b - a)
    fc, fd = _log_likelihood(x, c, kind), _log_likelihood(x, d, kind)
    for _ in range(60):
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - _GOLD * (b - a)
            fc = _log_likelihood(x, c, kind)
        else:
            a, c, fc = c, d, fd
            d = a + _GOLD * (b - a)
            fd = _log_likelihood(x, d, kind)
    return float(0.5 * (a + b))


class Transformer:
    """Fits a transform on training data and applies it (and its inverse) to data with the same columns.

    After `fit`: `lambdas_` (n_features,) for the power transforms, `quantiles_` (n_ref, n_features) for
    "quantile_normal", and `mean_` / `std_` (n_features,) when `standardize` is on.
    """

    def __init__(self, config: TransformerConfig | None = None) -> None:
        self.config = config or TransformerConfig()
        self.lambdas_: np.ndarray | None = None
        self.quantiles_: np.ndarray | None = None
        self.mean_: np.ndarray | None = None
        self.std_: np.ndarray | None = None
        self._fitted = False

    @property
    def _row_wise(self) -> bool:
        return self.config.method in ("unit_l1", "unit_l2")

    @staticmethod
    def _as_2d(X) -> np.ndarray:
        X = np.asarray(X, dtype=float)
        return X[:, None] if X.ndim == 1 else X

    def _raw(self, X: np.ndarray) -> np.ndarray:
        """Apply the column transform without the final standardization. X: (n, d)."""
        method = self.config.method
        if method == "log":
            if np.any(X + self.config.shift <= 0):
                raise ValueError("log needs x + shift > 0 everywhere")
            return np.log(X + self.config.shift)
        if method == "boxcox":
            if np.any(X <= 0):
                raise ValueError("boxcox needs strictly positive data; use yeojohnson otherwise")
            return np.column_stack([boxcox(X[:, j], self.lambdas_[j]) for j in range(X.shape[1])])
        if method == "yeojohnson":
            return np.column_stack([yeojohnson(X[:, j], self.lambdas_[j]) for j in range(X.shape[1])])
        # quantile_normal: value -> empirical CDF (linear interpolation) -> standard normal quantile
        probs = self._probs()
        cols = [np.interp(X[:, j], self.quantiles_[:, j], probs) for j in range(X.shape[1])]
        return _ppf(np.column_stack(cols))

    def _probs(self) -> np.ndarray:
        """Probability of each sorted reference value: (i + 0.5) / n, strictly inside (0, 1)."""
        n = self.quantiles_.shape[0]
        return (np.arange(n) + 0.5) / n

    def fit(self, X) -> "Transformer":
        """Learn the transform from X, shape (n_samples, n_features)."""
        X = self._as_2d(X)
        method = self.config.method
        if method in ("boxcox", "yeojohnson"):
            if method == "boxcox" and np.any(X <= 0):
                raise ValueError("boxcox needs strictly positive data; use yeojohnson otherwise")
            if self.config.lmbda is not None:
                self.lambdas_ = np.full(X.shape[1], float(self.config.lmbda))
            else:
                self.lambdas_ = np.array([fit_lambda(X[:, j], method) for j in range(X.shape[1])])
        elif method == "quantile_normal":
            self.quantiles_ = np.sort(X, axis=0)
        if self.config.standardize and not self._row_wise:
            raw = self._raw(X)
            self.mean_ = raw.mean(axis=0)
            std = raw.std(axis=0)
            self.std_ = np.where(std > 0, std, 1.0)
        self._fitted = True
        return self

    def transform(self, X) -> np.ndarray:
        """Transform X, shape (n_samples, n_features)."""
        X = self._as_2d(X)
        if self._row_wise:
            order = 1 if self.config.method == "unit_l1" else 2
            norms = np.linalg.norm(X, ord=order, axis=1, keepdims=True)
            return X / np.where(norms > 0, norms, 1.0)
        if not self._fitted:
            raise RuntimeError("call fit before transform")
        out = self._raw(X)
        if self.config.standardize:
            out = (out - self.mean_) / self.std_
        return out

    def inverse_transform(self, Y) -> np.ndarray:
        """Map transformed values back to the original scale. Not defined for the row-norm methods."""
        if self._row_wise:
            raise ValueError("unit-norm scaling discards the row norm and cannot be inverted")
        if not self._fitted:
            raise RuntimeError("call fit before inverse_transform")
        Y = self._as_2d(Y)
        if self.config.standardize:
            Y = Y * self.std_ + self.mean_
        method = self.config.method
        if method == "log":
            return np.exp(Y) - self.config.shift
        if method == "boxcox":
            return np.column_stack([boxcox_inverse(Y[:, j], self.lambdas_[j]) for j in range(Y.shape[1])])
        if method == "yeojohnson":
            return np.column_stack([yeojohnson_inverse(Y[:, j], self.lambdas_[j]) for j in range(Y.shape[1])])
        probs = self._probs()
        return np.column_stack([np.interp(_cdf(Y[:, j]), probs, self.quantiles_[:, j]) for j in range(Y.shape[1])])

    def fit_transform(self, X) -> np.ndarray:
        """Fit on X and return the transformed 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

Draw 1000 values from a log-normal distribution. Fit a Transformer with method boxcox, then yeojohnson, then quantile_normal through TransformerConfig, and compare histograms before and after. Print lambdas_ and explain why it is close to 0 for this data. Check that inverse_transform recovers the input. Then call fit_lambda on only 20 of the values several times with different samples and see how much the exponent varies.

Check on learning

  1. For log-normal data the fitted Box-Cox exponent comes out near 0. Why is that the expected answer?
    A way to think about it

    Recall what a log-normal variable is defined to be. Then read off which member of the Box-Cox family is the logarithm.

  2. You train a regression on the logarithm of house prices and convert predictions back with the exponential. Why is the average predicted price lower than the average true price?
    A way to think about it

    The exponential of an average is not the average of the exponentials. Think about which centre of a skewed distribution the back-transformed prediction lands on.

  3. When would a quantile map to a normal be a poor choice even though it always produces a perfect bell shape on the training data?
    A way to think about it

    Consider a column where the size of the gaps matters, or live data that goes beyond the training range. Ask what the map does to both.

  4. Scaling and transforming are often confused. If a column is already symmetric but measured in huge units, which do you need, and what would a log transform do to it?
    A way to think about it

    Separate the two problems: the units and the shape. A bend applied to a symmetric column creates skew in the other direction.