Chapter 7 of 42 · ~16 min read & lab+60 XP
Chapter 7 · Machine Learning

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

What Is It?

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.

Why Is It Required?

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.

Everyday Analogy: Using the Richter scale for earthquakes: instead of plotting 10 vs. 10,000,000 on one crowded line, a logarithm compresses orders of magnitude into a neat 1-to-8 scale.
Why ML Engineers & Data Scientists Actually Need This

Applying np.log1p to skewed money/count features is one of the highest-ROI 1-line improvements in tabular ML.

ML / AI Engineer

Log-transforming skewed targets (e.g., predicting log1p(price)) optimizes relative percentage errors instead of letting one $10M outlier hijack MSE.

Data Scientist

Power transforms (Yeo-Johnson) stabilize variance and dramatically improve Linear Regression, Logistic Regression, PCA, and GMM.

Interview & Debug Edge

Classic Data Science question: 'What is the difference between StandardScaler and a Log/Box-Cox transform, and why does Box-Cox fail on zeros?'

Step 0 · Test Your Gut Before Any Math!

Your feature net_profit contains negative losses (-500),zeros(500), zeros (0), and massive positive gains (+$200,000). Which power transform works out of the box?

What You Will Master in This Chapter
  • Explain why log1p(x) is preferred over log(x) for non-negative features that contain zeros.
  • Choose between Box-Cox (strictly positive x>0x > 0) 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.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
log⁡(1+x)\log(1 + x)Say aloud:“log1p transform”
Plain-English Meaning
Compresses huge right tails while safely mapping x = 0 to 0.
Everyday Example
log1p(0)=0, log1p(10)=2.4, log1p(10000)=9.2.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

TransformAllowed Input RangeWhen to Use
np.log1p(x)x≥0x \ge 0Counts, prices, revenue, clicks, session durations (fast & interpretable!)
Box-Coxx>0x > 0 strictlyPositive continuous features when you want an automated optimal λ\lambda
Yeo-JohnsonAny x∈Rx \in \mathbb{R}Skewed features that include zeros or negative values (e.g., profit/loss)
Quantile BinningAny x∈Rx \in \mathbb{R}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 z=log⁡(1+y)z = \log(1 + y) has two superpowers:

  1. It stops a single $20M mansion from dominating the squared error of 1,000 starter homes.
  2. Minimizing MSE on log⁡(1+y)\log(1 + y) is mathematically equivalent to minimizing RMSLE (relative percentage error).

Don't Forget: Always convert predictions back to dollars with y^=exp⁡(z^)−1\hat{y} = \exp(\hat{z}) - 1 (np.expm1) before reporting RMSE to stakeholders!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Input log transforms rarely change tree splits because log⁡(x)\log(x) is monotonic (preserves order). However, log-transforming a skewed target yy can still massively improve XGBoost regression!

Interactive Visual Lab
Lab Challenge: Observe how well-conditioned feature distributions stabilize optimization.
Interactive Animation • Feature Scaling & Optimization

Unscaled Ravine (Zig-Zag!) vs. StandardScaler Circle (Straight Shot!)

Watch both gradient-descent marbles race simultaneously with the exact same learning rate!

Raw Unscaled (Age vs. Salary)
After StandardScaler (μ=0, σ=1)
0%
GD Step 0/12
Raw Unscaled: steep salary-vs-age walls force wild vertical oscillation. StandardScaler (μ=0, σ=1): circular contours send gradients straight to the global minimum in half the steps!
Intuition Takeaway: Use log1p for skewed non-negative counts/money, Yeo-Johnson when negatives/zeros exist, and Quantile Binning to give linear models non-linear flexibility.
Production NumPy & PyTorch Code Patterns
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())
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Reporting RMSE in log-dollars (0.18) to a business stakeholder instead of inverting back to dollars with expm1.
Best Practice: Always invert target transforms back into original business units before computing final MAE/RMSE.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Why do ML engineers use np.log1p(x) instead of np.log(x) for count features like num_purchases?

Apply What You Learned — Solve Matching Coding Problems