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, 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, , 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.
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 (np.log1p) turns multiplicative differences into additive ones: 10 to 100 and 100 to 1000 become equal steps. It needs ; for counts with zeros, log1p is the usual choice.
Power transforms generalise the log with a parameter that is learned from the training data by maximum likelihood, choosing the that makes the result most normal:
Box-Cox requires strictly positive values. Yeo-Johnson extends the same idea to zero and negative values (it applies Box-Cox-like formulas to for and a mirrored version for ), 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 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
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 , 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 near 0 means "use the log", near 0.5 "use the square root", near 1 "leave it". Printing the learned 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, ):
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 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. Uselog1pfor counts, Yeo-Johnson for signed values, or fix the data. - Fitting or quantiles on all data: they are learned parameters; fit them on training data only.
- Using
Normalizeras 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
TransformedTargetRegressorand report in original units.
Practice
- For which data would you choose
Normalizer, for whichPowerTransformer?
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.
- 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 .)
Test yourself
What does Normalizer(norm='l2') do?
- Scales each column to mean 0 and variance 1
- Scales each row to length 1
- Maps values to [0, 1] per column
- Removes outliers
Box-Cox learns on a column. What transform is that close to?
- No transform
- Square root
- Natural logarithm
- Square
Which transform can handle negative values?
- Log
- Box-Cox
- Yeo-Johnson
- None
Why is QuantileTransformer robust to outliers?
- It deletes them
- It only uses ranks, so an extreme value is just the highest rank
- It uses the median
- It clips at 3 standard deviations