Sub topic 6
Log transforms, skew and binning
This chapter assumes you know basic pandas, scikit-learn's fit and transform workflow, and what a distribution and its mean and median are. It covers two ways to reshape a numeric column: transforming it to reduce skew, and binning it into ranges.
Why skew matters
A column is right-skewed when most values are small and a few are very large. Income, prices, counts and durations often look like this. The long tail has two effects:
- A few extreme values dominate the mean, the variance and any squared-error loss.
- Linear models, k-nearest neighbors and neural networks work with distances and weighted sums, so they are pulled toward the tail.
Tree-based models split on thresholds and only use the order of values. Monotonic transforms such as log therefore rarely change their results.
Log transforms
A log transform compresses large values more than small ones. A jump from 1,000 to 10,000 becomes the same step as 10 to 100. Use log1p, which computes log(1 + x). It handles zeros, and it is accurate for small values. It requires x > -1, so use it only on non-negative columns.
import numpy as np
import pandas as pd
income = pd.Series([20_000, 35_000, 48_000, 60_000, 2_500_000])
print(income.skew()) # strongly positive
print(np.log1p(income).skew()) # much closer to 0Other options: PowerTransformer (Yeo-Johnson) learns a power from the training data and also accepts negative values. A square root is a milder fix for count data.
If you transform the target, remember to invert the prediction. TransformedTargetRegressor does this for you.
Log then polynomial, inside a pipeline
Wrapping a transform in FunctionTransformer makes it a pipeline step. The following example logs the columns and then adds squared terms and products.
import numpy as np
from sklearn.preprocessing import FunctionTransformer, PolynomialFeatures
from sklearn.pipeline import make_pipeline
log_then_poly = make_pipeline(
FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
PolynomialFeatures(degree=2, interaction_only=False, include_bias=False),
)
X_new = log_then_poly.fit_transform([[10.0, 200.0], [20.0, 5000.0]])
print(X_new.shape) # (2, 5): two logs, two squares, one productnp.log1p has no learned state, so it cannot leak information. Learned transforms such as PowerTransformer must be fitted on training data only.
Binning
Binning replaces a number with the range it falls in. It can capture non-linear effects in a linear model and limit the influence of outliers. The cost is lost detail: values inside one bin become identical.
KBinsDiscretizer learns bin edges from the training data:
strategy="uniform": equal-width bins. Skewed data leaves most bins nearly empty.strategy="quantile": equal-count bins. This suits skewed data.strategy="kmeans": edges follow clusters in the values.
from sklearn.preprocessing import KBinsDiscretizer
binner = KBinsDiscretizer(n_bins=4, encode="onehot-dense", strategy="quantile")
print(binner.fit_transform(income.to_frame()))Use encode="onehot-dense" for linear models, so each bin gets its own weight. encode="ordinal" keeps one integer column and suits trees.
Common errors
- Applying
log1pto a column containing values below -1 producesNaN. - Computing bin edges on the full dataset before splitting leaks information about the test set. Keep the binner in the pipeline.
- Using too many bins gives sparse, noisy features.
- Transforming and then forgetting the transform at prediction time causes train-serving mismatch.
Exercise
A column of purchase amounts is right-skewed, and you are fitting a logistic regression. Why might you choose quantile binning over uniform binning, and where must the binner be fitted?
Show answer
With skewed data, uniform bins put most rows in the first few bins and leave the rest nearly empty, while quantile bins hold roughly equal numbers of rows. The binner must be fitted on training data only, ideally as a step inside a Pipeline, so cross-validation refits the bin edges on each training fold.