Lesson 7 of 9
Target Transformations: Log1p, Box-Cox & Power Transformations for Skewed Labels
When predicting continuous targets with severe positive skew (house prices, hospital stay length, insurance claims), standard squared loss (MSE) penalizes errors on high-value outliers disproportionately. Transforming the target distribution using Log1p (log(1 + y)), Box-Cox, or Yeo-Johnson stabilizes residual variance (homoscedasticity) and aligns loss optimization with relative percentage errors.
TransformedTargetRegressor Pipeline in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.compose import TransformedTargetRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
# Ingest housing dataset (Target: Median House Value, heavily skewed)
raw = fetch_california_housing(as_frame=True)
X, y = raw.data, raw.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# 1. BASELINE UNTRANSFORMED REGRESSION
model_untrans = Ridge(alpha=1.0)
model_untrans.fit(X_train, y_train)
y_pred_untrans = model_untrans.predict(X_test)
# 2. LOG-TRANSFORMED TARGET PIPELINE
# TransformedTargetRegressor handles log1p during fit() and expm1 during predict()
model_log = TransformedTargetRegressor(
regressor=Ridge(alpha=1.0),
func=np.log1p,
inverse_func=np.expm1
)
model_log.fit(X_train, y_train)
y_pred_log = model_log.predict(X_test)
print("=== TARGET TRANSFORMATION PERFORMANCE BENCHMARK ===")
print(f"Untransformed Target Test MAE : ${mean_absolute_error(y_test, y_pred_untrans)*100_000:,.2f}")
print(f"Log1p-Transformed Target MAE : ${mean_absolute_error(y_test, y_pred_log)*100_000:,.2f} (Error reduced!)")
print(f"R^2 Score: Untransformed = {r2_score(y_test, y_pred_untrans):.4f} | Log1p = {r2_score(y_test, y_pred_log):.4f}")Pro Tip: When to Use Quantile Target Transforms
If your target variable has extreme multimodal spikes or an intractable non-parametric distribution, wrap `TransformedTargetRegressor` with `sklearn.preprocessing.QuantileTransformer(output_distribution='normal')` to map the target directly onto a Gaussian curve.
MlHandlingSkewedTargets Visual Representation
Hands-On Challenge: Build a Box-Cox Target Wrapper
Configure a `TransformedTargetRegressor` that uses `scipy.stats.boxcox` with optimal lambda estimation during training and the inverse Box-Cox equation during inference.
Quick Quiz & Key Concept Checks
Common Pitfall: Forgetting to Inverse-Transform When Evaluating
If you train a model manually on `np.log1p(y_train)` and compute test MSE without inverting predictions with `np.expm1()`, your reported error will be in meaningless log units. Use `TransformedTargetRegressor` to automate inverse transformation.