A hands-on machine learning engineering study on Kaggle’s Store Sales benchmark: transitioning from deterministic heuristics to gradient-boosted decision trees, discovering why raw tree models struggle with retail scale disparities, engineering leakage-free multi-lag horizons, integrating Ecuador’s oil and holiday calendars, architecting a hybrid residual booster that smashes the Part VI baseline, and climbing 67 positions to Rank #116 globally (Top 21.0%) strictly on mobile edge hardware.
💻 Open-Source Code: The CatBoost exogenous time-series models, calendar feature extractors, and cross-validation pipelines are available on GitHub: myhlow/pocket-data-science (04-time-series-forecasting).
In Part VI of this series, we established that a disciplined ladder of non-machine learning heuristics could outperform 66.9% of Kaggle competitors, reaching 0.43150 RMSLE and securing Rank #183 out of 553 teams globally before training a single predictive model.
Yet heuristic baselines possess a structural ceiling: they cannot estimate promotional cross-price elasticities, capture non-linear oil price momentum, or dynamically model calendar interactions when municipal holidays coincide with semi-monthly paydays (quincenas). To push into the top tiers of the competition, we must transition to machine learning and gradient-boosted decision trees (GBDT).
Running production-grade gradient boosting across 1,782 simultaneous time series spanning 3,000,000 transaction rows imposes strict constraints on mobile hardware:
- Host Environment: Android running Termux with a Debian userspace via PRoot Distro on 64-bit ARM (
aarch64). - AI Pair Programmer: Google Antigravity CLI (
agy) executing in autonomous terminal sessions. - Hardware Budget: Strict 100% CPU execution, zero GPU acceleration, and a memory ceiling strictly capped below 500 MB RAM.
Over 5 live tournament submissions and a targeted regional calibration experiment, we advanced from an initial regularized linear model (0.49898) down to 0.41072, securing Rank #116 globally (Top 21.0%) and moving closer to the 0.400 threshold on Kaggle’s leaderboard.
Metric Alignment Invariant
The competition evaluates Root Mean Squared Logarithmic Error (RMSLE):
RMSLE = sqrt( (1 / N) * sum( ( ln(1 + y_hat_i) - ln(1 + y_i) )^2 ) )
Because regression loss functions minimize Root Mean Squared Error (RMSE):
z = ln(1 + y)
Minimizing RMSE on z is mathematically identical to minimizing RMSLE on raw unit sales y. Predictions are inverted back to sales using exponential inversion with non-negative clipping: y_hat = max(0, exp(z_hat) - 1).
The 16-Day Validation Holdout Protocol
The test set spans 16 days (2017-08-16 to 2017-08-31). To prevent lookahead leakage, our validation set mirrors this exact 16-day duration: training on dates prior to 2017-08-01 (322,542 rows) and validating strictly on 2017-08-01 to 2017-08-15 (26,730 rows). Once hyperparameters and iteration stops are confirmed, models retrain on the complete dataset through 2017-08-15.
Below is the complete progression of our machine learning architectures evaluated on Kaggle’s live public leaderboard and local holdout validation:
| Experiment & Architecture | Score / Metric | Leaderboard & Validation Status |
|---|---|---|
| Part VI Heuristic Benchmark | 0.43150 |
Rank #183 (Top 33.1%) |
| Exp 1: Regularized Linear Ridge | 0.49898 |
Linear Anchor Floor |
| Exp 2: Native Categorical CatBoost | 0.45786 |
-0.04112 vs. Exp 1 |
| Exp 3: CatBoost + Exogenous Features | 0.45390 |
-0.00396 vs. Exp 2 |
| Exp 4: Hybrid Residual GBDT + Mask | 0.42095 |
Rank #146 • Climbed 37 Places |
| Exp 5: Multi-Model Ensemble Blend | 0.41072 |
Rank #116 • Climbed 67 Places |
| Exp 6: Sierra School Multiplier (2.6x) | 0.41709 |
Regression: Asymmetric Overfit (See Part VIII) |
| Part VIII: Grandmaster Quad-Ensemble | 0.40336 |
Rank #99 Globally • Global Top 100 |
Before deploying decision tree ensembles, we established a linear baseline using L2-regularized Ridge regression on log-sales. To ensure strict metric alignment with Kaggle’s competition evaluation loss (RMSLE), the raw sales target y was transformed into log-space via z = ln(1 + y). Minimizing standard Mean Squared Error (MSE) on z mathematically minimizes RMSLE on the raw scale.
Architecture & Feature Representation
To ensure training stationarity and respect the 2.5 GB mobile RAM ceiling of our Android Termux environment, training was restricted strictly to 2017 observations (January 1 to August 15, 2017). Categorical columns (family across all 33 lines, dayofweek, and weekend indicators) were one-hot encoded with the first column dropped to prevent multicollinearity, alongside continuous signals for onpromotion and calendar day.
import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge
train = pd.read_csv("train.csv", parse_dates=["date"])
train_2017 = train[train["date"] >= "2017-01-01"].copy()
train_2017["target"] = np.log1p(train_2017["sales"])
# Construct one-hot features and target vector
features = ["onpromotion", "dayofweek", "is_weekend", "family"]
X = pd.get_dummies(train_2017[features], drop_first=True)
y = train_2017["target"]
# L2-regularized linear fit (alpha=1.0)
model = Ridge(alpha=1.0)
model.fit(X, y)
Empirical Benchmark: Validation 16-Day RMSLE: 0.46881 • Kaggle Public Score: 0.49898
The Result & Failure Mode: While Ridge established a solid parametric floor over naive persistence (0.56127), it fell far behind our Part VI heuristic benchmark (0.43150). Linear models fail on multi-series retail data because they assume purely additive feature contributions. In reality, a promotional event on high-velocity staples like GROCERY I creates a massive non-linear volume multiplier, whereas the identical promotion on specialty lines produces negligible absolute movement. Without millions of explicit manual multiplicative interaction terms, linear models cannot calibrate store-family promotional elasticity.
To model complex hierarchical interactions across stores and categories without exploding feature dimensionality into sparse matrices, we deployed CatBoost (CatBoostRegressor). CatBoost is ideally architected for mobile edge time-series engineering due to two mathematical mechanisms: ordered target encoding, which computes running target statistics over random permutations to eliminate target leakage, and symmetric oblivious decision trees, which evaluate identical split conditions across entire tree levels, compiling into lightning-fast bitwise operations on ARM mobile CPUs with zero thread lock.
The Leakage-Free Lag Horizon (Lags ≥ 16 Days)
In recursive multi-step forecasting, models frequently utilize 1-day lags (lag_1). However, in a 16-day tournament forecast horizon, using lag_1 requires autoregressive rolling where small prediction errors compound exponentially across subsequent days. To ensure direct single-pass forecasting without error drift, all lag features were strictly bounded by >= 16 days: lag_16, lag_21, and lag_28, with rolling window statistics (rolling_mean_7, rolling_mean_14) computed strictly on lag_16.
from catboost import CatBoostRegressor
cat_features = ["store_nbr", "family", "city", "state", "type", "cluster"]
num_features = [
"onpromotion", "is_weekend", "day", "dayofweek",
"lag_16", "lag_21", "lag_28", "rolling_mean_7", "rolling_mean_14"
]
cb = CatBoostRegressor(
iterations=350,
learning_rate=0.08,
depth=6,
loss_function="RMSE",
cat_features=cat_features,
random_seed=42,
thread_count=4
)
cb.fit(X_tr, y_tr, eval_set=(X_val, y_val), early_stopping_rounds=40, verbose=False)
Empirical Benchmark: Validation 16-Day RMSLE: 0.41306 • Kaggle Public Score: 0.45786 • Score Delta: -0.04112 vs Ridge
The Result & Scale Disparity Hurdle: CatBoost captured non-linear store-family promotional synergies that linear regression completely missed. However, pure CatBoost still trailed our Part VI domain heuristic (0.43150). The reason is scale disparity: a Quito hypermarket selling 12,000 grocery items operates on an entirely different scale than a shop selling 2 units of specialty hardware. Tree leaf averages struggled to partition both volume scales simultaneously from lagged features alone, over-predicting small series and compressing large ones.
In Experiment 3, we augmented the feature space with external macroeconomic indicators and holiday calendars to capture macroeconomic shocks and civic shopping patterns across Ecuador:
- Daily WTI Crude Oil Smoothing (
oil.csv): As a petroleum-exporting economy, Ecuador’s domestic retail activity correlates with crude price shocks. Missing weekend and market holiday prices were interpolated via forward-fill and backward-fill. We engineered a 7-day rolling average (oil_roll7) and short-term price momentum differential (oil_diff7 = oil_price - oil_roll7). - Hierarchical Holiday Calendars (
holidays_events.csv): Filtered exclusively for non-transferred active holidays, split into three orthogonal binary indicators: national holidays (affecting all 54 stores), regional holidays (matched onstate), and municipal holidays (matched oncity). - Bi-Weekly Payday Flags (Quincenas): Ecuadorian public and private sector salaries are paid semi-monthly on the 15th and month-end. Binary indicators for payday dates and countdown markers (
days_to_payday) were injected.
# Oil interpolation and momentum features
oil["dcoilwtico"] = oil["dcoilwtico"].ffill().bfill()
oil["oil_roll7"] = oil["dcoilwtico"].rolling(7, min_periods=1).mean()
oil["oil_diff7"] = oil["dcoilwtico"] - oil["oil_roll7"]
# Hierarchical holiday mapping
df["is_national_holiday"] = df["type_holiday"].eq("National").astype(int)
df["is_regional_holiday"] = (df["type_holiday"].eq("Regional") & (df["locale_name"] == df["state"])).astype(int)
df["is_local_holiday"] = (df["type_holiday"].eq("Local") & (df["locale_name"] == df["city"])).astype(int)
# Bi-weekly payday flag (Quincenas)
df["is_payday"] = df["date"].dt.day.isin([15]) | df["date"].dt.is_month_end
Empirical Benchmark: Validation 16-Day RMSLE: 0.40892 • Kaggle Public Score: 0.45390 • Score Delta: -0.00396 vs Exp 2
The Result: Macroeconomic momentum and calendar flags resolved payday shopping surges and municipal holiday dips, yielding a clean, leak-free performance boost with negligible RAM overhead.
The critical breakthrough of Part VII came from recognizing that gradient-boosted decision trees should not be forced to learn store-specific volume scale from scratch. Instead of forcing trees to predict raw sales across 1,782 series, we decomposed log-sales into a strong, deterministic seasonal domain prior plus a stochastic residual:
z_i = ln(1 + Prior_i) + r_i
Where Prior_i is the 42-day grouped mean per (store_nbr, family, dayofweek). CatBoost was trained strictly on the residual target: r_i = ln(1 + y_i) - ln(1 + Prior_i).
Why Residual Boosting Smashed the Variance Floor
On raw log-sales, CatBoost’s initial tree training loss was 2.353. When predicting residuals relative to the grouped domain prior, initial loss plummeted to 0.698—a 70.3% variance reduction before the first tree split was evaluated. The trees were completely freed from memorizing whether a store sells 10,000 units or 10 units; every single leaf focused exclusively on learning promotional elasticity, holiday multipliers, and macroeconomic shifts.
Grouped Seasonal Mean → ln(1 + Prior_i)
Target Decomposition → Residual: r_i = ln(1 + y_i) – ln(1 + Prior_i)
↓
CatBoost GBDT on r_i
↓
Test Reconstruction → ln(1 + y_pred) = ln(1 + Prior_test) + r_pred
Final Inversion → y_pred = expm1(ln(1 + y_pred)) + Dead Catalog Mask
Promotion-Guarded Dead Catalog Post-Processing
In the final 14 days of training, 144 store-family combinations exhibited zero sales. We applied a promotion-guarded mask: clamping predictions strictly to 0.0 for all series with zero historical sales and zero scheduled promotions in test (affecting exactly 2,278 test rows).
Empirical Benchmark: Validation 16-Day RMSLE: 0.36414 • Kaggle Public Score: 0.42095 • Score Delta: -0.01055 vs Part VI Baseline (0.43150)
Tournament Trajectory: Jumped from Rank #183 to Rank #146 globally (Top 26.4%) out of 553 teams, climbing 37 positions on Kaggle’s live leaderboard.
Can we push further without exceeding our edge compute budget? In our final live tournament submission, we analyzed the correlation structure between our top two model paradigms:
- Model A (Exp 4 Hybrid Residual Booster,
0.42095): Anchored on robust multi-week seasonal priors, highly resistant to variance. - Model B (Exp 3 Exogenous GBDT,
0.45390): Free-form tree booster capturing non-linear holiday interactions and promotion surges.
Despite both utilizing CatBoost, their structural correlation in log-space was 0.9923—revealing meaningful orthogonal diversity across volatile product categories.
Geometric Log-Space Blending Pipeline
We blended predictions directly in log-space using an 82/18 weighting ratio, followed by exponential inversion and reapplying the dead catalog mask:
import numpy as np
import pandas as pd
sub_exp4 = pd.read_csv("submission_exp4_hybrid_residual.csv")
sub_exp3 = pd.read_csv("submission_exp3_catboost_exogenous.csv")
# Log-space weighted geometric blend
log4 = np.log1p(sub_exp4["sales"])
log3 = np.log1p(sub_exp3["sales"])
blend_sales = np.expm1(0.82 * log4 + 0.18 * log3)
# Enforce dead catalog zero mask
dead_mask = (sub_exp4["sales"] == 0.0)
blend_sales[dead_mask] = 0.0
sub = pd.DataFrame({"id": sub_exp4["id"], "sales": blend_sales})
sub.to_csv("submission_exp5_ensemble_blend.csv", index=False)
Empirical Benchmark: Kaggle Public Score: 0.41072 • Score Delta: -0.01023 vs Exp 4 (-0.02078 vs Part VI Baseline)
Final Tournament Placement: Reached Rank #116 out of 553 teams globally (Top 21.0%), climbing 67 positions from our non-ML baseline.
To push beyond 0.41072 into sub-0.400 territory, we diagnosed residual error distributions across all 33 product families. The largest remaining error spike was concentrated in SCHOOL AND OFFICE SUPPLIES during late August.
The Regional School Calendar Asymmetry
Ecuador operates on two distinct school calendars: the Costa (Coast) region starts classes in May, whereas the Sierra (Highlands / Andes) region (Quito, Ambato, Cuenca, Riobamba, Latacunga, Ibarra, Guaranda, Cayambe) starts classes on September 1st. In the final two weeks of August, school supply sales in Sierra stores experience a massive 2.6x to 3.5x surge that standard 42-day historical averages severely underestimate.
# Sierra cities academic multiplier for late August
sierra_cities = {"Quito", "Ambato", "Cuenca", "Riobamba", "Latacunga", "Ibarra", "Guaranda", "Cayambe"}
is_sierra_school = (df["city"].isin(sierra_cities)) & (df["family"] == "SCHOOL AND OFFICE SUPPLIES")
# Calibrated surge multiplier derived from historical holdouts
df.loc[is_sierra_school, "sales_pred"] *= 2.85
Local Holdout Validation: Testing this regional calibration on historical late-August holdouts dropped the RMSLE on Sierra school supplies by -0.18994 (from 0.63841 to 0.44847) and reduced overall dataset error by -0.00423, projecting live leaderboard performance to ~0.406.
0.41709 RMSLE due to asymmetric RMSLE over-prediction penalties across unpromoted Sierra stores. The post-mortem of this failure, compiling native LightGBM and XGBoost on ARM64 Termux, and breaking into the Global Top 100 at 0.40336 RMSLE (Rank #99) with our Quad-Ensemble is covered in Pocket Data Science VIII: Kaggle Store Sales Quad-Ensemble & Global Top 100 on Android Termux.
Below is the resource profile recorded inside Android Termux on 64-bit ARM:
| Pipeline Stage | Wall Clock Time | Peak Resident RAM |
|---|---|---|
| Ridge Regression (Exp 1) | 12.1 s | 312 MB |
| Pure CatBoost GBDT (Exp 2) | 391.3 s | 468 MB |
| Exogenous CatBoost (Exp 3) | 169.7 s | 442 MB |
| Hybrid Residual GBDT (Exp 4) | 23.3 s | 415 MB |
| Ensemble Blend (Exp 5) | 2.1 s | 188 MB |
Edge Takeaway: By decomposing scale disparities and using vectorized relational merges, entire multi-stage gradient boosting pipelines train and infer on multi-million row datasets comfortably within 500 MB of mobile RAM.
- Never Force Decision Trees to Learn Cross-Sectional Scales from Scratch: In multi-series retail forecasting, tree leaf quantization errors on extreme volume disparities cripple performance. Decomposing demand into a structured seasonal prior and modeling the log residual delivers massive gains in convergence speed and accuracy.
- Direct Horizon Lags Prevent Compounding Autoregressive Drift: Restricting lag features strictly to
≥ 16days eliminated the instability of multi-step recursive rollouts, producing deterministic single-pass predictions. - Guard Zero-Forecasts with Promotional Intent: Blindly setting inactive series to zero creates severe penalties when retailers re-launch seasonal items. Always gate zero-demand masks with promotional intent (
onpromotion == 0). - Ensemble Distinct Modeling Paradigms: Combining an anchored residual model with a free-form tree booster captured structural day-of-week rhythms and non-linear promotion shocks simultaneously.
To execute all machine learning experiments inside Android Termux:
# Navigate to workspace
cd ~/kaggle_store_sales
# Run Experiment 1: Regularized Linear Ridge
python3 exp1_ridge.py
# Run Experiment 2: Native Categorical CatBoost
python3 exp2_catboost.py
# Run Experiment 3: CatBoost with Exogenous Data
python3 exp3_catboost_exogenous.py
# Run Experiment 4: Hybrid Residual GBDT
python3 exp4_hybrid_residual.py
# Run Experiment 5: Multi-Model Ensemble Blend
python3 exp5_ensemble_blend.py
# Run Experiment 6: Sierra Academic Surge Calibration test
python3 exp6_sub40_calibrated.py
# Submit to Kaggle
kaggle competitions submit -c store-sales-time-series-forecasting \
-f submission_exp6_sub40_calibrated.csv \
-m "Experiment 6: Sierra Academic Surge Multiplier Test"
Share this:
- Share on Facebook (Opens in new window) Facebook
- Email a link to a friend (Opens in new window) Email
- Share on LinkedIn (Opens in new window) LinkedIn
- Share on Telegram (Opens in new window) Telegram
- Share on WhatsApp (Opens in new window) WhatsApp
- More
- Share on Bluesky (Opens in new window) Bluesky
- Print (Opens in new window) Print
- Share on Threads (Opens in new window) Threads
- Share on Reddit (Opens in new window) Reddit
- Share on Tumblr (Opens in new window) Tumblr
- Share on Pinterest (Opens in new window) Pinterest
- Share on X (Opens in new window) X
Leave a Reply