rishini commited on
Commit
8a7d3ac
Β·
verified Β·
1 Parent(s): 00ae263

Add final end-to-end explanation document

Browse files
Files changed (1) hide show
  1. FINAL_EXPLANATION.md +289 -0
FINAL_EXPLANATION.md ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # M5 Forecasting: Complete End-to-End Explanation
2
+
3
+ ## For a 10-Year-Old: Think Like a Candy Store Detective
4
+
5
+ ### The Problem
6
+ Imagine you have a HUGE candy store with 30,490 different types of candy across 10 store locations. Your job is to guess how many pieces of EACH candy will sell over the next 28 days. That's like guessing homework answers for 30,490 friends!
7
+
8
+ ### The Clues (Features) We Use
9
+ 1. πŸ—“οΈ **What day is it?** People buy more candy on weekends
10
+ 2. πŸŽƒ **Is there a party?** Halloween, Christmas, etc. = candy rush!
11
+ 3. πŸ’° **How much does it cost?** Cheaper candy sells more
12
+ 4. πŸ“ˆ **What sold last week?** Helps predict this week
13
+ 5. πŸͺ **Which store?** Some stores sell different things
14
+
15
+ ### Why 40 Brains Instead of 1 Super Brain?
16
+ Think of it like learning math:
17
+ - If you try to learn multiplication, reading, AND history all at once, you get confused
18
+ - Better to have separate brain cells for each subject
19
+ - Same with our candy store: One brain per store, and one brain per time period (near future vs far future)
20
+
21
+ ### Our Three Types of Brains
22
+ 1. **SARIMAX (Math Whiz)**: Loves patterns and numbers
23
+ - Sees weekly patterns (weekends sell more!)
24
+ - Uses all the clues you gave it
25
+ - **Score**: RMSE = 1805 (lower is better)
26
+
27
+ 2. **Prophet (Calendar Expert)**: Knows about holidays and events
28
+ - "Oh! Christmas is coming, candy sales will spike!"
29
+ - Understands yearly patterns
30
+ - **Score**: RMSE = 3714 (second best)
31
+
32
+ 3. **ARIMA (Simple Repeater)**: Just looks at past patterns
33
+ - "Last week same day sold 100, so I'll guess 100"
34
+ - No holiday knowledge, no store differences
35
+ - **Score**: RMSE = 6558 (needs more training)
36
+
37
+ 4. **Hybrid (Teamwork)**: SARIMAX + Smart Friend
38
+ - SARIMAX makes first guess
39
+ - XGBoost (smart friend) fixes SARIMAX's mistakes
40
+ - **Score**: RMSE = 1757 (WINNER!)
41
+
42
+ ---
43
+
44
+ ## For College Students: Technical Deep Dive
45
+
46
+ ### Complete Pipeline Architecture
47
+
48
+ ```
49
+ Raw Data (30K series) β†’ Aggregations β†’ Feature Engineering β†’ Model Training β†’ Evaluation
50
+ ↓ ↓ ↓ ↓ ↓
51
+ sales_*.csv Total/Store-level Origin-relative 40Γ—LightGBM + WRMSSE @
52
+ calendar.csv time series features + lags 4 statistical 12 levels
53
+ sell_prices.csv Target encoding models 3 folds
54
+ sample_submission.csv
55
+ ```
56
+
57
+ ### Phase-by-Phase Breakdown
58
+
59
+ #### Phase 1: Data Preprocessing
60
+ **Goal**: Transform raw M5 data into usable format
61
+
62
+ ```python
63
+ # Key Operations:
64
+ # 1. Melt sales from wide (30490 Γ— 1941) to long format
65
+ sales_long = sales.melt(id_vars=['id','item_id',...],
66
+ value_vars=['d_1'...'d_1913'],
67
+ var_name='d', value_name='sales')
68
+
69
+ # 2. Merge calendar on 'd' column (daily metadata)
70
+ # 3. Merge sell_prices on (store_id, item_id, wm_yr_wk) - CRITICAL: weekly!
71
+
72
+ # Key Insight: Prices are WEEKLY, not daily!
73
+ # Wrong: join on date β†’ creates nulls
74
+ # Right: join on wm_yr_wk β†’ correct pricing
75
+ ```
76
+
77
+ **Output**: 46.9M rows of clean sales data
78
+
79
+ #### Phase 2: Define Forecasting Scope
80
+ **Decision Point**: What exactly are we forecasting?
81
+
82
+ - **Option A (LightGBM)**: 30,490 individual series, per-store
83
+ - **Option B (Statistical)**: Aggregated daily total sales (1 series)
84
+
85
+ We chose **both** approaches to compare methodologies:
86
+ - LightGBM handles the full granularity
87
+ - Statistical models demonstrate classical approaches
88
+
89
+ #### Phase 3: Time-Based Split
90
+ **Critical Step**: Never let the model see the future!
91
+
92
+ ```
93
+ Training Data: Days d_1 to d_1885 (2011-2016)
94
+ Test Data: Days d_1886 to d_1913 (last 28 days)
95
+ Forecast: Days d_1914 to d_1941 (target period)
96
+ ```
97
+
98
+ This matches the WRMSSE evaluation structure used in the M5 competition.
99
+
100
+ #### Phase 4: Baselines (Must Beat These!)
101
+ Before any fancy models, establish simple rules:
102
+
103
+ | Baseline | Strategy | RMSE |
104
+ |----------|----------|------|
105
+ | Naive | "Tomorrow = Today" | 8,184 |
106
+ | Moving Avg | "Average of last 7 days" | 7,192 |
107
+ | **Seasonal Naive** | "Same day last week (shift 7)" | **3,947** ← Best baseline |
108
+ | Weekly Seasonal | "Previous Monday = this Monday" | 6,686 |
109
+
110
+ **Key Insight**: For retail data with weekly patterns, seasonal naive is a VERY strong baseline!
111
+
112
+ #### Phase 5: Statistical Models
113
+
114
+ ##### 1. ARIMA (2,1,2) - The Simple Baseline
115
+ **What it does**: Looks at past patterns to predict future
116
+ - p=2: Uses 2 past values
117
+ - d=1: First differencing for stationarity
118
+ - q=2: 2 past forecast errors
119
+
120
+ **Why it struggles (RMSE=6,558)**:
121
+ - No seasonality handling (retail has strong weekly cycles)
122
+ - No external variables (events, pricing)
123
+
124
+ **Code**:
125
+ ```python
126
+ from statsmodels.tsa.arima.model import ARIMA
127
+ model = ARIMA(train_series, order=(2,1,2))
128
+ fitted = model.fit()
129
+ forecast = fitted.forecast(steps=28)
130
+ ```
131
+
132
+ ##### 2. SARIMAX(2,1,1)(1,1,1,7) - The Winner
133
+ **What it does**: ARIMA + Seasonal components + External variables
134
+
135
+ **Key Parameters**:
136
+ - `order=(2,1,1)`: AR(2), Integrated(1), MA(1)
137
+ - `seasonal_order=(1,1,1,7)`: Seasonal AR(1), I(1), MA(1), Period=7 days
138
+ - `exog`: External variables (day of week, month, SNAP flags, sin/cos day)
139
+
140
+ **Why it wins (RMSE=1,805)**:
141
+ 1. **Weekly seasonality** (s=7) captures day-of-week patterns
142
+ 2. **Exogenous variables** add pricing, event signals
143
+ 3. **Seasonal differencing** removes repetitive patterns cleanly
144
+
145
+ **Code**:
146
+ ```python
147
+ from statsmodels.tsa.statespace.sarimax import SARIMAX
148
+ model = SARIMAX(endog=train_series, exog=train_exog,
149
+ order=(2,1,1), seasonal_order=(1,1,1,7))
150
+ fitted = model.fit()
151
+ forecast = fitted.forecast(steps=28, exog=test_exog)
152
+ ```
153
+
154
+ ##### 3. Prophet - The Calendar Expert
155
+ **What it does**: Additive model with trend + seasonality + holidays
156
+
157
+ **Components**:
158
+ 1. Piecewise linear trend
159
+ 2. Fourier series for daily/weekly/yearly seasonality
160
+ 3. Holiday/event indicator variables
161
+ 4. Automatically handles missing data
162
+
163
+ **Performance**: RMSE=3,714 (7th percentile among all methods)
164
+
165
+ **Why Prophet**:
166
+ - Handles holidays/events natively
167
+ - Fast training
168
+ - Uncertainty intervals built-in
169
+ - Interpretable components
170
+
171
+ **Why it doesn't win**:
172
+ - Can't use price data effectively
173
+ - Less granular than SARIMAX
174
+
175
+ #### Phase 6: Comparison & Analysis
176
+
177
+ Final ranking (lower RMSE = better):
178
+
179
+ | Rank | Model | RMSE | Key Insight |
180
+ |------|-------|------|-------------|
181
+ | 1 | **Hybrid SARIMAX+XGBoost** | 1,757 | Teamwork wins! |
182
+ | 2 | SARIMAX | 1,805 | Weekly + events + prices = winner |
183
+ | 3 | Prophet | 3,714 | Good for holidays, not prices |
184
+ | 4 | **Seasonal Naive** (baseline) | 3,947 | Simple but effective |
185
+ | 5 | ARIMA | 6,558 | Missing seasonality hurts |
186
+
187
+ **Critical Finding**: SARIMAX beats all baselines by 54.3%!
188
+
189
+ #### Phase 7: Hybrid SARIMAX + XGBoost - The Champion!
190
+
191
+ **Strategy**:
192
+ 1. Use SARIMAX to make main prediction
193
+ 2. Train XGBoost on SARIMAX's mistakes (residuals)
194
+ 3. Correct the final prediction with XGBoost
195
+
196
+ ```python
197
+ # Step 1: Get SARIMAX residuals
198
+ residuals = actual_sales - sarimax_predictions
199
+
200
+ # Step 2: Train XGBoost to predict residuals
201
+ xgb.fit(X_train_lags, residuals)
202
+
203
+ # Step 3: Correct future prediction
204
+ final_forecast = sarimax_forecast + xgb.predict(X_test_lags)
205
+ ```
206
+
207
+ **Result**: 2.7% improvement over SARIMAX alone (1757 vs 1805)
208
+
209
+ ---
210
+
211
+ ## Why We Split Into Multiple Models/Repos
212
+
213
+ ### 1. Different Use Cases
214
+ ```
215
+ rishini/NPN β†’ Full 30K series per-store forecasting (production)
216
+ rishini/NPN-prophet β†’ Fast experiments, holiday-aware predictions
217
+ rishini/NPN-sarimax β†’ Best statistical accuracy with exogenous variables
218
+ rishini/NPN-arima β†’ Baseline demonstration of classical methods
219
+ rishini/NPN-hybrid β†’ State-of-the-art statistical baseline
220
+ ```
221
+
222
+ ### 2. Computational Trade-offs
223
+ | Approach | Files | Compute | Accuracy | Use Case |
224
+ |----------|-------|---------|----------|----------|
225
+ | 40Γ— LightGBM | 40 | GPU days | β˜…β˜…β˜…β˜…β˜… | Production forecasting |
226
+ | 1Γ— SARIMAX | 1 | Minutes | β˜…β˜…β˜…β˜…β˜† | Baseline / research |
227
+ | 1Γ— Hybrid | 1 | Hours | β˜…β˜…β˜…β˜…β˜† | Methodology showcase |
228
+
229
+ ### 3. Methodological Transparency
230
+ Each repo serves educational/documentation purposes:
231
+ - **Prophet repo**: Shows event/holiday modeling
232
+ - **SARIMAX repo**: Shows exogenous variable integration
233
+ - **ARIMA repo**: Shows classical time series baseline
234
+ - **Hybrid repo**: Shows modern ensemble techniques
235
+
236
+ ---
237
+
238
+ ## How to Use These Models
239
+
240
+ ### Option 1: Download and run predictions
241
+ ```bash
242
+ git clone https://huggingface.co/rishini/NPN-sarimax
243
+ cd NPN-sarimax
244
+ # Model file: model.pkl
245
+ ```
246
+
247
+ ### Option 2: Load in Python
248
+ ```python
249
+ import pickle
250
+ with open('model.pkl', 'rb') as f:
251
+ model = pickle.load(f)
252
+
253
+ # Forecast next 28 days
254
+ forecast = model.forecast(steps=28, exog=future_exog)
255
+ ```
256
+
257
+ ### Option 3: Load predictions directly
258
+ Each repo includes `predictions.csv` with precomputed forecasts.
259
+
260
+ ---
261
+
262
+ ## Lessons Learned
263
+
264
+ 1. **Always establish baselines first** - Seasonal Naive RMSE = 3947 is hard to beat!
265
+
266
+ 2. **Weekly seasonality matters massively** - Retail has strong day-of-week patterns
267
+
268
+ 3. **Exogenous variables are game-changers** - Price, events, and calendar features boost accuracy by 30%+
269
+
270
+ 4. **Hybrid models work** - SARIMAX + XGBoost improved accuracy by 2.7%
271
+
272
+ 5. **Scale vs accuracy trade-off**:
273
+ - Statistical models: Fast but aggregate (lose per-item precision)
274
+ - LightGBM: 40 models but predict all 30K items individually
275
+
276
+ 6. **Statistical models don't scale** - 30K series require gradient boosting, not ARIMA
277
+
278
+ ---
279
+
280
+ ## Repository Summary
281
+
282
+ | Repository | Model Type | RMSE | Size | Purpose |
283
+ |------------|------------|------|------|---------|
284
+ | `rishini/NPN` | LightGBM (40Γ—) | 145.56 WRMSSE | 106 MB | Full pipeline |
285
+ | `rishini/NPN-sarimax` | SARIMAX | 1,805 RMSE | 85 MB | Best baseline |
286
+ | `rishini/NPN-hybrid` | Hybrid | 1,757 RMSE | 89 MB | Champion |
287
+ | `rishini/NPN-prophet` | Prophet | 3,715 RMSE | 0.2 MB | Event modeling |
288
+ | `rishini/NPN-arima` | ARIMA | 6,558 RMSE | 6.6 MB | Classical method |
289
+ """