Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 2 of 9
Univariate Distribution Analysis, Skewness & Kurtosis Diagnostics
Linear models, neural networks, and distance-based estimators assume input features follow approximately Gaussian normal distributions with finite variance. Univariate distribution diagnostics evaluate three core properties: Central Tendency (mean vs median), Dispersion (variance, IQR), and Higher-Order Moments: Skewness (asymmetry around the mean) and Kurtosis (tail heaviness and propensity for extreme events).
Statistical Distribution Testing & Power Transformations
import numpy as np
import scipy.stats as stats
import pandas as pd
# Generate a right-skewed exponential distribution (common in revenue, transaction amounts)
np.random.seed(42)
raw_revenue = np.random.exponential(scale=500.0, size=2000) + 10.0
# 1. COMPUTE HIGHER-ORDER DISTRIBUTION MOMENTS
mean_val = np.mean(raw_revenue)
median_val = np.median(raw_revenue)
skewness = stats.skew(raw_revenue)
kurtosis = stats.kurtosis(raw_revenue) # Fisher's definition (normal = 0.0)
print(f"Raw Distribution Moments:")
print(f" Mean: ${mean_val:.2f} | Median: ${median_val:.2f}")
print(f" Skewness: {skewness:.4f} (Skew > 1 indicates severe right tail)")
print(f" Kurtosis: {kurtosis:.4f} (Kurtosis > 3 indicates heavy fat tails / leptokurtic)")
# 2. STATISTICAL NORMALITY HYPOTHESIS TESTS
# Shapiro-Wilk test (H0: data is normally distributed)
stat_sw, p_val_sw = stats.shapiro(raw_revenue[:500])
print(f" Shapiro-Wilk Test p-value: {p_val_sw:.4e} -> {'Reject Normality' if p_val_sw < 0.05 else 'Normal'}")
# 3. NORMALIZING POWER TRANSFORMATIONS
# (a) Log1p transformation: log(1 + x)
log_transformed = np.log1p(raw_revenue)
# (b) Box-Cox transformation: requires strictly positive data
boxcox_transformed, optimal_lambda = stats.boxcox(raw_revenue)
print(f"\nPost-Transformation Skewness Diagnostics:")
print(f" Log1p Skewness : {stats.skew(log_transformed):.4f}")
print(f" Box-Cox Skewness : {stats.skew(boxcox_transformed):.4f} (optimal lambda = {optimal_lambda:.2f})")Pro Tip: When to Log-Transform the Target Variable y
In regression tasks predicting positive monetary amounts (house prices, hospital stay costs, insurance payouts), the target is typically log-normally distributed. Transforming the target with `y_trans = np.log1p(y)` and training your model on `y_trans` stabilizes residual variance (homoscedasticity) and penalizes relative percentage errors rather than absolute dollar errors.
MlDistributionAnalysis Visual Representation
Hands-On Challenge: Quantile-Quantile (Q-Q) Plot Verification
Implement a function that computes theoretical normal quantiles against empirical sample quantiles, plotting a Q-Q plot to diagnose whether distribution departures are occurring in the center or in the extreme tail percentiles.
Quick Quiz & Key Concept Checks
Common Pitfall: Inverse Transforming Predictions Incorrectly
If you train a regression model on `y_log = np.log1p(y)`, you must invert the model's predictions back to original units using `np.expm1(y_pred)`. Forgetting to inverse-transform results in predictions that are orders of magnitude too small.