2.1.9Data Preprocessing & Feature Engineering

Log and power transformations

2,625 words12 min readdifficulty · medium1 backlinks

What Are These Transformations?

Why Each Transformation Works

1. Logarithmic Transformation

2. Box-Cox Transformation

3. Yeo-Johnson Transformation

When to Use Each

Common Mistakes

Mathematical Properties

When transformations DON'T help:

  • Tree-based models (Random Forest, XGBoost) — they're invariant to monotonic transforms
  • Data is already normal/symmetric
  • Small sample size (< 30) — transformation can introduce artifacts

Practical Workflow

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
 
# 1. Diagnose skewness
data = np.array([10, 15, 18, 22, 50, 120, 500])
skew = stats.skew(data)  # > 0 → right skew
print(f"Original skewness: {skew:.2f}")
 
# 2. Try transformations
log_data = np.log1p(data)
sqrt_data = np.sqrt(data)
bc_data, best_lambda = stats.boxcox(data + 1)  # +1 if zeros
 
print(f"Log skewness: {stats.skew(log_data):.2f}")
print(f"Box-Cox λ: {best_lambda:.2f}, skewness: {stats.skew(bc_data):.2f}")
 
# 3. Visualize
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
for ax, d title in zip(axes.flat,
                         [data, log_data, sqrt_data, bc_data],
                         ['Original', 'Log', 'Sqrt', 'Box-Cox']):
    ax.hist(d, bins=15, edgecolor='black', alpha=0.7)
    ax.set_title(f"{title}\nSkew: {stats.skew(d):.2f}")
Recall Explain Like I'm 12: Why Log Scales?

Imagine you're measuring how fast things grow. A bacteria colony doubles every hour: 1 → 2 → 4 → 8 → 16 → 32. If you plot this on regular paper, the line curves up super steep and you can't see the early numbers.

But here's the trick: each doubling is the same type of change (×2). So let's make a special ruler where equal distances mean "multiply by the same amount." Now1→2 is the same distance as 16→32 on your ruler. This is a log scale!

When you use log, going from $100 \to \infty1000 (×10) looks the same as \1000 \text{ to }10,000 (×10). That's why we log-transform income data—your brain thinks in terms of "how many times bigger," not "how many dollars more." It's the difference between "my salary doubled!" and "I got a \50k raise" (which means totally different things if you started at $25k vs $200k).

Connections

  • 2.1.05-Feature-Scaling — Transformations vs. standardization (transform shape, not just scale)
  • 2.1.08-Handling-Outliers — Log naturally compresses outliers
  • 3.2.01-Linear-Regression-Assumptions — Transforming targets for homoscedasticity
  • 2.2.03-Polynomial-Features — Alternative to log for capturing non-linearity
  • 4.1.02-Decision-Trees — Why trees don't need transformations (split-based)

#flashcards/ai-ml

What problem does log transformation solve? :: Reduces right skewness, compresses large values, converts multiplicative relationships to additive (e.g., income, population), stabilizes variance for heteroscedastic data.

Box-Cox formula for λ≠ 0
(x^λ - 1) / λ. The -1 and division by λ make it continuous at λ=0 (where it becomes log(x) by L'Hôpital's rule).
When must you use Yeo-Johnson instead of Box-Cox?
When data contains zero or negative values. Box-Cox requires x > 0; Yeo-Johnson handles all real numbers with separate formulas for x≥ 0 and x < 0.
Why add +1 in log(x+1) transformation?
Handles x=0 (since log(0) is undefined). Called1p in numpy. Alternative: add domain-appropriate constant (e.g., 1 for counts).
After training on log-transformed target, how do you get predictions in original units?
Apply inverse: exp(ŷ_log). Add bias correction exp(ŷ + σ²/2) due to Jensen's inequality if you need E[y], not median.
Should you fit Box-Cox λ before or after train/test split?
After. Fit λ on training data only, then apply the same λ to test data (like any other preprocessing parameter). Fitting on all data before split leaks information.
Which models don't benefit from log/power transformations?
Tree-based models (Random Forest, XGBoost, decision trees) because they're invariant to monotonic transformations—they split on thresholds, not distances.
What does Box-Cox λ=0.5 represent?
Square root transformation. λ=1 is identity (no transform), λ=0 is log, λ=-1 is reciprocal (-1/x).

Concept Map

motivates

includes

includes

includes

extends to

converts

offset via

searches for

maximizes

handles negatives

produces

achieves

satisfies

Skewed Data spanning orders of magnitude

Log and Power Transformations

Log Transform

Square Root lambda=0.5

Box-Cox

Yeo-Johnson

Normal-like Distribution

Stabilized Variance / Homoscedasticity

Multiplicative to Additive

log1p x+1 handles zeros

Optimal lambda

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Log aur power transformations ka basic idea ye hai kiagar apka data bahut skewed hai—matlab ek taraf extreme values hain (jaise salary data mein 20 lakh wale common hain par 2 crore wale bhi hain)—to directly model banana mushkil ho jata hai. Linear regression jaise algorithms assume karte hain ki data normally distributed hai, par real-world data mein ye rarely hota hai.

Log transformation sabse simple hai: log(x) apply karo. Ye bade values ko compress kar deta hai—jaise 1 crore aur 10 crore mein original space mein 9 crore ka farak hai, but log space mein sirf 1 ka farak (because log₁₀(10^7)=7 aur log₁₀(10^8)=8). Isliye salary, population, website traffic jaise exponential growth wale features ko log transform karne se model ko samajhna aasaan ho jata hai. Caveat: agar data mein zero ya negative values hain to log(x+1) use karna padega (warna -inf aa jayega aur code crash karega).

Box-Cox transformation ek step age hai—ye automatically best power (λ) dhundh leta hai jo data ko sabse zyada normal-looking banaye. λ=0 means log, λ=0.5 means square root, λ=1 means koi transformation nahi. Scikit-learn ka PowerTransformer ye sab automatic kar deta hai. Limitation: Box-Cox sirf positive values ke liye kaam karta hai.Agar negative values hain (jaise temperature anomalies: -5°C se +12°C), to Yeo-Johnson use karna padega jo negative values handle kar sakta hai.

Practical tip: Tree-based models (Random Forest, XGBoost) ko transformations ki zarurat nahi hoti kyunki wo splits par kaam karte hain, distance par nahi. But linear models, neural networks, aur SVM ke liye ye transformations bohot helpful hain. Aur haan, ek bahut common mistake: agar apne target variable (y) ko log-transform kiya hai, to predictions ko wapas original scale mein lane ke liye exp(ŷ) karna mat bhoolna!

Go deeper — visual, from zero

Test yourself — Data Preprocessing & Feature Engineering

Connections