Feature Transformations: Fixing Skewness with Log, Box-Cox, Yeo-Johnson & Binning
Why StandardScaler cannot fix heavy right tails, when to use log1p vs. Box-Cox vs. Yeo-Johnson, and how Quantile Binning helps linear models capture curves
Feature Transformations apply non-linear mathematical functions (Log, Square Root, Box-Cox, Yeo-Johnson, or Quantile Binning) to reshape heavily skewed distributions into cleaner, more symmetric shapes.
Real-world quantities like income, click counts, and house prices have massive right tails that violate linear model assumptions and stretch distances—and simple StandardScaler cannot change their shape.
Applying np.log1p to skewed money/count features is one of the highest-ROI 1-line improvements in tabular ML.
Log-transforming skewed targets (e.g., predicting log1p(price)) optimizes relative percentage errors instead of letting one $10M outlier hijack MSE.
Power transforms (Yeo-Johnson) stabilize variance and dramatically improve Linear Regression, Logistic Regression, PCA, and GMM.
Classic Data Science question: 'What is the difference between StandardScaler and a Log/Box-Cox transform, and why does Box-Cox fail on zeros?'
Your feature net_profit contains negative losses (-0), and massive positive gains (+$200,000). Which power transform works out of the box?
- Explain why
log1p(x)is preferred overlog(x)for non-negative features that contain zeros. - Choose between Box-Cox (strictly positive ) and Yeo-Johnson (handles zero and negative values).
- Use Equal-Width vs. Quantile Binning (Discretization) to let linear models capture non-linear bucket effects.
- Remember to invert target transformations (
np.expm1(y_pred)) when evaluating real-world error.
Scaling moves and stretches the ruler without changing the curve's shape; Non-Linear Transformation actually bends the ruler to pull runaway right tails back into a clean, well-behaved bell curve.
1. Choosing the Right Transformation
| Transform | Allowed Input Range | When to Use |
|---|---|---|
np.log1p(x) | Counts, prices, revenue, clicks, session durations (fast & interpretable!) | |
| Box-Cox | strictly | Positive continuous features when you want an automated optimal |
| Yeo-Johnson | Any | Skewed features that include zeros or negative values (e.g., profit/loss) |
| Quantile Binning | Any | Turning age or income into equal-sized decile buckets so linear models learn non-linear steps |
2. Transforming the Target y (And Inverting Back!)
When predicting house prices or ad revenue, training on has two superpowers:
- It stops a single $20M mansion from dominating the squared error of 1,000 starter homes.
- Minimizing MSE on is mathematically equivalent to minimizing RMSLE (relative percentage error).
Don't Forget: Always convert predictions back to dollars with (np.expm1) before reporting RMSE to stakeholders!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Input log transforms rarely change tree splits because is monotonic (preserves order). However, log-transforming a skewed target can still massively improve XGBoost regression!
Unscaled Ravine (Zig-Zag!) vs. StandardScaler Circle (Straight Shot!)
Watch both gradient-descent marbles race simultaneously with the exact same learning rate!
log1p for skewed non-negative counts/money, Yeo-Johnson when negatives/zeros exist, and Quantile Binning to give linear models non-linear flexibility.import numpy as np
# Fixing a heavily right-skewed income feature with log1p + Quantile Binning
incomes = np.array([0, 15_000, 32_000, 48_000, 65_000, 95_000, 250_000, 4_500_000], dtype=float)
def skewness(x: np.ndarray) -> float:
z = (x - x.mean()) / (x.std() + 1e-9)
return float((z ** 3).mean())
log_incomes = np.log1p(incomes)
# Quantile binning into 4 equal-count quartiles (0, 1, 2, 3)
edges = np.quantile(incomes, [0.25, 0.50, 0.75])
bins = np.digitize(incomes, edges)
print(f"Raw skewness: {skewness(incomes):.2f} (extreme right tail)")
print(f"log1p skewness: {skewness(log_incomes):.2f} (dramatically tamed!)")
print("Quartile bins: ", bins.tolist())
0.18) to a business stakeholder instead of inverting back to dollars with expm1.np.log1p(x) instead of np.log(x) for count features like num_purchases?