Zero Labs
Industry News / AI

XGBoost for Tabular Time Series: A Multi-Stage Framework for Inventory Recovery Forecasting

Source · Towards AI By Dan Nguyen

From the publisher’s feed, collected in the ZeroLabs newsroom.

When your target is zero-inflated and bounded, one model is never enough.Photo by Markus Winkler on UnsplashI recently had the opportunity to build a forecasting system for a large e-commerce network’s global fulfilment operation. The goal was deceptively simple: predict what fraction of inventory at a given processing site, for a given product group, in a given week, would fail to sell at full price and enter a downstream recovery process.What made this genuinely interesting from a modeling perspective had nothing to do with scale. It was the structure of the target itself. The distribution was severely zero-inflated and bounded on [0, 1]. No single off-the-shelf model handles both of those constraints simultaneously. The result was a two-stage XGBoost pipeline that I want to walk through here — including the feature engineering, the target transforms, the Optuna tuning setup, and the SHAP decomposition that made the predictions interpretable to the business.If you’ve used XGBoost for regression or classification before but haven’t applied it to time-structured tabular data with awkward target distributions, this tutorial is for you.Why XGBoost for Time Series?XGBoost is not a native time series model. It has no internal notion of sequence, autocorrelation, or temporal order. That’s actually fine — and in many tabular forecasting applications, it’s preferable to explicitly engineered temporal features over learned recurrence.The core appeal of XGBoost for this kind of problem comes down to a few practical properties. It handles heterogeneous tabular data well: integer identifiers, categorical site types, float proportions, and count volumes can all coexist in the same feature matrix without preprocessing gymnastics. It’s robust to missing values by design. Its built-in regularization — penalizing both tree complexity and leaf weight magnitude — reduces overfitting without requiring a separate pruning step. And for large datasets with many features, the histogram-based tree construction algorithm makes training fast.The tradeoff is that you are entirely responsible for encoding time. XGBoost sees each row as independent. To give it memory of the past, you have to engineer that memory yourself.The DataEach observation in the dataset represents a unique combination of fulfilment site, product group, and calendar week. For each such combination, the record captures:Total unit volume, weight, and cost of goodsProduct composition by fulfilment channel and high-level product type.Site-level metadata: country, state, site type, and a hashed site identifierThe recovery outcome: whether any units entered the recovery funnel that week, and if so, what fraction of total inventory they representedThe dataset spanned 2022 through 2025, with the full 2025 year held out as the test set. The training population exceeded 6 million site-product group-week observations after cleaning.Feature Engineering: Giving XGBoost a MemoryThis is the step that separates an XGBoost time series pipeline from a plain tabular model. The features below are the ones that ended up mattering most.Step 1: Build a Complete Weekly GridBefore computing any temporal features, you need a dense time index. Gaps in the data — weeks with no recorded activity — should be filled with explicit zero rows rather than left as missing observations. Without this, lag and rolling computations silently skip over gaps and produce misleading values.import pandas as pdimport numpy as npfrom itertools import productdef build_complete_grid(df: pd.DataFrame) -> pd.DataFrame: """Ensure every (site, product_group, week) triple has a row.""" sites = df["site_id"].unique() product_groups = df["product_group_id"].unique() weeks = pd.date_range(df["week_start"].min(), df["week_start"].max(), freq="W-MON") grid = pd.DataFrame( list(product(sites, product_groups, weeks)), columns=["site_id", "product_group_id", "week_start"] ) return grid.merge(df, on=["site_id", "product_group_id", "week_start"], how="left").fillna(0)Step 2: Lag FeaturesThe single most predictive signals in this dataset were lagged recovery rates at the (site, product group) level. XGBoost cannot look backward on its own — you have to pre-compute each lag.def add_lag_features(df: pd.DataFrame, target_col: str, lags: list[int]) -> pd.DataFrame: df = df.sort_values(["site_id", "product_group_id", "week_start"]) for lag in lags: df[f"{target_col}_lag_{lag}w"] = ( df.groupby(["site_id", "product_group_id"])[target_col] .shift(lag) ) return dfdf = add_lag_features(df, "recovery_rate", lags=[1, 2, 4, 8, 13, 26, 52])The 26- and 52-week lags capture long-run seasonal behavior. The 1- and 2-week lags capture recent momentum. Both matter, but for different reasons.Step 3: Rolling Windows and EWMAsRolling means smooth out week-to-week noise and give the model a stable estimate of a site-product group pair’s baseline recovery tendency. Exponentially weighted moving averages down-weight older observations, which is useful when recovery patterns shift over time.def add_rolling_features( df: pd.DataFrame, target_col: str, windows: list[int]) -> pd.DataFrame: grouped = df.groupby(["site_id", "product_group_id"])[target_col] for w in windows: df[f"{target_col}_rolling_mean_{w}w"] = ( grouped.transform(lambda x: x.shift(1).rolling(w, min_periods=1).mean()) ) df[f"{target_col}_ewma_{w}w"] = ( grouped.transform(lambda x: x.shift(1).ewm(span=w, min_periods=1).mean()) ) return dfdf = add_rolling_features(df, "recovery_rate", windows=[4, 8, 13, 26, 52])Note the .shift(1) inside each transform. This is critical: you are forecasting the current week's recovery rate, so the rolling window must be computed from the previous week backward. Without the shift, you leak the current observation into your feature, and your model will appear to perform far better than it actually does.Step 4: Entity-Level Baseline StatisticsFor each (site, product group) pair, compute three summary statistics from the training set only, then join them onto both training and test data. These act as entity-level priors that help the model generalize to weeks where temporal features are sparse.def compute_entity_baselines(train_df: pd.DataFrame, target_col: str) -> pd.DataFrame: stats = ( train_df[train_df[target_col] > 0] .groupby(["site_id", "product_group_id"])[target_col] .agg( baseline_mean="mean", baseline_std="std", baseline_count="count" ) .reset_index() ) return statsbaselines = compute_entity_baselines(train_df, "recovery_rate")# Join onto both splits; fall back to product-group-level and global priors for unseen pairstrain_df = train_df.merge(baselines, on=["site_id", "product_group_id"], how="left")test_df = test_df.merge(baselines, on=["site_id", "product_group_id"], how="left")product_group_baselines = ( train_df[train_df["recovery_rate"] > 0] .groupby("product_group_id")["recovery_rate"] .mean() .rename("product_group_baseline_mean"))global_mean = train_df[train_df["recovery_rate"] > 0]["recovery_rate"].mean()for df in [train_df, test_df]: df["baseline_mean"] = ( df["baseline_mean"] .fillna(df["product_group_id"].map(product_group_baselines)) .fillna(global_mean) )The Multi-Stage ApproachThis is the architectural decision that everything else depends on. Here is why a single XGBoost regressor fails here.The recovery rate distribution has two structural problems:Zero inflation. The majority of site-product group-week observations record zero recovery — the inventory sold. Fitting a single regressor on this mixture forces the model to balance two competing objectives: predicting when recovery is zero, and predicting its magnitude when it is not. It does neither well.Bounded target. Recovery rate lives on [0, 1]. Standard regression makes no such guarantee. A logit transform maps this to the real line for training, but the inverse sigmoid at inference time must be applied carefully when composing predictions across stages.The two stages address each problem in turn.Stage 1: Binary Classification for Funnel EntryStage 1 is a binary classifier estimating the probability that any recovery occurs in a given site-product group-week. All observations are used for training, including zero-recovery rows.import xgboost as xgbfrom sklearn.model_selection import train_test_split# Temporal split: earlier years train, most recent year teststrain_mask = df["week_start"].dt.year train_df = df[train_mask].copy()test_df = df[~train_mask].copy()FEATURE_COLS = [c for c in df.columns if c not in ["site_id", "product_group_id", "week_start", "recovery_rate", "entered_funnel"]]X_train = train_df[FEATURE_COLS]y_train = (train_df["recovery_rate"] > 0).astype(int)X_test = test_df[FEATURE_COLS]y_test = (test_df["recovery_rate"] > 0).astype(int)# Address class imbalance via scale_pos_weightpos_weight = (y_train == 0).sum() / (y_train == 1).sum()clf = xgb.XGBClassifier( objective="binary:logistic", max_depth=6, learning_rate=0.05, subsample=0.8, colsample_bytree=0.8, min_child_weight=5, gamma=0.1, reg_alpha=0.01, reg_lambda=1.0, scale_pos_weight=pos_weight, tree_method="hist", enable_categorical=True, n_estimators=1000, early_stopping_rounds=50, eval_metric="aucpr",)# Hold out a small validation set for early stoppingX_tr, X_val, y_tr, y_val = train_test_split( X_train, y_train, test_size=0.1, shuffle=False # shuffle=False to preserve order)clf.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=100)p_recovery = clf.predict_proba(X_test)[:, 1]Use AUC-PR rather than AUC-ROC for evaluation. With a heavily imbalanced class distribution, AUC-ROC is optimistic because it weighs true negatives heavily. AUC-PR focuses on the positive class, which is what matters operationally.Stage 2: Recovery Rate Regression (Conditional on Entry)Stage 2 trains a regressor on non-zero recovery rows only, estimating the magnitude of recovery conditional on it occurring. The product of Stage 1 and Stage 2 gives the unconditional recovery rate via the law of total expectation:E(recovery rate) = P(recovery > 0) × E(recovery rate | recovery > 0)The target is logit-transformed before training. This maps the bounded [0, 1] interval to the real line, preventing the model from generating out-of-range predictions and making gradient updates more stable near the boundaries.from scipy.special import logit, expit# Filter to non-zero rows onlytrain_nonzero = train_df[train_df["recovery_rate"] > 0].copy()test_nonzero = test_df[test_df["recovery_rate"] > 0].copy()# Clip slightly away from exact 0 and 1 before logit transform to avoid -inf / +infeps = 1e-6train_nonzero["target_logit"] = logit( train_nonzero["recovery_rate"].clip(eps, 1 - eps))X_reg_train = train_nonzero[FEATURE_COLS]y_reg_train = train_nonzero["target_logit"]X_reg_test = test_nonzero[FEATURE_COLS]y_reg_test = test_nonzero["recovery_rate"]# Custom eval metric: MAE in probability space, not logit spacedef prob_space_mae(y_pred, dtrain): y_true_prob = expit(dtrain.get_label()) y_pred_prob = expit(y_pred) mae = np.mean(np.abs(y_true_prob - y_pred_prob)) return "prob_mae", mae# Sample weights: upweight sparse mid-range recovery ratesdef compute_sample_weights(rates: pd.Series) -> np.ndarray: weights = np.ones(len(rates)) mid_mask = (rates > 0.1) & (rates weights[mid_mask] = 3.0 return weightssample_weights = compute_sample_weights(train_nonzero["recovery_rate"])reg = xgb.XGBRegressor( objective="reg:squarederror", max_depth=6, learning_rate=0.05, subsample=0.8, colsample_bytree=0.8, min_child_weight=5, gamma=0.1, reg_alpha=0.01, reg_lambda=1.0, tree_method="hist", enable_categorical=True, n_estimators=1000, early_stopping_rounds=50,)X_reg_tr, X_reg_val, y_reg_tr, y_reg_val, w_tr, _ = train_test_split( X_reg_train, y_reg_train, sample_weights, test_size=0.1, shuffle=False)reg.fit( X_reg_tr, y_reg_tr, sample_weight=w_tr, eval_set=[(X_reg_val, y_reg_val)], custom_metric=prob_space_mae, verbose=100,)# Combine stage 1 and stage 2 predictionsr_hat = expit(reg.predict(X_test)) # conditional rate (all test rows)p_hat = clf.predict_proba(X_test)[:, 1] # P(recovery > 0)combined_pred = p_hat * r_hatTemporal Train-Test SplitThis deserves its own section because it is the most common mistake in tabular time series work. Do not use random train-test splits. Do not use k-fold cross-validation with random shuffling.# Correct: temporal splittrain_df = df[df["week_start"].dt.year test_df = df[df["week_start"].dt.year == 2026]# Wrong: random split leaks future into trainingfrom sklearn.model_selection import train_test_splittrain_df, test_df = train_test_split(df, test_size=0.2) # DO NOT DO THISIf you use random splits, lag features computed from future observations will appear in your training rows, and your model will learn to condition on information it would never have at inference time. Your test metrics will look better than they are — sometimes dramatically so.For cross-validation within the training set during early stopping, use a holdout of the most recent training period rather than a random 10%. The XGBoost early_stopping_rounds mechanism with a temporally ordered validation set is a practical substitute for time-series cross-validation and adds minimal overhead.Hyperparameter Tuning with OptunaGrid search over this many hyperparameters is computationally prohibitive. Optuna’s Tree-structured Parzen Estimator (TPE) algorithm concentrates search effort in promising regions of the parameter space by building probabilistic models over which configurations performed well versus poorly in previous trials.import optunafrom sklearn.metrics import average_precision_scoredef objective_stage1(trial: optuna.Trial) -> float: params = { "max_depth": trial.suggest_int("max_depth", 3, 10), "learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3, log=True), "subsample": trial.suggest_float("subsample", 0.5, 1.0), "colsample_bytree": trial.suggest_float("colsample_bytree", 0.3, 1.0), "min_child_weight": trial.suggest_int("min_child_weight", 1, 50), "gamma": trial.suggest_float("gamma", 0.0, 5.0), "reg_alpha": trial.suggest_float("reg_alpha", 1e-8, 10.0, log=True), "reg_lambda": trial.suggest_float("reg_lambda", 1e-8, 10.0, log=True), "scale_pos_weight": pos_weight, "objective": "binary:logistic", "tree_method": "hist", "enable_categorical": True, "n_estimators": 1000, "early_stopping_rounds": 50, "eval_metric": "aucpr", } model = xgb.XGBClassifier(**params) model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=False) preds = model.predict_proba(X_val)[:, 1] return average_precision_score(y_val, preds)study = optuna.create_study(direction="maximize")study.optimize(objective_stage1, n_trials=50)best_params = study.best_paramsRun a separate Optuna study for each stage. The optimal depth and regularization for a binary classifier differ substantially from those of a regressor trained on a filtered, logit-transformed target.SHAP for InterpretabilitySHAP (SHapley Additive exPlanations) provides feature-level attribution that is consistent and theoretically grounded in cooperative game theory. For tree models, TreeExplainer computes exact SHAP values efficiently.import shapexplainer = shap.TreeExplainer(reg)shap_values = explainer.shap_values(X_reg_test.sample(10_000, random_state=42))shap.summary_plot(shap_values, X_reg_test.sample(10_000, random_state=42))Beyond standard feature importance, the additive property of SHAP values enables a useful decomposition: separate each prediction into a long-run baseline component (contributions from 26-week and 52-week lags, historical mean recovery rate) and a current-week deviation component (contributions from short-horizon lags, volume anomalies, channel mix shifts).BASELINE_FEATURES = [ "recovery_rate_rolling_mean_52w", "recovery_rate_rolling_mean_26w", "recovery_rate_lag_52w", "recovery_rate_lag_26w", "baseline_mean",]DEVIATION_FEATURES = [ "recovery_rate_lag_1w", "recovery_rate_lag_2w", "recovery_rate_ewma_4w", "units_total", "hazmat_share", # ... other short-horizon and inventory features]feature_names = X_reg_test.columns.tolist()baseline_idx = [feature_names.index(f) for f in BASELINE_FEATURES if f in feature_names]deviation_idx = [feature_names.index(f) for f in DEVIATION_FEATURES if f in feature_names]expected_logit = explainer.expected_valuebaseline_logit = expected_logit + shap_values[:, baseline_idx].sum(axis=1)deviation_logit = shap_values[:, deviation_idx].sum(axis=1)baseline_prob = expit(baseline_logit)deviation_prob = expit(baseline_logit + deviation_logit) - baseline_probThis decomposition produces three interpretable numbers per prediction: what history alone implies, how much this specific week deviates from that, and the combined forecast.Key TakeawaysA few things from this project that generalize broadly:Stage your model when the target distribution demands it. Zero-inflation and bounded targets are not quirks to be tolerated — they are signals that a single model is being asked to do incompatible things simultaneously. A hierarchical pipeline that addresses each structural problem separately is harder to build but substantially easier to diagnose and improve.Do not underestimate feature engineering. The dominant predictors in this model were lagged and rolling recovery rates. This is typical for autoregressive tabular forecasting problems: the strongest signal for next week’s behavior is usually last week’s behavior. The current-week deviation component added meaningful but secondary signal.Temporal data requires temporal evaluation. The temporal train-test split, the ordered early-stopping validation set, and the stratified performance breakdown by rate bucket all matter. Global MAE on a random test split will tell you almost nothing about how the model performs on the rare high-recovery cases that carry the most operational weight.ReferencesChen, T. and Guestrin, C. (2016). XGBoost: A scalable tree boosting system. Proc. 22nd ACM SIGKDD, pp. 785–794.Akiba, T. et al. (2019). Optuna: A next-generation hyperparameter optimization framework. Proc. 25th ACM SIGKDD, pp. 2623–2631.Lundberg, S. (2023). An introduction to explainable AI with Shapley values. SHAP Documentation.XGBoost for Tabular Time Series: A Multi-Stage Framework for Inventory Recovery Forecasting was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.