Predict customer spend with zero-inflated heavy-tailed regression
Machine LearningModel answerLast updated
Build a complete pipeline to forecast 90-day customer value from marketing and behavioral data, addressing zero inflation, multicollinearity, and leakage.
You are tasked with building a regression system to forecast 90-day customer spending at the individual level. The target exhibits two challenging properties: many customers spend nothing (creating a spike at zero), and a small subset generates extremely high revenue (creating a long right tail).
Available input signals include:
- Channel-specific marketing expenditure (search, social, display)
- Behavioral metrics capturing recency, frequency, and monetary patterns
- Device category and geographic location
- Duration since account creation
- Several hundred sparse campaign identifiers with high cardinality
Data complications you must address:
- Marketing spend features are highly correlated with each other
- Prediction uncertainty grows as predicted values increase
- Feature-target relationships may be nonlinear
- Data arrives with natural time ordering across multiple periods
Your task is to architect a complete modeling solution covering:
- Distribution and loss: Select and defend a loss function and distributional family appropriate for zero-inflated, heavy-tailed outcomes
- Feature transformations: Process continuous variables, encode high-cardinality categories without introducing leakage, and consolidate rare levels
- Penalty methods: Mitigate correlation through penalized estimation; derive the elastic net loss and explain when L1 versus L2 terms dominate
- Temporal validation: Construct a cross-validation framework that respects time dependencies and prevents future information from contaminating training
- Assumption checking: Identify and correct heteroskedasticity, nonlinearity, and outlier influence
- Prediction intervals: Generate well-calibrated uncertainty estimates and contrast different interval construction methods
- Model interpretation: Explain how you extract insight from linear model coefficients versus tree-based feature attributions
- Leakage mitigation: Enumerate the major sources of data leakage in this pipeline and describe prevention strategies
- Model comparison: Evaluate regularized linear models against gradient boosting across performance, interpretability, and stability dimensions
Hints
Hint 1
Distributions that accommodate exact zeros alongside continuous positive values are well-suited to revenue prediction
Hint 2
When encoding categories using target statistics, compute them out-of-sample within your training data to avoid overfitting
Hint 3
Temporal validation must account for the 90-day measurement window and block all future-dated information from training
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Distribution and Loss Function Selection
The target's characteristics—substantial probability mass at exactly zero combined with extreme right skewness—dictate the modeling framework. I recommend a Tweedie GLM with log link as the foundation.
The Tweedie distribution with power parameter between 1 and 2 is a compound Poisson-Gamma that naturally generates exact zeros with positive probability while producing a continuous, right-skewed distribution for non-zero values. Its variance structure Var(Y|X) = φ·μ^p explicitly captures heteroskedasticity: prediction variance scales with the predicted mean.
The log link guarantees non-negative predictions and produces multiplicative effects appropriate for monetary relationships: log(μ) = X^T β.
Select the power parameter p (commonly 1.3–1.7 for revenue applications) through maximum profile likelihood or cross-validation on deviance.
When to consider alternatives:
- Hurdle (two-part) model: Model P(Y > 0) and E[Y | Y > 0] separately, then combine. Appropriate when different features drive conversion versus spending magnitude.
- Quantile regression: Targets specific quantiles (median, 90th percentile) rather than the conditional mean. Useful for risk assessment but not mean prediction.
- Log-transformed least squares: Problematic because back-transformation introduces bias without correction, and zeros violate normality even after log1p transformation.
For gradient boosting, use a Tweedie objective function with the same power parameter.
Feature Engineering Pipeline
All statistics (means, standard deviations, encodings) must be computed exclusively on training data.
Continuous features: Apply log1p to marketing spend and monetary/frequency metrics to compress extreme values. Standardize all continuous inputs (zero mean, unit variance) for linear models so that penalty terms treat coefficients equivalently.
High-cardinality encoding: For campaign identifiers, apply smoothed target encoding:
encoded = (count_category × mean_category + smoothing × mean_overall) / (count_category + smoothing)
The smoothing constant (typically 10–50) shrinks low-frequency categories toward the global average.
Preventing encoding leakage: Within the training fold, use 5-fold splitting by user ID. Each observation receives an encoding derived from the remaining four folds only—never from its own fold. Validation and test observations use encodings computed on the full training set. This out-of-fold approach prevents the model from memorizing training labels through the encoding.
Rare category handling: Merge categories appearing fewer than 50–100 times into "OTHER." Reserve "UNSEEN" for categories absent from training but present at test time.
Simple categoricals: One-hot encode device and region features.
Elastic Net for Multicollinearity
The penalized GLM minimizes:
(1/n) Σᵢ deviance(yᵢ, β₀ + xᵢ^T β) + λ [α ||β||₁ + (1−α)/2 ||β||₂²]
The intercept β₀ receives no penalty. The regularization parameter λ controls overall shrinkage strength.
The mixing parameter α determines penalty character:
-
α ≈ 1 (L1-dominated): Drives coefficients to exactly zero, yielding sparse models. Among correlated predictors (marketing channels), L1 arbitrarily selects one and eliminates others. Selection varies across cross-validation folds.
-
α ≈ 0 (L2-dominated): Shrinks correlated coefficients toward each other but retains all features. Stable across resamples but provides no automatic selection.
-
Practical choice: Set α between 0.1 and 0.5. This achieves moderate sparsity for weak campaign effects while maintaining stable, interpretable coefficients for correlated channel features.
Tune λ and α together via inner cross-validation. Compute variance inflation factors before fitting; examine coefficient stability across bootstrap samples after fitting.
Temporal Cross-Validation Design
Outer evaluation loop: Define sequential cutoff times t₁ < t₂ < ... < tₖ. For cutoff tᵢ, test data comprises users evaluated at tᵢ.
90-day embargo: Training observations must close their label measurement window before the test cutoff: training_time + 90 days ≤ test_time. Without this gap, training labels temporally overlap test feature periods—a critical leakage source.
Inner tuning loop: Within each outer training set, apply the same time-based scheme to select hyperparameters (α, λ, p, tree depth, learning rate, iterations).
User-level grouping: Assign folds by user ID so one customer's observations never split across train and validation. For campaign analysis, either exclude campaigns spanning fold boundaries from training, or stratify results by seen versus unseen campaigns.
Report performance as mean ± standard deviation across outer folds. Outer fold results never influence model selection.
Diagnostic Procedures
Heteroskedasticity:
- Plot residuals against predictions; widening spread indicates heteroskedasticity
- For ordinary least squares, conduct Breusch-Pagan or White tests
- For GLMs, examine Pearson residuals: (observed − fitted) / √(variance_function)
- Regress log(squared residuals) on log(fitted); the slope approximates the variance power
Corrections:
- Use Tweedie GLM to model variance structure directly
- Apply heteroskedasticity-consistent standard errors (HC3)
- Transform the response to stabilize variance
Nonlinearity:
- Generate partial residual plots for key continuous features
- Create binned actual-versus-predicted plots
Fixes: Introduce natural cubic splines (3–5 knots) for features showing curvature. Add theoretically motivated interactions like device × channel. Tree models handle these automatically; their dependence plots guide linear model augmentation.
Outlier influence:
- Calculate Cook's distance and leverage
- Retain high-value customers—they are signal, not noise
- Apply robust loss functions (Huber for moderate robustness, Tukey biweight for aggressive downweighting)
- Winsorize input features if necessary, never the target
Calibrated Prediction Intervals
OLS intervals: ŷ ± critical_value × σ̂ × √(1 + x^T(X^TX)⁻¹x) assume constant Gaussian errors. They are:
- Symmetric and permit negative predictions
- Miscalibrated: too narrow for high-value users, too wide for low-value users
Preferred method—Conformal Quantile Regression:
- Train quantile models at the 2.5th and 97.5th percentiles using quantile loss
- On a held-out calibration set from recent data, compute conformity scores: max(lower_quantile − actual, actual − upper_quantile)
- Find the ⌈(n_cal + 1) × 0.95⌉ / n_cal quantile of these scores, call it Q̂
- Final intervals: [max(0, lower_quantile − Q̂), upper_quantile + Q̂]
This method provides finite-sample coverage guarantees under exchangeability and adapts interval width to each user's characteristics.
Temporal drift: Time trends violate exchangeability. Use only recent data for calibration, or apply weighted/adaptive conformal methods.
Alternative—bootstrap: Resample residuals or (X, y) pairs, refit, and extract percentiles. Computationally expensive and only asymptotically valid.
Validation: On test folds, report empirical coverage and mean interval width, overall and stratified by value decile or segment.
Interpretation Strategies
Linear model coefficients:
- Compute standardized coefficients: β̂_std = β̂ × sd(feature)
- Under log link, exp(β̂_std) gives the multiplicative change in expected value per one-standard-deviation increase
- Regularization biases estimates toward zero
- Correlated features share credit; interpret marketing channels jointly
- Coefficients reflect association, not causation
Tree model attributions—SHAP:
- TreeSHAP efficiently computes Shapley values satisfying: prediction = baseline + Σ feature_contributions
- Values are local (per-user) and additive
- For Tweedie GBMs, compute on the linear predictor scale (log-link space)
- Aggregate via mean absolute SHAP for global importance
- Dependence plots reveal nonlinear patterns and interactions
- SHAP does not isolate causal effects—only predictive contribution
Comparison: Coefficients provide stable global summaries for linear models; SHAP reveals complex interactions in tree models but at higher computational cost and lower interpretability.
Data Leakage Prevention
Primary leakage sources:
-
Target leakage: Features computed after the prediction cutoff or using post-cutoff information. Solution: enforce strict time cutoffs; use only data available at prediction time.
-
Label leakage in target encoding: Using the current observation's label in its own encoding. Solution: out-of-fold encoding within training; global statistics for validation/test.
-
Temporal leakage: Training labels that overlap test feature periods. Solution: 90-day embargo between training label close and test cutoff.
-
Group leakage: Same user in both training and validation with correlated behavior. Solution: split by user ID.
-
Test set contamination: Computing standardizations or encodings on combined train+test. Solution: fit all transformations on training only.
Validation: Check that no training observation has label_end_date > test_prediction_date. Verify target encodings change across folds. Confirm feature distributions shift appropriately across time splits.
Model Trade-off Analysis
Regularized linear model (Tweedie GLM):
- Performance: Good on well-specified relationships; struggles with complex interactions
- Interpretability: Coefficients directly quantify feature effects; stakeholders understand multiplicative impacts
- Robustness: Stable across samples; less sensitive to outliers with robust loss
- Inference: Standard errors and confidence intervals available
- Deployment: Fast scoring; minimal compute
Gradient boosted trees (Tweedie GBM):
- Performance: Captures nonlinearity and interactions automatically; typically 5–15% improvement on complex revenue data
- Interpretability: SHAP provides local explanations but is computationally expensive; harder to explain to non-technical stakeholders
- Robustness: Can overfit on small samples; requires careful tuning
- Inference: No analytic standard errors; must bootstrap
- Deployment: Slower prediction; larger model artifacts
Metric selection: Use mean absolute error (MAE) or quantile loss for robustness to heavy tails. Avoid RMSE, which overweights outliers. For percentage errors, use sMAPE or MAPE with epsilon (e.g., |y − ŷ| / (|y| + ε)) to avoid division by zero.
Recommendation: Start with a well-regularized GLM for baseline interpretability. Deploy GBM if performance gains justify reduced transparency. Consider ensembling both with learned weights for optimal performance-interpretability balance.