TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Unit Norm, Log, Power and Quantile Transforms

Unit Norm, Log, Power and Quantile Transforms

The linear scalers shift and stretch a column, but they never change its shape: a long right tail stays a long right tail. Incomes, prices, populations, waiting times and word counts are typically like that, with most values small and a few enormous. Linear models and neural networks find such columns hard: the few large values dominate the fit, and the relation to the target is often closer to linear in the logarithm of the value. This lesson covers the remaining four of the eight methods:

# Method Works on What it does
5 Unit-norm normalisation each row rescales a sample's vector to length 1
6 Log transform a column compresses large values, log⁡(1+x)\log(1 + x) for counts
7 Power transform (Box-Cox, Yeo-Johnson) a column finds the exponent that makes it most Gaussian-like
8 Quantile transform a column maps ranks to a uniform or normal distribution

Unit norm: scaling rows, not columns

Normalizer divides each sample by its own norm, x′=x/∥x∥2x' = x / \lVert x \rVert_2, so every row ends up with length 1. This is meant for data where the direction of the vector matters and its length does not: word counts of documents (a long document has bigger counts but the same topic), or embedding vectors compared by cosine similarity. After L2 normalisation, the dot product of two rows is their cosine similarity.

python · try it yourself
import numpy as np
from sklearn.preprocessing import Normalizer

# word counts for "goal", "match", "vote", "election" in three documents
docs = np.array([[4, 3, 0, 0],      # short sports article
                 [40, 30, 1, 0],    # long sports article
                 [0, 1, 6, 5]])     # politics
unit = Normalizer(norm="l2").fit_transform(docs)
print(np.round(unit, 3).tolist())
print("row lengths:", np.round(np.linalg.norm(unit, axis=1), 3).tolist())
print("cosine similarities:")
print(np.round(unit @ unit.T, 3).tolist())
[[0.8, 0.6, 0.0, 0.0], [0.8, 0.6, 0.02, 0.0], [0.0, 0.127, 0.762, 0.635]]
row lengths: [1.0, 1.0, 1.0]
cosine similarities:
[[1.0, 1.0, 0.076], [1.0, 1.0, 0.091], [0.076, 0.091, 1.0]]

The short and the long sports article have very different counts but almost the same direction, so their cosine similarity rounds to 1.0; each has a similarity of only 0.08 to 0.09 with the politics article. Note that Normalizer is stateless: it learns nothing in fit, because each row is normalised on its own. It therefore cannot leak, but it is also not a substitute for column scaling.

Log, Box-Cox and Yeo-Johnson

The log transform x′=log⁡(1+x)x' = \log(1 + x) (np.log1p) turns multiplicative differences into additive ones: 10 to 100 and 100 to 1000 become equal steps. It needs x>−1x > -1; for counts with zeros, log1p is the usual choice.

Power transforms generalise the log with a parameter λ\lambda that is learned from the training data by maximum likelihood, choosing the λ\lambda that makes the result most normal:

Box-Cox: x(λ)={xλ−1λλ≠0ln⁡xλ=0(x>0)\text{Box-Cox: } x^{(\lambda)} = \begin{cases} \dfrac{x^\lambda - 1}{\lambda} & \lambda \ne 0 \\ \ln x & \lambda = 0 \end{cases} \qquad (x > 0)

Box-Cox requires strictly positive values. Yeo-Johnson extends the same idea to zero and negative values (it applies Box-Cox-like formulas to x+1x + 1 for x≥0x \ge 0 and a mirrored version for x<0x < 0), so it works on any column. scikit-learn's PowerTransformer uses Yeo-Johnson by default and standardises the result afterwards.

Quantile transform

QuantileTransformer replaces each value by its rank among the training values (estimated from n_quantiles points) and maps that rank to a target distribution, uniform on [0,1][0, 1] or standard normal. It makes any continuous distribution exactly uniform or normal on the training data and is very robust to outliers (a huge value is just "the largest rank"). The price: it is non-linear and not smooth, it can distort distances between values that were close, and with few training rows the mapping is coarse.

Comparing them on a skewed column

python · try it yourself
import numpy as np
from scipy.stats import skew
from sklearn.preprocessing import PowerTransformer, QuantileTransformer

rng = np.random.default_rng(0)
income = rng.lognormal(mean=10.5, sigma=0.8, size=2000).reshape(-1, 1)
train, test = income[:1500], income[1500:]

def describe(name, z):
    z = z.ravel()
    print(f"{name:22s} skew {skew(z):6.2f}   min {z.min():9.2f}   median {np.median(z):9.2f}   max {z.max():10.2f}")

describe("raw", train)
describe("log", np.log(train))
bc = PowerTransformer(method="box-cox").fit(train)
describe("Box-Cox", bc.transform(train))
yj = PowerTransformer(method="yeo-johnson").fit(train)
describe("Yeo-Johnson", yj.transform(train))
qt = QuantileTransformer(n_quantiles=500, output_distribution="normal", random_state=0).fit(train)
describe("quantile -> normal", qt.transform(train))
print("learned lambdas: Box-Cox", round(float(bc.lambdas_[0]), 3), " Yeo-Johnson", round(float(yj.lambdas_[0]), 3))
describe("Box-Cox on test", bc.transform(test))
raw                    skew   2.74   min   1604.33   median  35706.85   max  422029.03
log                    skew  -0.08   min      7.38   median     10.48   max      12.95
Box-Cox                skew   0.00   min     -3.75   median     -0.02   max       3.23
Yeo-Johnson            skew   0.00   min     -3.75   median     -0.02   max       3.23
quantile -> normal     skew  -0.01   min     -5.20   median      0.00   max       5.20
learned lambdas: Box-Cox 0.033  Yeo-Johnson 0.033
Box-Cox on test        skew   0.07   min     -3.02   median     -0.06   max       2.83

The raw incomes have a skewness of 2.74 (0 means symmetric). The log already removes almost all of it, because this data was generated log-normal, and Box-Cox learns λ=0.033\lambda = 0.033, close to 0, which is the log. Yeo-Johnson ends up the same here, because all incomes are positive. The quantile transform produces a symmetric normal shape on the training data (skew -0.01); its most extreme values are capped near -5.2 and 5.2, the normal quantiles of the lowest and highest rank. The last line shows the transform learned on the training part applied to new data: it stays well-behaved, with no refitting.

Tip: Box-Cox with λ\lambda near 0 means "use the log", near 0.5 "use the square root", near 1 "leave it". Printing the learned λ\lambda tells you what the data needs.

Does it help the model?

Transforms help models that assume something about shapes (linear models, Gaussian naive Bayes, distance-based models) and do nothing for trees. Here a target depends linearly on the log of income, and we compare a linear regression on the raw and the transformed feature (5-fold CV, R2R^2):

python · try it yourself
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, PowerTransformer, QuantileTransformer, StandardScaler

rng = np.random.default_rng(1)
income = rng.lognormal(10.5, 0.8, 1500).reshape(-1, 1)
spend = 3.0 * np.log(income).ravel() + rng.normal(0, 0.5, 1500)

options = {
    "standardise only": StandardScaler(),
    "log1p": FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
    "Yeo-Johnson": PowerTransformer(),
    "quantile -> normal": QuantileTransformer(n_quantiles=300, output_distribution="normal"),
}
for name, t in options.items():
    r2 = cross_val_score(make_pipeline(t, LinearRegression()), income, spend, cv=5, scoring="r2")
    print(f"{name:20s} R2 {r2.mean():.3f}")
standardise only     R2 0.650
log1p                R2 0.959
Yeo-Johnson          R2 0.959
quantile -> normal   R2 0.955

With the raw feature, the straight line cannot follow the curved relation and R2R^2 stays at 0.650. The log matches the true relation exactly (0.959), and the two learned transforms reach the same level (0.959 and 0.955) without being told that the log was right. FunctionTransformer(np.log1p) is stateless, so it is safe anywhere; PowerTransformer and QuantileTransformer learn from data and belong inside the pipeline.

Pitfalls

  • Log of zero or negative values: np.log(0) is -inf. Use log1p for counts, Yeo-Johnson for signed values, or fix the data.
  • Fitting λ\lambda or quantiles on all data: they are learned parameters; fit them on training data only.
  • Using Normalizer as a column scaler: it scales rows. A tabular dataset with age and income does not become comparable column-wise by normalising each row.
  • Transforming the target and reporting errors on the transformed scale: an RMSE of 0.2 in log-dollars is not 0.2 dollars. Use TransformedTargetRegressor and report in original units.

Practice

  1. For which data would you choose Normalizer, for which PowerTransformer?
Answer

Normalizer for rows whose direction matters and length does not (term-frequency vectors, embeddings compared with cosine similarity). PowerTransformer for individual skewed columns (incomes, durations) feeding a model that prefers roughly Gaussian inputs.

  1. A column holds account balances between -5,000 and 2,000,000. Which of log, Box-Cox and Yeo-Johnson can be applied directly?
Answer

Only Yeo-Johnson: the log and Box-Cox need positive values. (Alternatively, model sign and magnitude separately: a flag for negative and log⁡(1+∣x∣)\log(1 + \lvert x \rvert).)

Test yourself

What does Normalizer(norm='l2') do?

  1. Scales each column to mean 0 and variance 1
  2. Scales each row to length 1
  3. Maps values to [0, 1] per column
  4. Removes outliers

Box-Cox learns λ=0.02\lambda = 0.02 on a column. What transform is that close to?

  1. No transform
  2. Square root
  3. Natural logarithm
  4. Square

Which transform can handle negative values?

  1. Log
  2. Box-Cox
  3. Yeo-Johnson
  4. None

Why is QuantileTransformer robust to outliers?

  1. It deletes them
  2. It only uses ranks, so an extreme value is just the highest rank
  3. It uses the median
  4. It clips at 3 standard deviations