Sub topic 6
Log transforms, skew and binning
This chapter assumes you know basic pandas, the scikit-learn fit and transform workflow, and what mean, variance and a distribution are. It also assumes you have read the earlier chapters on data leakage and scaling. Here you will learn how to reshape skewed numeric columns and when to turn a number into bins.
Why skew causes trouble
A distribution is right-skewed when most values are small and a long tail of large values stretches to the right. Income, prices, counts of page views and time between events usually look like this.
Skew hurts in several ways:
- Linear models, logistic regression and neural networks respond to the raw size of a value. A few huge values dominate the fit.
- Distance-based models such as k-nearest neighbors and SVMs let the tail control distances.
- Many relationships are multiplicative. Doubling income may matter as much at 20,000 as at 200,000. A log scale turns that ratio into an equal step.
- Standard scaling does not remove skew. It shifts and rescales the values but keeps the shape.
Tree-based models (decision trees, random forests, gradient boosting) only compare values to thresholds. Any monotonic transform, one that preserves order, leaves their splits unchanged. Do not expect a log transform to improve a tree model through the feature itself. It can still help if the target is skewed or if you later combine the column with others in a linear step.
Measuring skew
Check skew before you transform. A histogram is the first tool. A number helps when you screen many columns.
import numpy as np
from scipy.stats import skew
rng = np.random.default_rng(0)
income = rng.lognormal(mean=10, sigma=1, size=1000)
print("raw skew:", round(skew(income), 2))
print("log1p skew:", round(skew(np.log1p(income)), 2))A skew near 0 means a roughly symmetric shape. As a rough guide, absolute values above about 1 are worth a look. The number is only a screening aid, so confirm it with a plot.
Log transforms
The logarithm compresses large values much more than small ones. Use np.log1p, which computes log(1 + x). It handles zeros, and it is accurate for tiny values.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, KBinsDiscretizer, StandardScaler
rng = np.random.default_rng(0)
df = pd.DataFrame({
"income": rng.lognormal(mean=10, sigma=1, size=1000),
"age": rng.integers(18, 80, size=1000),
})
prep = ColumnTransformer([
("log", Pipeline([
("log", FunctionTransformer(np.log1p, feature_names_out="one-to-one")),
("scale", StandardScaler()),
]), ["income"]),
("bin", KBinsDiscretizer(n_bins=5, encode="onehot-dense", strategy="quantile"), ["age"]),
])
Xt = prep.fit_transform(df)
print(Xt.shape)
print(prep.get_feature_names_out())This pipeline logs and then scales the income column, and it bins age into five groups. The feature_names_out="one-to-one" argument lets get_feature_names_out work, which matters when you inspect coefficients later.
Common errors with logs
- Negative values.
log1preturnsnanfor values below -1, andnp.logfails for anything at or below 0. Check the column's minimum first. If the column can be negative, use a signed transform or a Yeo-Johnson transform (below). - Using
log(x)on zeros. This gives-inf, which then breaks the scaler or model. Uselog1p. - Forgetting that units matter.
log1pon a value measured in dollars behaves differently from the same value in thousands of dollars, because the+1is relatively larger or smaller. For columns with small values, consider a different offset, or use a power transform. - Interpreting coefficients. In a linear model, a coefficient on
log(income)describes the effect of a proportional change, not a fixed amount.
A log transform with no learned parameters is stateless, so it cannot leak information from the test set. The scaler that follows it is not stateless, which is why both belong inside the pipeline.
Power and quantile transforms
When you do not want to pick a function by hand, scikit-learn can learn one.
import numpy as np
from scipy.stats import skew
from sklearn.preprocessing import PowerTransformer, QuantileTransformer
rng = np.random.default_rng(0)
X = rng.lognormal(mean=10, sigma=1, size=(1000, 1))
yj = PowerTransformer(method="yeo-johnson").fit_transform(X)
qt = QuantileTransformer(
output_distribution="normal", n_quantiles=200, random_state=0
).fit_transform(X)
print("yeo-johnson skew:", round(skew(yj.ravel()), 2))
print("quantile skew:", round(skew(qt.ravel()), 2))| Transform | What it does | Handles negatives | Notes |
|---|---|---|---|
| `log1p` | Fixed log curve | No (below -1) | Stateless, easy to explain |
| `PowerTransformer("yeo-johnson")` | Learns a power parameter per column | Yes | Also standardizes by default |
| `PowerTransformer("box-cox")` | Same idea | No, needs strictly positive values | Fails on zeros |
| `QuantileTransformer` | Maps ranks to a target distribution | Yes | Needs enough rows. It flattens outliers and distorts distances between nearby values |
PowerTransformer and QuantileTransformer learn parameters from data. Fit them on the training fold only, which means inside a pipeline.
Binning
Binning (also called discretization) replaces a number with the interval it falls into. The model then sees a category such as "age 30 to 40" instead of 34.
Reasons to bin:
- A linear model can fit a non-linear shape, because each bin gets its own weight.
- Binning limits the influence of outliers, because the extreme values share the last bin.
- Business rules often work in bands (tax brackets, age groups).
Reasons not to bin:
- You throw away information inside each bin. Two values at opposite ends of a bin look identical.
- Tree models already find their own thresholds, so binning rarely helps them.
- A value just across a bin edge gets a very different representation from its close neighbor.
KBinsDiscretizer has three strategies:
| Strategy | Bin edges | Use when |
|---|---|---|
| `uniform` | Equal-width intervals | The data is spread evenly. Skewed data leaves most bins empty |
| `quantile` | Each bin holds about the same number of rows | The data is skewed. This is the usual default choice |
| `kmeans` | Edges come from 1-D clustering | Natural clusters exist |
The edges are learned from the training data. If you compute them on the full dataset, you leak information about the test distribution.
If a column has many tied values, quantile edges can collapse into duplicates. Recent scikit-learn versions drop the duplicate bins and warn, so you may get fewer bins than you asked for. Check n_bins_ after fitting.
Skewed targets
A skewed target in regression needs a different tool, because you must undo the transform to get predictions in the original units.
import numpy as np
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import LinearRegression
reg = TransformedTargetRegressor(
regressor=LinearRegression(),
func=np.log1p,
inverse_func=np.expm1,
)TransformedTargetRegressor fits the model on the logged target and applies expm1 to predictions. Metrics computed on the returned predictions are in original units. Note that the back-transformed prediction estimates a median-like value, not the mean, so it tends to run low for the average.
Choosing a treatment
Edge cases to remember
- Outliers after logging. A log shrinks a tail but does not remove errors such as a value of 9,999,999 used as a missing code. Fix those first, as described in the missing values chapter.
- Zero-inflated columns. A column with many zeros and a skewed positive part (such as spend per customer) may work better as two features: a zero indicator and
log1pof the amount. - Inverse transforms for features. You rarely need to undo a feature transform, but reports that show raw values need the original column kept alongside it.
- Constant columns. A power transform on a constant column fails or returns meaningless numbers. Drop constants before transforming.
Exercise
A column claims has many zeros and a long right tail, and you will feed it to logistic regression. Which transform do you apply, and why must a KBinsDiscretizer for another column be fitted inside the pipeline instead of on the full dataset?
Show answer
Use np.log1p, because it handles zeros and compresses the tail. Optionally add a separate "claims is zero" indicator, since zero-heavy columns carry two signals. The discretizer learns its bin edges from the data, so fitting it on the full dataset would let test-set values shape the edges, which is leakage. Inside a pipeline, cross-validation refits the edges on each training fold only.
Exercise
You log-transform a column with np.log and the model starts producing nan errors. The column's minimum is 0. What is the cause, and what are two fixes?
Show answer
np.log(0) is -inf, which breaks downstream steps. Fixes: switch to np.log1p, or use PowerTransformer(method="yeo-johnson"), which accepts zeros and negatives.