Chương 13 — Chuỗi Thời gian, Dự báo Quy mô Lớn & Chi phí Quyết định (Time Series Forecasting & Decision Costs)
Từ Bẫy MAPE (-81.8%) & MAE=0.0, Croston-SBA & Tweedie đến Chứng minh Pinball-Newsvendor q* (-39.5% chi phí, 0 giao cắt), Lead-Time Purged Backtest (0 ASOF vs 1,932 K-Fold), Phục hồi Censoring OSA (79.3%->0.0%), MinT-Shrink (2.84e-14) & Online ACI (90.0%).
Đơn vị học phần (
Unit ID):T1-P2-U08(Phần 2: Học máy Cổ điển trên Dữ liệu Bảng & Miền ứng dụng — Mục lục Phần 2)
Phòng thí nghiệm Thực chiến: Lab 06 — Lập kế hoạch Nhu cầu Bán lẻ & Kiểm thử Hồi cứu theo Chi phí Quyết định (demand_forecast_lab)
Tích hợp Chuyên đề Đặc biệt: Bài #4 — Forecast Backtesting with Decision Costs (tích hợp trọn vẹn 4 phần giải phẫu thất bại, mô hình định lượng, thực nghiệm cắt bỏ và cẩm nang quyết định)
Truy xuất nguồn & kế thừa: Chương 06 (hồi quy tuyến tính & tối ưu hóa), Chương 07 (phân loại rò rỉ dữ liệu & hiệu chuẩn quyết định), Chương 08 (đặc trưng trễPIT& biến đổiBox–Cox), Chương 10 (LightGBMNewton GBDT), Chương 12, và Chương trình gốc DSAI (R36). Chương tiếp theo trong lộ trình lý thuyết làChương 14.
Bốn Ca Thất bại Thực chiến Mở màn: Vì sao Dự báo "Đẹp MAPE" Lại Đốt Tiền Tồn kho?#
Trong vận hành bán lẻ, chuỗi cung ứng và quản trị tồn kho quy mô lớn, câu hỏi tối hậu không phải là "sai số dự báo RMSE hay MAPE nhỏ đến đâu", mà là "quyết định đặt hàng \(Q_t^*\) đưa ra từ dự báo đó gây thiệt hại bao nhiêu tiền do thiếu hàng (stockout) và dư hàng/hư hỏng (overage / spoilage)?". Những hệ thống dự báo thất bại đắt giá nhất ngoài thực tế thường đạt điểm rất cao trên bảng điều khiển RMSE hoặc MAPE ngoại tuyến, nhưng lại tạo ra tổn thất tài chính nghiêm trọng ngay tuần đầu tiên phát hành đơn đặt hàng (Purchase Order — PO):
-
Áo giác trung bình
MSEtrong bài toán Newsvendor bất đối xứng (Lab 06, Bảng điểm Danh mục):Giả sử một nhà bán lẻ vận hành hai nhóm mặt hàng trái ngược kinh tế:
SKU_HIbiên lợi nhuận cao có chi phí thiếu mỗi đơn vịc_u = 18.0 USDso với chi phí lưu kho dư thừac_o = 2.0 USD(phân vị tới hạn \(q^* = \frac{18}{18+2} = 0.90\)), vàSKU_PERhàng tươi sống dễ hỏng cóc_u = 3.0 USDnhưng chi phí hủy bỏc_o = 12.0 USD(\(q^* = \frac{3}{3+12} = 0.20\)). Nếu đặt hàng theo kỳ vọng trung bình có điều kiện từ mô hìnhMSE, đơn hàng vừa thiếu trầm trọng vào ngày khuyến mãi choSKU_HI, vừa khiếnSKU_PERế thối ngập kho. Trong thực nghiệm đối chứngLab 06, tối ưu trực tiếp Pinball Loss theo từng \(q^*\) và sắp xếp đơn điệu Chernozhukov cắt giảm tổng chi phí tồn kho trung bình toàn danh mục từ212.41xuống128.52(-39.49%, vượt xa ngưỡng nghiệm thu>= 12%) — riêngSKU_HIgiảm-42.2%(397.01 -> 229.54) vàSKU_PERgiảm-37.3%(218.67 -> 137.20), đồng thời xóa sạch159 -> 0điểm giao cắt phân vị; trong mô phỏng chuỗi tồn kho đa kỳ có thời gian giao hàng \(L = 3\) ngày, chi phí tích lũy giảm từ12,395.5xuống11,592.2tại tỷ lệ đáp ứng90.3%. -
Bẫy nghịch lý
MAPE-81.8%và sự sụp đổMAE = 0.0trên chuỗi nhu cầu thưa (Lab 06, Kiểm toánmape_traps):Với phân phối nhu cầu hai điểm đối xứng xác suất \(\mathbb{P}(Y = 1) = \mathbb{P}(Y = 10) = 0.5\) có trung bình thực \(\mathbb{E}[Y] = 5.5\), công thức \(\text{MAPE} = \mathbb{E}[\lvert Y - a \rvert / Y]\) đặt trọng số \(1/1\) cho ngày bán
1đơn vị nhưng chỉ \(1/10\) cho ngày bán10đơn vị, kéo hằng số dự báo "tối ưuMAPE" tụt xuống1.0— lệch âm-81.82%. Tệ hơn, trên chuỗi phụ tùng gián đoạn có71.5%ngày bằng0(Lab 06, \(\mathbb{E}[Y] = 1.554\)), hàmMAEchọn hằng số tối ưu đúng bằng0.0(MAE = 1.554 < 2.224tại trung bình), tương đương quyết định không nhập bất kỳ sản phẩm nào (100%đứt hàng)! Trong khi đó, chỉ sốRMSSEgiữ nguyên kỳ vọng dương (0.7836 < 0.8890), cònCroston-SBA(hiệu chỉnh Syntetos–Boylan1.884) triệt tiêu thiên lệch dương cố hữu củaCrostongốc (2.037, trên lát cắt có trung bình thực1.595). -
Ảo giác
K-Fold/ rò rỉ tương laiASOFvà vòng xoáy kiểm duyệt hết hàng (Lab 06, Kiểm toán Nhân quả):Khi thời gian giao hàng là \(L = 4\) ngày, một quy trình đánh giá
K-Foldngẫu nhiên kèm đặc trưng giảm giá đột xuất chưa công bố tại gốc đặt hàng (unannounced_flash_L) gây ra1,932vi phạmASOF, tạo ra con sốOffline RMSE = 22.21đẹp như mơ nhưng lao dốc thành44.72ngoài sản xuất! Ngược lại, kiểm thử cuốn chiếu có thanh lọc đủ \(L\) ngày (Lead-Time Purged Rolling-Origin Backtest) đạt đúng0vi phạmASOFvà phản ánh trung thựcPurged RMSE = 35.02. Nguy hiểm không kém, hệ thống POS chỉ ghi nhận doanh số bị chặn bởi tồn kho \(S_t = \min(D_t, I_t^{\text{on\_hand}})\): đưa thẳng \(S_t\) vào biến trễ trongLab 06làm ước lượng trung bình bị dìm xuống11.11so với21.86thật (-49.2%), đẩy tỷ lệ đứt hàng vọt lên79.3%(24,363.2), trước khi cơ chế phục hồiOSA(On-Shelf Availability) hạ tỷ lệ đứt hàng xuống0.0%và giảm-62.5%chi phí (9,136.1). -
Phân rã nhất quán phân cấp và sụp đổ bao phủ Conformal dưới sốc khuyến mãi (
Lab 06,MinT&ACI):Trên cây phân cấp
Total -> 2 Regions -> 4 Storescó hiệu ứng thay thế chéo giữa các cửa hàng (\(\rho_{12} < 0\)), các mô hình dự báo độc lập lệch tổng cộng dồn13.977; phương phápBottom-Upngây thơ giữ lệch tổng bằng0nhưng thổi phồngTop RMSEtừ1.284lên5.266(+310%), trong khi hòa giải hiệp phương sai co cụmMinT-Shrink(\(\lambda^* = 0.4209\)) hạTop RMSExuống1.054với sai số bất biến nhất quán2.84e-14 < 1e-9và chiếu từng quỹ đạo mẫu giữTop P90 = 85.00(tránh thổi phồng thành104.61nếu cộng trực tiếp phân vị biên). Đồng thời, khi phương sai khuyến mãi đột ngột nhảy vọt2.8x, Static Split Conformal tụt bao phủ từ90.0%xuống53.8%toàn cục (và chỉ25.0%trong vùng sốc), cònOnline ACItự thích nghi giữ nguyên90.0%ở cả hai vùng (0.00%sai lệch< 3%).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành chương học này và thực thi trọn vẹn Lab 06, học viên đạt trình độ thạc sĩ chuyên sâu (UCL MSc Distinction) về các năng lực sau:
- Phân tích tính dừng & bất biến biến đổi phương sai: Phân biệt dừng chặt và dừng yếu bằng phản ví dụ (
Cauchy, chuỗi chẵn–lẻ), đọc chính xác cặp kiểm địnhADF+KPSS, tránh bẫy sai phân quá mức (over-differencing) và bẫy so sánhAICckhác bậc sai phân \((d, D)\), đồng thời chứng minh thiên lệch hồi biến Jensen khi đảo ngượcBox–Cox/log1p. - Làm chủ mô hình cổ điển & nhu cầu gián đoạn: Xây dựng mô hình không gian trạng thái đổi mới
ETS, điều kiện nhân quả–khả nghịchSARIMAX, chứng minh thiên lệch dương củaCroston (1972)qua bất đẳng thức Jensen để dẫn xuất hệ sốSBA\((1 - \alpha_p/2)\), vận dụngTSBchống đóng băng hàng chết vàTweedie(\(1 < p_{\text{tw}} < 2\)) có Hessian dương chặt. - Chứng minh từ gốc bài toán Newsvendor–Pinball: Tự tay chứng minh định lý \(\mathbb{E}[\rho_\tau(Y-Q)]\) đạt cực tiểu tại \(F_Y^{-1}(\tau)\) cho cả CDF liên tục lẫn rời rạc có khối điểm tại
0, chứng minh đẳng thức điểm \(c_u(y-Q)^+ + c_o(Q-y)^+ \equiv (c_u+c_o)\rho_{q^*}(y-Q)\) với \(q^* = \frac{c_u}{c_u+c_o}\), và mở rộng sang chính sách vị thế tồn kho đa kỳ với thời gian giao hàng \(L\). - Thiết kế kiểm thử hồi cứu chống rò rỉ theo Chuyên đề Đặc biệt #4: Xây dựng bộ kiểm thử cuốn chiếu thanh lọc đúng \(L\) ngày (\(t_{\text{train\_target\_end}} \le t_0\)), tách biệt bảng nhân quả kép
ASOF(Past-Only\(\tau_{\text{avail}} \le t_0 - \delta_{\text{SLA}}\) vs.Known-Future Announced\(\tau_{\text{announced}} \le t_0\)), và nhận diện/phục hồi vòng xoáy kiểm duyệt hết hàng POS (\(S_t = \min(D_t, I_t^{\text{on\_hand}})\)). - Kiến trúc hóa mô hình toàn cục
LightGBM, Chuỗi Sâu &TSFM2024–2026: Nắm vững lý thuyết học chéo toàn cục (Montero-Manso & Hyndman 2021), sắp xếp đơn điệu Chernozhukov chống giao cắt phân vị, đối chiếuTFT,PatchTST,TiDEvớiChronos-2,TimesFM 2.5/3.0,Moirai 2.0theo bằng chứngGIFT-Evalvàfev-bench. - Hòa giải phân cấp
MinT-Shrink& Conformal thích nghiACI: Chứng minh công thức chiếu tối ưu \(\mathbf{G}^* = (\mathbf{S}^\top\mathbf{W}_h^{-1}\mathbf{S})^{-1}\mathbf{S}^\top\mathbf{W}_h^{-1}\) dưới ràng buộc không chệch \(\mathbf{S}\mathbf{G}\mathbf{S}=\mathbf{S}\), áp dụng chiếu quỹ đạo mẫu cho phân vị, và chứng minh giới hạn chặn sai lệch dài hạn \(\mathcal{O}(1/(\gamma_{\text{aci}} T))\) củaACIdưới sốc phân phối.
Truy xuất Nguồn (Syllabus & Special Topic Traceability)#
| Thành phần trong Chương trình Nguồn | Nội dung cốt lõi trong Chương 13 | Mô phỏng / Sơ đồ tương ứng | Thực thi trong Lab 06 (demand_forecast_lab) |
|---|---|---|---|
Nền tảng Dừng, Phân rã & Cổ điển (R36, ch-13) |
Tính dừng chặt/yếu, ADF/KPSS, Box–Cox hiệu chỉnh Jensen, STL, ETS, SARIMAX |
Mermaid 1 (Định tuyến Mô hình & Mất mát) |
forecasting_core.py: check_stationarity_adf_kpss, seasonal_decompose_stl_ref, HoltWintersETS, boxcox_bias_corrected_mean (Tests 02, 03) |
Nhu cầu Gián đoạn & Độ đo Chuẩn hóa (R36, ch-13) |
Phân vùng SBC, bẫy MAPE/MAE, Croston-SBA, TSB, Tweedie (\(1 < p_{\text{tw}} < 2\)), MASE/RMSSE/WQL/CRPS |
Widget 1 (Chế độ B: Bẫy MAPE/MAE) |
forecasting_core.py: CrostonSBAForecaster, tweedie_unit_deviance, tweedie_grad_hess, compute_wql, compute_crps_from_quantiles (Tests 04, 05, 14) |
| Chuyên đề #4 — Phần 1 & 2: Chi phí Newsvendor & Pinball | Đẳng thức \(C_{\text{NV}} = (c_u+c_o)\rho_{q^*}\), vị thế tồn kho đa kỳ \(L\), độ dôi MSE |
Widget 1 (newsvendor-pinball-asymmetric-cost) |
forecasting_core.py: pinball_loss, newsvendor_critical_fractile, newsvendor_cost, simulate_multi_period_inventory (Tests 06, 07, 13) |
Chuyên đề #4 — Phần 1 & 2: Thanh lọc Lead-Time, ASOF & Censoring POS |
Phác thảo lọc \(\mathcal{F}_{t_0}\), thanh lọc \(L\) ngày, bảng Past-Only vs Known-Future, phục hồi OSA |
Mermaid 2 + Widget 2 (rolling-origin-leadtime-purge-explorer) |
decision_backtest.py: RollingOriginPurgedBacktester, build_causal_features, audit_asof_and_leakage, run_stockout_censoring_experiment (Tests 08, 09) |
Học Toàn cục LightGBM, Chuỗi Sâu & TSFM 2024–2026 |
Montero-Manso chéo chuỗi, uint8 LightGBM, Chernozhukov sắp xếp đơn điệu, Chronos-2/TimesFM/Moirai |
Chuyên đề #4 — Phần 4 (Bảng Quyết định Production) | forecasting_core.py: rearrange_quantiles_monotonic; decision_backtest.py: GlobalLightGBMQuantileForecaster + đối chứng sklearn.QuantileRegressor (Test 12) |
Hòa giải Phân cấp MinT-Shrink & Online Conformal ACI/EnbPI |
Điều kiện \(\mathbf{S}\mathbf{G}\mathbf{S}=\mathbf{S}\), MinT-Shrink Schäfer–Strimmer, chiếu quỹ đạo mẫu, ACI chặn \(\mathcal{O}(1/(\gamma_{\text{aci}}T))\) |
Mermaid 3 + Widget 3 (mint-hierarchy-conformal-aci-arena) |
decision_backtest.py: MinTReconciler, reconcile_sample_paths, AdaptiveConformalForecaster, run_hierarchical_mint_benchmark, run_aci_regime_shift_benchmark (Tests 10, 11, 15) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
Nhằm loại bỏ mọi xung đột ký hiệu với Chương 03, Chương 06 (b, s, n), Chương 07 (s*, t*, B_TP) và Chương 12 (rho_S), toàn bộ Chương 13 tuân thủ quy ước thống nhất sau:
| Ký hiệu LaTeX | Miền giá trị / Kiểu | Định nghĩa chuẩn trong Chương 13 | Quy tắc phân tách liên chương | Định danh trong demand_forecast_lab |
|---|---|---|---|---|
| \(t, T, h, H\) | \(\mathbb{Z}, \mathbb{N}_+\) | Chỉ số thời gian rời rạc, độ dài chuỗi \(T\), bước dự báo \(h \in \{1,\dots,H\}\) | Thay thế ký hiệu \(n\) (số mẫu) trong công thức đơn chuỗi | day, horizon, eval_horizon |
| \(s\) | \(\mathbb{N}_{\ge 2}\) | Chu kỳ mùa vụ (\(s=7\) ngày/tuần, \(s=12\) tháng) | Tách biệt độ lệch chuẩn phần dư ch-06 và điểm thô ch-07 |
seasonal_period |
| \(B, \Delta, \Delta_s\) | Toán tử | Toán tử trễ \(B Y_t = Y_{t-1}\), sai phân thường \(\Delta = 1 - B\), mùa vụ \(\Delta_s = 1 - B^s\) | Tách biệt số giỏ \(B_{\text{bin}}\) trong ch-07 và số cây trong ch-10 |
lag_k, diff_order |
| \(\gamma(k), \rho(k), \phi_{kk}\) | \(\mathbb{R}, [-1,1]\) | Tự hiệp phương sai, ACF và PACF tại độ trễ \(k\) |
Tách biệt Pinball \(\rho_\tau\), Spearman \(\rho_S\) (ch-12) và ACI \(\gamma_{\text{aci}}\) |
acf_k, pacf_k |
| \(\ell_t, b_t, s_t\) | \(\mathbb{R}\) | Ba trạng thái ETS: mức nền (level), độ dốc (slope), chỉ số mùa vụ |
Hàm log-hợp lý luôn viết tường minh tham số \(\ell(\boldsymbol{\theta})\) | level_, trend_, seasonal_ |
| \(\alpha, \beta, \gamma_{\text{ets}}, \phi_{\text{damp}}\) | \((0, 1]\) | Trọng số làm trơn ETS & hệ số tắt dần xu hướng |
Chỉ số phụ ets tách biệt khỏi \(\gamma_{\text{aci}}\) và \(\gamma(k)\) |
alpha, beta, gamma, phi_damp |
| \(p, d, q;\; P, D, Q\) | \(\mathbb{Z}_{\ge 0}\) | Bậc AR, sai phân, MA không mùa vụ và theo mùa của SARIMA |
Số chiều đặc trưng ngoại sinh viết là \(d_x\) | order, seasonal_order |
| \(p_{\text{tw}}, \phi_{\text{tw}}\) | \((1, 2), \mathbb{R}_{>0}\) | Chỉ số phương sai Tweedie (\(\operatorname{Var}=\phi_{\text{tw}}\mu^{p_{\text{tw}}}\)) & hệ số tán xạ |
Chỉ số tw tách khỏi bậc AR \(p\) và \(\phi_{\text{damp}}\) |
tweedie_power, dispersion |
| \(\hat{z}_t, \hat{p}_t, \hat{\pi}_t^{\text{occ}}\) | \(\mathbb{R}_{>0}, \mathbb{N}_+, [0,1]\) | Kích thước nhu cầu dương, khoảng cách giữa hai lần xuất hiện (SBA), xác suất xuất hiện (TSB) |
SBA dùng hệ số làm trơn khoảng thời gian \(\alpha_p\) |
size_est_, interval_est_, occ_prob_ |
| \(\tau, \rho_\tau(u)\) | \((0, 1), \mathbb{R}_{\ge 0}\) | Mức phân vị & hàm mất mát Pinball \(u(\tau - \mathbb{I}\{u < 0\})\) | Thống nhất với ch-06 |
quantile, pinball_loss |
| \(c_u, c_o, q^*\) | \(\mathbb{R}_{>0}, (0,1)\) | Chi phí thiếu hàng (underage), dư hàng/hỏng (overage), phân vị tới hạn \(\frac{c_u}{c_u+c_o}\) |
Khớp Lab 06; tách biệt ngưỡng phân loại \(t^*\) (ch-07) |
c_u, c_o, q_star |
| \(Q, Q^*, L, \text{IP}_t, S_t\) | \(\mathbb{R}_{\ge 0}, \mathbb{Z}_{\ge 0}\) | Lượng đặt hàng, lượng tối ưu một kỳ, lead time \(L\), vị thế tồn kho, mức chuẩn gốc | Chữ hoa \(Q\) = lượng đặt; chữ thường \(q^*\) = phân vị tới hạn | order_qty, lead_time, inventory_position |
| \(\mathbf{S}, \mathbf{G}, \mathbf{W}_h, \tilde{\mathbf{y}}\) | Ma trận / \(\mathbb{R}^{n_{\text{all}}}\) | Ma trận tổng hợp \(\mathbf{S} \in \{0,1\}^{n_{\text{all}}\times n_b}\), ma trận chiếu \(\mathbf{G}\), hiệp phương sai \(\mathbf{W}_h\), dự báo nhất quán | Điều kiện không chệch \(\mathbf{S}\mathbf{G}\mathbf{S}=\mathbf{S} \iff \mathbf{G}\mathbf{S}=\mathbf{I}_{n_b}\) | S_matrix, G_matrix, W_shrink |
| \(\alpha_{\text{conf}}, \alpha_t, \gamma_{\text{aci}}, \operatorname{err}_t\) | \((0,1), \mathbb{R}, \{0,1\}\) | Mức sai bao phủ mục tiêu (0.10), mức ACI tức thời, bước học ACI, chỉ báo trượt \(\mathbb{I}\{y_t \notin \hat{C}_t\}\) |
Tách biệt khỏi tham số ETS \(\alpha\) |
alpha, alpha_t, gamma, miscoverage |
Trụ cột 1 — Nền tảng Stochastic, Mô hình Cổ điển, Độ đo Chuẩn hóa & Chứng minh Tối ưu Newsvendor–Pinball#
1.1 Tính dừng, Toán tử Trễ, Bẫy Sai phân Quá mức & Thiên lệch Hồi biến Jensen#
Một chuỗi thời gian \(\{Y_t\}_{t \in \mathbb{Z}}\) trên không gian xác suất \((\Omega, \mathcal{F}, \mathbb{P})\) là dừng chặt (strictly stationary) nếu với mọi tập hữu hạn \(k \ge 1\), mọi bộ chỉ số \((t_1,\dots,t_k) \in \mathbb{Z}^k\) và mọi bước dịch thời gian \(h \in \mathbb{Z}\), phân phối đồng thời hoàn toàn bất biến:
Trong thực tế thống kê, ta thường làm việc với điều kiện nhẹ hơn là dừng yếu / dừng hiệp phương sai (weak / covariance stationarity), đòi hỏi ba tính chất: (i) mô-men bậc hai hữu hạn \(\mathbb{E}[Y_t^2] < \infty\), (ii) kỳ vọng không đổi theo thời gian \(\mathbb{E}[Y_t] = \mu\), và (iii) tự hiệp phương sai chỉ phụ thuộc vào độ trễ \(k = \lvert t_1 - t_2 \rvert\): \(\operatorname{Cov}(Y_t, Y_{t-k}) = \gamma(k)\), từ đó định nghĩa hàm tự tương quan ACF \(\rho(k) := \gamma(k)/\gamma(0) \in [-1, 1]\). Hai khái niệm này không kéo theo nhau:
- Dừng chặt không suy ra dừng yếu: Chuỗi biến độc lập cùng phân phối \(Y_t \stackrel{\text{i.i.d.}}{\sim} \operatorname{Cauchy}(0, 1)\) hoàn toàn dừng chặt vì phân phối đồng thời bất biến theo phép dịch, nhưng kỳ vọng và phương sai đều không tồn tại (\(\mathbb{E}[Y_t^2] = \infty\)).
- Dừng yếu không suy ra dừng chặt: Nếu các vị trí chẵn \(Y_{2m} \sim \mathcal{N}(0, 1)\) và các vị trí lẻ \(Y_{2m+1} \sim \operatorname{Uniform}[-\sqrt{3}, \sqrt{3}]\) độc lập với nhau, mọi biến đều có \(\mathbb{E}[Y_t] = 0\), \(\operatorname{Var}(Y_t) = 1\), \(\gamma(k) = \mathbb{I}\{k = 0\}\), tức thỏa mãn dừng yếu, nhưng phân phối biên tại \(t\) chẵn và \(t\) lẻ khác hẳn nhau. Chỉ khi \(\{Y_t\}\) là quá trình Gauss đồng thời, dừng yếu mới tương đương với dừng chặt.
Để biến đổi chuỗi không dừng về chuỗi dừng, ta sử dụng đại số toán tử trễ \(B Y_t := Y_{t-1}\) và \(B^k Y_t = Y_{t-k}\). Với \(\lvert \phi \rvert < 1\) và phương sai bị chặn, phép nghịch đảo toán tử cho phép khai triển \((1 - \phi B)^{-1} = \sum_{j=0}^\infty \phi^j B^j\). Khi lấy sai phân bậc một \(\Delta Y_t := (1 - B) Y_t = Y_t - Y_{t-1}\) hoặc sai phân mùa vụ \(\Delta_s Y_t := (1 - B^s) Y_t = Y_t - Y_{t-s}\), cần đặc biệt cảnh giác bệnh lý sai phân quá mức (over-differencing): nếu áp dụng \(\Delta\) lên một chuỗi nhiễu trắng đã dừng \(Y_t = \mu + \varepsilon_t\) (\(\varepsilon_t \sim \text{WN}(0, \sigma^2)\)), ta thu được \(\Delta Y_t = \varepsilon_t - \varepsilon_{t-1} = (1 - B)\varepsilon_t\). Phương sai lập tức tăng gấp đôi lên \(2\sigma^2\), đồng thời sinh ra nghiệm đơn vị giả tạo trong phần trung bình trượt (MA unit root \(\theta_1 = -1\), với \(\rho(1) = -0.5\)) khiến quá trình ước lượng hợp lý cực đại (MLE) của ARIMA rơi vào bất ổn định số học.
Khi phân biệt chuỗi nghiệm đơn vị (unit-root \(Y_t = \mu_0 + Y_{t-1} + \varepsilon_t\), phương sai tăng tuyến tính \(\operatorname{Var}(Y_t \mid Y_0) = t\sigma^2 \to \infty\), cú sốc tồn tại vĩnh viễn \(\to\) xử lý bằng sai phân) với chuỗi dừng quanh xu thế (trend-stationary \(Y_t = \beta_0 + \beta_1 t + \eta_t\), phương sai hữu hạn \(\to\) xử lý bằng khử xu thế hồi quy), một kiểm định đơn lẻ rất dễ kết luận nhầm. Quy chuẩn kiểm định cặp đôi đối nghịch giả thuyết không:
- Augmented Dickey–Fuller (
ADF, Dickey & Fuller 1979; Said & Dickey 1984): Ước lượng hồi quy \(\Delta y_t = \alpha_{\text{adf}} + \beta_{\text{adf}} t + \gamma_{\text{adf}} y_{t-1} + \sum_{j=1}^k \delta_j \Delta y_{t-j} + \varepsilon_t\) với giả thuyết không \(H_0: \gamma_{\text{adf}} = 0\) (có nghiệm đơn vị / không dừng) đối đầu \(H_1: \gamma_{\text{adf}} < 0\) (dừng). Lưu ý thống kê \(t\) tuân theo phân phối Dickey–Fuller lệch trái phi chuẩn, vàADFcó lực kiểm định rất thấp khi \(\phi_1 \in [0.90, 0.99]\) hoặc khi chuỗi chứa điểm gãy cấu trúc (Perron 1989). - Kiểm định
KPSS(Kwiatkowski, Phillips, Schmidt & Shin, 1992): Phân rã \(y_t = \xi t + r_t + \varepsilon_t\) với \(r_t = r_{t-1} + u_t\), đặt giả thuyết không \(H_0: \sigma_u^2 = 0\) (dừng theo mức hoặc theo xu thế) đối đầu \(H_1: \sigma_u^2 > 0\) (có nghiệm đơn vị), dùng thống kê \(\operatorname{LM} = \frac{1}{T^2 \hat{\sigma}_{\text{HAC}}^2} \sum_{t=1}^T S_t^2\) phụ thuộc băng thông Newey–West.
Quy tắc ra quyết định kết hợp trong Lab 06 (check_stationarity_adf_kpss): chỉ kết luận chuỗi dừng (\(d = 0\)) khi ADF bác bỏ \(H_0\) (\(p < 0.05\)) VÀ KPSS không bác bỏ \(H_0\) (\(p \ge 0.05\)); nếu cả hai cùng bất đồng, cần kiểm tra độ dài mùa vụ \(s\) hoặc điểm gãy cấu trúc.
Trong chuỗi nhu cầu bán lẻ, phương sai thường tỷ lệ thuận với mức kỳ vọng (dị phương sai dương lệch phải). Biến đổi ổn định phương sai Box–Cox (\(y_t > 0\)) hay log1p(y_t) (khi có \(y_t = 0\)) làm phẳng sai số trên thang \(Z_t = f(Y_t)\), nhưng đặt ra một cái bẫy kinh điển khi quy đổi ngược dự báo: vì hàm nghịch đảo \(f^{-1}\) là hàm lồi chặt (chẳng hạn \(\exp(z)\) với \(\lambda_{\text{bc}} = 0\)), bất đẳng thức Jensen khẳng định \(\mathbb{E}[f^{-1}(Z)] > f^{-1}(\mathbb{E}[Z])\). Đảo ngược trực tiếp \(\hat{y} = f^{-1}(\hat{\mu}_z)\) chỉ thu được trung vị có điều kiện, làm ước lượng kỳ vọng bị hụt âm hệ thống. Khai triển Taylor bậc hai cho phép hiệu chỉnh thiên lệch Jensen (FPP3 & Lab 06, boxcox_bias_corrected_mean):
Ngược lại, do biến đổi đơn điệu bảo toàn thứ tự xếp hạng, phân vị hoàn toàn đẳng biến (quantile equivariance): \(Q_\tau(Y) = f^{-1}(Q_\tau(Z))\) không bao giờ cần nhân hệ số hiệu chỉnh Jensen! Đây là lý do thực hành trong Chương 13 rằng nếu mục tiêu tối hậu là tối ưu tồn kho theo phân vị tới hạn \(q^*\), mô hình phân vị có thể dự báo trực tiếp mà không gặp rắc rối tích phân lại phân phối sai số. Tương tự, khi sử dụng phân rã STL (Seasonal and Trend decomposition using Loess, Cleveland et al., 1990) để tách \(y_t = T_t + S_t + R_t\) qua hai vòng lặp LOESS + trọng số kháng ngoại lai bisquare Tukey (\(h_{\text{rob}} = 6\operatorname{Med}(\lvert R \rvert)\)), kỹ sư tuyệt đối chỉ được khớp STL riêng trong từng cửa sổ huấn luyện [1..t0] vì bộ làm trơn LOESS dùng lân cận hai phía — chạy STL trên toàn bộ tập dữ liệu trước khi chia tàu huấn luyện/kiểm thử sẽ bơm thông tin tương lai ngược về quá khứ.
1.2 Mô hình Tham số Cổ điển (ETS & ARIMA / SARIMAX)#
Hệ phân loại ETS(E, T, S) (Error, Trend, Seasonal — Hyndman et al., 2002, 2008) hệ thống hóa các phương pháp làm trơn hàm mũ dưới dạng mô hình không gian trạng thái đổi mới (innovations state-space models) với một nguồn nhiễu \(\varepsilon_t \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(0, \sigma^2)\) duy nhất, cho phép sinh trực tiếp phân phối dự báo và khoảng tin cậy giải tích. Năm cấu hình cốt lõi cần phân biệt rõ hành vi tại biên bằng 0:
Mô hình (ETS Code) |
Phương trình đo lường (\(y_t\)) | Phương trình chuyển trạng thái | Dự báo điểm \(h\) bước (\(\hat{y}_{T+h \mid T}\)) | Lưu ý vận hành & Bẫy biên |
|---|---|---|---|---|
SES ETS(A,N,N) |
\(y_t = \ell_{t-1} + \varepsilon_t\) | \(\ell_t = \ell_{t-1} + \alpha \varepsilon_t\) | \(\ell_T\) | Tương đương ARIMA(0,1,1) với \(\theta_1 = \alpha - 1\) |
Holt Linear ETS(A,A,N) |
\(y_t = \ell_{t-1} + b_{t-1} + \varepsilon_t\) | \(\ell_t = \ell_{t-1} + b_{t-1} + \alpha \varepsilon_t\), \(b_t = b_{t-1} + \beta \varepsilon_t\) | \(\ell_T + h\, b_T\) | Ngoại suy tuyến tính vô hạn dễ bùng nổ ở \(h\) dài |
Damped Holt ETS(A,A_d,N) |
\(y_t = \ell_{t-1} + \phi_{\text{damp}} b_{t-1} + \varepsilon_t\) | \(\ell_t = \ell_{t-1} + \phi_{\text{damp}} b_{t-1} + \alpha \varepsilon_t\), \(b_t = \phi_{\text{damp}} b_{t-1} + \beta \varepsilon_t\) | \(\ell_T + \big(\sum_{j=1}^h \phi_{\text{damp}}^j\big) b_T\) | \(\phi_{\text{damp}} \in [0.80, 0.98]\) làm bão hòa xu hướng rất hiệu quả |
Holt-Winters Cộng ETS(A,A,A) |
\(y_t = \ell_{t-1} + b_{t-1} + s_{t-s} + \varepsilon_t\) | \(\ell_t = \ell_{t-1}+b_{t-1}+\alpha\varepsilon_t\), \(b_t = b_{t-1}+\beta\varepsilon_t\), \(s_t = s_{t-s}+\gamma_{\text{ets}}\varepsilon_t\) | \(\ell_T + h\,b_T + s_{T+h-s(k+1)}\) | An toàn tuyệt đối khi chuỗi có giá trị \(y_t = 0\) (Lab 06) |
Holt-Winters Nhân ETS(M,A,M) |
\(y_t = (\ell_{t-1}+b_{t-1})s_{t-s}(1+\varepsilon_t)\) | \(\ell_t = (\ell_{t-1}+b_{t-1})(1+\alpha\varepsilon_t)\), \(s_t = s_{t-s}(1+\gamma_{\text{ets}}\varepsilon_t)\) | \((\ell_T + h\,b_T)s_{T+h-s(k+1)}\) | Sụp đổ/chia 0 nếu có ngày \(y_t = 0\) hoặc đóng cửa |
Với bài toán có biến ngoại sinh (giá, khuyến mãi đã công bố trước), mô hình chuẩn là Hồi quy với Sai số SARIMA (Regression with SARIMA errors — lưu ý khác biệt tinh tế so với đưa \(\mathbf{x}_t\) vào bên trong phương trình sai phân thuần túy vì giữ diễn giải trực tiếp hệ số \(\boldsymbol{\beta}\)):
Hai điều kiện bất biến đại số đảm bảo mô hình hợp lệ: quá trình \(\eta_t\) (sau sai phân) là nhân quả (causal — biểu diễn được thành \(\text{MA}(\infty)\) chỉ gồm hiện tại và quá khứ \(\varepsilon_t, \varepsilon_{t-1}, \dots\)) khi và chỉ khi mọi nghiệm của đa thức tự hồi quy \(\phi_{\text{tot}}(z) = \phi_p(z)\Phi_P(z^s) = 0\) nằm ngoài vòng tròn đơn vị (\(\lvert z \rvert > 1\)); và quá trình là khả nghịch (invertible — biểu diễn được sai số theo quá khứ quan sát \(\text{AR}(\infty)\)) khi và chỉ khi mọi nghiệm của \(\theta_{\text{tot}}(z) = 0\) thỏa \(\lvert z \rvert > 1\). Cuối cùng, một lỗi kinh điển khi chọn mô hình là dùng AICc để so sánh ARIMA(1,0,1) với ARIMA(1,1,1) hoặc mô hình log với mô hình gốc: hàm hợp lý cực đại được tính trên biến sau khi đã sai phân/biến đổi có độ dài hiệu dụng và Jacobian khác nhau, do đó AICc tuyệt đối không so sánh chéo qua các bậc \((d, D)\) hoặc \(\lambda_{\text{bc}}\) khác nhau. Bắt buộc cố định \((d, D)\) trước bằng cặp ADF–KPSS / kiểm định mùa vụ Canova–Hansen (giống thuật toán Hyndman–Khandakar 2008) rồi mới dùng AICc tìm \((p, q, P, Q)\).
1.3 Nhu cầu Gián đoạn, Phản chứng MAPE/MAE, Croston-SBA, TSB & Tweedie#
Hầu hết danh mục bán lẻ và phụ tùng (M5: 60%–70% ngày bằng 0) không phải là đường cong mượt mà nằm ở vùng thưa. Ma trận phân loại Syntetos–Boylan–Croston (SBC, 2005) chia chuỗi theo khoảng cách trung bình giữa hai lần phát sinh nhu cầu dương \(\text{ADI} = \frac{T}{\sum_{t=1}^T \mathbb{I}\{y_t > 0\}}\) và bình phương hệ số biến thiên kích thước dương \(\text{CV}^2 = (\hat{\sigma}_z / \hat{\mu}_z)^2\):
- Mượt (
Smooth): \(\text{ADI} < 1.32,\ \text{CV}^2 \le 0.49\) (ETS/SARIMAXcổ điển hiệu quả). - Thất thường (
Erratic): \(\text{ADI} < 1.32,\ \text{CV}^2 > 0.49\) (biến động lớn, cần phân vị /LightGBM). - Gián đoạn (
Intermittent): \(\text{ADI} \ge 1.32,\ \text{CV}^2 \le 0.49\) (Croston-SBA/TSB/Tweedie). - Cục bộ / Cực thưa (
Lumpy): \(\text{ADI} \ge 1.32,\ \text{CV}^2 > 0.49\) (Tweedie+Pinballtrực tiếp hoặc bảo hiểm mức nền).
Tại sao mọi đội ngũ đặt KPI bằng MAPE hay MAE trên hai nhóm dưới cùng đều thất bại thảm khốc?
-
Giải phẫu Bẫy
MAPE(Kolassa 2016, 2020): Tại \(y_t = 0\), \(\lvert y_t - \hat{y}_t \rvert / y_t = \infty\). Ngay cả khi lọc bỏ những ngày \(y_t = 0\), điều kiện tối ưu bậc nhất của rủi ro kỳ vọng \(\mathbb{E}[\lvert Y - a \rvert / Y]\) đòi hỏi:\[\frac{d}{da}\mathbb{E}\!\left[\frac{\lvert Y - a \rvert}{Y}\right] = 0 \iff \mathbb{E}\!\left[\frac{\mathbb{I}\{Y \le a^*\}}{Y}\right] = \frac{1}{2}\mathbb{E}\!\left[\frac{1}{Y}\right].\]Xét phân phối thực nghiệm trong
Lab 06: \(Y \in \{1, 10\}\) đồng xác suất \(0.5\). Khi đó \(\mathbb{E}[Y^{-1}] = 0.5(1 + 0.1) = 0.55 \implies \frac{1}{2}\mathbb{E}[Y^{-1}] = 0.275\). Tại \(a = 1\), vế trái đã nhảy từ0lên0.50 > 0.275, nên điểm tối ưu duy nhất củaMAPElà \(a^* = 1.0\) trong khi trung bình thực là \(5.5\) — tương đương thiên lệch âm-81.82%! Chọn mô hình bằngMAPEthực chất đang trao giải thưởng cho mô hình đánh tụt dự báo xuống đáy phân phối. -
Giải phẫu Sụp đổ
MAE = 0.0: Hàm mất mátMAE(\(\rho_{0.5}(u) \cdot 2\)) tối thiểu hóa tại trung vị của \(Y\). Nếu xác suất ngày không bán được vượt quá \(50\%\) (\(\mathbb{P}(Y = 0) > 0.5\), ví dụ71.5%trongLab 06), trung vị bằng đúng0.0: dự báo "tối ưuMAE" là đặt toàn bộ chuỗi dự báo bằng0.0, gây100%thiếu hàng và không mang lại bất kỳ thông tin đặt hàng nào.
Để dự báo đúng kỳ vọng cho chuỗi gián đoạn bằng phương pháp thống kê nhẹ, Croston (1972) tách riêng chuỗi thành hai thành phần chỉ cập nhật tại các kỳ có \(y_t > 0\): kích thước nhu cầu dương \(\hat{z}_t = \alpha_z y_t + (1 - \alpha_z)\hat{z}_{t-1}\) và khoảng cách giữa hai lần mua \(\hat{p}_t = \alpha_p k_t + (1 - \alpha_p)\hat{p}_{t-1}\) (với \(k_t\) là số ngày kể từ lần xuất hiện trước), rồi dự báo tốc độ cầu mỗi kỳ \(\hat{y}^{\text{Croston}} = \hat{z}_t / \hat{p}_t\). Tuy nhiên, Syntetos & Boylan (2005) đã chứng minh phương pháp Croston bị thiên lệch dương có hệ thống. Thật vậy, ngay cả khi kích thước \(z_k\) độc lập với khoảng cách \(p_k\) và ước lượng riêng lẻ đều không chệch (\(\mathbb{E}[\hat{z}_k] = \mu_z\), \(\mathbb{E}[\hat{p}_k] = \mu_p\)), vì hàm \(g(u) = 1/u\) là hàm lồi chặt trên \((0, \infty)\), theo bất đẳng thức Jensen ta luôn có \(\mathbb{E}[1/\hat{p}_k] > 1/\mathbb{E}[\hat{p}_k] = 1/\mu_p\). Khai triển Taylor bậc hai quanh \(\mu_p\) với phương sai dừng của bộ làm trơn mũ \(\operatorname{Var}(\hat{p}_k) = \frac{\alpha_p}{2 - \alpha_p}\sigma_p^2\) (và \(\sigma_p^2 = \mu_p(\mu_p - 1)\) với biến hình học):
Do đó, nhân bộ dự báo Croston với hệ số hiệu chỉnh SBA (Syntetos–Boylan Approximation) thu được ước lượng không chệch bậc đầu:
Một điểm mù còn lại của cả Croston và SBA là khoảng ước lượng \(\hat{p}_t\) chỉ cập nhật khi có phát sinh nhu cầu \(y_t > 0\) — nếu một SKU trở thành hàng chết (ngừng bán 180 ngày liên tiếp), dự báo SBA vẫn "đóng băng" ở giá trị dương cũ. TSB (Teunter, Syntetos & Babai, 2011) khắc phục triệt để bằng cách cập nhật xác suất xuất hiện nhu cầu \(\hat{\pi}_t^{\text{occ}} = \alpha_{\text{occ}}\,\mathbb{I}\{y_t > 0\} + (1 - \alpha_{\text{occ}})\hat{\pi}_{t-1}^{\text{occ}}\) ở mọi kỳ \(t\) rồi trả về \(\hat{y}_{t+h \mid t}^{\text{TSB}} = \hat{\pi}_t^{\text{occ}}\,\hat{z}_t\), giúp dự báo suy giảm mượt mà về 0 khi sản phẩm hết vòng đời.
Khi bước sang học máy dạng bảng (LightGBM, GLM), họ phân phối tự nhiên cho dữ liệu bán lẻ có khối xác suất tại 0 cộng đuôi liên tục lệch phải là Compound Poisson–Gamma Tweedie (Jørgensen 1987; Dunn & Smyth 2005) với chỉ số phương sai \(1 < p_{\text{tw}} < 2\). Ta mô hình hóa tổng lượng bán trong ngày như tổng \(Y = \sum_{j=1}^N G_j\) của số lượt khách \(N \sim \operatorname{Poisson}(\lambda_{\text{tw}})\) với kích thước mỗi giỏ \(G_j \stackrel{\text{i.i.d.}}{\sim} \operatorname{Gamma}(\alpha_\Gamma, \theta_{\text{tw}})\). Kỳ vọng là \(\mu\), phương sai tuân theo quy luật lũy thừa \(\operatorname{Var}(Y) = \phi_{\text{tw}}\mu^{p_{\text{tw}}}\), và khối xác suất tại \(0\) cho đúng xác suất không bán được đơn hàng nào: \(\ln \mathbb{P}(Y = 0) = -\lambda_{\text{tw}} = -\frac{\mu^{2-p_{\text{tw}}}}{\phi_{\text{tw}}(2-p_{\text{tw}})}\). Đặt liên kết logarit \(\mu_i = e^{\eta_i}\), hàm lệch đơn vị (unit deviance) là:
Đạo hàm bậc nhất và bậc hai của bán-hàm-lệch \(\ell_{\text{tw}}(y_i, \eta_i) = -y_i \frac{e^{(1-p_{\text{tw}})\eta_i}}{1-p_{\text{tw}}} + \frac{e^{(2-p_{\text{tw}})\eta_i}}{2-p_{\text{tw}}}\) theo điểm thô \(\eta_i\) lần lượt là:
Vì \(1 < p_{\text{tw}} < 2\) và \(y_i \ge 0\), cả hai số hạng trong \(h_i\) đều không âm và số hạng thứ hai dương ngặt, bảo đảm hàm mất mát lồi chặt theo \(\eta_i\) với Hessian dương tuyệt đối tại mọi điểm (ngay cả khi \(y_i = 0\)), giúp bước nhảy Newton trong LightGBM (objective="tweedie") hội tụ cực kỳ ổn định!
1.4 Hệ thống Độ đo Đánh giá Chuẩn hóa Không Rò rỉ Số Không#
Thay thế hoàn toàn MAPE và MAE thô bằng bộ bốn chuẩn hóa công nghiệp và học thuật (M5 / FPP3):
MASE(Hyndman & Koehler, IJF 2006): Chuẩn hóa sai số tuyệt đối ngoài mẫu bằng sai số tuyệt đối của bộ dự báo ngây thơ theo mùa trên tập huấn luyện (in-sample), miễn nhiễm hoàn toàn với \(y_{T+h} = 0\):\[\operatorname{MASE} = \frac{\frac{1}{H}\sum_{h=1}^H \lvert y_{T+h} - \hat{y}_{T+h} \rvert}{\frac{1}{T-s}\sum_{t=s+1}^T \lvert y_t - y_{t-s} \rvert}.\]RMSSE&WRMSSE(Makridakis et al., M5 2022): Chuẩn hóa bình phương sai số ngoài mẫu bằng MSE ngây thơ 1-bước trên lịch sử tích cực rồi cân trọng số theo doanh thu \(\omega_i\) (trung bình hóa về chuỗi đúng kỳ vọng thay vì trung vị0):\[\operatorname{RMSSE}_i = \sqrt{\frac{\frac{1}{H}\sum_{h=1}^H (y_{i,T+h} - \hat{y}_{i,T+h})^2}{\frac{1}{T-1}\sum_{t=2}^T (y_{i,t} - y_{i,t-1})^2}}, \qquad \operatorname{WRMSSE} = \sum_{i} \omega_i \operatorname{RMSSE}_i.\]WQL(Weighted Quantile Loss): Đánh giá sai lệch từng mức phân vị \(\tau\), chuẩn hóa theo tổng nhu cầu thực tế:\[\operatorname{WQL}[\tau] = \frac{2\sum_{i,h}\rho_\tau\!\left(y_{i,T+h} - \hat{q}_{i,T+h}(\tau)\right)}{\sum_{i,h} \lvert y_{i,T+h} \rvert} \quad \Longrightarrow \quad \operatorname{WQL}[0.5] \equiv \operatorname{WAPE}.\]CRPS(Continuous Ranked Probability Score): Quy tắc chấm điểm nghiêm ngặt chuẩn xác (strictly proper scoring rule) đánh giá toàn bộ phân phối dự báo tích lũy \(F\), tương đương tích phân gấp đôi kỳ vọng Pinball Loss trên tất cả các mức phân vị \(\tau \in (0, 1)\):\[\operatorname{CRPS}(F, y) = \int_{-\infty}^{\infty} \left(F(z) - \mathbb{I}\{y \le z\}\right)^2 dz = 2 \int_0^1 \rho_\tau\!\left(y - F^{-1}(\tau)\right) d\tau.\]
1.5 Định lý Cốt lõi (Chuyên đề #4): Tương đương Giải tích Pinball Loss \(\leftrightarrow\) Newsvendor \(q^*\) & Tồn kho Đa kỳ#
Xét hàm mất mát Pinball tại mức \(\tau \in (0, 1)\) trên sai số \(u = y - a\):
Định lý 1 (Pinball Loss hồi phục chính xác phân vị \(\tau\)): Cho biến ngẫu nhiên \(Y\) có \(\mathbb{E}[\lvert Y \rvert] < \infty\) và hàm phân phối tích lũy \(F_Y(z) = \mathbb{P}(Y \le z)\). Khi đó mọi điểm tối tiểu của hàm rủi ro \(R_\tau(a) := \mathbb{E}[\rho_\tau(Y - a)]\) đều thỏa điều kiện \(F_Y(a^{*-}) \le \tau \le F_Y(a^*)\), tức \(a^* = F_Y^{-1}(\tau)\) là phân vị bậc \(\tau\) của \(Y\).
Chứng minh cho cả CDF liên tục lẫn rời rạc / có khối điểm tại 0: Viết \(R_\tau(a) = \tau\,\mathbb{E}[(Y - a)\mathbb{I}\{Y > a\}] + (1 - \tau)\,\mathbb{E}[(a - Y)\mathbb{I}\{Y \le a\}]\). Xét bước dịch \(a + \varepsilon\) (\(\varepsilon > 0\)); với mọi hiện thực \(Y(\omega)\) ta có \(\lvert \rho_\tau(Y - (a+\varepsilon)) - \rho_\tau(Y - a) \rvert \le \varepsilon\), do đó theo Định lý Hội tụ Bị chặn (Dominated Convergence), ta được phép đưa giới hạn đạo hàm phải qua dấu kỳ vọng:
Tương tự lấy giới hạn trái (\(\varepsilon \uparrow 0\)) sử dụng tính liên tục phải có giới hạn trái của CDF, biến cố đổi dấu xảy ra ở \(Y < a\) thay vì \(Y \le a\), cho đạo hàm trái \(D_- R_\tau(a) = F_Y(a^-) - \tau\). Vì \(R_\tau(a)\) là hàm lồi theo \(a\), điều kiện cần và đủ để \(a^*\) cực tiểu toàn cục là \(0 \in \partial R_\tau(a^*) = [F_Y(a^{*-}) - \tau,\ F_Y(a^*) - \tau]\), tương đương đúng với bất đẳng thức \(F_Y(a^{*-}) \le \tau \le F_Y(a^*)\) (trùng \(F_Y(a^*) = \tau\) khi \(F_Y\) liên tục và tăng ngặt). \(\blacksquare\)
Định lý 2 (Tương đương Newsvendor–Pinball & Phân vị tới hạn \(q^*\)): Trong bài toán người bán báo (Newsvendor) với chi phí thiếu mỗi đơn vị là \(c_u > 0\) (underage / lost margin + penalty) và chi phí dư thừa mỗi đơn vị là \(c_o > 0\) (overage / holding + spoilage), hàm chi phí thực tế khi đặt hàng lượng \(Q \in \mathbb{R}\) và nhu cầu về là \(y\) là:
Đặt phân vị tới hạn (critical fractile) \(q^* := \frac{c_u}{c_u + c_o} \in (0, 1)\). Ta có \(c_u = (c_u + c_o)q^*\) và \(c_o = (c_u + c_o)(1 - q^*)\). Thay trực tiếp vào từng nhánh \((y \ge Q)\) và \((y < Q)\) cho đẳng thức điểm chính xác với mọi \((y, Q)\):
Vì \((c_u + c_o) > 0\) là hằng số dương độc lập với \(Q\), bài toán chọn lượng đặt hàng \(Q^*\) tối thiểu hóa kỳ vọng thiệt hại \(\mathbb{E}[C_{\text{NV}}(Y, Q \mid \mathcal{F}_t)]\) hoàn toàn tương đương với bài toán hồi quy phân vị tối thiểu hóa \(\mathbb{E}[\rho_{q^*}(Y - Q \mid \mathcal{F}_t)]\), cho nghiệm tối ưu đóng:
Hệ quả định lượng độ dôi chi phí của MSE: Giả sử \(Y \mid \mathcal{F}_t \sim \mathcal{N}(\mu, \sigma^2)\) và một hệ thống ngây thơ dùng dự báo MSE đặt hàng \(Q^{\text{MSE}} = \mu\). Tại điểm này \(\mathbb{E}[(Y - \mu)^+] = \mathbb{E}[(\mu - Y)^+] = \sigma \varphi(0) = \frac{\sigma}{\sqrt{2\pi}}\), dẫn đến \(C(\mu) = (c_u + c_o)\frac{\sigma}{\sqrt{2\pi}}\). Trong khi đó tại \(Q^* = \mu + z^*\sigma\) với \(z^* = \Phi^{-1}(q^*)\), tích phân chuẩn cho chi phí cực tiểu \(C(Q^*) = (c_u + c_o)\,\sigma\,\varphi(z^*)\). Tỷ số tổn thất vượt mức do dùng sai hàm mất mát là:
Tại tỷ lệ bất đối xứng SKU_HI trong Lab 06 (\(c_u = 18,\ c_o = 2 \implies q^* = 0.90,\ z^* = 1.2816\)), dự báo trung bình MSE đội chi phí gấp \(\exp(1.2816^2 / 2) = 2.273\times\) (+127.3%) ngay cả khi ước lượng \(\mu\) hoàn hảo tuyệt đối! Trong thực tế phân phối bán lẻ lệch phải (như Gamma hay Poisson–Gamma), tỷ số thiệt hại còn nghiêm trọng hơn vì đuôi phải dày làm \(\mu < Q^*\) cách xa hơn nữa ở phân vị 0.90 hoặc đảo ngược rất mạnh ở phân vị 0.20 cho hàng tươi sống.
Mở rộng sang Chuỗi cung ứng Đa kỳ với Thời gian Giao hàng \(L\): Trong kho vận thực tế, đơn hàng \(Q_t\) đặt tại gốc \(t\) chỉ cập bến sau \(L \ge 1\) kỳ (tại đầu kỳ \(t + L\)). Để không đặt trùng những đơn đang đi trên đường, trạng thái quyết định không phải là tồn kho hiện hữu \(I_t^{\text{net}}\) mà là vị thế tồn kho (Inventory Position):
Dưới cơ chế đặt trước (backordering), vị thế tồn kho sau khi đặt \(Q_t\) sẽ cân đối tổng cầu tích lũy trên cửa sổ bảo vệ \(L+1\) kỳ \(Y_{t+1:t+L+1} := \sum_{h=1}^{L+1} D_{t+h}\), dẫn đến chính sách mức gốc (Order-Up-To / Base-Stock Policy) tối ưu cục bộ:
Dưới cơ chế mất đơn hàng (lost sales) phổ biến ở siêu thị và thương mại điện tử (\(I_{t+1}^{\text{on\_hand}} = (I_t^{\text{on\_hand}} + Q_{t-L} - D_t)^+\)), nghiệm chính sách mức gốc vẫn tiệm cận tối ưu khi \(c_u / c_o \to \infty\) (Zipkin 2008; Huh et al., 2009), nhưng đòi hỏi ước lượng chuẩn xác phân phối tổng cầu trên cửa sổ lead time \(Y^{(L)}\) thay vì xấp xỉ \(L \cdot \sigma_1^2\) (vốn sai nặng do sai số dự báo giữa các ngày \(t+1, \dots, t+L\) luôn tự tương quan dương: \(\operatorname{Var}(\sum_{h=1}^L e_h) \gg \sum_{h=1}^L \sigma_h^2\)).
Thực hành tương tác mối quan hệ giải tích giữa chi phí bất đối xứng \((c_u, c_o)\), đường cong chữ V lệch tâm của Pinball Loss, độ đội chi phí của MSE, cũng như nghịch lý MAPE = -81.8% và sụp đổ MAE = 0.0 ngay trong trình mô phỏng dưới đây:
Trụ cột 2 — Tích hợp Chuyên đề Đặc biệt #4, Học Toàn cục LightGBM, Chuỗi Sâu, Foundation TS 2024–2026, Hòa giải MinT-Shrink & Conformal ACI#
2.1 Chuyên đề Đặc biệt #4 (Phần 1 & 2): Giải phẫu Thất bại Backtest & Mô hình Hình thức Nhân quả ASOF#
Kết nối Chuyên đề #4 (Forecast Backtesting with Decision Costs): Toàn bộ phần 2.1 dưới đây trình bày trọn vẹn Phần 1 (Ca Thất bại Cụ thể) và Phần 2 (Mô hình Hình thức Định lượng) của Chuyên đề Đặc biệt #4; Phần 3 (Thực nghiệm Cắt bỏ Có kiểm soát) được trình bày tại Trụ cột 4 gắn kết 1–1 với Lab 06, và Phần 4 (Cẩm nang Ra Quyết định Production) được đặt tại Trụ cột 3.
Phần 1 — Ca Thất bại Cụ thể trong Kiểm thử Hồi cứu Chuỗi Cung ứng#
Trong dự báo tài chính hay bán lẻ, một mô hình thường sụp đổ ngoài sản xuất theo bốn cơ chế ghép nối sau:
- Đánh giá một bước (
h = 1) cho bài toán đặt hàng đa bước (L >= 3ngày): Khi thời gian giao hàng của nhà cung cấp là \(L = 4\) ngày, đơn hàng chốt tại gốc \(t_0\) phải đủ phủ nhu cầu tích lũy \([t_0+1, t_0+L]\). Đánh giá sai ởh = 1rồi nhân tuyến tính với \(L\) bỏ qua hiệp phương sai dương giữa sai số các ngày liên tiếp và đánh sập khoảng đệm an toàn \(S_t^*\). - Xâm lấn nhãn đa kỳ không thanh lọc (Un-purged Multi-Horizon Target Overlap) & Chia
K-FoldNgẫu nhiên: Nếu nhãn mục tiêu tại gốc \(t\) là tổng cầu tương lai \(Y_t^{(L)} = \sum_{h=1}^L D_{t+h}\), thì mọi mẫu huấn luyện có gốc \(t_{\text{train}} \in (t_0 - L,\ t_0]\) đều có nhãn chồng lấn trực tiếp sang tương lai \([t_0+1, t_0+L]\)! Chưa kể việc xáo trộn ngẫu nhiênK-Foldcho phép câyLightGBMđọc lén giá và cấu trúc mùa của các ngày sau \(t_0\) để đoán ngược quá khứ. - Rò rỉ bảng
ASOFtừ biến tương lai chưa công bố (unannounced_flash_promo): Kỹ sư thường ghép cộtdiscount_pctthực tế từ bảng POS lịch sử làm biến ngoại sinh tương lai. Trong dữ liệu lịch sử, cột này trộn lẫn khuyến mãi định kỳ (được duyệt trước \(14\) ngày) với giảm giá giờ chót tại cửa hàng (chỉ xuất hiện lúc mở ca trong ngày \(t_0+h\)). Kết quảLab 06: chạyK-Foldkèm cột giảm giá chưa công bố tạo ra1,932vi phạmASOF, khiến lỗi ngoại tuyến giả tạo tụt đẹp xuống22.21nhưng nổ tung thành44.72khi vận hành trực tuyến! - Vòng xoáy kiểm duyệt hết hàng POS (
Stockout Right-Censoring Death Spiral): Hệ thống thu ngân chỉ ghi nhận doanh số khả dụng \(S_t = \min(D_t, I_t^{\text{on\_hand}})\) (dữ liệu bị kiểm duyệt phải). Khi tồn kho bằng0, \(S_t = 0\) dù nhu cầu thực \(D_t = 25\). Nếu đưa thẳng \(S_t\) vào đặc trưng trễ (lag_7,roll_mean_14), mô hình tưởng sức mua đã sụt giảm, dự báo thấp hơn cho kỳ sau \(\to\) đơn nhập hàng càng bé \(\to\) càng nhanh hết hàng \(\to\) doanh số ghi nhận lại về0. TrongLab 06, vòng xoáy này khiến doanh số quan sát lệch-49.16%(11.11vs21.86), tỷ lệ đứt hàng vọt lên79.3%!
Phần 2 — Mô hình Hình thức Định lượng: Kiểm thử Cuốn chiếu Thanh lọc Lead-Time & Trường lọc Kép ASOF#
Tại mọi gốc đặt hàng \(t_0 \in \{t_{\text{start}}, t_{\text{start}}+\Delta_{\text{step}}, \dots\}\), trường lọc thông tin khả dụng \(\mathcal{F}_{t_0}\) phải tách rạch ròi thành hai bảng dữ liệu bitemporal độc lập (build_causal_features & audit_asof_and_leakage trong Lab 06):
- Bảng Quá khứ Bị trễ Quan sát (Past-Only Table): Mọi đặc trưng trễ, trung bình trượt, biến động tồn kho hoặc nhiệt độ thực tế \(\mathbf{x}_{i, t}^{\text{past}}\) chỉ được gia nhập tập đặc trưng cho gốc đặt hàng \(t_0\) nếu dấu thời gian sẵn sàng thực tế (availability timestamp đã cộng trễ ETL \(\delta_{\text{SLA}}\)) thỏa:
\[\tau_{\text{avail}}(\mathbf{x}^{\text{past}}) \le t_0 - \delta_{\text{SLA}}.\]
- Bảng Tương lai Đã Công bố Trước (Known-Future Announced Table): Các biến lịch dương/âm, ngày nghỉ lễ, bảng giá và lịch khuyến mãi định kỳ tương lai \(\mathbf{u}_{i, t_0+h}\) cho \(h \in \{1,\dots,L\}\) chỉ hợp lệ nếu thời điểm khóa lịch công bố (announcement timestamp) xảy ra trước hoặc đúng gốc \(t_0\):
\[\tau_{\text{announced}}(\mathbf{u}_{i, t_0+h}) \le t_0 \qquad (\forall h \in \{1,\dots,L\}).\]Mọi giảm giá flash bất ngờ có \(\tau_{\text{announced}} > t_0\) đều phải gán về
0/ thiếu giá trị tại thời điểm suy luận \(t_0\). - Bất biến Thanh lọc Lead-Time (Purged Rolling-Origin Invariant): Với mục tiêu tổng cầu trên chân trời \(L\) ngày \(Y_{i,t}^{(L)} = \sum_{h=1}^L D_{i, t+h}\), tập huấn luyện ở lượt đánh giá có gốc \(t_0\) chỉ được chứa các hàng \(t_{\text{train}}\) thỏa mãn điều kiện biên kết thúc mục tiêu:
\[t_{\text{train\_target\_end}} := t_{\text{train}} + L \le t_0 \iff t_{\text{train}} \le t_0 - L.\]Nói cách khác, tồn tại một vùng thanh lọc bắt buộc dài \(L\) ngày ngay trước gốc \(t_0\): các hàng có gốc nằm trong \((t_0 - L,\ t_0]\) bị loại bỏ hoàn toàn khỏi tập huấn luyện để không một mẩu nhãn \(D_{t_0+h}\) nào bị rò vào tham số cây hoặc tham số chuẩn hóa. Khi kiểm thử nối tiếp theo lịch triển khai (Expanding hoặc Rolling Window), mọi đặc trưng tính trên cửa sổ trượt (
STL, chuẩn hóa z-score, co cụmMinT) đều tái ước lượng nội bộ trên \(\mathcal{F}_{t_0}\). - Phá vỡ Censoring POS qua Cờ
OSA& Khôi phục Nhu cầu: Ghi nhận cờ nhị phân \(c_t = \mathbb{I}\{I_t^{\text{on\_hand}} = 0 \text{ hoặc hết hàng giữa ca}\}\) (stockout indicator). Khi \(c_t = 1\), biến trễ không dùng giá trị \(S_t\) bị cắt cụt thô mà gán mask / khôi phục có điều kiện (uncensoring) bằng kỳ vọng cắt cụt hoặcOSA-imputed demand \(\hat{D}_t^{\text{uncens}} = \mathbb{E}[D_t \mid D_t \ge S_t, \mathcal{F}_{t-1}]\) trước khi nạp vào cây trễ cho các chu kỳ kế tiếp.
Khám phá trực quan trên dòng thời gian lý do K-Fold / chưa thanh lọc \(L\) ngày gây ra 1,932 vi phạm ASOF và xem vòng xoáy đứt hàng 79.3% -> 0.0% trong trình mô phỏng tương tác sau:
2.2 Mô hình Bảng Toàn cục (Global Panel GBDT — LightGBM Quantile & Tweedie)#
Cho đến tận những năm 2020, ngành dự báo còn tranh luận giữa hai thái cực: huấn luyện một mô hình tham số riêng cho từng chuỗi (Local Paradigm: \(M\) chuỗi \(\implies M\) mô hình ETS/ARIMA, độ phức tạp \(\mathcal{O}(M \cdot C_{\text{local}})\) và phương sai ước lượng cực lớn khi chuỗi ngắn) so với mô hình hóa toàn bộ danh mục chung một hàm phi tuyến (Global Paradigm). Montero-Manso & Hyndman (IJF 2021) chứng minh một kết quả lý thuyết then chốt: bằng cách gom toàn bộ \(M\) chuỗi vào một hàm toàn cục duy nhất \(\hat{y}_{i,t+h} = f_\theta(\mathbf{x}_{i,t}, \mathbf{u}_{i,t+h}, \mathbf{s}_i)\) (với \(\mathbf{s}_i\) là siêu dữ liệu tĩnh như category, store_id, sku_embedding), độ phức tạp thống kê là bất biến \(\mathcal{O}(C_{\text{global}})\) không tăng theo số lượng \(M\) mặt hàng, đồng thời một mạng/rừng cây đủ sâu có khả năng xấp xỉ bất kỳ tập hợp mô hình địa phương dị nhất nào nhờ chia nhánh theo đặc trưng nhận dạng chuỗi. Bằng chứng thực nghiệm lớn nhất là cuộc thi M5 (Makridakis et al., IJF 2022) trên 42,840 chuỗi bán lẻ phân cấp của Walmart: các biến thể Global LightGBM thống trị tuyệt đối ở cả hai đường đua Accuracy (WRMSSE) và Uncertainty (WQL).
Trong LightGBM toàn cục cho đa chân trời \(h \in \{1,\dots,H\}\), có ba chiến lược thiết kế bảng:
| Chiến lược đa chân trời | Biểu diễn dữ liệu | Động học sai số & bộ nhớ | Bẫy Production cần tránh |
|---|---|---|---|
| Đệ quy (Recursive) | Huấn luyện 1 bước \(\hat{f}(\mathbf{x}_{i,t})\), lấy đầu ra nạp lại làm lag_1 cho bước \(t+2\) |
Nhẹ khi huấn luyện; nhưng sai số tích lũy mũ khi \(h\) lớn | Không thể lan truyền chính xác phân vị ngoài mẫu nếu không mô phỏng Monte Carlo từng bước |
| Trực tiếp (Direct \(H\) mô hình) | Tách \(H\) mô hình độc lập \(\hat{f}_h(\mathbf{x}_{i,t}) \approx y_{i,t+h}\) | Không cộng dồn sai số trệ; nhưng tốn \(H \times\) bộ nhớ/thời gian bảo trì | Đường cong dự báo theo \(h\) dễ bị giật cục (răng cưa giữa \(h=7\) và \(h=8\)) |
| Gộp Trực tiếp Toàn cục (Direct-Global Pooled) | Gộp \((i, t, h) \mapsto y_{i,t+h}\) vào một bảng chung, thêm đặc trưng h và biến công bố tương lai \(\mathbf{u}_{i,t+h}\) |
Chia sẻ sức mạnh mẫu xuyên chân trời trong 1 mô hình duy nhất; căn chỉnh khít \(\mathbf{u}_{i,t+h}\) | Mọi biến trễ bắt buộc neo cứng tại gốc \(t_0\) (\(k \ge h\) nếu dùng tính năng dạng panel 1 bước), không rò tương lai u_{t+h} |
Cơ chế bên trong LightGBM cho Pinball (objective="quantile") và Tweedie (objective="tweedie"):
- Vấn đề đạo hàm bậc hai bằng
0củaPinball Loss: Với \(\rho_\tau(y - \hat{y})\), đạo hàm bậc hai theo \(\hat{y}\) bằng0hầu khắp nơi (và \(\infty\) tại gốc0), khiến công thức chuẩn của bước Newton \(-\sum g_i / (\sum h_i + \lambda)\) bị vô nghĩa! Giải pháp thanh lịch củaLightGBMlà gán giả-Hessian đồng nhất \(h_i = 1\) trong suốt bước quét tìm điểm tách cây (chọn nhánh dựa trên cực đại hóa \(\Delta \text{Gain}\) từ gradient \(\pm \tau, \pm(1-\tau)\)), sau đó khi kết thúc xây cấu trúc cây, thuật toán tính lại chính xác giá trị tối ưu tại từng lá bằng trung vị có trọng số bậc \(\tau\) (weighted \(\tau\)-quantile) của các phần dư rơi vào lá đó! Trong khi đóXGBoost 2.0+hỗ trợ vector đa phân vị (reg:quantileerror) vàCatBoosthỗ trợMultiQuantileđồng thời trong một rừng cây duy nhất. - Tốc độ & dấu chân bộ nhớ
uint8: Nhờ lượng tử hóa đặc trưng liên tục vào255giỏ (max_bin=255), toàn bộ ma trận thiết kế của10 triệudòng \(\times 60\) cột chỉ chiếm600 MBRAM dạnguint8thay vì4.8 GBởfloat64, đạt độ trễ suy luận trực tuyến0.3–3 msp99 trên CPU.
Bệnh lý Giao cắt Phân vị (Quantile Crossing) & Định lý Sắp xếp Đơn điệu (Chernozhukov, Fernández-Val & Galichon, Econometrica 2010):
Khi huấn luyện nhiều cây phân vị độc lập cho lưới \(\tau_1 < \tau_2 < \dots < \tau_K\), hoàn toàn có thể xảy ra nghịch lý \(\hat{q}_{0.20}(\mathbf{x}) > \hat{q}_{0.50}(\mathbf{x})\) tại những vùng thưa dữ liệu (Lab 06 ghi nhận 159 giao cắt thô trên tập kiểm thử!). Để triệt tiêu, ta chỉ cần áp dụng sắp xếp đơn điệu đẳng phân (isotonic rearrangement): với mỗi hàng dự báo \(\mathbf{x}\), sắp xếp lại vector phân vị theo thứ tự không giảm \(\tilde{q}_{\tau_k}(\mathbf{x}) := \hat{q}_{(\tau_k)}(\mathbf{x})\) (hoặc dùng chuẩn hóa tích phân đều liên tục). Định lý Chernozhukov chứng minh kết quả tuyệt đẹp: phép sắp xếp lại không những ép bất biến \(\tilde{q}_{\tau_1} \le \dots \le \tilde{q}_{\tau_K}\) mà còn co hẹp ngặt khoảng cách \(L_r([0,1])\) tới đường cong phân vị thật (strict contraction — nghĩa là dự báo sau sắp xếp vừa hợp lệ vừa chính xác hơn theo Pinball và CRPS!).
2.3 Mô hình Chuỗi Sâu & Hệ sinh thái Foundation Models 2024–2026 (TSFM)#
Khi dữ liệu có chuỗi lịch sử dài, cấu trúc chú ý (attention) hoặc thiếu hoàn toàn lịch sử (SKU mới), hai làn sóng kiến trúc mới bổ sung trực tiếp cho LightGBM:
-
Chuỗi Sâu Chuyên biệt (Deep Sequence Forecasters):
Temporal Fusion Transformer (TFT)(Lim et al., IJF 2021): Kiến trúc đầu bảng cho dữ liệu bán lẻ có nhiều loại đặc trưng nhờ tách cứng 3 luồng đầu vào: biến tĩnh (Static), biến quá khứ (Past-Only) và biến tương lai đã biết (Known-Future). Dùng mạng cổng phần dư (GRN), mạng chọn biến (VSN) đọc tầm quan trọng từng đặc trưng ở mỗi bước thời gian, bộ mã hóaLSTMkết hợp đa đầu chú ý có chung ma trận \(\mathbf{W}_V\) để diễn giải được trọng số chú ý và xuất trực tiếp nhiều phân vị bằng Pinball Loss.PatchTST(Nie et al., ICLR 2023): Khắc phục nhược điểm Transformer token từng bước thời gian bằng 3 ý tưởng: (i) Độc lập kênh (Channel-Independence — CI) xử lý từng biến riêng để tránh quá khớp nhiễu liên kênh, (ii) chuẩn hóa thuận nghịch theo từng cửa sổRevINchống trôi phân phối trung bình/phương sai, và (iii) gộp từng đoạn \(P\) bước dịch bước \(S\) thành một patch làm token, rút giảm độ phức tạp tự chú ý từ \(\mathcal{O}(L^2)\) xuống còn \(\mathcal{O}((L/S)^2)\) (giảm256xphép tính khi \(P=S=16\)).- Những kẻ thách thức Tuyến tính / MLP:
DLinear(Zeng et al., AAAI 2023) tách xu hướng bằng trung bình trượt + 2 ánh xạ tuyến tính (\(\mathcal{O}(L H)\), cực nhanh nhưng yếu khi có biến ngoại sinh phi tuyến như khuyến mãi chồng chéo);N-HiTS(Challu et al., AAAI 2023) gộp đa tỷ lệ tần số phân cấp (multi-rate pooling);TiDE(Das et al., TMLR 2023) nén mã hóa-giải mã MLP dày đặc hợp nhất cả 3 loại biến (tĩnh, quá khứ, tương lai) với tốc độ nhanh hơnPatchTST5–10x.
-
Mô hình Nền tảng Chuỗi Thời gian 2024–2026 (Time Series Foundation Models — TSFM):
- Hệ sinh thái
Chronos\(\to\)Chronos-Bolt\(\to\)Chronos-2(Amazon Science):Chronos(Ansari et al., TMLR 2024): Chuẩn hóa theo trung bình, lượng tử hóa giá trị thành4,096token từ vựng và huấn luyện trên họ mô hình ngôn ngữT5(20M–710Mtham số) kết hợp chuỗi tổng hợp GPKernelSynth; điểm yếu là sinh tự hồi quy chậm.Chronos-Bolt(cuối 2024): Chuyển sang mã hóa theo patch + giải mã trực tiếp9phân vị một lần, đạt tốc độ250xnhanh hơn và tiết kiệm20xbộ nhớ.Chronos-2(Ansari, Shchur et al., Oct 2025,arXiv:2510.15821): Mô hình encoder-only120Mtham số trang bị cơ chế Time Attention + Group Attention cho phép học ngữ cảnh (in-context learning) không cần tinh chỉnh trên đồng thời biến đa biến, biến quá khứ và biến tương lai đã biết (hỗ trợ ngữ cảnh8,192, dự báo1,024bước, tốc độ>300 chuỗi/giâytrên GPU A10G).
- Hệ sinh thái
TimesFM 1.0\(\to\)2.0/2.5/3.0(Google Research):TimesFM 1.0(Das et al., ICML 2024,200M): Transformer decoder-only tiền huấn luyện trên100 tỷđiểm thời gian với patching bất đối xứng (đầu vào = 32, đầu ra = 128).TimesFM 2.5(200M, giấy phép Apache 2.0, ngữ cảnh tới16,384điểm, đầu ra phân vị liên tục + bộ ghép ngoại sinh tuyến tínhXReg) vàTimesFM 3.0(330M,>1 nghìn tỷđiểm, hỗ trợ bản địa đa biến và ngoại sinh nhưng không thương mại hóa trọng số).
- Hệ sinh thái
Moirai\(\to\)Moirai-MoE\(\to\)Moirai 2.0(Salesforce AI) &TabPFN-TS:Moirai 1.0(Woo et al., ICML 2024 Oral) trên khoLOTSA(27 tỷquan sát) dùng Any-Variate Attention và phân phối hỗn hợp 4 thành phần (Student-t, Negative Binomial, Log-Normal, Normal);Moirai-MoE(Liu et al., ICML 2025) đưa chuyên gia thưa cấp token thay cho đầu chia tần số cố định;Moirai 2.0(Liu et al., Nov 2025,arXiv:2511.11698) chuyển sang decoder-only đa phân vị (nhanh hơn2x, nhỏ hơn30xbản1.0-Large).TabPFN-TS(Hoo et al., 2025,arXiv:2501.02945) ánh xạ chuỗi + đặc trưng lịch Fourier vàoTabPFN v2đạt điểm cao trên một số tập chuẩn zero-shot nhỏ.
- Thực chứng khách quan (
GIFT-EvalarXiv:2410.10393,fev-bencharXiv:2509.26468): Các bảng xếp hạng độc lập chứng minh một thực tế cực kỳ quan trọng: các TSFM đơn biến thế hệ 2024 thất bại trước mô hình bảng có biến ngoại sinh trên các bài toán bán lẻ & năng lượng thật. Mặc dùChronos-2thu hẹp đáng kể khoảng cách nhờ Group Attention, mộtGlobal LightGBM(Quantile/Tweedie) được tinh chỉnh chuẩnASOFvẫn thống trị trên tập bán lẻ dày đặc có \(> 20\) biến ngoại sinh bảng (giá, khuyến mãi đa tầng, cấu trúc cửa hàng, tồn kho) với chi phí suy luận CPU< 5 ms— còn TSFM tỏa sáng rực rỡ nhất ở bài toán SKU mới ra mắt (cold-start \(< 30\) ngày)!
- Hệ sinh thái
2.4 Hòa giải Phân cấp MinT-Shrink & Chiếu Quỹ đạo Mẫu#
Trong doanh nghiệp, dự báo không nằm rời rạc: tổng nhu cầu công ty \(\mathbf{y}_t \in \mathbb{R}^{n_{\text{all}}}\) được kết cấu từ vector chuỗi lá đáy \(\mathbf{b}_t \in \mathbb{R}^{n_b}\) (chẳng hạn \(4\) cửa hàng) thông qua ma trận tổng hợp (summing matrix) \(\mathbf{S} = \begin{bmatrix} \mathbf{A} \\ \mathbf{I}_{n_b} \end{bmatrix} \in \{0, 1\}^{n_{\text{all}} \times n_b}\) sao cho mọi dữ liệu thực tế luôn thỏa mãn không gian con nhất quán:
Tuy nhiên, khi chạy dự báo độc lập \(\hat{\mathbf{y}}_{T+h \mid T}\) ở từng nút (ví dụ dùng LightGBM cho từng cấp), điều kiện tổng gần như chắc chắn bị phá vỡ (\(\hat{\mathbf{y}}_{\text{top}} \neq \sum \hat{\mathbf{b}}_j\), lệch tới 13.977 trong Lab 06), tạo xung đột giữa bộ phận thu mua tổng công ty và giám đốc vùng (hiệu ứng roi da — Bullwhip Effect).
Xét mọi phép hòa giải tuyến tính dạng \(\tilde{\mathbf{y}} = \mathbf{S}\mathbf{G}\hat{\mathbf{y}}\) trong đó ma trận \(\mathbf{G} \in \mathbb{R}^{n_b \times n_{\text{all}}}\) ánh xạ toàn bộ dự báo gốc về cấp đáy rồi cộng ngược lên qua \(\mathbf{S}\) (P = S G là ma trận chiếu vào không gian ảnh của \(\mathbf{S}\)).
Điều kiện Không chệch (Unbiasedness): Nếu dự báo gốc không chệch (\(\mathbb{E}[\hat{\mathbf{y}}] = \mathbb{E}[\mathbf{y}] = \mathbf{S}\mathbb{E}[\mathbf{b}]\)), thì \(\tilde{\mathbf{y}}\) không chệch với mọi \(\mathbf{b}\) khi và chỉ khi:
Định lý Tối ưu MinT (Wickramasuriya, Athanasopoulos & Hyndman, JASA 2019): Giả sử \(\mathbf{W}_h = \operatorname{Var}(\mathbf{y}_{T+h} - \hat{\mathbf{y}}_{T+h \mid T}) \succ 0\) là ma trận hiệp phương sai sai số dự báo gốc cỡ \(n_{\text{all}} \times n_{\text{all}}\). Khi đó ma trận hiệp phương sai sai số sau hòa giải là \(\mathbf{V}_h = \operatorname{Var}(\mathbf{y}_{T+h} - \tilde{\mathbf{y}}) = \mathbf{S}\mathbf{G}\mathbf{W}_h\mathbf{G}^\top\mathbf{S}^\top\). Cực tiểu hóa tổng phương sai vết ma trận \(\operatorname{tr}(\mathbf{S}\mathbf{G}\mathbf{W}_h\mathbf{G}^\top\mathbf{S}^\top)\) dưới ràng buộc đẳng thức tuyến tính \(\mathbf{G}\mathbf{S} = \mathbf{I}_{n_b}\) bằng nhân tử Lagrange cho nghiệm đóng duy nhất (Minimum Trace — MinT):
Đáng chú ý, hầu hết các phương pháp kinh điển đều chỉ là trường hợp riêng dưới giả định đơn giản hóa \(\mathbf{W}_h = k_h \mathbf{W}_1\):
Bottom-Up: Đặt \(\mathbf{G} = [\mathbf{0}_{n_b \times n_a}\ \ \mathbf{I}_{n_b}]\). Không chệch (\(\mathbf{G}\mathbf{S} = \mathbf{I}_{n_b}\)), nhưng bỏ hoàn toàn tín hiệu sạch ở cấp tổng/vùng khiến nhiễu ở lá cộng dồn đẩyTop RMSEtừ1.284vọt lên5.266trongLab 06.Top-Down(theo tỷ trọng cố định \(\mathbf{p}\)): Đặt \(\mathbf{G} = [\mathbf{p}\ \ \mathbf{0}_{n_b \times (n_{\text{all}}-1)}]\). Khác biệt căn bản là hầu như luôn bị thiên lệch trừ khi phân bổ thật giữa các cửa hàng là hằng số bất biến, nên vi phạm \(\mathbf{S}\mathbf{G}\mathbf{S} = \mathbf{S}\) khi cơ cấu mùa vụ giữa các vùng thay đổi!MinT-OLS: Thay \(\mathbf{W}_1 = \mathbf{I}\), chỉ cần ma trận \(\mathbf{S}\), đã hạTop RMSEtrongLab 06xuống1.154.WLS-Struct: Thay \(\mathbf{W}_1 = \operatorname{diag}(\mathbf{S}\mathbf{1})\), chi phí cực nhẹ \(\mathcal{O}(n)\), thích hợp khi cây lên tới hàng triệu nút nhưng bỏ qua tương quan chéo.MinT-Shrink(Chuẩn SOTA): Dùng co cụm Schäfer–Strimmer / Ledoit–Wolf hướng về đường chéo: \(\hat{\mathbf{W}}_1^{\text{shrink}} = \lambda^*\hat{\mathbf{D}}_1 + (1 - \lambda^*)\hat{\mathbf{W}}_1 \succ 0\) với tham số co cụm tối ưu \(\lambda^* \in [0, 1]\) tính giải tích từ phương sai các phần tử ngoài đường chéo. Phép co cụm đảm bảo ma trận hiệp phương sai luôn xác định dương và khả nghịch ngay cả khi số chiều \(n_{\text{all}} > T\), đồng thời tận dụng tương quan âm giữa hai cửa hàng thay thế nhau để giảm đồng thời sai số của CẢ cấp tổng (1.054) lẫn cấp lá (2.644)! Hơn nữa, dùng biểu diễn không gian hạch (null-space) \(\mathbf{U}^\top \mathbf{y}_t = \mathbf{0}\) rút độ phức tạp nghịch đảo từ \(\mathcal{O}(n_{\text{all}}^3)\) xuống \(\mathcal{O}(n_a^3)\) (chỉ tính trên \(n_a\) nút tổng hợp).
Bẫy Cộng Phân vị Biên & Hòa giải Quỹ đạo Mẫu (Sample-Path Reconciliation, Panagiotelis et al., EJOR 2023): Một sai lầm phổ biến là lấy trực tiếp vector phân vị P90 biên của các nút rồi nhân với \(\mathbf{S}\mathbf{G}\)! Vì phân vị không có tính cộng tính tuyến tính (\(Q_{0.90}(B_1 + B_2) < Q_{0.90}(B_1) + Q_{0.90}(B_2)\) bất cứ khi nào hai cửa hàng không tương quan thuận hoàn toàn +1), cộng phân vị biên sẽ thổi phồng tồn kho an toàn ở tổng kho (Top P90 = 104.61 trong Lab 06). Cách làm chuẩn là rút \(M\) quỹ đạo mẫu đồng thời \(\hat{\mathbf{y}}^{(j)}\) (\(j=1,\dots,M\)) từ hàm phân phối dự báo (dùng Gaussian/copula hoặc hoán vị thứ hạng Empirical Copula / Schaake Shuffle theo phần dư lịch sử), áp dụng phép chiếu \(\tilde{\mathbf{y}}^{(j)} = \mathbf{S}\mathbf{G}^*\hat{\mathbf{y}}^{(j)}\) lên từng quỹ đạo mẫu rồi mới lấy phân vị 0.90 trên tập mẫu đã hòa giải (Top P90 = 85.00 chính xác trong Lab 06)!
2.5 Dự báo Conformal Chuỗi Thời gian Dưới Sốc Phân phối (EnbPI, SPCI, ACI & CQR)#
Như đã trình bày ở Chương 03, Static Split Conformal Prediction (SCP) đảm bảo \(\mathbb{P}(Y_{T+1} \in \hat{C}(\mathbf{x}_{T+1})) \ge 1 - \alpha_{\text{conf}}\) với điều kiện các cặp \((\mathbf{x}_t, y_t)\) có thể hoán vị (exchangeable). Nhưng trong chuỗi thời gian bán lẻ, giả định hoán vị bị phá vỡ bởi cả hai cơ chế: tự tương quan nối tiếp và dịch chuyển phân phối (distribution shift) khi chiến dịch Flash Sale bùng nổ làm phương sai nhiễu nhân 2.8x. Hệ quả thực chứng trong Lab 06: Static SCP giữ nguyên bán kính từ giai đoạn bình lặng, khiến tỷ lệ bao phủ sập từ 90.0% xuống còn 53.8% toàn cục và chỉ 25.0% trong vùng sốc!
Ba giải pháp hiện đại giúp giữ vững bao phủ không cần giả định phân phối trên chuỗi thời gian:
EnbPI(Xu & Xie, ICML 2021) &SPCI(Xu & Xie, ICML 2023):EnbPIhuấn luyện một tập hợp các mô hình trên nhiều mẫu bootstrap theo khối, tính phần dư Leave-One-Out trên tập huấn luyện và cập nhật hàng đợi trượt FIFO độ dài \(W\) bằng phần dư thực tế mới quan sát — không cần huấn luyện lại mô hình khi dịch chuyển phân phối nhẹ (86.9%trênLab 06).SPCItiến thêm một bước bằng cách dùng Quantile Random Forest dự báo phân vị phần dư có điều kiện theo các phần dư trễ trước đó để nắm bắt dị phương sai (volatility clustering).-
ACI(Adaptive Conformal Inference,Gibbs & Candès, NeurIPS 2021): Ý tưởng cốt lõi là biến bài toán kiểm soát bao phủ thành một vòng hồi tiếp điều khiển mức \(\alpha_t\) trực tuyến: tại thời điểm \(t\), dựng khoảng tin cậy ở mức danh nghĩa \(1 - \alpha_t\) (chẳng hạn dùng điểm không phù hợp kiểuCQR,Romano et al., NeurIPS 2019: \(E_t = \max\{\hat{q}_{\alpha_{\text{lo}}}(\mathbf{x}_t) - y_t,\ y_t - \hat{q}_{\alpha_{\text{hi}}}(\mathbf{x}_t)\}\) giúp chiều rộng khoảng tự giãn nở theo biến động khuyến mãi). Sau khi nhận kết quả chín sau \(L\) ngày và kiểm tra chỉ báo trượt \(\operatorname{err}_t := \mathbb{I}\{y_t \notin \hat{C}_t(\mathbf{x}_t)\}\),ACIcập nhật:\[\alpha_{t+1} = \alpha_t + \gamma_{\text{aci}}\!\left(\alpha_{\text{conf}} - \operatorname{err}_t\right),\]trong đó nếu \(\alpha_t \le 0\) ta gán \(\hat{C}_t = \mathbb{R}\) (chắc chắn bao phủ \(\implies \operatorname{err}_t = 0\)) và nếu \(\alpha_t \ge 1\) ta gán \(\hat{C}_t = \emptyset\) (\(\implies \operatorname{err}_t = 1\)).
Định lý Giới hạn Chặn & Tiệm cận Không phụ thuộc Phân phối (
Gibbs & Candès, Bổ đề 4.1): Giả sử \(\alpha_1 \in [0, 1]\) và \(\gamma_{\text{aci}} > 0\). Bằng quy nạp toán học, giả sử \(\alpha_t \in [-\gamma_{\text{aci}},\ 1 + \gamma_{\text{aci}}]\):- Nếu \(\alpha_t < 0\), quy ước \(\hat{C}_t = \mathbb{R} \implies \operatorname{err}_t = 0\), nên \(\alpha_{t+1} = \alpha_t + \gamma_{\text{aci}}\alpha_{\text{conf}} > \alpha_t \ge -\gamma_{\text{aci}}\) và \(\alpha_{t+1} < \gamma_{\text{aci}}\alpha_{\text{conf}} < 1 + \gamma_{\text{aci}}\).
- Nếu \(\alpha_t > 1\), quy ước \(\hat{C}_t = \emptyset \implies \operatorname{err}_t = 1\), nên \(\alpha_{t+1} = \alpha_t + \gamma_{\text{aci}}(\alpha_{\text{conf}} - 1) < \alpha_t \le 1 + \gamma_{\text{aci}}\) và \(\alpha_{t+1} > 1 - \gamma_{\text{aci}}(1 - \alpha_{\text{conf}}) > -\gamma_{\text{aci}}\).
- Nếu \(\alpha_t \in [0, 1]\), hiển nhiên \(\alpha_{t+1} \in [-\gamma_{\text{aci}}, 1 + \gamma_{\text{aci}}]\).
Suy ra \(\alpha_t \in [-\gamma_{\text{aci}},\ 1 + \gamma_{\text{aci}}]\) đúng với mọi \(t \ge 1\) không phụ thuộc bất kỳ phân phối dữ liệu nào! Tổng lồng nhau (telescoping sum) hai vế từ \(t = 1\) đến \(T\):
\[\frac{\alpha_{T+1} - \alpha_1}{\gamma_{\text{aci}} T} = \alpha_{\text{conf}} - \frac{1}{T}\sum_{t=1}^T \operatorname{err}_t \implies \left\lvert \frac{1}{T}\sum_{t=1}^T \operatorname{err}_t - \alpha_{\text{conf}} \right\rvert \le \frac{\max\{\alpha_1, 1-\alpha_1\} + \gamma_{\text{aci}}}{\gamma_{\text{aci}} T} = \mathcal{O}\!\left(\frac{1}{\gamma_{\text{aci}} T}\right).\]Đây chính là cơ sở toán học giải thích vì sao trong
Lab 06(Test 11), mặc dù biến động tăng2.8xbất ngờ,Online ACIgiữ bao phủ thực nghiệm ở đúng90.0%trên cả chuỗi lẫn ngay bên trong cửa sổ sốc (0.00%sai lệch< 3%). Để tự động hóa việc chọn \(\gamma_{\text{aci}}\) trong thực tế,AgACI(Zaffran et al., ICML 2022) vàDtACI(Gibbs & Candès, JMLR 2024) duy trì song song một rổ chuyên gia chạy nhiều giá trị \(\{\gamma_k\}\) rồi tổng hợp trọng số theo tổn thất Pinball trực tuyến.
So sánh trực tiếp hành vi của MinT-Shrink (cũng như ảnh hưởng hệ số thay thế \(\rho_{12} < 0\)) và quỹ đạo thích nghi \(\alpha_t\) của Online ACI so với Static Split Conformal trong trình mô phỏng tương tác thứ ba:
2.6 Kiến trúc Hệ thống Production Quy mô 50M Chuỗi & Ngưỡng Tài nguyên#
Khi mở rộng hệ thống từ bài thí nghiệm vài trăm chuỗi sang doanh nghiệp bán lẻ 100,000 SKU x 500 cửa hàng = 50 triệu chuỗi ngày, nút thắt cổ chai không nằm ở công thức Pinball mà ở trộn bảng ASOF, bùng nổ ma trận hiệp phương sai \(50\text{M} \times 50\text{M}\) (nếu áp MinT toàn cục một khối khổng lồ), và ngân sách SLA ban đêm (batch window < 4 giờ) cùng p99 < 5 ms cho API đặt hàng lại trực tuyến. Kiến trúc chuẩn công nghiệp chia tách ba tầng định tuyến và phân rã MinT theo từng sku_id:
| Thành phần Hệ thống | Động cơ / Thuật toán | Quy mô Bộ nhớ (50M chuỗi = 100k SKU x 500 Cửa hàng) |
Thời gian / SLA Mục tiêu |
|---|---|---|---|
Kho Đặc trưng ASOF |
Polars lazy / Spark Arrow băm theo sku_id |
~600 GB Parquet (18.25 tỷ dòng/năm), 32–64 nút worker |
25–45 phút |
Đuôi Thưa (18M chuỗi) |
StatsForecast (Numba JIT Croston-SBA/TSB) |
1M chuỗi trong 5–25 phút trên 100 vCPU |
< 2 giờ |
Chủ lực (30M chuỗi) |
Global LightGBM (uint8 max_bin=255, 50 pool ngành hàng) |
64 vCPU: huấn luyện 30–60 phút, chấm 8–15 phút; < 3 ms online |
< 75 phút |
Cold-Start (2M chuỗi) |
Chronos-2 (120M) / TimesFM 2.5 GPU batch |
> 300 chuỗi/giây trên 1× A10G (< 15 phút trên 8× A10G) |
< 30 phút |
Hòa giải Phân cấp MinT |
Block MinT-Shrink độc lập từng SKU (500 cửa hàng) + WLS-Struct |
Chỉ 2.4 MB / SKU (\(550 \times 550\)); tránh thảm họa \(40\text{ GiB+}\) |
< 5 phút |
Online ACI + Đẩy PO |
Hàng đợi trượt W = 60 + cập nhật \(\alpha_t\) chi phí \(\mathcal{O}(1)\) |
< 100 MB trạng thái cả cụm; < 1 ms online |
< 1 phút |
Trụ cột 3 — Chuyên đề #4 (Phần 4): Cẩm nang Ra Quyết định Production, Chống Mẫu & Mã Python Thực thi Đầu-Cuối#
3.1 Chuyên đề #4 — Phần 4: Cẩm nang Ra Quyết định Lựa chọn Mô hình Dự báo (Production Decision Playbook)#
Bảng dưới đây tổng hợp tiêu chuẩn ra quyết định kiến trúc cho đội ngũ Khoa học Dữ liệu và Kỹ sư ML khi thiết kế hệ thống dự báo gắn chi phí quyết định:
| Tiêu chí Vận hành | StatsForecast (ETS / SARIMAX / Croston-SBA / TSB) |
Global LightGBM (Quantile q* / Tweedie + Sắp xếp) |
Deep Sequence (TFT / PatchTST / TiDE) |
Foundation TS (Chronos-2 / TimesFM 2.5 / Moirai 2.0) |
|---|---|---|---|---|
| Vùng ứng dụng vàng (Sweet Spot) | Chuỗi dài đồng đều ít ngoại sinh (ETS) hoặc đuôi phụ tùng cực thưa ADI >= 1.32 (SBA/TSB) |
Mặc định công nghiệp cho bán lẻ quy mô lớn: \(>1,000\) SKU dày đặc, \(>20\) biến ngoại sinh bảng, mục tiêu Newsvendor \(q^*\) | Bài toán chuỗi cực dài cần mô hình hóa tương tác phi tuyến sâu giữa lịch sử dài (L > 500) và lịch công bố phức tạp |
SKU mới ra mắt (cold-start \(< 30\) ngày), bài toán đa tần suất zero-shot hoặc làm điểm chuẩn baseline nhanh trước khi xây feature store |
Hỗ trợ Biến ngoại sinh (Known-Future) |
Kém với nhiều biến phi tuyến (SARIMAX chỉ tuyến tính, ETS/SBA không nhận) |
Xuất sắc: Gắn tự nhiên khuyến mãi, giá chéo, lịch nghỉ, tồn kho ngay tại bảng \((i, t, h)\) | Tốt (TFT, TiDE tách riêng 3 nhánh tĩnh/quá khứ/tương lai; DLinear/PatchTST gốc kém hơn) |
Đã cải thiện mạnh ở Chronos-2 (Group Attention) & TimesFM 2.5 XReg, nhưng vẫn kém hơn LightGBM trên >20 biến tương tác |
| Hỗ trợ Chi phí Quyết định \(q^*\) & Phân phối | Tham số giải tích Gauss/âm nhị thức (nhưng sụp nếu lệch chuẩn mạnh) | Tối ưu trực tiếp Pinball(q*) + sắp xếp đơn điệu Chernozhukov không cần giả định phân phối |
Hỗ trợ trực tiếp Multi-Quantile Pinball loss trong 1 lần lan truyền |
Xuất sẵn 9–100 phân vị liên tục (Chronos-Bolt/2, Moirai 2.0) cho phép nội suy thẳng tới \(q^*\) |
Năng lực Xử lý Chuỗi Đếm / Số 0 nhiều |
Tốt với Croston-SBA / TSB |
Rất mạnh với Tweedie (\(1 < p_{\text{tw}} < 2\)) hoặc Quantile trực tiếp trên lưới \(q^*\) |
Trung bình (dễ trôi về giá trị dương nhỏ với sai số chuẩn Gauss trừ phi dùng đầu ra phân phối rời rạc) | Khá tốt ở quy mô nhỏ, dễ nhiễu trên dữ liệu có mật độ 0 > 80% |
| Hạ tầng Suy luận & Chi phí SLA | Rẻ nhất (CPU thuần, Numba JIT 1M chuỗi < 25 phút) |
Rẻ & Siêu nhanh (< 3 ms p99 CPU), dung lượng uint8 nhẹ gấp 8x float64 |
Đắt (cần GPU, tốn công tinh chỉnh siêu tham số và lịch trình học) | Cần GPU batch (A10G/L4 cho >300 chuỗi/s); chi phí đắt hơn LightGBM 10–50x nếu chạy trực tiếp trên 30M chuỗi |
Khuyến nghị Quyết định (Go / No-Go) |
Chọn cho Tầng C (18M đuôi thưa) và baseline nhanh |
Chọn làm Tầng B Xương sống Production kết hợp MinT-Shrink + ACI |
Chỉ chọn nếu chứng minh vượt Global LightGBM \(\ge 3\%\) trên Backtest Thanh lọc Lead-Time |
Chọn cho Tầng A (Cold-Start); cấm thay mù toàn bộ LightGBM nếu chưa qua kiểm chứng fev-bench-style |
3.2 Ma trận 8 Chống Mẫu Production & Cổng Kiểm soát Tự động CI/CD#
| # | Chống mẫu (Anti-Pattern) | Triệu chứng Thất bại Âm thầm | Cổng Kiểm soát Tự động (CI/CD & Canary Gate) |
|---|---|---|---|
| 1 | Đánh giá hay tối ưu bằng MAPE hoặc MAE trên SKU thưa |
MAPE chia 0 hoặc kéo tụt dự báo -81.8%; MAE trả về 0.0 khi tỷ lệ 0 > 50% |
Cấm từ khóa mape trong hàm mục tiêu/cổng duyệt; bắt buộc dùng WRMSSE, WQL, CRPS, Newsvendor Cost |
| 2 | Lấy điểm trung bình MSE đưa thẳng vào đơn đặt hàng |
SKU_HI thiếu hàng lúc cao điểm, SKU_PER ế thối (+39%–127% chi phí đội thêm) |
Cổng bắt buộc: chính sách phân vị \(q^*\) phải giảm chi phí Newsvendor >= 12% so với MSE trên tập thanh lọc |
| 3 | Đánh giá ở h = 1 trong khi lead time giao hàng \(L \ge 3\) ngày |
Đánh giá quá thấp phương sai tổng hợp tích lũy & bỏ trống khoảng thanh lọc \(L\) ngày | Khẳng định cấu hình kiểm thử có chân trời đánh giá khớp L và purge_gap >= L |
| 4 | Dùng K-Fold ngẫu nhiên hoặc gia nhập giảm giá chưa công bố |
Điểm ngoại tuyến ảo tụt thấp (22.21) rồi sụp (44.72) ngay ngày lên sản xuất |
Bộ kiểm toán ASOF khẳng định 0 vi phạm (\(\tau_{\text{avail}} \le t_0\) & \(\tau_{\text{announced}} \le t_0\)) |
| 5 | Huấn luyện biến trễ bằng doanh số POS thô không lọc hết hàng | Vòng xoáy sụt cung đẩy tỷ lệ đứt hàng vọt tới 79% với độ lệch âm gần -50% |
Cảnh báo khi on_hand == 0 vượt 5%; bắt buộc gắn cờ is_stockout (OSA) & phục hồi |
| 6 | Bỏ qua hòa giải hoặc dùng Bottom-Up ngây thơ |
sum(store) != region, hiệu ứng roi da Bullwhip thổi phồng Top RMSE (+310%) |
Khẳng định max_abs(S @ b_tilde - y_tilde) < 1e-9 via MinT-Shrink / WLS-Struct |
| 7 | Dùng Static Split Conformal xuyên qua mùa khuyến mãi sốc |
Tỷ lệ bao phủ sụt từ 90% còn 25%–54% ngay khi phương sai nhảy vọt |
Đóng băng phát hành nếu sai lệch bao phủ sau sốc >= 3%; bắt buộc CQR + Online ACI |
| 8 | Dựng ma trận MinT toàn cục \(50\text{M} \times 50\text{M}\) hoặc gọi TSFM bừa bãi |
Tràn RAM (OOM \(>40\text{ GiB}\)) hoặc trễ SLA giao đơn ban đêm |
Bắt buộc phân rã MinT theo từng block SKU / WLS-Struct và định tuyến đúng 3 Tầng |
3.3 Mẹo Công nghiệp SOTA 2025–2026: Động lực Khuyến mãi Bán lẻ (Post-Promo Pantry Loading, Cannibalization), TiRex Zero-Shot & Chính sách Giá Động (Principal Tip #13)#
Khi chuyển chuỗi dự báo nhu cầu bán lẻ từ mô hình thí nghiệm sang hệ thống bổ sung hàng tự động trong các đợt khuyến mãi lớn, 3 động lực thực chiến sau quyết định trực tiếp biên lợi nhuận và tỷ lệ ứ đọng hàng hóa:
- Bẫy
Post-Promo Pantry Loading& Tự Ăn mòn Chéo SKU (Cannibalization):Post-Promo Pantry Loading(Tích trữ Hậu Khuyến mãi / Forward Buying): Đối với hàng tiêu dùng thiết yếu hoặc sản phẩm lưu trữ được (sữa, cà phê, chất tẩy rửa, đồ hộp), người tiêu dùng mua gom2–4×nhu cầu bình thường trong tuần giảm giá sâu (flash sale/bundle) rồi ngưng mua suốt1–3tuần kế tiếp để tiêu thụ lượng tích trữ (post-promo dip). Mô hình chỉ đưa vào biến cờis_promo_ttại ngày \(t\) sẽ dự báo đúng đỉnh khuyến mãi nhưng ước lượng lố nghiêm trọng ngay sau ngày kết thúc khuyến mãi, đẩy hàng tồn kho ứ đọng lên cao. Khắc phục bắt buộc: bổ sung các đặc trưng trễ phản ánh cường độ tích trữ tiền kỳ (days_since_last_promo,cumulative_promo_discount_14d,post_promo_cooldown_decay) và đo tổng chi phíNewsvendortrên trọn chu kỳ trước–trong–hậu khuyến mãi.Cannibalization(Tự Ăn mòn Nhu cầu Chéo Danh mục): Khi giảm giá25%–40%choSKU A(cùng danh mục / cùng thương hiệu / dung tích thay thế), một phần lớn doanh số tăng thêm củaSKU Akhông phải nhu cầu mới mà bị hút trực tiếp từSKU BvàSKU Cbán nguyên giá trên cùng kệ hàng! Nếu dự báo từng SKU độc lập không nhìn thấy bảng trạng thái chéo (min_competitor_price_ratio_in_cat,share_of_category_on_promo,cross_sku_price_elasticity), mô hình sẽ đặt thừa hàng loạt cho các SKU nguyên giá trong tuầnSKU Akhuyến mãi, đồng thời bỏ qua cấu trúc hiệp phương sai âm giữa các SKU thay thế khi chạy hòa giảiMinT-Shrink.
- Đột phá
TiRex(xLSTMZero-ShotTSFM) vs. TransformerTSFMTrên Chuỗi Lưu lượng Liên tục: Bên cạnh các mô hình nền tảng dựa trên Transformer (Chronos-2,TimesFM 2.5,Moirai 2.0),TiRex(NX-AI, xây dựng trên kiến trúcxLSTMthay cho Self-Attention bậc hai) nổi bật trên bảng chuẩn zero-shotGIFT-Evalchỉ với ~35M–38M tham số (cùng biến thểTiRex-2hỗ trợ đa biến và biến ngoại sinh theo luồng streaming). Nhờ cấu trúc bộ nhớ hồi quy liên tục (state tracking) với chi phí cập nhật tuyến tính hằng số \(\mathcal{O}(1)\) mỗi patch khi luồng dữ liệu mới chảy vào,TiRexđặc biệt phù hợp cho bài toán SKU mới ra mắt (cold-start), bổ sung hàng thời gian thực trên hạ tầng biên/GPU nhỏ hoặc làm mô hình chuẩn đối chứng nhanh; tuy nhiên trên danh mục dày đặc có \(>20\) biếnCannibalization& bảng tồn kho đa tầng,Global LightGBM(Quantile/Tweedie) +Online ACIvẫn là xương sống tối ưu chi phíSLA < 3 ms. - Nối Dự báo Sang Chính sách Giá Động / Bandit & Kiểm định
Safe OPE: Khi tự động hóa quyết định mức giảm giá hoặc tồn kho đệm trực tuyến quaContextual Bandits, không bao giờ đánh giá chính sách mới \(\pi\) bằngIPSthô thiếu chuẩn hóa: phải ghi nhật ký xác suất chọn hành động thực tếlog_propensitylúc phục vụ, dùngSNIPS/DR-OPEkẹp trọng số (hoặcSWITCH-DR) để chặn bùng nổ phương sai \(w_i = \pi(a_i \mid x_i)/\pi_0(a_i \mid x_i)\), chỉ cập nhật phần thưởng sau cửa sổ trưởng thành trễ giao nhận/hoàn hàng (\(L + \Delta_{\text{return}}\)), và áp dụng cổngShadow -> Canary (SRM Gate) -> Auto-Rollback(kế thừa kỷ luậtDelayed Feedback&Online ACItừ §2.5 vàch-07).
3.4 Mã Python Thực thi Đầu-Cuối (Không Rò rỉ, Đã Chạy Kiểm chứng)#
Đoạn mã hoàn chỉnh dưới đây tự chạy độc lập trên môi trường .venv (numpy, scipy, lightgbm), tái hiện trọn vẹn cùng lúc: (1) mô phỏng danh mục hai nhóm đối nghịch SKU_HI (\(q^*=0.90\)) và SKU_PER (\(q^*=0.20\)) với thanh lọc nghiêm ngặt \(L = 4\) ngày (train_end - lead_time), (2) huấn luyện Global LightGBM bằng Pinball Loss so với MSE + sắp xếp đơn điệu Chernozhukov, (3) xác minh đẳng thức điểm Newsvendor–Pinball tới < 1e-11, (4) kiểm chứng đồng nhất thức \(\mathbf{S}\mathbf{G}^*\mathbf{S}=\mathbf{S}\) của MinT-Shrink, (5) kiểm chứng Online ACI dưới sốc phương sai, và (6) kiểm chứng bẫy MAPE = 1.0 trên {1, 10}:
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from lightgbm import LGBMRegressor
from scipy.optimize import minimize_scalar
@dataclass(frozen=True)
class SKUProfile:
name: str
c_u: float
c_o: float
base_demand: float
promo_lift: float
@property
def critical_fractile(self) -> float:
return self.c_u / (self.c_u + self.c_o)
def pinball_loss(y_true: np.ndarray, y_pred: np.ndarray, tau: float) -> float:
err = y_true - y_pred
return float(np.mean(np.where(err >= 0.0, tau * err, (tau - 1.0) * err)))
def newsvendor_cost(y_true: np.ndarray, order_qty: np.ndarray, c_u: float, c_o: float) -> float:
shortage = np.maximum(y_true - order_qty, 0.0)
overage = np.maximum(order_qty - y_true, 0.0)
return float(np.mean(c_u * shortage + c_o * overage))
def simulate_panel_and_evaluate(seed: int = 42) -> dict[str, float]:
rng = np.random.default_rng(seed)
skus = [
SKUProfile("SKU_HI", c_u=18.0, c_o=2.0, base_demand=38.0, promo_lift=18.0),
SKUProfile("SKU_PER", c_u=3.0, c_o=12.0, base_demand=42.0, promo_lift=14.0),
]
n_days, train_end, lead_time = 460, 320, 4
taus = (0.10, 0.20, 0.50, 0.80, 0.90)
X_rows: list[np.ndarray] = []
y_rows: list[float] = []
sku_idx_rows: list[int] = []
day_rows: list[int] = []
for s_idx, sku in enumerate(skus):
t = np.arange(n_days, dtype=float)
promo = (rng.random(n_days) < 0.16).astype(float)
dow = t % 7.0
weekly = 1.0 + 0.18 * np.sin(2.0 * np.pi * dow / 7.0)
mean_d = sku.base_demand * weekly + sku.promo_lift * promo
shape = np.where(promo > 0.5, 4.5, 8.0)
scale = mean_d / shape
demand = rng.gamma(shape=shape, scale=scale)
for origin in range(14, n_days - lead_time):
# Đặc trưng ASOF nhân quả chặt tại gốc đặt hàng <= origin
lag7_obs = float(np.mean(demand[origin - 7 : origin + 1]))
future_promo_sum = float(np.sum(promo[origin + 1 : origin + 1 + lead_time]))
y_lead = float(np.sum(demand[origin + 1 : origin + 1 + lead_time]))
X_rows.append(
np.array(
[float(s_idx), dow[origin], lag7_obs, future_promo_sum],
dtype=float,
)
)
y_rows.append(y_lead)
sku_idx_rows.append(s_idx)
day_rows.append(origin)
X = np.vstack(X_rows)
y = np.asarray(y_rows, dtype=float)
sku_ids = np.asarray(sku_idx_rows, dtype=int)
days = np.asarray(day_rows, dtype=int)
# Chia cuốn chiếu thanh lọc Lead-Time: nhãn huấn luyện kết thúc <= gốc đánh giá
train_mask = days <= (train_end - lead_time)
test_mask = days >= train_end
assert int(np.sum(train_mask & (days + lead_time > train_end))) == 0
X_tr, y_tr = X[train_mask], y[train_mask]
X_te, y_te = X[test_mask], y[test_mask]
sku_te = sku_ids[test_mask]
mse_model = LGBMRegressor(
objective="regression",
n_estimators=120,
learning_rate=0.06,
num_leaves=15,
min_child_samples=15,
random_state=seed,
verbose=-1,
).fit(X_tr, y_tr)
pred_mse = np.maximum(0.0, mse_model.predict(X_te))
q_preds = np.column_stack(
[
LGBMRegressor(
objective="quantile",
alpha=tau,
n_estimators=120,
learning_rate=0.06,
num_leaves=15,
min_child_samples=15,
random_state=seed,
verbose=-1,
)
.fit(X_tr, y_tr)
.predict(X_te)
for tau in taus
]
)
raw_crossings = int(np.sum(np.diff(q_preds, axis=1) < -1e-9))
# Sắp xếp đơn điệu Chernozhukov triệt tiêu toàn bộ giao cắt phân vị
q_sorted = np.sort(np.maximum(0.0, q_preds), axis=1)
assert int(np.sum(np.diff(q_sorted, axis=1) < 0.0)) == 0
mse_costs: list[float] = []
nv_costs: list[float] = []
for s_idx, sku in enumerate(skus):
mask = sku_te == s_idx
q_idx = taus.index(round(sku.critical_fractile, 2))
order_nv = q_sorted[mask, q_idx]
order_mse = pred_mse[mask]
c_mse = newsvendor_cost(y_te[mask], order_mse, sku.c_u, sku.c_o)
c_nv = newsvendor_cost(y_te[mask], order_nv, sku.c_u, sku.c_o)
# Kiểm chứng đẳng thức Pinball <-> Newsvendor tới sai số máy
p_nv = (sku.c_u + sku.c_o) * pinball_loss(
y_te[mask], order_nv, sku.critical_fractile
)
assert abs(c_nv - p_nv) < 1e-11
mse_costs.append(c_mse)
nv_costs.append(c_nv)
mean_mse_cost = float(np.mean(mse_costs))
mean_nv_cost = float(np.mean(nv_costs))
reduction_pct = 100.0 * (mean_mse_cost - mean_nv_cost) / mean_mse_cost
# Kiểm chứng đồng nhất thức chiếu MinT-Shrink: S @ G @ S == S
S = np.array(
[
[1, 1, 1, 1],
[1, 1, 0, 0],
[0, 0, 1, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
dtype=float,
)
res_cov = np.cov(rng.normal(0.0, 2.0, size=(7, 120)))
diag_cov = np.diag(np.diag(res_cov))
w_shrink = 0.42 * diag_cov + 0.58 * res_cov
w_inv = np.linalg.inv(w_shrink)
G_star = np.linalg.solve(S.T @ w_inv @ S, S.T @ w_inv)
sgs_err = float(np.max(np.abs(S @ G_star @ S - S)))
assert sgs_err < 1e-12
# Kiểm chứng Online ACI giữ bao phủ 90.0% qua vùng sốc biến động
alpha_target, gamma, alpha_t = 0.10, 0.06, 0.10
errs_shock = rng.normal(
0.0, np.concatenate([np.full(80, 3.0), np.full(120, 8.5)])
)
hist_abs = np.abs(rng.normal(0.0, 3.0, size=50))
covered = []
for e_t in errs_shock:
q_lvl = float(np.clip(1.0 - alpha_t, 0.0, 1.0))
rad = (
np.inf
if alpha_t <= 0.0
else (0.0 if alpha_t >= 1.0 else float(np.quantile(hist_abs, q_lvl)))
)
err_ind = 1.0 if abs(e_t) > rad else 0.0
covered.append(1.0 - err_ind)
alpha_t = alpha_t + gamma * (alpha_target - err_ind)
hist_abs = np.append(hist_abs[1:], abs(e_t))
# Kiểm chứng thiên lệch điều hòa MAPE trên {1, 10}
opt_mape = minimize_scalar(
lambda a: 0.5 * (abs(1.0 - a) / 1.0 + abs(10.0 - a) / 10.0),
bounds=(0.5, 11.0),
method="bounded",
).x
return {
"mean_mse_cost": mean_mse_cost,
"mean_nv_cost": mean_nv_cost,
"reduction_pct": reduction_pct,
"raw_crossings": float(raw_crossings),
"sgs_err": sgs_err,
"aci_cov": float(np.mean(covered)),
"mape_opt": float(opt_mape),
}
if __name__ == "__main__":
stats = simulate_panel_and_evaluate(seed=42)
print(
f"NV_Cost: {stats['mean_mse_cost']:.2f} -> {stats['mean_nv_cost']:.2f} "
f"(-{stats['reduction_pct']:.1f}%) | Crossings={int(stats['raw_crossings'])}->0 | "
f"MinT_SGS_err={stats['sgs_err']:.2e} | ACI_cov={stats['aci_cov']*100:.1f}% | "
f"MAPE_opt={stats['mape_opt']:.3f}"
)
Khi thực thi trực tiếp đoạn mã trên bằng Python 3.10+ (seed=42), đầu ra xác nhận toàn bộ lý thuyết bằng số đo lặp lại chính xác:
NV_Cost: 227.14 -> 144.20 (-36.5%) | Crossings=47->0 | MinT_SGS_err=2.22e-16 | ACI_cov=90.0% | MAPE_opt=1.000
Trụ cột 4 — Thực hành Toàn diện Lab 06 & Chuyên đề #4 Phần 3 (Thực nghiệm Cắt bỏ Có kiểm soát)#
Phòng thí nghiệm Lab 06 (demand_forecast_lab) tại hướng dẫn Lab 06 triển khai đầy đủ kiến trúc hai tầng chuẩn production:
- Tầng 1 Thuần NumPy (
src/demand_forecast_lab/forecasting_core.py): Cài đặt cấu hìnhPydantic v2(extra="forbid", kiểm tra biên nghiêm ngặtStationarityConfig,HoltWintersConfig,CrostonSBAConfig,NewsvendorConfig,InventorySimConfig), kiểm địnhcheck_stationarity_adf_kpss, phân rãseasonal_decompose_stl_ref, hiệu chỉnh Jensenboxcox_bias_corrected_mean,HoltWintersETS,CrostonSBAForecaster&TSB, độ lệch & HessianTweedie(tweedie_unit_deviance,tweedie_grad_hess), hệ thống độ đopinball_loss,compute_mase,compute_rmsse,compute_wql,compute_crps_from_quantiles, sắp xếp đơn điệurearrange_quantiles_monotonic, công thức Newsvendor (newsvendor_critical_fractile,newsvendor_cost), bộ mô phỏng tồn kho đa kỳ có đơn hàng đang đi trên đườngsimulate_multi_period_inventory, và kiểm toánaudit_mape_and_mae_traps. - Tầng 2 SOTA & Kiểm thử Hồi cứu (
src/demand_forecast_lab/decision_backtest.py): Sinh dữ liệu bảng bán lẻ thực tế có khuyến mãi định kỳ, giảm giá flash bất ngờ, kiểm duyệt hết hàng và cấu trúc phân cấp có tương quan thay thế chéo (generate_retail_demand_panel), xây dựng đặc trưng nhân quảbuild_causal_features& cổng kiểm toánaudit_asof_and_leakage, bộ kiểm thử cuốn chiếu thanh lọc lead timeRollingOriginPurgedBacktester, mô hình toàn cụcGlobalLightGBMQuantileForecaster(quantile&tweedie), đối chứngrun_sklearn_quantile_parity_check, thực nghiệmrun_stockout_censoring_experiment, hòa giảiMinTReconciler+reconcile_sample_paths, vàAdaptiveConformalForecaster(ACI,EnbPI,Static Split) dưới sốc phân phối.
4.1 Lệnh Thực thi Chuẩn trong Lab 06#
cd 02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/lab-06-retail-demand-planning-cost-backtest
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --seed 42 --output artifacts/ch13_lab06_results.json
D:\FSDS-SOTA-Curriculum\.venv\Scripts\ruff.exe check src scripts tests
D:\FSDS-SOTA-Curriculum\.venv\Scripts\mypy.exe src
D:\FSDS-SOTA-Curriculum\.venv\Scripts\pytest.exe -p no:cacheprovider -v
4.2 Chuyên đề #4 — Phần 3: Kết quả Thực nghiệm Cắt bỏ Có kiểm soát (artifacts/ch13_lab06_results.json, --seed 42)#
Bảng A — 6 KPI Cổng Nghiệm thu Toàn hệ thống (workbench_panels)#
| Chỉ số Cổng Nghiệm thu | Giá trị Đối chuẩn (Baseline) |
Giá trị Đề xuất (Lab 06 SOTA) |
Ngưỡng Nghiệm thu | Trạng thái |
|---|---|---|---|---|
| Chi phí Newsvendor Danh mục | 212.41 (MSE mean) |
128.52 (LightGBM Pinball q*, -39.5%) |
Giảm >= 12.0% |
Đạt |
Kiểm toán Nhân quả ASOF (\(L=4\)) |
1,932 vi phạm (K-Fold rò rỉ) |
0 vi phạm (Purged Rolling-Origin) |
== 0 vi phạm |
Đạt |
Sai lệch RMSE Rò rỉ vs Thực tế |
22.21 (ảo) \(\to\) 44.72 (live) |
35.02 (phản ánh trung thực ngoại tuyến) |
Không rò rỉ | Đạt |
| Tỷ lệ Đứt hàng Censoring POS | 79.3% (chi phí 24,363.2) |
0.0% (phục hồi OSA, chi phí 9,136.1, -62.5%) |
Giảm mạnh đứt hàng | Đạt |
Hòa giải Phân cấp MinT-Shrink |
13.977 lệch tổng (5.266 Top BU) |
2.84e-14 lệch tổng (Top RMSE = 1.054) |
< 1e-9 |
Đạt |
Bao phủ Online ACI Dưới Sốc (90%) |
53.8% tổng / 25.0% sốc (Static) |
90.0% tổng & sốc (0.00% sai lệch) |
Sai lệch < 3.0% |
Đạt |
Bảng B — Chi tiết Cắt bỏ Thành phần Newsvendor, Gián đoạn, Censoring, Phân cấp & Conformal#
| Thí nghiệm Thành phần | Nhóm / Phương pháp | Số đo Ghi nhận Chính xác (artifacts/ch13_lab06_results.json) |
Kết luận Kỹ thuật |
|---|---|---|---|
Newsvendor Pinball vs MSE |
SKU_HI (\(q^*=0.90\)) / SKU_PER (\(q^*=0.20\)) / Đa kỳ \(L=3\) |
SKU_HI: 397.01 -> 229.54 (-42.18%); SKU_PER: 218.67 -> 137.20 (-37.26%); Giao cắt: 159 -> 0; Đa kỳ: 12,395.5 -> 11,592.2 (90.3% fill) |
Sắp xếp đơn điệu Chernozhukov triệt tiêu 100% giao cắt và Pinball giảm mạnh chi phí cả hai phía biên |
Bẫy MAPE, MAE & Gián đoạn |
{1, 10} / Chuỗi 71.5% số 0 / Croston vs SBA |
MAPE opt = 1.0 (-81.82% vs 5.5); MAE opt = 0.0 (1.554 < 2.224) vs RMSSE (0.7836 < 0.8890); SBA = 1.884 vs Croston = 2.037 (thực 1.595) |
RMSSE miễn nhiễm 0; SBA khử thiên lệch dương của Croston |
Kiểm duyệt POS & Đối chứng sklearn |
Naive POS vs OSA / sklearn.QuantileRegressor vs IRLS |
Naive POS mean = 11.11 vs 21.86 (-49.16%); sklearn Pinball 0.5045 vs NumPy IRLS 0.5047 (chênh dự báo tối đa 0.2823) |
Bắt buộc dùng cờ OSA chống vòng xoáy đứt hàng; Tầng 1 khớp sát nghiệm quy hoạch tuyến tính sklearn |
Hòa giải Phân cấp (Total -> 2R -> 4S) |
Base / Bottom-Up / MinT-OLS / WLS-Struct / MinT-Shrink |
Top RMSE: 1.284 (Base), 5.266 (BU), 1.154 (OLS), 1.858 (WLS), 1.054 (Shrink, \(\lambda^* = 0.4209\), All RMSE = 2.123, SGS_err = 1.67e-15); Quỹ đạo mẫu Top P90 = 85.00 < 104.61 |
MinT-Shrink khai thác hiệp phương sai âm giữa cửa hàng, hạ sai số cả cấp tổng lẫn cấp lá |
Conformal Dưới Sốc Biến động 2.8x |
Static Split / EnbPI / Online ACI (\(\gamma=0.06, W=50\)) |
Static: 53.75% (25.0% sốc, lệch 36.25%); EnbPI: 86.88% (lệch 3.12%); ACI: 90.00% (90.0% sốc, lệch 0.00%, độ rộng hữu hạn TB 15.21) |
ACI hồi phục tức thì khi bước sang vùng sốc phân phối (< 3%) |
(Trên chế độ chạy nhanh --quick, các chỉ số giữ nguyên cùng xu hướng chặt chẽ: chi phí danh mục giảm -46.4% 192.46 -> 103.17, 0 vi phạm ASOF với Purged RMSE = 31.04 so với 1,392 vi phạm 27.61 -> 44.04 của K-Fold rò rỉ).
4.3 Hợp đồng 16 Bài kiểm thử Tự động (tests/test_demand_forecast_lab.py)#
| STT | Tên hàm kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc |
|---|---|---|
1 |
test_01_pydantic_configs_strict_forbid |
Từ chối trường lạ (extra="forbid") và chặn miền sai (alpha, 1 < tweedie_power < 2, c_u > 0, lead_time >= 1) |
2 |
test_02_stationarity_adf_kpss_and_stl_decomposition |
Phân biệt đúng bước ngẫu nhiên vs AR(1) qua cặp ADF + KPSS; STL tách đúng xu hướng + mùa vụ |
3 |
test_03_holtwinters_ets_and_boxcox_jensen_correction |
HoltWintersETS bắt đúng sóng mùa vụ; xác minh exp(mu + sigma^2/2) khử thiên lệch âm Jensen |
4 |
test_04_mape_downward_bias_and_mae_zero_collapse_traps |
Chứng minh nghiệm MAPE trên {1,10} là 1.0 (-81.8%) và nghiệm MAE trên 70% số 0 là 0.0 |
5 |
test_05_croston_sba_bias_correction_and_tweedie_convexity |
Kiểm chứng SBA < Croston khử lệch dương, TSB suy giảm trên chuỗi số 0 dài, và Tweedie Hessian h > 0 mọi nơi |
6 |
test_06_pinball_newsvendor_exact_identity_and_quantile_sorting |
Đẳng thức Newsvendor–Pinball sai lệch < 1e-12; rearrange_quantiles_monotonic xóa giao cắt và hạ Pinball |
7 |
test_07_newsvendor_quantile_policy_beats_mse_by_ge_12pct |
Tổng chi phí danh mục của chính sách \(q^*\) giảm >= 12% so với dự báo MSE |
8 |
test_08_rolling_origin_leadtime_purge_zero_asof_violations |
Khẳng định train_target_end <= origin_ts, avail_ts <= origin_ts, announced_ts <= origin_ts, 0 vi phạm ASOF |
9 |
test_09_stockout_right_censoring_spiral_vs_uncensored_recovery |
Khẳng định vòng xoáy POS gây đứt hàng nặng và độ lệch âm so với phục hồi OSA |
10 |
test_10_mint_reconciliation_coherence_and_accuracy_lift |
Kiểm chứng SGS == S (< 1e-10), coherence_err < 1e-9, MinT-Shrink thắng Base/Bottom-Up, quỹ đạo mẫu đúng P90 |
11 |
test_11_aci_conformal_coverage_within_3pct_under_regime_shift |
Khẳng định Static tụt bao phủ (< 80%) còn ACI giữ sai lệch < 3% quanh 90% |
12 |
test_12_tier2_lightgbm_quantile_tweedie_and_sklearn_parity |
Chạy GlobalLightGBMQuantileForecaster (quantile + tweedie), 0 giao cắt, đối chứng sklearn.QuantileRegressor |
13 |
test_13_multi_period_inventory_simulator_pipeline_conservation |
Bảo toàn vị thế \(\text{IP}_t = I_t^{\text{net}} + \text{OO}_t\), độ trễ hàng về \(L\), và giảm chi phí thực tế |
14 |
test_14_crps_and_wql_proper_scoring_consistency |
Kiểm chứng đồng nhất thức WQL[0.5] == WAPE và CRPS ưu tiên phân phối hiệu chuẩn đúng |
15 |
test_15_cli_demo_execution_and_workbench_json_schema |
Thực thi run_lab_demo.py --quick, xác thực 6 KPI, 4 biểu đồ, 4 bảng và mọi ngưỡng nghiệm thu |
16 |
test_16_security_only_ast_deserialization_guard |
Quét AST toàn bộ src/, scripts/, tests/ khẳng định 0 import deserialization không an toàn |
Trụ cột 5 — Văn liệu Nền tảng, Hệ sinh thái Ôn tập & Thang chấm Rubric#
5.1 Sáu Công trình Học thuật Nền tảng & SOTA (2005–2026)#
- Syntetos, A. A., & Boylan, J. E. (2005). The accuracy of intermittent demand estimates. International Journal of Forecasting, 21(2), 303–314. (Dẫn xuất hệ số \((1 - \alpha_p/2)\) khử thiên lệch dương cố hữu của
Croston (1972)và thiết lập ma trận phân loạiADI–CV^2). - Wickramasuriya, S. L., Athanasopoulos, G., & Hyndman, R. J. (2019). Optimal forecast reconciliation for hierarchical and grouped time series through trace minimization. Journal of the American Statistical Association (JASA), 114(526), 804–819. (Chứng minh định lý
MinTvà phép co cụmMinT-Shrinkđảm bảo tổng nhất quán mọi cấp và tối ưu vết phương sai sai số). - Gibbs, I., & Candès, E. J. (2021 & 2024). Adaptive Conformal Inference Under Distribution Shift (
NeurIPS 2021) & Conformal Inference for Online Prediction with Arbitrary Distribution Shifts (JMLR 2024). (Định lý cập nhật \(\alpha_{t+1} = \alpha_t + \gamma(\alpha - \operatorname{err}_t)\) bị chặn \([-\gamma, 1+\gamma]\) đảm bảo sai lệch bao phủ dài hạn \(\mathcal{O}(1/(\gamma T))\) dưới sốc phân phối bất kỳ). - Montero-Manso, P., & Hyndman, R. J. (2021) & Makridakis, S., Spiliotis, E., & Assimakopoulos, V. (2022). Principles and algorithms for forecasting groups of time series: Locality and globality (
IJF 2021) & M5 accuracy and uncertainty competitions (IJF 2022). (Chứng minh lý thuyết và thực nghiệm trên42,840chuỗi bán lẻ cho ưu thế áp đảo của mô hình toàn cụcLightGBM+WRMSSE). - Ansari, A. F., Shchur, O., et al. (2024–2025). Chronos: Learning the Language of Time Series (
TMLR 2024) & Chronos-2: From Univariate to Universal Forecasting (arXiv:2510.15821). (Kiến trúc Time + Group Attention mở rộngTSFMsang học ngữ cảnh đa biến và có biến ngoại sinh đã biết). - Das, A., et al. (2024) —
TimesFM; Woo, G., et al. (2024) —Moirai; Liu, X., et al. (2025) —Moirai 2.0; Shchur, O., et al. (2025) —fev-bench(arXiv:2509.26468). (Chuỗi nghiên cứu foundation models quy mô100B–1Tđiểm và chuẩn đối chứng nghiêm ngặt chỉ ra ranh giới thực tế giữa zero-shot TSFM và mô hình bảng có biến ngoại sinh).
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
-
Q1(Tính dừng & Jensen Box-Cox): KhiADFbác bỏ \(H_0\) (p < 0.05) vàKPSSkhông bác bỏ (p >= 0.05), chuỗi được xem là dừng; đồng thời nghịch đảo trực tiếp \(f^{-1}(\hat{\mu}_z)\) sau biến đổi log chỉ cho trung vị, cần hiệu chỉnh Jensen \(\exp(\hat{\mu}_z + \frac{1}{2}\hat{\sigma}_z^2)\) để thu kỳ vọng đúng (còn phân vị bất biến dưới biến đổi đơn điệu). -
Q2(BẫyMAPE/MAE,SBA&Tweedie): Trên{1, 10},MAPEchọn1.0(-81.8%thiên lệch âm); trên chuỗi có71.5%ngày bằng0,MAEchọn0.0;SBAnhân \((1 - \alpha_p/2)\) để triệt tiêu thiên lệch dương củaCroston; cònTweedie(\(1 < p_{\text{tw}} < 2\)) đảm bảo Hessian \(h_i > 0\) tại mọi điểm kể cả \(y_i = 0\). -
Q3(Tương đương Newsvendor–Pinball): Vì \(c_u(y-Q)^+ + c_o(Q-y)^+ \equiv (c_u+c_o)\rho_{q^*}(y-Q)\) tại \(q^* = \frac{c_u}{c_u+c_o}\), tối ưuPinballtrực tiếp cắt giảm-39.5%chi phí danh mục (SKU_HI -42.2%,SKU_PER -37.3%) so với trung bìnhMSE. -
Q4(Thanh lọc Lead-Time \(L=4\) & Kiểm toánASOF):K-Foldkèmunannounced_flash_Lgây1,932vi phạmASOFtạo ảo giác22.21 -> 44.72ngoài thực tế; kiểm thử cuốn chiếu thanh lọc giữ \(t_{\text{target\_end}} \le t_0\) (0vi phạmASOF,35.02) đo đúng năng lực triển khai. -
Q5(Vòng xoáy Censoring POS): Doanh số POS bị chặn \(S_t = \min(D_t, I_t^{\text{on\_hand}})\) đánh lừa biến trễ, kéo đứt hàng lên79.3%(-49.2%độ lệch); phục hồiOSAđưa đứt hàng về0.0%và giảm-62.5%chi phí. -
Q6(Global LightGBMvsTSFM): ChọnChronos-2/TimesFM 2.5/Moirai 2.0cho SKU mới ra mắt (cold-start < 30 ngày); chọnGlobal LightGBM(Quantile/Tweedie) cho danh mục dày đặc \(>20\) biến ngoại sinh bảng, chi phí bất đối xứng \(q^*\) vàSLA < 5 msCPU. -
Q7(MinT-Shrink& Quỹ đạo mẫu):Bottom-Upthổi phồngTop RMSElên5.266, trong khiMinT-Shrink(\(\lambda^* = 0.421\)) tận dụng hiệp phương sai âm giữa cửa hàng hạTop RMSExuống1.054(lệch tổng2.84e-14), và chiếu từng quỹ đạo mẫu choTop P90 = 85.00 < 104.61. -
Q8(Online ACIDưới Sốc2.8x): Static Split Conformal mất tính hoán vị nên tụt bao phủ còn53.8%(25.0%vùng sốc);Online ACIcập nhật \(\alpha_{t+1} = \alpha_t + \gamma(\alpha - \operatorname{err}_t)\) giữ nguyên bao phủ thực nghiệm90.0%(0.00%sai lệch< 3%).
5.3 Sáu Bài tập Lập trình & Chứng minh Trọng số (Bài tập 1..6)#
-
Bài tập 1 (
15%) — Phân tích Tính dừng (ADF/KPSS), Thiên lệch Jensen Box-Cox & BẫyMAPE/MAE:Viết phương trình hồi quy
ADFvà thống kêKPSS, giải thích vì saoAICckhông so sánh chéo hai bậc sai phân \(d\) khác nhau, rồi dùngcheck_stationarity_adf_kpss,boxcox_bias_corrected_meanvàaudit_mape_and_mae_trapschứng minh thực nghiệm-81.8%thiên lệchMAPE, sụp đổMAE = 0.0và tính ổn định củaRMSSE. -
Bài tập 2 (
15%) — Chứng minhCrostonLệch Dương, Dẫn xuấtSBA (2005),TSB& Tính LồiTweedie:Dùng khai triển Taylor bậc hai cho \(g(u)=1/u\) và phương sai dừng \(\operatorname{Var}(\hat{p}_k) = \frac{\alpha_p}{2-\alpha_p}\sigma_p^2\) để thu được hệ số \((1 - \alpha_p/2)\) của
SBA; tính \(g_i, h_i\) của hàm lệchTweediedưới liên kết log và chứng minhh_i > 0với mọi \(y_i \ge 0\); đối chứng số trênCrostonSBAForecastervàtweedie_grad_hess. -
Bài tập 3 (
20%) — Chứng minh Tương đươngPinball\(\leftrightarrow\) Newsvendor \(q^*\) & Thực nghiệm Giảm \(\ge 12\%\) Chi phí:Hoàn thành chứng minh định lý vi phân dưới dấu tích phân (cả đạo hàm phải và trái cho CDF rời rạc tại
0), chứng minh đẳng thức điểm \(C_{\text{NV}} = (c_u+c_o)\rho_{q^*}\), tính tỷ số dôi chi phí \(\exp((z^*)^2/2)\) củaMSE, và chạyGlobalLightGBMQuantileForecaster+rearrange_quantiles_monotonictrênLab 06(-39.5%,159 -> 0giao cắt). -
Bài tập 4 (
20%) — Thiết kế Kiểm thử Cuốn chiếu Thanh lọc Lead-Time \(L\), Kiểm toánASOF& Phục hồiOSA:Chứng minh bất biến \(t_{\text{train\_target\_end}} \le t_{\text{eval\_origin}}\) tương ứng khoảng thanh lọc \(L\) ngày, lập lược đồ phân tách bảng
Past-Only(\(\tau_{\text{avail}} \le t_0\)) khỏiKnown-Future Announced(\(\tau_{\text{announced}} \le t_0\)), và chạyRollingOriginPurgedBacktester,audit_asof_and_leakage,run_stockout_censoring_experiment(0vi phạmASOF,-62.5%chi phí sau phục hồiOSA). -
Bài tập 5 (
15%) — Dẫn xuất Hòa giảiMinT-Shrink& Phản chứng Cộng Phân vị Biên:Giải bài toán nhân tử Lagrange cực tiểu hóa \(\operatorname{tr}(\mathbf{S}\mathbf{G}\mathbf{W}_h\mathbf{G}^\top\mathbf{S}^\top)\) dưới ràng buộc \(\mathbf{G}\mathbf{S}=\mathbf{I}_{n_b}\) để thu được \(\mathbf{G}^* = (\mathbf{S}^\top\mathbf{W}_h^{-1}\mathbf{S})^{-1}\mathbf{S}^\top\mathbf{W}_h^{-1}\), viết công thức co cụm Schäfer–Strimmer, và chạy
MinTReconciler+reconcile_sample_pathskiểm chứng sai số \(\mathbf{S}\mathbf{G}\mathbf{S}-\mathbf{S} < 10^{-12}\) vàTop P90 = 85.00 < 104.61. -
Bài tập 6 (
15%) — Chứng minh ChặnACI& Kiểm định Đầu-CuốiLab 06(16/16 Pytest):Chứng minh quy nạp \(\alpha_t \in [-\gamma_{\text{aci}}, 1+\gamma_{\text{aci}}]\) và cận sai lệch \(\mathcal{O}(1/(\gamma_{\text{aci}} T))\) từ phép cộng tổng lồng nhau (telescoping sum); chạy
run_aci_regime_shift_benchmark(90.0%bao phủ trong vùng sốc) và xác nhận trọn bộruff,mypy,pytest(16/16đạt) cùng CLIrun_lab_demo.py.
5.4 Thang chấm Rubric (UCL MSc Grading Rubric)#
| Cấp độ Đạt chuẩn | Tiêu chí Chứng minh & Lý thuyết | Tiêu chí Hệ thống & Thực nghiệm Lab 06 |
|---|---|---|
Principal / MSc Distinction (>= 85%) |
Trình bày trọn vẹn các chứng minh không chệch SBA, đẳng thức Pinball <-> Newsvendor trên CDF rời rạc, nhân tử Lagrange MinT với \(\mathbf{S}\mathbf{G}\mathbf{S}=\mathbf{S}\), và chứng minh quy nạp chặn ACI; không nhầm lẫn ký hiệu t, q*, p_tw hay bẫy AICc |
Thực thi toàn bộ 16/16 pytest (0 lỗi ruff/mypy), giảm chi phí danh mục -39.5%, 0 vi phạm ASOF, MinT-Shrink < 1e-9, ACI sai lệch < 3%, giải thích thấu đáo mọi đánh đổi LightGBM vs Chronos-2/TimesFM |
Senior / Đạt chuẩn (70% – 84%) |
Nắm vững quy tắc ADF/KPSS, hiệu chỉnh Jensen, đẳng thức \(q^* = \frac{c_u}{c_u+c_o}\), nguyên tắc thanh lọc \(L\) ngày và co cụm MinT-Shrink nhưng thiếu một số bước chi tiết trong chứng minh giới hạn quy nạp hoặc đạo hàm subgradient |
Hoàn tất các thí nghiệm chính của Lab 06 vượt các ngưỡng nghiệm thu (>= 12%, 0 ASOF, < 3% ACI, < 1e-9 MinT), còn sai sót nhỏ ở phân tích chi phí 50M chuỗi hoặc đồng nhất thức quỹ đạo mẫu |
Cần khắc phục (< 70%) |
Vẫn đề xuất MAPE / MAE cho SKU thưa, dùng K-Fold ngẫu nhiên trên chuỗi thời gian, nhầm lẫn trung bình MSE với mức đặt hàng tối ưu hoặc cộng trực tiếp phân vị biên theo cây phân cấp |
Để lọt vi phạm ASOF > 0, bỏ qua cờ kiểm duyệt hết hàng OSA, hoặc chưa vượt được các cổng kiểm thử tự động trong tests/test_demand_forecast_lab.py |
Newsvendor Pinball(q*) vs MSE Mean Decision Cost (Lower is Better)
Conformal Empirical Coverage Across Promo Volatility Shock (Target = 90.0%)
Hierarchical Reconciliation Top-Level RMSE (Total -> Region -> 4 Stores)
Stockout Censoring Rate & Leaky vs Purged Backtest Gap
Newsvendor Asymmetric Decision Cost vs Point Baselines (Purged L=4 Backtest)
| SKU / Regime | Critical q* | MSE Cost | Pinball(q*) Cost | Cost Reduction |
|---|---|---|---|---|
| Portfolio Pooled | Mixed (0.20..0.90) | 212.41 | 128.52 | -39.5% |
| SKU_HI (High-Margin) | 0.90 (c_u=18, c_o=2) | 397.01 | 229.54 | -42.2% |
| SKU_PER (Perishable) | 0.20 (c_u=3, c_o=12) | 218.67 | 137.20 | -37.3% |
| Multi-Period Sim (L=3) | 0.90 Lost-Sales | 12395.5 | 11592.2 | 90.3% fill |
Rolling-Origin Lead-Time Purge Audit & Stockout Censoring Spiral
| Audit Scenario | ASOF Violations | Offline vs Live | Stockout / Bias |
|---|---|---|---|
| Purged Rolling-Origin (L=4) | 0 (PASS) | RMSE 35.02 -> 35.02 | 0 future leaks |
| Leaky K-Fold + Future Flash | 1932 (FAIL) | RMSE 22.21 -> 44.72 | Collapses live |
| Naive Censored POS Lags | — | Cost 24363.2 | SO 79.3% (-49.2%) |
| OSA Uncensored + q* Buffer | — | Cost 9136.1 | SO 0.0% (-62.5%) |
Hierarchical Reconciliation Comparison (Total -> 2 Regions -> 4 Stores)
| Method | Top RMSE | Bottom RMSE | Coherence Err | SGS - S Err |
|---|---|---|---|---|
| Base Unreconciled | 1.284 | 3.166 | 13.977 | — |
| Bottom-Up | 5.266 | 3.166 | 0.00e+00 | 0.00e+00 |
| MinT-OLS | 1.154 | 2.669 | 5.68e-14 | 6.94e-17 |
| MinT-Shrink | 1.054 | 2.644 | 2.84e-14 | 1.67e-15 |
Conformal Time-Series Adaptation & Intermittent Demand Sanity
| Wrapper / Estimator | Target / True | Observed Metric | Deviation / Notes |
|---|---|---|---|
| Static Split Conformal | 90.0% Cov | 53.8% (Shock 25.0%) | Err 36.25% (FAIL) |
| EnbPI FIFO Window (W=50) | 90.0% Cov | 86.9% | Err 3.12% |
| Online ACI-CQR (gamma=0.06) | 90.0% Cov | 90.0% (Shock 90.0%) | Err 0.00% (<3% PASS) |
| ETS / Croston-SBA / TSB | Int Mean 1.59 | ETS=14.02 | SBA=1.88 | Croston=2.04 | TSB=2.84 |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/lab-06-retail-demand-planning-cost-backtest
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "demand-forecast-lab"
version = "0.1.0"
description = "Lab 06: Retail Demand Planning, Asymmetric Newsvendor Pinball Costs, Lead-Time Purged Backtesting, Hierarchical MinT-Shrink & Online ACI Conformal Forecasting (T1-P2-U08)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"lightgbm>=4.0",
"numpy>=1.26",
"pandas>=2.2",
"pydantic>=2.0",
"scikit-learn>=1.4",
"scipy>=1.12",
]
[project.optional-dependencies]
dev = [
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 06 (`T1-P2-U08`): Retail Demand Forecasting, Decision Costs & Purged Backtesting."""
from __future__ import annotations
from demand_forecast_lab.decision_backtest import (
ACIConfig,
AdaptiveConformalForecaster,
BacktestConfig,
GlobalLightGBMQuantileForecaster,
MinTConfig,
MinTReconciler,
PanelModelConfig,
RollingOriginPurgedBacktester,
audit_asof_and_leakage,
build_causal_features,
generate_retail_demand_panel,
reconcile_sample_paths,
run_full_ch13_lab06_benchmarks,
)
from demand_forecast_lab.forecasting_core import (
CrostonSBAConfig,
CrostonSBAForecaster,
HoltWintersConfig,
HoltWintersETS,
InventorySimConfig,
NewsvendorConfig,
StationarityConfig,
audit_mape_and_mae_traps,
boxcox_bias_corrected_mean,
check_stationarity_adf_kpss,
compute_crps_from_quantiles,
compute_mase,
compute_rmsse,
compute_wql,
newsvendor_cost,
newsvendor_critical_fractile,
pinball_loss,
rearrange_quantiles_monotonic,
seasonal_decompose_stl_ref,
simulate_multi_period_inventory,
tweedie_grad_hess,
tweedie_unit_deviance,
)
__all__ = [
"ACIConfig",
"AdaptiveConformalForecaster",
"BacktestConfig",
"CrostonSBAConfig",
"CrostonSBAForecaster",
"GlobalLightGBMQuantileForecaster",
"HoltWintersConfig",
"HoltWintersETS",
"InventorySimConfig",
"MinTConfig",
"MinTReconciler",
"NewsvendorConfig",
"PanelModelConfig",
"RollingOriginPurgedBacktester",
"StationarityConfig",
"audit_asof_and_leakage",
"audit_mape_and_mae_traps",
"boxcox_bias_corrected_mean",
"build_causal_features",
"check_stationarity_adf_kpss",
"compute_crps_from_quantiles",
"compute_mase",
"compute_rmsse",
"compute_wql",
"generate_retail_demand_panel",
"newsvendor_cost",
"newsvendor_critical_fractile",
"pinball_loss",
"rearrange_quantiles_monotonic",
"reconcile_sample_paths",
"run_full_ch13_lab06_benchmarks",
"seasonal_decompose_stl_ref",
"simulate_multi_period_inventory",
"tweedie_grad_hess",
"tweedie_unit_deviance",
]
"""Tier 1 Reference Core: Stationarity, ETS, Croston-SBA/TSB, Tweedie, Pinball & Newsvendor Economics."""
from __future__ import annotations
from collections import deque
from typing import Literal
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field, model_validator
class StationarityConfig(BaseModel):
"""Strict configuration for ADF / KPSS stationarity testing."""
model_config = ConfigDict(extra="forbid")
adf_lags: int = Field(default=2, ge=0, le=24)
trend: Literal["c", "ct"] = "c"
kpss_lags: int | None = Field(default=None, ge=1, le=30)
class HoltWintersConfig(BaseModel):
"""Configuration for additive / damped Holt-Winters state-space ETS."""
model_config = ConfigDict(extra="forbid")
seasonal_period: int = Field(default=7, ge=2, le=366)
alpha: float = Field(default=0.30, gt=0.0, le=1.0)
beta: float = Field(default=0.08, ge=0.0, le=1.0)
gamma: float = Field(default=0.20, ge=0.0, le=1.0)
phi_damp: float = Field(default=0.95, gt=0.0, le=1.0)
damped: bool = True
class CrostonSBAConfig(BaseModel):
"""Configuration for Croston, Syntetos-Boylan (SBA), and TSB intermittent forecasters."""
model_config = ConfigDict(extra="forbid")
method: Literal["croston", "sba", "tsb"] = "sba"
alpha_size: float = Field(default=0.15, gt=0.0, le=1.0)
alpha_interval: float = Field(default=0.15, gt=0.0, le=1.0)
class NewsvendorConfig(BaseModel):
"""Asymmetric Newsvendor unit economics contract."""
model_config = ConfigDict(extra="forbid")
c_u: float = Field(..., gt=0.0, description="Underage/stockout penalty per unit short.")
c_o: float = Field(..., gt=0.0, description="Overage/holding/spoilage cost per excess unit.")
@property
def critical_fractile(self) -> float:
"""Return optimal Newsvendor critical fractile q* = c_u / (c_u + c_o)."""
return float(self.c_u / (self.c_u + self.c_o))
class InventorySimConfig(BaseModel):
"""Multi-period inventory replenishment simulation configuration."""
model_config = ConfigDict(extra="forbid")
c_u: float = Field(..., gt=0.0)
c_o: float = Field(..., gt=0.0)
lead_time: int = Field(default=3, ge=1, le=30)
lost_sales: bool = True
initial_stock: float | None = Field(default=None, ge=0.0)
@model_validator(mode="after")
def _validate_costs(self) -> InventorySimConfig:
if not np.isfinite(self.c_u) or not np.isfinite(self.c_o):
raise ValueError("Unit costs c_u and c_o must be finite.")
return self
def check_stationarity_adf_kpss(
y: NDArray[np.float64] | list[float],
config: StationarityConfig | None = None,
) -> dict[str, float | bool | str]:
"""Run deterministic OLS ADF unit-root test and Newey-West KPSS stationarity test."""
cfg = config or StationarityConfig()
arr = np.asarray(y, dtype=np.float64)
if arr.ndim != 1 or arr.size < 24:
raise ValueError("Series must be 1D with at least 24 observations.")
n_obs = arr.size
dy = np.diff(arr)
p = min(cfg.adf_lags, max(0, (n_obs - 8) // 4))
start = p
dep = dy[start:]
m = dep.size
cols: list[NDArray[np.float64]] = [np.ones(m, dtype=np.float64)]
if cfg.trend == "ct":
cols.append(np.arange(1, m + 1, dtype=np.float64))
cols.append(arr[start : n_obs - 1])
for lag in range(1, p + 1):
cols.append(dy[start - lag : n_obs - 1 - lag])
x_adf = np.column_stack(cols)
beta_hat, _, _, _ = np.linalg.lstsq(x_adf, dep, rcond=None)
resid = dep - x_adf @ beta_hat
dof = max(1, m - x_adf.shape[1])
sigma2 = float(np.dot(resid, resid) / dof)
xtx_inv = np.linalg.pinv(x_adf.T @ x_adf)
gamma_idx = 2 if cfg.trend == "ct" else 1
se_gamma = float(np.sqrt(max(1e-18, sigma2 * xtx_inv[gamma_idx, gamma_idx])))
adf_stat = float(beta_hat[gamma_idx] / se_gamma)
adf_crit_5pct = -3.43 if cfg.trend == "ct" else -2.88
adf_rejects = bool(adf_stat < adf_crit_5pct)
# KPSS test: regress on constant (or constant + linear trend), compute Bartlett HAC variance
t_idx = np.arange(1, n_obs + 1, dtype=np.float64)
x_kpss = (
np.column_stack([np.ones(n_obs), t_idx])
if cfg.trend == "ct"
else np.ones((n_obs, 1), dtype=np.float64)
)
k_beta, _, _, _ = np.linalg.lstsq(x_kpss, arr, rcond=None)
e_kpss = arr - x_kpss @ k_beta
s_cum = np.cumsum(e_kpss)
nw_lags = cfg.kpss_lags if cfg.kpss_lags is not None else max(1, int(4.0 * (n_obs / 100.0) ** 0.25))
hac_var = float(np.dot(e_kpss, e_kpss) / n_obs)
for lag in range(1, min(nw_lags, n_obs - 1) + 1):
weight = 1.0 - lag / (nw_lags + 1.0)
cov_lag = float(np.dot(e_kpss[lag:], e_kpss[:-lag]) / n_obs)
hac_var += 2.0 * weight * cov_lag
hac_var = max(1e-12, hac_var)
kpss_stat = float(np.sum(s_cum**2) / (n_obs**2 * hac_var))
kpss_crit_5pct = 0.146 if cfg.trend == "ct" else 0.463
kpss_rejects = bool(kpss_stat > kpss_crit_5pct)
if adf_rejects and not kpss_rejects:
regime = "stationary"
elif not adf_rejects and kpss_rejects:
regime = "unit_root"
elif adf_rejects and kpss_rejects:
regime = "trend_or_break"
else:
regime = "inconclusive"
return {
"adf_stat": adf_stat,
"adf_crit_5pct": adf_crit_5pct,
"adf_rejects_unit_root": adf_rejects,
"kpss_stat": kpss_stat,
"kpss_crit_5pct": kpss_crit_5pct,
"kpss_rejects_stationarity": kpss_rejects,
"regime": regime,
}
def _weighted_local_linear_smooth(
y: NDArray[np.float64],
window: int,
weights: NDArray[np.float64] | None = None,
) -> NDArray[np.float64]:
"""Compute causal-safe 1D LOESS-style local linear smoothing over full training slice."""
n = y.size
w_ext = np.ones(n, dtype=np.float64) if weights is None else np.asarray(weights, dtype=np.float64)
half = max(1, window // 2)
out = np.empty(n, dtype=np.float64)
idx_all = np.arange(n, dtype=np.float64)
for t in range(n):
lo = max(0, t - half)
hi = min(n, t + half + 1)
x_win = idx_all[lo:hi] - float(t)
max_d = max(1.0, float(np.max(np.abs(x_win))))
u = np.abs(x_win) / (max_d + 1e-9)
tricube = np.where(u < 1.0, (1.0 - u**3) ** 3, 0.0)
w = tricube * w_ext[lo:hi]
if float(np.sum(w)) <= 1e-12:
out[t] = float(y[t])
continue
sw = np.sqrt(w)
design = np.column_stack([sw, sw * x_win])
rhs = sw * y[lo:hi]
coef, _, _, _ = np.linalg.lstsq(design, rhs, rcond=None)
out[t] = float(coef[0])
return out
def seasonal_decompose_stl_ref(
y: NDArray[np.float64] | list[float],
period: int = 7,
n_inner: int = 2,
n_outer: int = 2,
) -> dict[str, NDArray[np.float64]]:
"""Pure-NumPy STL additive decomposition with Tukey bisquare robustness weights."""
arr = np.asarray(y, dtype=np.float64)
n = arr.size
if n < 2 * period:
raise ValueError("Series length must be at least 2 * period for STL.")
trend = np.zeros(n, dtype=np.float64)
seasonal = np.zeros(n, dtype=np.float64)
rob_weights = np.ones(n, dtype=np.float64)
trend_win = max(period + 1, int(np.ceil(1.5 * period)) | 1)
seas_win = max(5, (n // (2 * period)) | 1)
for _outer in range(max(1, n_outer)):
for _inner in range(max(1, n_inner)):
detrended = arr - trend
cycle = np.zeros(n, dtype=np.float64)
for phase in range(period):
sub_idx = np.arange(phase, n, period)
sub_vals = detrended[sub_idx]
sub_w = rob_weights[sub_idx]
cycle[sub_idx] = _weighted_local_linear_smooth(sub_vals, seas_win, sub_w)
# Low-pass mean-centering filter preventing trend leakage into seasonal state
kernel = np.ones(period, dtype=np.float64) / float(period)
padded = np.pad(cycle, (period // 2, period - 1 - period // 2), mode="edge")
lowpass = np.convolve(padded, kernel, mode="valid")[:n]
seasonal = cycle - lowpass
seasonal -= float(np.mean(seasonal))
trend = _weighted_local_linear_smooth(arr - seasonal, trend_win, rob_weights)
remainder = arr - trend - seasonal
med_abs = float(np.median(np.abs(remainder)))
h_rob = max(1e-9, 6.0 * med_abs)
u = np.abs(remainder) / h_rob
rob_weights = np.where(u < 1.0, (1.0 - u**2) ** 2, 0.0)
remainder = arr - trend - seasonal
return {
"trend": trend,
"seasonal": seasonal,
"remainder": remainder,
"robust_weights": rob_weights,
}
def boxcox_bias_corrected_mean(
mu_z: NDArray[np.float64] | float,
var_z: NDArray[np.float64] | float,
lam: float = 0.0,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Return (naive_median_backtransform, jensen_bias_corrected_mean) from transformed space."""
mu = np.asarray(mu_z, dtype=np.float64)
var = np.maximum(0.0, np.asarray(var_z, dtype=np.float64))
if abs(lam) < 1e-10:
naive = np.exp(mu)
corrected = np.exp(mu + 0.5 * var)
return naive, corrected
inner = np.maximum(1e-9, lam * mu + 1.0)
naive = inner ** (1.0 / lam)
correction = 1.0 + (var * (1.0 - lam)) / (2.0 * inner**2)
corrected = naive * correction
return naive, corrected
class HoltWintersETS:
"""Additive / damped Holt-Winters innovations state-space forecaster."""
def __init__(self, config: HoltWintersConfig | None = None) -> None:
self.config = config or HoltWintersConfig()
self.level_: float = 0.0
self.trend_: float = 0.0
self.seasonal_: NDArray[np.float64] = np.zeros(self.config.seasonal_period, dtype=np.float64)
self.fitted_: NDArray[np.float64] = np.array([], dtype=np.float64)
self.residuals_: NDArray[np.float64] = np.array([], dtype=np.float64)
self.sigma_: float = 1.0
def fit(self, y: NDArray[np.float64] | list[float]) -> HoltWintersETS:
"""Fit ETS state recursion strictly causally across training observations."""
arr = np.asarray(y, dtype=np.float64)
s = self.config.seasonal_period
if arr.ndim != 1 or arr.size < 2 * s:
raise ValueError(f"HoltWintersETS requires at least {2 * s} observations.")
n = arr.size
phi = self.config.phi_damp if self.config.damped else 1.0
alpha, beta, gamma = self.config.alpha, self.config.beta, self.config.gamma
level = float(np.mean(arr[:s]))
trend = float((np.mean(arr[s : 2 * s]) - np.mean(arr[:s])) / s)
seas_buf = list(arr[:s] - level)
seas_mean = float(np.mean(seas_buf))
seas_buf = [v - seas_mean for v in seas_buf]
fitted = np.empty(n, dtype=np.float64)
residuals = np.empty(n, dtype=np.float64)
for t in range(n):
s_prev = seas_buf[t % s]
y_hat = level + phi * trend + s_prev
eps = float(arr[t] - y_hat)
fitted[t] = y_hat
residuals[t] = eps
new_level = level + phi * trend + alpha * eps
new_trend = phi * trend + beta * eps
seas_buf[t % s] = s_prev + gamma * eps
level = new_level
trend = new_trend
self.level_ = level
self.trend_ = trend
last_cycle = np.empty(s, dtype=np.float64)
for offset in range(s):
last_cycle[offset] = seas_buf[(n + offset) % s]
self.seasonal_ = last_cycle
self.fitted_ = fitted
self.residuals_ = residuals
denom = max(1, (n - s) - 3)
self.sigma_ = float(np.sqrt(np.sum(residuals[s:] ** 2) / denom)) if n > 2 * s else float(
np.std(residuals)
)
return self
def predict(
self,
horizon: int,
z_crit: float = 1.6448536269514722,
) -> dict[str, NDArray[np.float64]]:
"""Predict h-step point mean and analytical state-space innovation intervals."""
if horizon < 1:
raise ValueError("Horizon must be >= 1.")
s = self.config.seasonal_period
phi = self.config.phi_damp if self.config.damped else 1.0
alpha, beta, gamma = self.config.alpha, self.config.beta, self.config.gamma
point = np.empty(horizon, dtype=np.float64)
std_h = np.empty(horizon, dtype=np.float64)
phi_sum = 0.0
cum_c2 = 0.0
for h in range(1, horizon + 1):
phi_sum += phi**h
seas_val = float(self.seasonal_[(h - 1) % s])
point[h - 1] = self.level_ + phi_sum * self.trend_ + seas_val
std_h[h - 1] = self.sigma_ * float(np.sqrt(1.0 + cum_c2))
phi_j = (1.0 - phi**h) / (1.0 - phi) if abs(1.0 - phi) > 1e-8 else float(h)
c_h = alpha + beta * phi_j + (gamma if (h % s == 0) else 0.0)
cum_c2 += c_h * c_h
return {
"mean": point,
"std": std_h,
"lower": point - z_crit * std_h,
"upper": point + z_crit * std_h,
}
class CrostonSBAForecaster:
"""Intermittent demand forecaster supporting Croston (1972), SBA (2005) & TSB (2011)."""
def __init__(self, config: CrostonSBAConfig | None = None) -> None:
self.config = config or CrostonSBAConfig()
self.size_est_: float = 0.0
self.interval_est_: float = 1.0
self.occ_prob_: float = 0.0
self.fitted_: NDArray[np.float64] = np.array([], dtype=np.float64)
def fit(self, y: NDArray[np.float64] | list[float]) -> CrostonSBAForecaster:
"""Fit causal intermittent state updates across training history."""
arr = np.asarray(y, dtype=np.float64)
if arr.ndim != 1 or arr.size < 2 or np.any(arr < 0.0):
raise ValueError("Intermittent demand series must be 1D non-negative with >= 2 points.")
nz_idx = np.flatnonzero(arr > 0.0)
if nz_idx.size == 0:
self.size_est_ = 0.0
self.interval_est_ = float(arr.size)
self.occ_prob_ = 0.0
self.fitted_ = np.zeros_like(arr)
return self
a_z = self.config.alpha_size
a_p = self.config.alpha_interval
z_est = float(arr[nz_idx[0]])
p_est = max(1.0, float(nz_idx[0] + 1))
occ_est = float(np.mean(arr[: max(2, nz_idx[0] + 1)] > 0.0))
fitted = np.empty(arr.size, dtype=np.float64)
periods_since = 1
for t, val in enumerate(arr):
if self.config.method == "croston":
pred = z_est / max(1.0, p_est)
elif self.config.method == "sba":
pred = (1.0 - 0.5 * a_p) * (z_est / max(1.0, p_est))
else:
pred = occ_est * z_est
fitted[t] = pred
is_pos = val > 0.0
occ_est = a_p * (1.0 if is_pos else 0.0) + (1.0 - a_p) * occ_est
if is_pos:
z_est = a_z * float(val) + (1.0 - a_z) * z_est
if t > nz_idx[0]:
p_est = a_p * float(periods_since) + (1.0 - a_p) * p_est
periods_since = 1
else:
periods_since += 1
self.size_est_ = z_est
self.interval_est_ = p_est
self.occ_prob_ = occ_est
self.fitted_ = fitted
return self
def predict(self, horizon: int) -> NDArray[np.float64]:
"""Return flat multi-step intermittent expected demand rate."""
if horizon < 1:
raise ValueError("Horizon must be >= 1.")
if self.size_est_ <= 0.0:
return np.zeros(horizon, dtype=np.float64)
if self.config.method == "croston":
rate = self.size_est_ / max(1.0, self.interval_est_)
elif self.config.method == "sba":
rate = (1.0 - 0.5 * self.config.alpha_interval) * (
self.size_est_ / max(1.0, self.interval_est_)
)
else:
rate = self.occ_prob_ * self.size_est_
return np.full(horizon, float(rate), dtype=np.float64)
def tweedie_unit_deviance(
y_true: NDArray[np.float64] | list[float],
mu_pred: NDArray[np.float64] | list[float],
power: float = 1.35,
) -> float:
"""Compute mean Tweedie unit deviance d(y, mu) for 1 < p < 2."""
if not (1.0 < power < 2.0):
raise ValueError("Tweedie variance power p must satisfy 1 < p < 2.")
y = np.maximum(0.0, np.asarray(y_true, dtype=np.float64))
mu = np.maximum(1e-9, np.asarray(mu_pred, dtype=np.float64))
term1 = np.where(y > 0.0, (y ** (2.0 - power)) / ((1.0 - power) * (2.0 - power)), 0.0)
term2 = (y * (mu ** (1.0 - power))) / (1.0 - power)
term3 = (mu ** (2.0 - power)) / (2.0 - power)
return float(np.mean(2.0 * (term1 - term2 + term3)))
def tweedie_grad_hess(
y_true: NDArray[np.float64] | list[float],
log_mu: NDArray[np.float64] | list[float],
power: float = 1.35,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Compute exact gradient and strictly positive Hessian of Tweedie quasi-likelihood under log-link."""
if not (1.0 < power < 2.0):
raise ValueError("Tweedie variance power p must satisfy 1 < p < 2.")
y = np.maximum(0.0, np.asarray(y_true, dtype=np.float64))
eta = np.clip(np.asarray(log_mu, dtype=np.float64), -20.0, 20.0)
e1 = np.exp((1.0 - power) * eta)
e2 = np.exp((2.0 - power) * eta)
grad = -y * e1 + e2
hess = (power - 1.0) * y * e1 + (2.0 - power) * e2
return grad, hess
def pinball_loss(
y_true: NDArray[np.float64] | list[float],
y_pred: NDArray[np.float64] | list[float],
tau: float,
) -> float:
"""Compute mean Pinball (quantile) loss rho_tau(y - y_hat)."""
if not (0.0 < tau < 1.0):
raise ValueError("Quantile level tau must lie strictly in (0, 1).")
y = np.asarray(y_true, dtype=np.float64)
q = np.asarray(y_pred, dtype=np.float64)
u = y - q
loss = np.where(u >= 0.0, tau * u, (tau - 1.0) * u)
return float(np.mean(loss))
def compute_mase(
y_train: NDArray[np.float64],
y_true: NDArray[np.float64],
y_pred: NDArray[np.float64],
seasonal_period: int = 1,
) -> float:
"""Compute Hyndman & Koehler (2006) Mean Absolute Scaled Error."""
s = max(1, seasonal_period)
if y_train.size <= s:
raise ValueError("y_train must exceed seasonal_period.")
scale = float(np.mean(np.abs(y_train[s:] - y_train[:-s])))
scale = max(1e-9, scale)
return float(np.mean(np.abs(y_true - y_pred)) / scale)
def compute_rmsse(
y_train: NDArray[np.float64],
y_true: NDArray[np.float64],
y_pred: NDArray[np.float64],
) -> float:
"""Compute M5 Root Mean Squared Scaled Error safe at y_true == 0."""
if y_train.size < 2:
raise ValueError("y_train must contain >= 2 points.")
scale = float(np.mean((y_train[1:] - y_train[:-1]) ** 2))
scale = max(1e-9, scale)
mse = float(np.mean((y_true - y_pred) ** 2))
return float(np.sqrt(mse / scale))
def compute_wql(
y_true: NDArray[np.float64] | list[float],
y_pred_q: NDArray[np.float64] | list[float],
tau: float,
) -> float:
"""Compute Weighted Quantile Loss WQL[tau] = 2 * sum(pinball) / sum(|y|)."""
y = np.asarray(y_true, dtype=np.float64)
q = np.asarray(y_pred_q, dtype=np.float64)
u = y - q
loss = np.where(u >= 0.0, tau * u, (tau - 1.0) * u)
denom = max(1e-9, float(np.sum(np.abs(y))))
return float(2.0 * np.sum(loss) / denom)
def compute_crps_from_quantiles(
y_true: NDArray[np.float64] | list[float],
quantile_preds: NDArray[np.float64],
taus: NDArray[np.float64] | list[float],
) -> float:
"""Approximate Continuous Ranked Probability Score via trapezoidal Pinball integral."""
y = np.asarray(y_true, dtype=np.float64)
taus_arr = np.asarray(taus, dtype=np.float64)
if quantile_preds.ndim != 2 or quantile_preds.shape != (y.size, taus_arr.size):
raise ValueError("quantile_preds must have shape (n_samples, n_quantiles).")
if not np.all(np.diff(taus_arr) > 0.0):
raise ValueError("taus must be strictly increasing.")
losses = np.array(
[pinball_loss(y, quantile_preds[:, j], float(taus_arr[j])) for j in range(taus_arr.size)]
)
# Use trapezoidal integration across [0, 1] by linearly extending endpoints to tau=0 and tau=1
tau_ext = np.concatenate([[0.0], taus_arr, [1.0]])
loss_ext = np.concatenate([[losses[0]], losses, [losses[-1]]])
return float(2.0 * np.trapezoid(loss_ext, tau_ext))
def rearrange_quantiles_monotonic(quantile_matrix: NDArray[np.float64]) -> NDArray[np.float64]:
"""Eliminate quantile crossings via Chernozhukov et al. (2010) row-wise monotone rearrangement."""
arr = np.asarray(quantile_matrix, dtype=np.float64)
if arr.ndim != 2:
raise ValueError("quantile_matrix must be 2D (n_samples, n_quantiles).")
return np.sort(arr, axis=1)
def newsvendor_critical_fractile(c_u: float, c_o: float) -> float:
"""Return optimal Newsvendor fractile q* = c_u / (c_u + c_o)."""
cfg = NewsvendorConfig(c_u=c_u, c_o=c_o)
return cfg.critical_fractile
def newsvendor_cost(
y_true: NDArray[np.float64] | list[float],
order_qty: NDArray[np.float64] | list[float],
c_u: float,
c_o: float,
) -> float:
"""Compute mean asymmetric Newsvendor underage + overage cost."""
cfg = NewsvendorConfig(c_u=c_u, c_o=c_o)
y = np.asarray(y_true, dtype=np.float64)
q = np.asarray(order_qty, dtype=np.float64)
shortage = np.maximum(0.0, y - q)
overage = np.maximum(0.0, q - y)
return float(np.mean(cfg.c_u * shortage + cfg.c_o * overage))
def simulate_multi_period_inventory(
demand: NDArray[np.float64] | list[float],
order_up_to_targets: NDArray[np.float64] | list[float],
config: InventorySimConfig,
) -> dict[str, float | NDArray[np.float64]]:
"""Simulate periodic-review replenishment with L-day pipeline arrival and censoring telemetry."""
d_arr = np.maximum(0.0, np.asarray(demand, dtype=np.float64))
s_arr = np.maximum(0.0, np.asarray(order_up_to_targets, dtype=np.float64))
if d_arr.ndim != 1 or s_arr.shape != d_arr.shape:
raise ValueError("demand and order_up_to_targets must be 1D arrays of equal length.")
n = d_arr.size
lead_time = config.lead_time
on_hand = (
float(config.initial_stock)
if config.initial_stock is not None
else float(np.mean(d_arr[: min(7, n)]))
)
backorder = 0.0
pipeline: deque[float] = deque([0.0] * lead_time, maxlen=lead_time)
sales = np.empty(n, dtype=np.float64)
unmet = np.empty(n, dtype=np.float64)
ending_stock = np.empty(n, dtype=np.float64)
orders_placed = np.empty(n, dtype=np.float64)
inv_pos_trace = np.empty(n, dtype=np.float64)
stockout_flags = np.zeros(n, dtype=bool)
for t in range(n):
arriving = pipeline.popleft()
available = on_hand + arriving
effective_demand = float(d_arr[t]) + (0.0 if config.lost_sales else backorder)
short = max(0.0, effective_demand - available)
on_hand = max(0.0, available - effective_demand)
backorder = 0.0 if config.lost_sales else short
# Compute inventory position BEFORE placing period-t replenishment order
inv_pos = on_hand - backorder + float(sum(pipeline))
order_t = max(0.0, float(s_arr[t]) - inv_pos)
pipeline.append(order_t)
sales[t] = min(float(d_arr[t]), available)
unmet[t] = short
ending_stock[t] = on_hand
orders_placed[t] = order_t
inv_pos_trace[t] = inv_pos
stockout_flags[t] = short > 1e-9 or on_hand <= 1e-9
total_shortage_cost = float(config.c_u * np.sum(unmet))
total_holding_cost = float(config.c_o * np.sum(ending_stock))
total_cost = total_shortage_cost + total_holding_cost
return {
"total_cost": total_cost,
"mean_daily_cost": total_cost / float(n),
"shortage_cost": total_shortage_cost,
"holding_cost": total_holding_cost,
"stockout_rate": float(np.mean(stockout_flags)),
"fill_rate": float(np.sum(sales) / max(1e-9, float(np.sum(d_arr)))),
"sales": sales,
"ending_stock": ending_stock,
"orders_placed": orders_placed,
"inv_pos_trace": inv_pos_trace,
"stockout_flags": stockout_flags.astype(np.float64),
}
def audit_mape_and_mae_traps(seed: int = 42) -> dict[str, float]:
"""Quantify MAPE downward harmonic bias, zero-division failure, and MAE zero-collapse."""
# 1. Exact analytical two-point counterexample: Y in {1, 10} equally likely
y_pair = np.array([1.0, 10.0], dtype=np.float64)
grid = np.linspace(0.5, 10.5, 201)
mape_vals = np.array([float(np.mean(np.abs(y_pair - a) / y_pair)) for a in grid])
mape_opt_a = float(grid[int(np.argmin(mape_vals))])
true_mean_pair = float(np.mean(y_pair))
mape_downward_bias_pct = 100.0 * (mape_opt_a - true_mean_pair) / true_mean_pair
# 2. Intermittent SKU (72% zeros)
rng = np.random.default_rng(seed)
n = 1000
is_pos = rng.random(n) < 0.28
sizes = rng.gamma(shape=2.5, scale=1.7, size=n)
y_int = np.where(is_pos, np.round(sizes, 2) + 1.0, 0.0)
zero_fraction = float(np.mean(y_int == 0.0))
# Optimal constant predictor under MAE on >50% zero demand is 0.0!
cand_const = np.linspace(0.0, float(np.mean(y_int)) * 1.5, 151)
mae_grid = [float(np.mean(np.abs(y_int - c))) for c in cand_const]
mae_opt_const = float(cand_const[int(np.argmin(mae_grid))])
mae_at_zero = float(np.mean(np.abs(y_int - 0.0)))
mae_at_mean = float(np.mean(np.abs(y_int - float(np.mean(y_int)))))
rmsse_at_mean = compute_rmsse(y_int[:500], y_int[500:], np.full(500, float(np.mean(y_int[:500]))))
rmsse_at_zero = compute_rmsse(y_int[:500], y_int[500:], np.zeros(500))
return {
"pair_true_mean": true_mean_pair,
"pair_mape_optimal": mape_opt_a,
"pair_mape_downward_bias_pct": mape_downward_bias_pct,
"intermittent_zero_fraction": zero_fraction,
"intermittent_true_mean": float(np.mean(y_int)),
"intermittent_mae_optimal_const": mae_opt_const,
"intermittent_mae_at_zero": mae_at_zero,
"intermittent_mae_at_mean": mae_at_mean,
"intermittent_rmsse_at_mean": rmsse_at_mean,
"intermittent_rmsse_at_zero": rmsse_at_zero,
}
"""Tier 2 SOTA Parity, Lead-Time Purged Backtest, MinT Reconciliation & Online ACI Conformal."""
from __future__ import annotations
from typing import Any, Literal
import lightgbm as lgb
import numpy as np
import pandas as pd
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from sklearn.linear_model import QuantileRegressor
from sklearn.model_selection import KFold
from demand_forecast_lab.forecasting_core import (
CrostonSBAConfig,
CrostonSBAForecaster,
HoltWintersConfig,
HoltWintersETS,
InventorySimConfig,
audit_mape_and_mae_traps,
newsvendor_critical_fractile,
pinball_loss,
rearrange_quantiles_monotonic,
simulate_multi_period_inventory,
)
class BacktestConfig(BaseModel):
"""Lead-time purged rolling-origin backtest contract."""
model_config = ConfigDict(extra="forbid")
lead_time: int = Field(default=4, ge=1, le=21)
min_train_days: int = Field(default=84, ge=28, le=365)
eval_window: int = Field(default=24, ge=7, le=90)
step_size: int = Field(default=24, ge=7, le=90)
max_folds: int = Field(default=4, ge=2, le=12)
class MinTConfig(BaseModel):
"""Hierarchical reconciliation configuration."""
model_config = ConfigDict(extra="forbid")
method: Literal["bottom_up", "mint_ols", "wls_struct", "mint_shrink"] = "mint_shrink"
min_shrinkage: float = Field(default=0.0, ge=0.0, le=1.0)
class ACIConfig(BaseModel):
"""Online Adaptive Conformal Inference (ACI) / EnbPI configuration."""
model_config = ConfigDict(extra="forbid")
alpha: float = Field(default=0.10, gt=0.01, lt=0.50)
gamma: float = Field(default=0.06, gt=0.001, le=0.50)
window_size: int = Field(default=50, ge=10, le=500)
method: Literal["split_conformal", "enbpi_fifo", "aci_cqr"] = "aci_cqr"
class PanelModelConfig(BaseModel):
"""Global LightGBM quantile / Tweedie panel model configuration."""
model_config = ConfigDict(extra="forbid")
n_estimators: int = Field(default=130, ge=20, le=1000)
learning_rate: float = Field(default=0.06, gt=0.005, le=0.5)
num_leaves: int = Field(default=23, ge=4, le=128)
tweedie_power: float = Field(default=1.35, gt=1.01, lt=1.99)
random_state: int = 42
def generate_retail_demand_panel(seed: int = 42, quick: bool = False) -> pd.DataFrame:
"""Generate deterministic multi-echelon retail SKU x Store demand panel with bitemporal flags."""
rng = np.random.default_rng(seed)
n_days = 180 if quick else 240
stores = [
("S1", "North", 1.15),
("S2", "North", 0.95),
("S3", "South", 1.10),
("S4", "South", 0.90),
]
skus = [
# sku_id, sku_idx, archetype, base_level, c_u, c_o, is_intermittent
("SKU_HI", 0, "high_margin", 24.0, 18.0, 2.0, False),
("SKU_PER", 1, "perishable", 26.0, 3.0, 12.0, False),
("SKU_INT", 2, "intermittent", 5.5, 8.0, 2.0, True),
]
days = np.arange(n_days, dtype=np.int64)
weekly = 1.0 + 0.22 * np.sin(2.0 * np.pi * days / 7.0) + 0.10 * np.cos(2.0 * np.pi * days / 7.0)
trend = 1.0 + 0.0012 * days
# Pre-announced promo schedule (tau_announced <= t_origin) vs unannounced flash markdowns
announced_promo_global = ((days % 28) >= 18) & ((days % 28) <= 21)
flash_days = rng.random(n_days) < 0.14
rows: list[dict[str, Any]] = []
for sku_id, sku_idx, arch, base_lvl, c_u, c_o, is_int in skus:
q_star = newsvendor_critical_fractile(c_u, c_o)
for store_idx, (store_id, region_id, store_mult) in enumerate(stores):
ann_promo = announced_promo_global.astype(np.float64)
flash_disc = np.where(flash_days & (rng.random(n_days) < 0.85), 1.0, 0.0)
if is_int:
occ = rng.random(n_days) < (0.28 + 0.10 * ann_promo)
gamma_sizes = rng.gamma(shape=2.2, scale=base_lvl / 2.2, size=n_days)
demand = np.where(occ, np.maximum(1.0, np.round(gamma_sizes, 1)), 0.0)
demand = demand * (1.0 + 0.45 * flash_disc)
else:
shock_regime = (days >= (n_days - 56)).astype(np.float64)
mean_d = (
base_lvl * store_mult * weekly * trend * (1.0 + 0.42 * ann_promo + 0.55 * flash_disc)
)
# Right-skewed Gamma demand captures real retail tail risk for both q20 & q90
gamma_shape = np.where((shock_regime > 0.5) | (ann_promo > 0.5), 3.2, 5.2)
raw = rng.gamma(shape=gamma_shape, scale=mean_d / gamma_shape)
demand = np.maximum(0.0, np.round(raw, 2))
# Simulate occasional stockout censoring (~12% of peak days)
cap = np.percentile(demand, 84) * (1.0 - 0.15 * flash_disc)
is_stockout = (demand > cap) & (not is_int)
observed_sales = np.where(is_stockout, np.round(cap, 2), demand)
for d_i in range(n_days):
rows.append(
{
"day": int(d_i),
"sku_id": sku_id,
"sku_idx": sku_idx,
"archetype": arch,
"store_id": store_id,
"store_idx": store_idx,
"region_id": region_id,
"true_demand": float(demand[d_i]),
"observed_sales": float(observed_sales[d_i]),
"is_stockout": bool(is_stockout[d_i]),
"announced_promo": float(ann_promo[d_i]),
"promo_announced_ts": int(d_i - 14), # Announced 14 days ahead
"unannounced_flash_discount": float(flash_disc[d_i]),
"flash_avail_ts": int(d_i), # Unknown before target day d_i!
"c_u": float(c_u),
"c_o": float(c_o),
"q_star": float(q_star),
}
)
return pd.DataFrame(rows).sort_values(["sku_id", "store_id", "day"]).reset_index(drop=True)
def build_causal_features(
panel_df: pd.DataFrame,
lead_time: int = 4,
include_leaky_future: bool = False,
) -> pd.DataFrame:
"""Build strict origin-anchored causal features targeting cumulative L-day demand Y^(L)."""
if lead_time < 1:
raise ValueError("lead_time must be >= 1.")
chunks: list[pd.DataFrame] = []
for (_sku, _store), grp in panel_df.groupby(["sku_id", "store_id"], sort=True):
g = grp.sort_values("day").reset_index(drop=True)
dem = g["true_demand"].to_numpy(dtype=np.float64)
ann = g["announced_promo"].to_numpy(dtype=np.float64)
flash = g["unannounced_flash_discount"].to_numpy(dtype=np.float64)
days = g["day"].to_numpy(dtype=np.int64)
n = dem.size
for t0 in range(21, n - lead_time):
hist = dem[: t0 + 1]
# Strictly causal features up to origin t0
lag_1 = float(hist[-1])
lag_7 = float(hist[-7])
roll_mean_7 = float(np.mean(hist[-7:]))
roll_mean_14 = float(np.mean(hist[-14:]))
roll_std_14 = float(np.std(hist[-14:], ddof=1))
roll_q80_21 = float(np.quantile(hist[-21:], 0.80))
zero_rate_14 = float(np.mean(hist[-14:] <= 1e-9))
# Known-future announced promotions over [t0+1 .. t0+lead_time]
ann_sum_l = float(np.sum(ann[t0 + 1 : t0 + 1 + lead_time]))
max_ann_ts = int(np.max(g["promo_announced_ts"].to_numpy()[t0 + 1 : t0 + 1 + lead_time]))
dow = int((days[t0] + 1) % 7)
# Target cumulative demand over [t0+1 .. t0+lead_time]
target_cum_l = float(np.sum(dem[t0 + 1 : t0 + 1 + lead_time]))
target_end_ts = int(days[t0 + lead_time])
row: dict[str, Any] = {
"origin_ts": int(days[t0]),
"feature_avail_ts": int(days[t0]),
"promo_announced_ts": max_ann_ts,
"target_end_ts": target_end_ts,
"sku_id": g["sku_id"].iloc[t0],
"sku_idx": int(g["sku_idx"].iloc[t0]),
"archetype": g["archetype"].iloc[t0],
"store_id": g["store_id"].iloc[t0],
"store_idx": int(g["store_idx"].iloc[t0]),
"region_id": g["region_id"].iloc[t0],
"lag_1": lag_1,
"lag_7": lag_7,
"roll_mean_7": roll_mean_7,
"roll_mean_14": roll_mean_14,
"roll_std_14": roll_std_14,
"roll_q80_21": roll_q80_21,
"zero_rate_14": zero_rate_14,
"announced_promo_L": ann_sum_l,
"dow": dow,
"c_u": float(g["c_u"].iloc[t0]),
"c_o": float(g["c_o"].iloc[t0]),
"q_star": float(g["q_star"].iloc[t0]),
"target_cum_L": target_cum_l,
}
if include_leaky_future:
row["unannounced_flash_L"] = float(np.sum(flash[t0 + 1 : t0 + 1 + lead_time]))
row["flash_avail_ts"] = int(days[t0 + lead_time])
chunks.append(pd.DataFrame([row]))
out_df = pd.concat(chunks, ignore_index=True)
return out_df.sort_values(["origin_ts", "sku_idx", "store_idx"]).reset_index(drop=True)
def audit_asof_and_leakage(
train_df: pd.DataFrame,
eval_df: pd.DataFrame,
feature_cols: list[str],
) -> dict[str, int | bool]:
"""Audit strict ASOF feature causality, promo announcement timestamps, and L-day purge gap."""
violations = 0
# 1. Purge gap check: all training target windows must complete at or before min(eval origin)
max_train_target_end = int(train_df["target_end_ts"].max())
min_eval_origin = int(eval_df["origin_ts"].min())
purge_violated = max_train_target_end > min_eval_origin
if purge_violated:
violations += int((train_df["target_end_ts"] > min_eval_origin).sum())
# 2. Past feature availability check
past_viol_tr = int((train_df["feature_avail_ts"] > train_df["origin_ts"]).sum())
past_viol_ev = int((eval_df["feature_avail_ts"] > eval_df["origin_ts"]).sum())
violations += past_viol_tr + past_viol_ev
# 3. Promo announcement availability check
promo_viol_tr = int((train_df["promo_announced_ts"] > train_df["origin_ts"]).sum())
promo_viol_ev = int((eval_df["promo_announced_ts"] > eval_df["origin_ts"]).sum())
violations += promo_viol_tr + promo_viol_ev
# 4. Forbidden future column leak check
leaky_cols = {"unannounced_flash_L", "flash_avail_ts", "target_cum_L", "target_end_ts"}
leaked_col_count = len(leaky_cols.intersection(feature_cols))
if leaked_col_count > 0:
violations += int(len(eval_df)) * leaked_col_count
return {
"asof_violations": violations,
"purge_violated": purge_violated,
"leaked_col_count": leaked_col_count,
"max_train_target_end": max_train_target_end,
"min_eval_origin": min_eval_origin,
"is_clean": violations == 0,
}
class RollingOriginPurgedBacktester:
"""Expanding-window rolling-origin backtester enforcing an L-day purge gap."""
def __init__(self, config: BacktestConfig | None = None) -> None:
self.config = config or BacktestConfig()
def split(self, feat_df: pd.DataFrame) -> list[tuple[pd.DataFrame, pd.DataFrame, int]]:
"""Yield (train_df, eval_df, fold_id) with zero target overlap across origin cutoffs."""
origins = np.sort(feat_df["origin_ts"].unique())
min_o = int(origins[0])
max_o = int(origins[-1])
first_eval = min_o + self.config.min_train_days
if first_eval >= max_o:
raise ValueError("Dataset too short for min_train_days + eval_window.")
splits: list[tuple[pd.DataFrame, pd.DataFrame, int]] = []
fold_id = 0
cur_start = first_eval
while cur_start <= max_o and fold_id < self.config.max_folds:
cur_end = cur_start + self.config.eval_window - 1
# Purge condition: training sample targets must finish strictly <= cur_start
train_mask = feat_df["target_end_ts"] <= cur_start
eval_mask = (feat_df["origin_ts"] >= cur_start) & (feat_df["origin_ts"] <= cur_end)
train_sub = feat_df.loc[train_mask].copy()
eval_sub = feat_df.loc[eval_mask].copy()
if not train_sub.empty and not eval_sub.empty:
splits.append((train_sub, eval_sub, fold_id))
fold_id += 1
cur_start += self.config.step_size
if not splits:
raise ValueError("No valid purged rolling-origin splits constructed.")
return splits
CAUSAL_FEATURE_COLS: list[str] = [
"sku_idx",
"store_idx",
"lag_1",
"lag_7",
"roll_mean_7",
"roll_mean_14",
"roll_std_14",
"roll_q80_21",
"zero_rate_14",
"announced_promo_L",
"dow",
]
class GlobalLightGBMQuantileForecaster:
"""Global panel GBDT optimizing MSE, Tweedie, and multi-quantile Pinball with monotonic fix."""
def __init__(
self,
quantiles: tuple[float, ...] = (0.10, 0.20, 0.50, 0.80, 0.90),
config: PanelModelConfig | None = None,
feature_cols: list[str] | None = None,
) -> None:
self.quantiles = quantiles
self.config = config or PanelModelConfig()
self.feature_cols = feature_cols or list(CAUSAL_FEATURE_COLS)
self.mean_model_: lgb.LGBMRegressor | None = None
self.tweedie_model_: lgb.LGBMRegressor | None = None
self.quantile_models_: dict[float, lgb.LGBMRegressor] = {}
def _base_params(self) -> dict[str, Any]:
return {
"n_estimators": self.config.n_estimators,
"learning_rate": self.config.learning_rate,
"num_leaves": self.config.num_leaves,
"min_child_samples": 10,
"subsample": 0.85,
"colsample_bytree": 0.90,
"random_state": self.config.random_state,
"n_jobs": 1,
"verbosity": -1,
}
def fit(
self,
train_df: pd.DataFrame,
target_col: str = "target_cum_L",
) -> GlobalLightGBMQuantileForecaster:
"""Fit MSE point, Tweedie, and per-tau Pinball LightGBM models on panel data."""
x_tr = train_df[self.feature_cols]
y_tr = train_df[target_col].to_numpy(dtype=np.float64)
cat_cols: list[str] = [c for c in ("sku_idx", "store_idx", "dow") if c in self.feature_cols]
self.mean_model_ = lgb.LGBMRegressor(objective="regression", **self._base_params())
self.mean_model_.fit(x_tr, y_tr, categorical_feature=cat_cols)
self.tweedie_model_ = lgb.LGBMRegressor(
objective="tweedie",
tweedie_variance_power=self.config.tweedie_power,
**self._base_params(),
)
self.tweedie_model_.fit(x_tr, np.maximum(0.0, y_tr), categorical_feature=cat_cols)
self.quantile_models_ = {}
for tau in self.quantiles:
qm = lgb.LGBMRegressor(objective="quantile", alpha=float(tau), **self._base_params())
qm.fit(x_tr, y_tr, categorical_feature=cat_cols)
self.quantile_models_[float(tau)] = qm
return self
def predict(self, eval_df: pd.DataFrame) -> dict[str, NDArray[np.float64]]:
"""Predict MSE mean, Tweedie mean, raw quantiles, and rearranged monotonic quantiles."""
if self.mean_model_ is None or self.tweedie_model_ is None:
raise RuntimeError("GlobalLightGBMQuantileForecaster must be fit before predict.")
x_ev = eval_df[self.feature_cols]
mean_pred = np.maximum(0.0, np.asarray(self.mean_model_.predict(x_ev), dtype=np.float64))
tweedie_pred = np.maximum(0.0, np.asarray(self.tweedie_model_.predict(x_ev), dtype=np.float64))
q_raw = np.column_stack(
[
np.maximum(0.0, np.asarray(self.quantile_models_[float(tau)].predict(x_ev), dtype=np.float64))
for tau in self.quantiles
]
)
q_sorted = rearrange_quantiles_monotonic(q_raw)
crossings = int(np.sum(np.diff(q_raw, axis=1) < -1e-9))
return {
"mean": mean_pred,
"tweedie": tweedie_pred,
"quantiles_raw": q_raw,
"quantiles": q_sorted,
"crossing_count": np.array([crossings], dtype=np.float64),
}
def run_stockout_censoring_experiment(seed: int = 42) -> dict[str, float]:
"""Compare naive POS-censored lag forecasting vs OSA-uncensored Newsvendor ordering."""
rng = np.random.default_rng(seed)
n_days = 140
t_arr = np.arange(n_days, dtype=np.float64)
true_demand = np.maximum(
2.0,
np.round(22.0 + 4.0 * np.sin(t_arr * 2.0 * np.pi / 7.0) + rng.normal(0.0, 4.5, n_days), 1),
)
lead_time = 2
c_u, c_o = 16.0, 2.0 # q* = 0.8889
# Policy A: Naive POS feedback (censored sales + omitting L+1 protection horizon)
on_hand_a = 12.0
pipe_a = [0.0] * lead_time
hist_sales_a = [14.0] * 7
sales_a_list: list[float] = []
stockouts_a = 0
cost_a = 0.0
for t in range(n_days):
avail = on_hand_a + pipe_a.pop(0)
d = float(true_demand[t])
sold = min(d, avail)
short = max(0.0, d - avail)
on_hand_a = max(0.0, avail - d)
if short > 1e-9 or on_hand_a <= 1e-9:
stockouts_a += 1
cost_a += c_u * short + c_o * on_hand_a
sales_a_list.append(sold)
hist_sales_a.append(sold)
naive_target = float(np.mean(hist_sales_a[-7:])) * float(lead_time)
inv_pos = on_hand_a + sum(pipe_a)
pipe_a.append(max(0.0, naive_target - inv_pos))
# Policy B: OSA-uncensored demand + Newsvendor q* safety buffer
on_hand_b = 42.0
pipe_b = [22.0] * lead_time
hist_uncensored_b = list(true_demand[:14])
sales_b_list: list[float] = []
stockouts_b = 0
cost_b = 0.0
q_star = newsvendor_critical_fractile(c_u, c_o)
for t in range(n_days):
avail = on_hand_b + pipe_b.pop(0)
d = float(true_demand[t])
sold = min(d, avail)
short = max(0.0, d - avail)
on_hand_b = max(0.0, avail - d)
is_so = short > 1e-9 or on_hand_b <= 1e-9
if is_so:
stockouts_b += 1
cost_b += c_u * short + c_o * on_hand_b
sales_b_list.append(sold)
# Uncensoring imputation using historical non-stockout upper quantile when stockout occurs
imputed = max(sold, float(np.quantile(hist_uncensored_b[-14:], 0.85))) if is_so else sold
hist_uncensored_b.append(imputed)
mu_hat = float(np.mean(hist_uncensored_b[-14:]))
sig_hat = float(np.std(hist_uncensored_b[-14:], ddof=1))
# Order-up-to target over L+1 protection window using critical fractile buffer
from scipy.stats import norm
z_star = float(norm.ppf(q_star))
target_s = (lead_time + 1) * mu_hat + z_star * float(np.sqrt(lead_time + 1)) * sig_hat * 1.15
inv_pos = on_hand_b + sum(pipe_b)
pipe_b.append(max(0.0, target_s - inv_pos))
true_mean = float(np.mean(true_demand))
naive_mean = float(np.mean(sales_a_list))
uncens_mean = float(np.mean(sales_b_list))
return {
"true_demand_mean": true_mean,
"naive_censored_sales_mean": naive_mean,
"naive_bias_pct": 100.0 * (naive_mean - true_mean) / true_mean,
"naive_stockout_rate": stockouts_a / float(n_days),
"naive_total_cost": cost_a,
"uncensored_sales_mean": uncens_mean,
"uncensored_stockout_rate": stockouts_b / float(n_days),
"uncensored_total_cost": cost_b,
"cost_reduction_pct": 100.0 * (cost_a - cost_b) / cost_a,
}
def _schafer_strimmer_cov(residuals: NDArray[np.float64]) -> tuple[NDArray[np.float64], float]:
"""Compute Schäfer-Strimmer (2005) Ledoit-Wolf shrinkage covariance of residual matrix (T x n_all)."""
t_len, n_series = residuals.shape
centered = residuals - np.mean(residuals, axis=0, keepdims=True)
emp_cov = (centered.T @ centered) / float(max(1, t_len - 1))
diag_std = np.sqrt(np.maximum(1e-12, np.diag(emp_cov)))
inv_std = 1.0 / diag_std
corr = emp_cov * np.outer(inv_std, inv_std)
np.fill_diagonal(corr, 1.0)
# Estimate variance of off-diagonal empirical correlations
norm_res = centered * inv_std
num = 0.0
den = 0.0
for i in range(n_series):
for j in range(i + 1, n_series):
prod_ij = norm_res[:, i] * norm_res[:, j]
var_rij = float(np.sum((prod_ij - corr[i, j]) ** 2) * t_len / float(max(1, (t_len - 1) ** 3)))
num += var_rij
den += float(corr[i, j] ** 2)
lam = min(1.0, max(0.0, num / max(1e-12, den))) if den > 1e-12 else 1.0
shrunk_corr = (1.0 - lam) * corr + lam * np.eye(n_series, dtype=np.float64)
w_shrink = shrunk_corr * np.outer(diag_std, diag_std)
return w_shrink, lam
class MinTReconciler:
"""Hierarchical forecast reconciler implementing Bottom-Up, MinT-OLS, WLS-Struct & MinT-Shrink."""
def __init__(self, summing_matrix: NDArray[np.float64], config: MinTConfig | None = None) -> None:
self.s_mat = np.asarray(summing_matrix, dtype=np.float64)
self.config = config or MinTConfig()
self.n_all, self.n_b = self.s_mat.shape
self.g_mat_: NDArray[np.float64] = np.zeros((self.n_b, self.n_all), dtype=np.float64)
self.shrinkage_lam_: float = 0.0
def fit(self, in_sample_residuals: NDArray[np.float64] | None = None) -> MinTReconciler:
"""Solve optimal projection G minimizing trace(S G W G^T S^T) s.t. G S = I."""
s = self.s_mat
method = self.config.method
if method == "bottom_up":
n_a = self.n_all - self.n_b
self.g_mat_ = np.hstack([np.zeros((self.n_b, n_a), dtype=np.float64), np.eye(self.n_b)])
return self
if method == "mint_ols":
w_inv = np.eye(self.n_all, dtype=np.float64)
elif method == "wls_struct":
counts = np.maximum(1.0, s.sum(axis=1))
w_inv = np.diag(1.0 / counts)
else:
if in_sample_residuals is None:
raise ValueError("MinT-Shrink requires in_sample_residuals of shape (T, n_all).")
w_shrink, lam = _schafer_strimmer_cov(np.asarray(in_sample_residuals, dtype=np.float64))
if self.config.min_shrinkage > lam:
lam = self.config.min_shrinkage
emp = np.cov(in_sample_residuals, rowvar=False)
w_shrink = (1.0 - lam) * emp + lam * np.diag(np.diag(emp))
self.shrinkage_lam_ = lam
w_inv = np.linalg.pinv(w_shrink + 1e-8 * np.eye(self.n_all))
st_winv = s.T @ w_inv
self.g_mat_ = np.linalg.solve(st_winv @ s, st_winv)
return self
def reconcile(self, base_forecasts: NDArray[np.float64]) -> NDArray[np.float64]:
"""Project base forecasts (n_all,) or (n_samples, n_all) onto coherent subspace col(S)."""
arr = np.asarray(base_forecasts, dtype=np.float64)
proj = self.s_mat @ self.g_mat_
if arr.ndim == 1:
return proj @ arr
if arr.ndim == 2:
return arr @ proj.T
raise ValueError("base_forecasts must be 1D or 2D.")
def coherence_error(self, forecasts: NDArray[np.float64]) -> float:
"""Compute max |y_top_part - A @ y_bottom| incoherence across nodes."""
arr = np.asarray(forecasts, dtype=np.float64)
n_a = self.n_all - self.n_b
agg_mat = self.s_mat[:n_a, :]
if arr.ndim == 1:
return float(np.max(np.abs(arr[:n_a] - agg_mat @ arr[n_a:])))
return float(np.max(np.abs(arr[:, :n_a] - arr[:, n_a:] @ agg_mat.T)))
def reconcile_sample_paths(
reconciler: MinTReconciler,
sample_paths: NDArray[np.float64],
tau: float = 0.90,
) -> dict[str, NDArray[np.float64]]:
"""Reconcile joint sample paths (n_draws, n_all) before extracting coherent marginal quantiles."""
paths = np.asarray(sample_paths, dtype=np.float64)
if paths.ndim != 2 or paths.shape[1] != reconciler.n_all:
raise ValueError("sample_paths must have shape (n_draws, n_all).")
coherent_paths = reconciler.reconcile(paths)
coherent_quantiles = np.quantile(coherent_paths, tau, axis=0)
naive_marginal_q = np.quantile(paths, tau, axis=0)
naive_summed_top = float(np.sum(naive_marginal_q[reconciler.n_all - reconciler.n_b :]))
return {
"coherent_quantiles": coherent_quantiles,
"naive_marginal_quantiles": naive_marginal_q,
"naive_summed_top_quantile": np.array([naive_summed_top], dtype=np.float64),
}
def run_hierarchical_mint_benchmark(seed: int = 42) -> dict[str, Any]:
"""Run controlled Total -> 2 Regions -> 4 Stores MinT reconciliation benchmark."""
rng = np.random.default_rng(seed)
# 7 series: [Total, North, South, S1, S2, S3, S4]
s_mat = np.array(
[
[1, 1, 1, 1],
[1, 1, 0, 0],
[0, 0, 1, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
dtype=np.float64,
)
t_total = 260
t_hist = 140
# True bottom demands with intra-region substitution (-0.45 correlation between S1<->S2 & S3<->S4)
cov_b = np.array(
[
[4.5, -2.0, 0.2, 0.1],
[-2.0, 4.5, 0.1, 0.2],
[0.2, 0.1, 4.5, -2.0],
[0.1, 0.2, -2.0, 4.5],
],
dtype=np.float64,
)
t_idx = np.arange(t_total, dtype=np.float64)
means_b = 20.0 + 3.0 * np.sin(2.0 * np.pi * t_idx[:, None] / 7.0) + np.array([2.0, -1.0, 1.5, 0.5])
b_true = means_b + rng.multivariate_normal(np.zeros(4), cov_b, size=t_total)
y_true = b_true @ s_mat.T
# Noisy independent base forecasts: store errors carry negative substitution covariance
noise_base = np.zeros_like(y_true)
noise_base[:, 3:] = rng.normal(0.0, 0.8, size=(t_total, 4)) + rng.multivariate_normal(
np.zeros(4), cov_b * 2.2, size=t_total
)
noise_base[:, 1:3] = rng.normal(0.0, 1.5, size=(t_total, 2))
noise_base[:, 0] = rng.normal(0.0, 1.25, size=t_total)
y_hat_base = y_true + noise_base
resid_hist = y_true[:t_hist] - y_hat_base[:t_hist]
y_eval_true = y_true[t_hist:]
y_eval_base = y_hat_base[t_hist:]
methods: tuple[Literal["bottom_up", "mint_ols", "wls_struct", "mint_shrink"], ...] = (
"bottom_up",
"mint_ols",
"wls_struct",
"mint_shrink",
)
results: dict[str, dict[str, float]] = {
"base_unreconciled": {
"top_rmse": float(np.sqrt(np.mean((y_eval_true[:, 0] - y_eval_base[:, 0]) ** 2))),
"bottom_rmse": float(np.sqrt(np.mean((y_eval_true[:, 3:] - y_eval_base[:, 3:]) ** 2))),
"all_rmse": float(np.sqrt(np.mean((y_eval_true - y_eval_base) ** 2))),
"coherence_err": float(
np.max(np.abs(y_eval_base[:, :3] - y_eval_base[:, 3:] @ s_mat[:3, :].T))
),
}
}
shrink_reconciler: MinTReconciler | None = None
for m in methods:
rec = MinTReconciler(s_mat, MinTConfig(method=m)).fit(resid_hist)
y_rec = rec.reconcile(y_eval_base)
# Check S G S == S
sgs_err = float(np.max(np.abs(s_mat @ rec.g_mat_ @ s_mat - s_mat)))
results[m] = {
"top_rmse": float(np.sqrt(np.mean((y_eval_true[:, 0] - y_rec[:, 0]) ** 2))),
"bottom_rmse": float(np.sqrt(np.mean((y_eval_true[:, 3:] - y_rec[:, 3:]) ** 2))),
"all_rmse": float(np.sqrt(np.mean((y_eval_true - y_rec) ** 2))),
"coherence_err": rec.coherence_error(y_rec),
"sgs_identity_err": sgs_err,
}
if m == "mint_shrink":
shrink_reconciler = rec
assert shrink_reconciler is not None
# Sample-path quantile reconciliation vs naive marginal P90 sum
base_draws = y_eval_base[0][None, :] + rng.multivariate_normal(
np.zeros(7), np.cov(resid_hist, rowvar=False), size=800
)
sp = reconcile_sample_paths(shrink_reconciler, base_draws, tau=0.90)
return {
"methods": results,
"shrinkage_lambda": float(shrink_reconciler.shrinkage_lam_),
"sample_path_top_p90": float(sp["coherent_quantiles"][0]),
"naive_sum_stores_p90": float(sp["naive_summed_top_quantile"][0]),
}
class AdaptiveConformalForecaster:
"""Online time-series conformal predictor: Static Split, EnbPI FIFO, and ACI (Gibbs & Candes)."""
def __init__(self, config: ACIConfig | None = None) -> None:
self.config = config or ACIConfig()
def evaluate_series(
self,
y_true: NDArray[np.float64],
q_lo_base: NDArray[np.float64],
q_hi_base: NDArray[np.float64],
cal_end_idx: int,
) -> dict[str, Any]:
"""Run online sequential interval calibration and return empirical coverage + widths."""
y = np.asarray(y_true, dtype=np.float64)
q_lo = np.asarray(q_lo_base, dtype=np.float64)
q_hi = np.asarray(q_hi_base, dtype=np.float64)
if not (y.shape == q_lo.shape == q_hi.shape):
raise ValueError("y_true, q_lo_base, q_hi_base must have matching 1D shapes.")
scores_cal = np.maximum(q_lo[:cal_end_idx] - y[:cal_end_idx], y[:cal_end_idx] - q_hi[:cal_end_idx])
hist_scores = list(scores_cal[-self.config.window_size :])
alpha_target = self.config.alpha
alpha_t = alpha_target
n_test = y.size - cal_end_idx
lower_out = np.empty(n_test, dtype=np.float64)
upper_out = np.empty(n_test, dtype=np.float64)
errs = np.empty(n_test, dtype=np.float64)
alpha_trace = np.empty(n_test, dtype=np.float64)
static_q = float(np.quantile(scores_cal, min(0.999, max(0.001, 1.0 - alpha_target))))
for idx, t in enumerate(range(cal_end_idx, y.size)):
if self.config.method == "split_conformal":
q_adj = static_q
lo_t = float(q_lo[t] - q_adj)
hi_t = float(q_hi[t] + q_adj)
err_t = 1.0 if (y[t] < lo_t or y[t] > hi_t) else 0.0
elif self.config.method == "enbpi_fifo":
q_adj = float(np.quantile(hist_scores[-self.config.window_size :], 1.0 - alpha_target))
lo_t = float(q_lo[t] - q_adj)
hi_t = float(q_hi[t] + q_adj)
err_t = 1.0 if (y[t] < lo_t or y[t] > hi_t) else 0.0
else:
# Gibbs & Candes (2021) exact ACI boundary semantics:
# alpha_t <= 0 -> C_t = R (err_t = 0); alpha_t >= 1 -> C_t = empty (err_t = 1).
if alpha_t <= 0.0:
lo_t = float("-inf")
hi_t = float("inf")
err_t = 0.0
elif alpha_t >= 1.0:
lo_t = float("inf")
hi_t = float("-inf")
err_t = 1.0
else:
eff_level = float(np.clip(1.0 - alpha_t, 0.0, 1.0))
q_adj = float(np.quantile(hist_scores[-self.config.window_size :], eff_level))
lo_t = float(q_lo[t] - q_adj)
hi_t = float(q_hi[t] + q_adj)
err_t = 1.0 if (y[t] < lo_t or y[t] > hi_t) else 0.0
lower_out[idx] = lo_t
upper_out[idx] = hi_t
errs[idx] = err_t
alpha_trace[idx] = alpha_t
new_score = float(max(q_lo[t] - y[t], y[t] - q_hi[t]))
hist_scores.append(new_score)
if self.config.method == "aci_cqr":
alpha_t = alpha_t + self.config.gamma * (alpha_target - err_t)
emp_cov = float(1.0 - np.mean(errs))
target_cov = 1.0 - alpha_target
finite_mask = np.isfinite(lower_out) & np.isfinite(upper_out)
mean_width = (
float(np.mean(upper_out[finite_mask] - lower_out[finite_mask]))
if np.any(finite_mask)
else 0.0
)
return {
"method": self.config.method,
"target_coverage": target_cov,
"empirical_coverage": emp_cov,
"coverage_error_abs": float(abs(emp_cov - target_cov)),
"mean_width": mean_width,
"infinite_interval_frac": float(np.mean(np.isneginf(lower_out) & np.isposinf(upper_out))),
"empty_interval_frac": float(np.mean(np.isposinf(lower_out) & np.isneginf(upper_out))),
"lower": lower_out,
"upper": upper_out,
"alpha_trace": alpha_trace,
}
def run_aci_regime_shift_benchmark(seed: int = 42) -> dict[str, Any]:
"""Compare Static Split Conformal vs EnbPI vs Online ACI across a 2.75x promo shift."""
rng = np.random.default_rng(seed)
n_total = 500
cal_end = 180
shock_start, shock_end = 260, 420
t_idx = np.arange(n_total, dtype=np.float64)
base_signal = 50.0 + 8.0 * np.sin(2.0 * np.pi * t_idx / 7.0)
in_shock = (t_idx >= shock_start) & (t_idx < shock_end)
noise_sd = np.where(in_shock, 5.6, 2.0)
shift = np.where(in_shock, 3.8, 0.0)
y = base_signal + shift + rng.normal(0.0, noise_sd)
# Base model trained on calm historical uncertainty
q_lo = base_signal - 2.6
q_hi = base_signal + 2.6
static_res = AdaptiveConformalForecaster(ACIConfig(alpha=0.10, method="split_conformal")).evaluate_series(
y, q_lo, q_hi, cal_end
)
enbpi_res = AdaptiveConformalForecaster(
ACIConfig(alpha=0.10, window_size=50, method="enbpi_fifo")
).evaluate_series(y, q_lo, q_hi, cal_end)
aci_res = AdaptiveConformalForecaster(
ACIConfig(alpha=0.10, gamma=0.06, window_size=50, method="aci_cqr")
).evaluate_series(y, q_lo, q_hi, cal_end)
shock_slice = slice(shock_start - cal_end, shock_end - cal_end)
y_shk = y[shock_start:shock_end]
static_shock_cov = float(
np.mean((y_shk >= static_res["lower"][shock_slice]) & (y_shk <= static_res["upper"][shock_slice]))
)
aci_shock_cov = float(
np.mean((y_shk >= aci_res["lower"][shock_slice]) & (y_shk <= aci_res["upper"][shock_slice]))
)
return {
"target_coverage": 0.90,
"static_overall_cov": static_res["empirical_coverage"],
"static_err_abs": static_res["coverage_error_abs"],
"static_shock_cov": static_shock_cov,
"enbpi_overall_cov": enbpi_res["empirical_coverage"],
"enbpi_err_abs": enbpi_res["coverage_error_abs"],
"aci_overall_cov": aci_res["empirical_coverage"],
"aci_err_abs": aci_res["coverage_error_abs"],
"aci_shock_cov": aci_shock_cov,
"aci_mean_width": aci_res["mean_width"],
}
def run_sklearn_quantile_parity_check(seed: int = 42) -> dict[str, float]:
"""Compare Tier 1 linear Pinball optimization vs Tier 2 scikit-learn QuantileRegressor."""
rng = np.random.default_rng(seed)
n = 320
x = rng.normal(0.0, 1.0, size=(n, 3))
y = 10.0 + 2.5 * x[:, 0] - 1.2 * x[:, 1] + rng.gamma(2.0, 1.5, size=n)
tau = 0.85
sk_qr = QuantileRegressor(quantile=tau, alpha=0.0).fit(x[:220], y[:220])
pred_sk = sk_qr.predict(x[220:])
pinball_sk = pinball_loss(y[220:], pred_sk, tau)
# Pure NumPy IRLS convergence check matching exact LP QuantileRegressor
x_tr_b = np.column_stack([np.ones(220), x[:220]])
x_ev_b = np.column_stack([np.ones(100), x[220:]])
w = np.linalg.lstsq(x_tr_b, y[:220], rcond=None)[0]
for _ in range(90):
r = y[:220] - x_tr_b @ w
weights = np.where(r >= 0.0, tau, 1.0 - tau) / np.maximum(1e-6, np.abs(r))
xw = x_tr_b * weights[:, None]
w = np.linalg.solve(xw.T @ x_tr_b + 1e-8 * np.eye(4), xw.T @ y[:220])
pred_np = x_ev_b @ w
pinball_np = pinball_loss(y[220:], pred_np, tau)
return {
"sklearn_pinball_loss": pinball_sk,
"numpy_irls_pinball_loss": pinball_np,
"max_pred_diff": float(np.max(np.abs(pred_sk - pred_np))),
}
def run_full_ch13_lab06_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute full Ch 13 + Lab 06 verification pipeline and format workbench_panels."""
panel = generate_retail_demand_panel(seed=seed, quick=quick)
lead_time = 4
causal_df = build_causal_features(panel, lead_time=lead_time, include_leaky_future=False)
leaky_df = build_causal_features(panel, lead_time=lead_time, include_leaky_future=True)
backtester = RollingOriginPurgedBacktester(
BacktestConfig(
lead_time=lead_time,
min_train_days=68 if quick else 84,
eval_window=20,
step_size=24,
max_folds=3 if quick else 4,
)
)
splits = backtester.split(causal_df)
model_cfg = PanelModelConfig(n_estimators=90 if quick else 130, random_state=seed)
total_asof_violations = 0
mse_costs: list[float] = []
pinball_costs: list[float] = []
hi_mse_costs: list[float] = []
hi_pin_costs: list[float] = []
per_mse_costs: list[float] = []
per_pin_costs: list[float] = []
purged_rmses: list[float] = []
crossing_raw_total = 0
crossing_fixed_total = 0
for train_sub, eval_sub, _fold_id in splits:
audit = audit_asof_and_leakage(train_sub, eval_sub, CAUSAL_FEATURE_COLS)
total_asof_violations += int(audit["asof_violations"])
assert audit["is_clean"], f"ASOF leakage detected: {audit}"
forecaster = GlobalLightGBMQuantileForecaster(
quantiles=(0.10, 0.20, 0.50, 0.80, 0.90),
config=model_cfg,
feature_cols=CAUSAL_FEATURE_COLS,
).fit(train_sub)
preds = forecaster.predict(eval_sub)
crossing_raw_total += int(preds["crossing_count"][0])
crossing_fixed_total += int(np.sum(np.diff(preds["quantiles"], axis=1) < -1e-9))
y_ev = eval_sub["target_cum_L"].to_numpy(dtype=np.float64)
q_mat = preds["quantiles"]
mean_hat = preds["mean"]
purged_rmses.append(float(np.sqrt(np.mean((y_ev - mean_hat) ** 2))))
# Match each row's exact Newsvendor fractile q* to nearest modeled quantile column
taus_arr = np.array([0.10, 0.20, 0.50, 0.80, 0.90])
q_stars = eval_sub["q_star"].to_numpy(dtype=np.float64)
c_u_arr = eval_sub["c_u"].to_numpy(dtype=np.float64)
c_o_arr = eval_sub["c_o"].to_numpy(dtype=np.float64)
chosen_idx = np.argmin(np.abs(taus_arr[None, :] - q_stars[:, None]), axis=1)
pin_order = q_mat[np.arange(y_ev.size), chosen_idx]
row_mse_cost = c_u_arr * np.maximum(0.0, y_ev - mean_hat) + c_o_arr * np.maximum(
0.0, mean_hat - y_ev
)
row_pin_cost = c_u_arr * np.maximum(0.0, y_ev - pin_order) + c_o_arr * np.maximum(
0.0, pin_order - y_ev
)
mse_costs.append(float(np.mean(row_mse_cost)))
pinball_costs.append(float(np.mean(row_pin_cost)))
hi_mask = eval_sub["sku_id"].to_numpy() == "SKU_HI"
per_mask = eval_sub["sku_id"].to_numpy() == "SKU_PER"
if np.any(hi_mask):
hi_mse_costs.append(float(np.mean(row_mse_cost[hi_mask])))
hi_pin_costs.append(float(np.mean(row_pin_cost[hi_mask])))
if np.any(per_mask):
per_mse_costs.append(float(np.mean(row_mse_cost[per_mask])))
per_pin_costs.append(float(np.mean(row_pin_cost[per_mask])))
mean_mse_cost = float(np.mean(mse_costs))
mean_pin_cost = float(np.mean(pinball_costs))
cost_reduction_pct = 100.0 * (mean_mse_cost - mean_pin_cost) / max(1e-9, mean_mse_cost)
hi_cost_cut_pct = 100.0 * (float(np.mean(hi_mse_costs)) - float(np.mean(hi_pin_costs))) / max(
1e-9, float(np.mean(hi_mse_costs))
)
per_cost_cut_pct = 100.0 * (float(np.mean(per_mse_costs)) - float(np.mean(per_pin_costs))) / max(
1e-9, float(np.mean(per_mse_costs))
)
# Leaky K-Fold + unannounced flash discount contrast benchmark
leaky_cols = CAUSAL_FEATURE_COLS + ["unannounced_flash_L"]
leaky_pre = leaky_df[leaky_df["origin_ts"] < int(leaky_df["origin_ts"].quantile(0.75))]
leaky_oot = leaky_df[leaky_df["origin_ts"] >= int(leaky_df["origin_ts"].quantile(0.75))]
kf = KFold(n_splits=3, shuffle=True, random_state=seed)
tr_idx, va_idx = next(kf.split(leaky_pre))
leaky_tr = leaky_pre.iloc[tr_idx]
leaky_va = leaky_pre.iloc[va_idx]
leaky_audit = audit_asof_and_leakage(leaky_tr, leaky_va, leaky_cols)
leaky_model = GlobalLightGBMQuantileForecaster(
config=model_cfg, feature_cols=leaky_cols
).fit(leaky_tr)
leaky_offline_rmse = float(
np.sqrt(np.mean((leaky_va["target_cum_L"].to_numpy() - leaky_model.predict(leaky_va)["mean"]) ** 2))
)
# At live order time, unannounced flash discounts are unavailable (= 0)!
live_oot_blind = leaky_oot.copy()
live_oot_blind["unannounced_flash_L"] = 0.0
live_preds = leaky_model.predict(live_oot_blind)["mean"]
leaky_live_rmse = float(
np.sqrt(np.mean((live_oot_blind["target_cum_L"].to_numpy() - live_preds) ** 2))
)
purged_rmse = float(np.mean(purged_rmses))
# Additional controlled sub-benchmarks
mape_audit = audit_mape_and_mae_traps(seed=seed)
censor_res = run_stockout_censoring_experiment(seed=seed)
mint_res = run_hierarchical_mint_benchmark(seed=seed)
aci_res = run_aci_regime_shift_benchmark(seed=seed)
parity_res = run_sklearn_quantile_parity_check(seed=seed)
# Classical ETS vs Croston-SBA vs TSB baseline comparison on intermittent & calm seasonal slices
hi_series = panel[(panel["sku_id"] == "SKU_HI") & (panel["store_id"] == "S1")]["true_demand"].to_numpy()
ets = HoltWintersETS(HoltWintersConfig(seasonal_period=7)).fit(hi_series[:-70])
ets_rmse = float(np.sqrt(np.mean((hi_series[-70:-56] - ets.predict(14)["mean"]) ** 2)))
int_series = panel[(panel["sku_id"] == "SKU_INT") & (panel["store_id"] == "S1")]["true_demand"].to_numpy()
croston = CrostonSBAForecaster(CrostonSBAConfig(method="croston")).fit(int_series[:-28])
sba = CrostonSBAForecaster(CrostonSBAConfig(method="sba")).fit(int_series[:-28])
tsb = CrostonSBAForecaster(CrostonSBAConfig(method="tsb")).fit(int_series[:-28])
# Multi-period inventory simulation on SKU_HI holdout using true 4-day cumulative quantile q*=0.90
hi_hist = hi_series[:-60]
hi_eval_slice = hi_series[-60:]
cum_4d_hist = np.convolve(hi_hist, np.ones(4, dtype=np.float64), mode="valid")
mse_order_up_to = float(np.mean(cum_4d_hist))
nv_order_up_to = float(np.quantile(cum_4d_hist, 0.90))
init_stk = float(np.mean(hi_hist)) * 2.0
sim_mse = simulate_multi_period_inventory(
hi_eval_slice,
np.full(60, mse_order_up_to),
InventorySimConfig(c_u=18.0, c_o=2.0, lead_time=3, lost_sales=True, initial_stock=init_stk),
)
sim_nv = simulate_multi_period_inventory(
hi_eval_slice,
np.full(60, nv_order_up_to),
InventorySimConfig(c_u=18.0, c_o=2.0, lead_time=3, lost_sales=True, initial_stock=init_stk),
)
mint_methods = mint_res["methods"]
workbench_panels = {
"kpis": [
{
"id": "kpi_newsvendor_cost_cut",
"label": "Newsvendor Pinball q* Cost Lift",
"value": f"-{cost_reduction_pct:.1f}%",
"unit": f"(HI -{hi_cost_cut_pct:.1f}% | PER -{per_cost_cut_pct:.1f}%)",
"status": "ok",
"detail": (
f"Direct Pinball(q*) policy reduces mean L-day cost {mean_mse_cost:.1f} -> "
f"{mean_pin_cost:.1f} vs MSE mean baseline."
),
},
{
"id": "kpi_asof_purged_audit",
"label": "Lead-Time Purged ASOF Audit",
"value": f"{total_asof_violations} viol",
"unit": f"| Leaky KFold={leaky_audit['asof_violations']}",
"status": "ok",
"detail": (
f"Purged L={lead_time}d backtest RMSE={purged_rmse:.2f} vs Leaky KFold offline "
f"{leaky_offline_rmse:.2f} -> live {leaky_live_rmse:.2f}."
),
},
{
"id": "kpi_aci_conformal_coverage",
"label": "Online ACI Promo-Shock Coverage",
"value": f"{aci_res['aci_overall_cov']:.1%}",
"unit": f"(err {aci_res['aci_err_abs']:.2%} < 3%)",
"status": "ok",
"detail": (
f"Static Split Conformal collapses to {aci_res['static_overall_cov']:.1%} "
f"({aci_res['static_shock_cov']:.1%} in shock); ACI holds {aci_res['aci_shock_cov']:.1%}."
),
},
{
"id": "kpi_mint_hierarchical_coherence",
"label": "MinT-Shrink Coherence & Top RMSE",
"value": f"{mint_methods['mint_shrink']['top_rmse']:.2f}",
"unit": f"(err {mint_methods['mint_shrink']['coherence_err']:.1e})",
"status": "ok",
"detail": (
f"Base incoherence {mint_methods['base_unreconciled']['coherence_err']:.2f}, "
f"Top RMSE {mint_methods['base_unreconciled']['top_rmse']:.2f} -> MinT-Shrink "
f"{mint_methods['mint_shrink']['top_rmse']:.2f}."
),
},
{
"id": "kpi_stockout_censoring_rescue",
"label": "Stockout Censoring Spiral Rescue",
"value": (
f"{censor_res['naive_stockout_rate']:.1%} -> "
f"{censor_res['uncensored_stockout_rate']:.1%}"
),
"unit": f"(-{censor_res['cost_reduction_pct']:.1f}% cost)",
"status": "warn",
"detail": (
f"Naive censored POS lags underestimate mean {censor_res['naive_bias_pct']:.1f}% "
f"vs OSA uncensored recovery."
),
},
{
"id": "kpi_mape_mae_trap_audit",
"label": "MAPE Bias & MAE Zero-Collapse",
"value": f"{mape_audit['pair_mape_downward_bias_pct']:.1f}% | MAE=0.0",
"unit": f"({mape_audit['intermittent_zero_fraction']:.0%} zeros)",
"status": "critical",
"detail": (
"MAPE optimum on {1,10} picks 1.0 (-81.8% vs 5.5); MAE picks 0.0 on 70%+ sparse SKUs."
),
},
],
"bars": [
{
"id": "bar_newsvendor_vs_mse_cost",
"title": "Newsvendor Pinball(q*) vs MSE Mean Decision Cost (Lower is Better)",
"metric_label": "Mean Decision Cost",
"items": [
{
"label": "mse_mean_portfolio",
"value": mean_mse_cost,
"display": f"{mean_mse_cost:.2f}",
"css_class": "is-slow",
},
{
"label": "pinball_qstar_portfolio",
"value": mean_pin_cost,
"display": f"{mean_pin_cost:.2f} (-{cost_reduction_pct:.1f}%)",
"css_class": "is-fast",
},
{
"label": "sku_hi_mse_vs_q90",
"value": float(np.mean(hi_mse_costs)),
"display": (
f"MSE {float(np.mean(hi_mse_costs)):.1f} "
f"vs q90 {float(np.mean(hi_pin_costs)):.1f}"
),
"css_class": "is-mid",
},
{
"label": "sku_per_mse_vs_q20",
"value": float(np.mean(per_mse_costs)),
"display": (
f"MSE {float(np.mean(per_mse_costs)):.1f} "
f"vs q20 {float(np.mean(per_pin_costs)):.1f}"
),
"css_class": "is-mid",
},
],
},
{
"id": "bar_conformal_coverage_shift",
"title": "Conformal Empirical Coverage Across Promo Volatility Shock (Target = 90.0%)",
"metric_label": "Coverage",
"items": [
{
"label": "static_split_in_shock",
"value": aci_res["static_shock_cov"],
"display": f"{aci_res['static_shock_cov']:.1%} (FAIL)",
"css_class": "is-slow",
},
{
"label": "static_split_overall",
"value": aci_res["static_overall_cov"],
"display": f"{aci_res['static_overall_cov']:.1%}",
"css_class": "is-slow",
},
{
"label": "enbpi_fifo_overall",
"value": aci_res["enbpi_overall_cov"],
"display": f"{aci_res['enbpi_overall_cov']:.1%}",
"css_class": "is-mid",
},
{
"label": "online_aci_cqr_overall",
"value": aci_res["aci_overall_cov"],
"display": f"{aci_res['aci_overall_cov']:.1%} (shock {aci_res['aci_shock_cov']:.1%})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_mint_hierarchical_rmse",
"title": "Hierarchical Reconciliation Top-Level RMSE (Total -> Region -> 4 Stores)",
"metric_label": "Top-Level RMSE",
"items": [
{
"label": "naive_bottom_up",
"value": mint_methods["bottom_up"]["top_rmse"],
"display": f"{mint_methods['bottom_up']['top_rmse']:.2f}",
"css_class": "is-slow",
},
{
"label": "base_unreconciled",
"value": mint_methods["base_unreconciled"]["top_rmse"],
"display": (
f"{mint_methods['base_unreconciled']['top_rmse']:.2f} "
f"(incoh {mint_methods['base_unreconciled']['coherence_err']:.2f})"
),
"css_class": "is-mid",
},
{
"label": "mint_ols",
"value": mint_methods["mint_ols"]["top_rmse"],
"display": f"{mint_methods['mint_ols']['top_rmse']:.2f}",
"css_class": "is-fast",
},
{
"label": "mint_shrink",
"value": mint_methods["mint_shrink"]["top_rmse"],
"display": (
f"{mint_methods['mint_shrink']['top_rmse']:.2f} "
f"(lam={mint_res['shrinkage_lambda']:.2f})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_censoring_and_leakage_rmse",
"title": "Stockout Censoring Rate & Leaky vs Purged Backtest Gap",
"metric_label": "Rate / RMSE",
"items": [
{
"label": "naive_censored_stockout",
"value": censor_res["naive_stockout_rate"],
"display": f"Stockout {censor_res['naive_stockout_rate']:.1%}",
"css_class": "is-slow",
},
{
"label": "uncensored_nv_stockout",
"value": censor_res["uncensored_stockout_rate"],
"display": f"Stockout {censor_res['uncensored_stockout_rate']:.1%}",
"css_class": "is-fast",
},
{
"label": "leaky_kfold_offline_rmse",
"value": leaky_offline_rmse / 25.0,
"display": f"Offline {leaky_offline_rmse:.2f} -> Live {leaky_live_rmse:.2f}",
"css_class": "is-mid",
},
{
"label": "purged_rolling_rmse",
"value": purged_rmse / 25.0,
"display": f"Honest Purged {purged_rmse:.2f}",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_newsvendor_and_metrics",
"title": "Newsvendor Asymmetric Decision Cost vs Point Baselines (Purged L=4 Backtest)",
"columns": ["SKU / Regime", "Critical q*", "MSE Cost", "Pinball(q*) Cost", "Cost Reduction"],
"rows": [
[
"Portfolio Pooled",
"Mixed (0.20..0.90)",
f"{mean_mse_cost:.2f}",
f"{mean_pin_cost:.2f}",
f"-{cost_reduction_pct:.1f}%",
],
[
"SKU_HI (High-Margin)",
"0.90 (c_u=18, c_o=2)",
f"{float(np.mean(hi_mse_costs)):.2f}",
f"{float(np.mean(hi_pin_costs)):.2f}",
f"-{hi_cost_cut_pct:.1f}%",
],
[
"SKU_PER (Perishable)",
"0.20 (c_u=3, c_o=12)",
f"{float(np.mean(per_mse_costs)):.2f}",
f"{float(np.mean(per_pin_costs)):.2f}",
f"-{per_cost_cut_pct:.1f}%",
],
[
"Multi-Period Sim (L=3)",
"0.90 Lost-Sales",
f"{float(sim_mse['total_cost']):.1f}",
f"{float(sim_nv['total_cost']):.1f}",
f"{float(sim_nv['fill_rate']):.1%} fill",
],
],
},
{
"id": "tbl_backtest_and_censoring",
"title": "Rolling-Origin Lead-Time Purge Audit & Stockout Censoring Spiral",
"columns": ["Audit Scenario", "ASOF Violations", "Offline vs Live", "Stockout / Bias"],
"rows": [
[
"Purged Rolling-Origin (L=4)",
f"{total_asof_violations} (PASS)",
f"RMSE {purged_rmse:.2f} -> {purged_rmse:.2f}",
"0 future leaks",
],
[
"Leaky K-Fold + Future Flash",
f"{leaky_audit['asof_violations']} (FAIL)",
f"RMSE {leaky_offline_rmse:.2f} -> {leaky_live_rmse:.2f}",
"Collapses live",
],
[
"Naive Censored POS Lags",
"—",
f"Cost {censor_res['naive_total_cost']:.1f}",
f"SO {censor_res['naive_stockout_rate']:.1%} ({censor_res['naive_bias_pct']:.1f}%)",
],
[
"OSA Uncensored + q* Buffer",
"—",
f"Cost {censor_res['uncensored_total_cost']:.1f}",
(
f"SO {censor_res['uncensored_stockout_rate']:.1%} "
f"(-{censor_res['cost_reduction_pct']:.1f}%)"
),
],
],
},
{
"id": "tbl_mint_hierarchy",
"title": "Hierarchical Reconciliation Comparison (Total -> 2 Regions -> 4 Stores)",
"columns": ["Method", "Top RMSE", "Bottom RMSE", "Coherence Err", "S*G*S - S Err"],
"rows": [
[
"Base Unreconciled",
f"{mint_methods['base_unreconciled']['top_rmse']:.3f}",
f"{mint_methods['base_unreconciled']['bottom_rmse']:.3f}",
f"{mint_methods['base_unreconciled']['coherence_err']:.3f}",
"—",
],
[
"Bottom-Up",
f"{mint_methods['bottom_up']['top_rmse']:.3f}",
f"{mint_methods['bottom_up']['bottom_rmse']:.3f}",
f"{mint_methods['bottom_up']['coherence_err']:.2e}",
f"{mint_methods['bottom_up']['sgs_identity_err']:.2e}",
],
[
"MinT-OLS",
f"{mint_methods['mint_ols']['top_rmse']:.3f}",
f"{mint_methods['mint_ols']['bottom_rmse']:.3f}",
f"{mint_methods['mint_ols']['coherence_err']:.2e}",
f"{mint_methods['mint_ols']['sgs_identity_err']:.2e}",
],
[
"MinT-Shrink",
f"{mint_methods['mint_shrink']['top_rmse']:.3f}",
f"{mint_methods['mint_shrink']['bottom_rmse']:.3f}",
f"{mint_methods['mint_shrink']['coherence_err']:.2e}",
f"{mint_methods['mint_shrink']['sgs_identity_err']:.2e}",
],
],
},
{
"id": "tbl_conformal_and_intermittent",
"title": "Conformal Time-Series Adaptation & Intermittent Demand Sanity",
"columns": ["Wrapper / Estimator", "Target / True", "Observed Metric", "Deviation / Notes"],
"rows": [
[
"Static Split Conformal",
"90.0% Cov",
f"{aci_res['static_overall_cov']:.1%} (Shock {aci_res['static_shock_cov']:.1%})",
f"Err {aci_res['static_err_abs']:.2%} (FAIL)",
],
[
"EnbPI FIFO Window (W=50)",
"90.0% Cov",
f"{aci_res['enbpi_overall_cov']:.1%}",
f"Err {aci_res['enbpi_err_abs']:.2%}",
],
[
"Online ACI-CQR (gamma=0.06)",
"90.0% Cov",
f"{aci_res['aci_overall_cov']:.1%} (Shock {aci_res['aci_shock_cov']:.1%})",
f"Err {aci_res['aci_err_abs']:.2%} (<3% PASS)",
],
[
"ETS / Croston-SBA / TSB",
f"Int Mean {float(np.mean(int_series[:-28])):.2f}",
f"ETS={ets_rmse:.2f} | SBA={float(sba.predict(1)[0]):.2f}",
f"Croston={float(croston.predict(1)[0]):.2f} | TSB={float(tsb.predict(1)[0]):.2f}",
],
],
},
],
}
return {
"config": {"seed": seed, "quick": quick, "lead_time": lead_time},
"workbench_panels": workbench_panels,
"newsvendor_backtest": {
"mean_mse_cost": mean_mse_cost,
"mean_pinball_cost": mean_pin_cost,
"cost_reduction_pct": cost_reduction_pct,
"hi_mse_cost": float(np.mean(hi_mse_costs)),
"hi_pinball_cost": float(np.mean(hi_pin_costs)),
"hi_cost_cut_pct": hi_cost_cut_pct,
"per_mse_cost": float(np.mean(per_mse_costs)),
"per_pinball_cost": float(np.mean(per_pin_costs)),
"per_cost_cut_pct": per_cost_cut_pct,
"crossing_raw_total": crossing_raw_total,
"crossing_fixed_total": crossing_fixed_total,
"purged_rmse": purged_rmse,
"asof_violations": total_asof_violations,
"leaky_asof_violations": int(leaky_audit["asof_violations"]),
"leaky_offline_rmse": leaky_offline_rmse,
"leaky_live_rmse": leaky_live_rmse,
},
"mape_traps": mape_audit,
"censoring_audit": censor_res,
"hierarchical_mint": mint_res,
"conformal_aci": aci_res,
"tier2_parity": parity_res,
"classical_baselines": {
"ets_hi_rmse": ets_rmse,
"intermittent_true_mean": float(np.mean(int_series[:-28])),
"croston_pred": float(croston.predict(1)[0]),
"sba_pred": float(sba.predict(1)[0]),
"tsb_pred": float(tsb.predict(1)[0]),
"multi_period_sim_mse_cost": float(sim_mse["total_cost"]),
"multi_period_sim_nv_cost": float(sim_nv["total_cost"]),
"multi_period_sim_nv_fill_rate": float(sim_nv["fill_rate"]),
},
}
"""End-to-end CLI benchmark runner for Lab 06: Retail Demand Planning & Cost-Aware Backtesting."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import demand_forecast_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from demand_forecast_lab.decision_backtest import run_full_ch13_lab06_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for Lab 06 Demand Forecasting & Decision-Cost Backtest."""
parser = argparse.ArgumentParser(
description="Run Ch 13 + Lab 06: Retail Demand Forecasting, Newsvendor Costs & Purged Backtest."
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample sizes for fast CI verification.",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch13_lab06_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute benchmarks, print formatted summary telemetry, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch13_lab06_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
nv = payload["newsvendor_backtest"]
mp = payload["mape_traps"]
cs = payload["censoring_audit"]
mt = payload["hierarchical_mint"]["methods"]
ac = payload["conformal_aci"]
print("=== Ch 13 + Lab 06: Retail Demand Planning & Decision-Cost Backtesting ===")
print(
f"[1] Newsvendor Pinball(q*) vs MSE Mean: "
f"Cost {nv['mean_mse_cost']:.2f} -> {nv['mean_pinball_cost']:.2f} "
f"(-{nv['cost_reduction_pct']:.1f}% | HI -{nv['hi_cost_cut_pct']:.1f}% | "
f"PER -{nv['per_cost_cut_pct']:.1f}%)"
)
print(
f"[2] Purged Backtest (L={payload['config']['lead_time']}d): "
f"ASOF Violations={nv['asof_violations']} (Purged RMSE={nv['purged_rmse']:.2f}) "
f"| Leaky KFold Violations={nv['leaky_asof_violations']} "
f"(Offline {nv['leaky_offline_rmse']:.2f} -> Live {nv['leaky_live_rmse']:.2f})"
)
print(
f"[3] Traps & Censoring: MAPE Bias={mp['pair_mape_downward_bias_pct']:.1f}%, "
f"MAE opt={mp['intermittent_mae_optimal_const']:.1f} ({mp['intermittent_zero_fraction']:.0%} zeros) "
f"| Stockout Spiral {cs['naive_stockout_rate']:.1%} -> {cs['uncensored_stockout_rate']:.1%}"
)
print(
f"[4] MinT & Online ACI: Base Top RMSE {mt['base_unreconciled']['top_rmse']:.2f} -> "
f"MinT-Shrink {mt['mint_shrink']['top_rmse']:.2f} "
f"(Coherence={mt['mint_shrink']['coherence_err']:.2e}) "
f"| Static Conf={ac['static_overall_cov']:.1%} (Shock {ac['static_shock_cov']:.1%}) "
f"-> ACI={ac['aci_overall_cov']:.1%} (Err={ac['aci_err_abs']:.2%})"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 automated unit, mathematical, anti-leakage, Tier-2 parity & AST security tests for Lab 06."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
from demand_forecast_lab.decision_backtest import (
CAUSAL_FEATURE_COLS,
ACIConfig,
AdaptiveConformalForecaster,
BacktestConfig,
GlobalLightGBMQuantileForecaster,
MinTConfig,
MinTReconciler,
PanelModelConfig,
RollingOriginPurgedBacktester,
audit_asof_and_leakage,
build_causal_features,
generate_retail_demand_panel,
reconcile_sample_paths,
run_aci_regime_shift_benchmark,
run_full_ch13_lab06_benchmarks,
run_hierarchical_mint_benchmark,
run_sklearn_quantile_parity_check,
run_stockout_censoring_experiment,
)
from demand_forecast_lab.forecasting_core import (
CrostonSBAConfig,
CrostonSBAForecaster,
HoltWintersConfig,
HoltWintersETS,
InventorySimConfig,
NewsvendorConfig,
StationarityConfig,
audit_mape_and_mae_traps,
boxcox_bias_corrected_mean,
check_stationarity_adf_kpss,
compute_crps_from_quantiles,
compute_mase,
compute_wql,
newsvendor_cost,
newsvendor_critical_fractile,
pinball_loss,
rearrange_quantiles_monotonic,
seasonal_decompose_stl_ref,
simulate_multi_period_inventory,
tweedie_grad_hess,
tweedie_unit_deviance,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
# ---------------------------------------------------------------------------
# Test 1: Strict Pydantic v2 Extra-Forbid Contracts & Bounds
# ---------------------------------------------------------------------------
def test_01_pydantic_configs_strict_forbid() -> None:
with pytest.raises(ValidationError):
StationarityConfig(unknown_arg=1) # type: ignore[call-arg]
with pytest.raises(ValidationError):
NewsvendorConfig(c_u=-1.0, c_o=2.0)
with pytest.raises(ValidationError):
PanelModelConfig(tweedie_power=2.5) # strictly 1 < p < 2
with pytest.raises(ValidationError):
ACIConfig(alpha=0.8) # strictly < 0.50
with pytest.raises(ValidationError):
BacktestConfig(lead_time=0)
nv = NewsvendorConfig(c_u=18.0, c_o=2.0)
assert nv.critical_fractile == pytest.approx(0.90)
# ---------------------------------------------------------------------------
# Test 2: Stationarity ADF/KPSS & Additive STL Decomposition
# ---------------------------------------------------------------------------
def test_02_stationarity_adf_kpss_and_stl_decomposition() -> None:
rng = np.random.default_rng(42)
n = 160
eps = rng.normal(0.0, 1.0, size=n)
# Stationary AR(1)
ar1 = np.zeros(n)
for t in range(1, n):
ar1[t] = 0.45 * ar1[t - 1] + eps[t]
res_stat = check_stationarity_adf_kpss(ar1, StationarityConfig(adf_lags=2, trend="c"))
assert res_stat["adf_rejects_unit_root"] is True
assert res_stat["kpss_rejects_stationarity"] is False
assert res_stat["regime"] == "stationary"
# Unit-root random walk
rw = np.cumsum(eps)
res_rw = check_stationarity_adf_kpss(rw, StationarityConfig(adf_lags=2, trend="c"))
assert res_rw["adf_rejects_unit_root"] is False
assert res_rw["kpss_rejects_stationarity"] is True
assert res_rw["regime"] == "unit_root"
# STL decomposition recovers additive trend + weekly seasonality + spike remainder
t_idx = np.arange(n, dtype=np.float64)
trend_true = 20.0 + 0.15 * t_idx
seas_true = 6.0 * np.sin(2.0 * np.pi * t_idx / 7.0)
y_stl = trend_true + seas_true + rng.normal(0.0, 0.4, size=n)
y_stl[50] += 18.0 # outlier promo spike
decomp = seasonal_decompose_stl_ref(y_stl, period=7, n_inner=2, n_outer=3)
assert np.allclose(decomp["trend"] + decomp["seasonal"] + decomp["remainder"], y_stl, atol=1e-10)
assert np.corrcoef(decomp["seasonal"], seas_true)[0, 1] > 0.96
assert decomp["robust_weights"][50] < 0.25
# ---------------------------------------------------------------------------
# Test 3: Holt-Winters ETS & Box-Cox Jensen Bias Correction
# ---------------------------------------------------------------------------
def test_03_holtwinters_ets_and_boxcox_jensen_correction() -> None:
rng = np.random.default_rng(7)
n = 112
t_idx = np.arange(n, dtype=np.float64)
y = 50.0 + 0.3 * t_idx + 8.0 * np.sin(2.0 * np.pi * t_idx / 7.0) + rng.normal(0.0, 1.0, size=n)
ets = HoltWintersETS(HoltWintersConfig(seasonal_period=7, alpha=0.35, beta=0.05, gamma=0.25)).fit(y[:-14])
fc = ets.predict(horizon=14)
rmse = float(np.sqrt(np.mean((y[-14:] - fc["mean"]) ** 2)))
assert rmse < 3.0
assert np.all(np.diff(fc["std"]) >= -1e-12) # uncertainty grows with horizon
# Jensen bias correction strictly exceeds naive median back-transform when var > 0 and lam < 1
naive_log, corr_log = boxcox_bias_corrected_mean(mu_z=np.array([2.0]), var_z=np.array([0.36]), lam=0.0)
assert float(corr_log[0]) == pytest.approx(float(np.exp(2.0 + 0.18)), rel=1e-10)
assert float(corr_log[0]) > float(naive_log[0])
naive_bc, corr_bc = boxcox_bias_corrected_mean(mu_z=np.array([3.0]), var_z=np.array([0.40]), lam=0.5)
assert float(corr_bc[0]) > float(naive_bc[0])
# ---------------------------------------------------------------------------
# Test 4: MAPE Downward Harmonic Bias & MAE Zero-Collapse Traps
# ---------------------------------------------------------------------------
def test_04_mape_downward_bias_and_mae_zero_collapse_traps() -> None:
audit = audit_mape_and_mae_traps(seed=42)
assert audit["pair_true_mean"] == pytest.approx(5.5)
assert audit["pair_mape_optimal"] == pytest.approx(1.0, abs=0.06)
assert audit["pair_mape_downward_bias_pct"] < -75.0
# When zero rate > 50%, MAE optimal constant forecast collapses to 0.0!
assert audit["intermittent_zero_fraction"] > 0.65
assert audit["intermittent_mae_optimal_const"] == pytest.approx(0.0, abs=1e-6)
assert audit["intermittent_mae_at_zero"] < audit["intermittent_mae_at_mean"]
# RMSSE avoids zero-collapse and strictly prefers true mean over predicting zero!
assert audit["intermittent_rmsse_at_mean"] < audit["intermittent_rmsse_at_zero"]
# ---------------------------------------------------------------------------
# Test 5: Croston Upward Bias vs SBA, TSB Dead-Stock Decay & Tweedie Convexity
# ---------------------------------------------------------------------------
def test_05_croston_sba_bias_correction_and_tweedie_convexity() -> None:
rng = np.random.default_rng(42)
# Generate stationary intermittent demand with mean rate ~ 0.25 * 8.0 = 2.0
n = 4000
occ = rng.random(n) < 0.25
sizes = rng.gamma(shape=4.0, scale=2.0, size=n)
y = np.where(occ, sizes, 0.0)
true_rate = float(np.mean(y))
c_cfg = CrostonSBAConfig(method="croston", alpha_size=0.25, alpha_interval=0.25)
s_cfg = CrostonSBAConfig(method="sba", alpha_size=0.25, alpha_interval=0.25)
croston = CrostonSBAForecaster(c_cfg).fit(y)
sba = CrostonSBAForecaster(s_cfg).fit(y)
c_pred = float(croston.fitted_[500:].mean())
sba_pred = float(sba.fitted_[500:].mean())
assert abs(sba_pred - true_rate) < abs(c_pred - true_rate)
assert sba_pred == pytest.approx((1.0 - 0.25 / 2.0) * c_pred, rel=1e-10)
# Dead-stock streak: Croston/SBA freeze while TSB decays toward 0
y_dead = np.concatenate([y[:200], np.zeros(80)])
sba_dead = CrostonSBAForecaster(
CrostonSBAConfig(method="sba", alpha_size=0.2, alpha_interval=0.2)
).fit(y_dead)
tsb_dead = CrostonSBAForecaster(
CrostonSBAConfig(method="tsb", alpha_size=0.2, alpha_interval=0.2)
).fit(y_dead)
assert float(tsb_dead.predict(1)[0]) < 0.05 * float(sba_dead.predict(1)[0])
# Tweedie Hessian strictly positive and unit deviance minimized at y == mu
y_tw = np.array([0.0, 1.5, 6.2, 0.0, 3.8])
eta = np.array([-0.5, 0.4, 1.8, 0.0, 1.2])
grad, hess = tweedie_grad_hess(y_tw, eta, power=1.35)
assert grad.shape == y_tw.shape
assert np.all(hess > 0.0)
assert tweedie_unit_deviance(y_tw, np.maximum(1e-6, y_tw), power=1.35) < tweedie_unit_deviance(
y_tw, np.full_like(y_tw, 3.0), power=1.35
)
# ---------------------------------------------------------------------------
# Test 6: Exact Pinball <-> Newsvendor Identity & Monotone Quantile Sorting
# ---------------------------------------------------------------------------
def test_06_pinball_newsvendor_exact_identity_and_quantile_sorting() -> None:
rng = np.random.default_rng(11)
y = rng.gamma(shape=3.0, scale=4.0, size=500)
q_ord = rng.uniform(2.0, 22.0, size=500)
c_u, c_o = 14.0, 3.5
q_star = newsvendor_critical_fractile(c_u, c_o)
nv_cost = newsvendor_cost(y, q_ord, c_u, c_o)
pin_cost = (c_u + c_o) * pinball_loss(y, q_ord, q_star)
assert nv_cost == pytest.approx(pin_cost, abs=1e-12)
# Chernozhukov monotone rearrangement eliminates crossings and never increases Pinball loss
taus = np.array([0.1, 0.5, 0.9])
q_true = np.column_stack([np.quantile(y, t) for t in taus]) + rng.normal(0.0, 1.2, size=(500, 3))
# Force crossings explicitly
q_crossed = q_true.copy()
q_crossed[:80, 0] = q_crossed[:80, 1] + 2.5
assert np.any(np.diff(q_crossed, axis=1) < 0.0)
q_fixed = rearrange_quantiles_monotonic(q_crossed)
assert np.all(np.diff(q_fixed, axis=1) >= -1e-12)
loss_before = sum(pinball_loss(y, q_crossed[:, j], float(taus[j])) for j in range(3))
loss_after = sum(pinball_loss(y, q_fixed[:, j], float(taus[j])) for j in range(3))
assert loss_after <= loss_before + 1e-12
# ---------------------------------------------------------------------------
# Test 7: Newsvendor Pinball Policy Reduces Cost by >= 12% vs MSE Mean Baseline
# ---------------------------------------------------------------------------
def test_07_newsvendor_quantile_policy_beats_mse_by_ge_12pct() -> None:
res = run_full_ch13_lab06_benchmarks(seed=42, quick=True)
nv = res["newsvendor_backtest"]
assert nv["cost_reduction_pct"] >= 12.0
assert nv["hi_cost_cut_pct"] >= 12.0
assert nv["per_cost_cut_pct"] >= 12.0
assert nv["crossing_fixed_total"] == 0
# ---------------------------------------------------------------------------
# Test 8: Lead-Time Purged Rolling-Origin Backtest & Zero ASOF Violations
# ---------------------------------------------------------------------------
def test_08_rolling_origin_leadtime_purge_zero_asof_violations() -> None:
panel = generate_retail_demand_panel(seed=42, quick=True)
lead_time = 4
causal_df = build_causal_features(panel, lead_time=lead_time, include_leaky_future=False)
backtester = RollingOriginPurgedBacktester(
BacktestConfig(lead_time=lead_time, min_train_days=68, eval_window=20, step_size=24, max_folds=3)
)
splits = backtester.split(causal_df)
assert len(splits) >= 2
for tr, ev, _fid in splits:
audit = audit_asof_and_leakage(tr, ev, CAUSAL_FEATURE_COLS)
assert audit["asof_violations"] == 0
assert audit["purge_violated"] is False
assert audit["max_train_target_end"] <= audit["min_eval_origin"]
assert audit["is_clean"] is True
# Confirm leaky setup triggers ASOF violation detection
leaky_df = build_causal_features(panel, lead_time=lead_time, include_leaky_future=True)
bad_audit = audit_asof_and_leakage(
leaky_df.iloc[:200],
leaky_df.iloc[150:250],
CAUSAL_FEATURE_COLS + ["unannounced_flash_L"],
)
assert bad_audit["asof_violations"] > 0
assert bad_audit["is_clean"] is False
# ---------------------------------------------------------------------------
# Test 9: Stockout Right-Censoring Death Spiral vs OSA-Uncensored Recovery
# ---------------------------------------------------------------------------
def test_09_stockout_right_censoring_spiral_vs_uncensored_recovery() -> None:
res = run_stockout_censoring_experiment(seed=42)
assert res["naive_bias_pct"] < -5.0
assert res["naive_stockout_rate"] > 0.45
assert res["uncensored_stockout_rate"] < res["naive_stockout_rate"] - 0.25
assert res["uncensored_total_cost"] < res["naive_total_cost"]
# ---------------------------------------------------------------------------
# Test 10: Hierarchical MinT Reconciliation Coherence (< 1e-9) & RMSE Lift
# ---------------------------------------------------------------------------
def test_10_mint_reconciliation_coherence_and_accuracy_lift() -> None:
mint_out = run_hierarchical_mint_benchmark(seed=42)
methods = mint_out["methods"]
assert methods["base_unreconciled"]["coherence_err"] > 0.5
for m_name in ("bottom_up", "mint_ols", "wls_struct", "mint_shrink"):
assert methods[m_name]["coherence_err"] < 1e-9
assert methods[m_name]["sgs_identity_err"] < 1e-10
assert methods["mint_shrink"]["top_rmse"] < methods["base_unreconciled"]["top_rmse"]
assert methods["mint_shrink"]["top_rmse"] < methods["bottom_up"]["top_rmse"]
# Sample-path P90 top forecast is strictly less inflated than summing store P90s
assert mint_out["sample_path_top_p90"] < mint_out["naive_sum_stores_p90"]
# ---------------------------------------------------------------------------
# Test 11: Online ACI Conformal Coverage Within < 3% Under Regime Shift
# ---------------------------------------------------------------------------
def test_11_aci_conformal_coverage_within_3pct_under_regime_shift() -> None:
aci_out = run_aci_regime_shift_benchmark(seed=42)
assert aci_out["static_err_abs"] > 0.08 # static conformal fails badly under shock
assert aci_out["static_shock_cov"] < 0.72
assert aci_out["aci_err_abs"] < 0.03 # strict < 3% target deviation gate!
assert aci_out["aci_shock_cov"] > aci_out["static_shock_cov"] + 0.10
# Verify AdaptiveConformalForecaster bounded alpha_t invariant [-gamma, 1 + gamma]
# and exact Gibbs-Candes (2021) edge semantics for alpha_t <= 0 (R) and alpha_t >= 1 (empty)
rng = np.random.default_rng(7)
y_seq = 20.0 + rng.normal(0.0, 3.0, size=180)
aci_mod = AdaptiveConformalForecaster(ACIConfig(alpha=0.10, gamma=0.06, window_size=30, method="aci_cqr"))
out_seq = aci_mod.evaluate_series(y_seq, np.full(180, 17.5), np.full(180, 22.5), cal_end_idx=60)
assert np.all(out_seq["alpha_trace"] >= -0.06 - 1e-12)
assert np.all(out_seq["alpha_trace"] <= 1.06 + 1e-12)
assert bool(np.isfinite(out_seq["mean_width"]))
# Force alpha_t <= 0 under persistent shock -> must emit (-inf, +inf)
y_shock = np.concatenate([np.full(40, 20.0), np.full(25, 100.0)])
shk_cfg = ACIConfig(alpha=0.10, gamma=0.10, window_size=20, method="aci_cqr")
shk_res = AdaptiveConformalForecaster(shk_cfg).evaluate_series(
y_shock, np.full(65, 19.0), np.full(65, 21.0), cal_end_idx=40
)
neg_idx = np.flatnonzero(shk_res["alpha_trace"] <= 0.0)
assert len(neg_idx) > 0
assert np.all(np.isneginf(shk_res["lower"][neg_idx]) & np.isposinf(shk_res["upper"][neg_idx]))
# Force alpha_t >= 1 under hyper-conservative initial bands -> must emit empty (+inf, -inf)
y_empty = np.full(90, 20.0)
emp_cfg = ACIConfig(alpha=0.45, gamma=0.45, window_size=20, method="aci_cqr")
emp_res = AdaptiveConformalForecaster(emp_cfg).evaluate_series(
y_empty, np.full(90, 0.0), np.full(90, 40.0), cal_end_idx=30
)
ge1_idx = np.flatnonzero(emp_res["alpha_trace"] >= 1.0)
assert len(ge1_idx) > 0
assert np.all(np.isposinf(emp_res["lower"][ge1_idx]) & np.isneginf(emp_res["upper"][ge1_idx]))
# ---------------------------------------------------------------------------
# Test 12: Tier 2 LightGBM Quantile/Tweedie & Sklearn QuantileRegressor Parity
# ---------------------------------------------------------------------------
def test_12_tier2_lightgbm_quantile_tweedie_and_sklearn_parity() -> None:
parity = run_sklearn_quantile_parity_check(seed=42)
assert abs(parity["sklearn_pinball_loss"] - parity["numpy_irls_pinball_loss"]) < 0.05
assert parity["max_pred_diff"] < 0.35
panel = generate_retail_demand_panel(seed=42, quick=True)
causal_df = build_causal_features(panel, lead_time=4, include_leaky_future=False)
tr = causal_df[causal_df["target_end_ts"] <= 100]
ev = causal_df[causal_df["origin_ts"] >= 100]
lgb_model = GlobalLightGBMQuantileForecaster(
quantiles=(0.20, 0.50, 0.90),
config=PanelModelConfig(n_estimators=50, random_state=42),
).fit(tr)
preds = lgb_model.predict(ev)
assert np.all(np.diff(preds["quantiles"], axis=1) >= -1e-12)
assert np.all(preds["tweedie"] > 0.0)
assert np.all(np.isfinite(preds["mean"]))
# ---------------------------------------------------------------------------
# Test 13: Multi-Period Inventory Pipeline Conservation & Lead-Time Dynamics
# ---------------------------------------------------------------------------
def test_13_multi_period_inventory_simulator_pipeline_conservation() -> None:
demand = np.array([10.0, 12.0, 8.0, 15.0, 11.0, 9.0, 14.0, 10.0], dtype=np.float64)
targets = np.full(8, 35.0, dtype=np.float64)
sim = simulate_multi_period_inventory(
demand,
targets,
InventorySimConfig(c_u=12.0, c_o=3.0, lead_time=2, lost_sales=True, initial_stock=20.0),
)
assert sim["total_cost"] > 0.0
assert 0.0 <= float(sim["fill_rate"]) <= 1.0
orders = sim["orders_placed"]
inv_pos = sim["inv_pos_trace"]
assert isinstance(orders, np.ndarray) and isinstance(inv_pos, np.ndarray)
# Inventory position + order placed equals base-stock target whenever IP <= target
assert np.allclose(inv_pos + orders, np.maximum(inv_pos, targets), atol=1e-10)
# ---------------------------------------------------------------------------
# Test 14: Proper Scoring Consistency (WQL[0.5] == WAPE & CRPS / MASE)
# ---------------------------------------------------------------------------
def test_14_crps_and_wql_proper_scoring_consistency() -> None:
rng = np.random.default_rng(99)
y_train = np.maximum(1.0, 20.0 + rng.normal(0.0, 3.0, size=60))
y_test = np.maximum(1.0, 20.0 + rng.normal(0.0, 3.0, size=100))
med = np.full_like(y_test, float(np.median(y_test)))
wql_50 = compute_wql(y_test, med, tau=0.5)
wape = float(np.sum(np.abs(y_test - med)) / np.sum(np.abs(y_test)))
assert wql_50 == pytest.approx(wape, rel=1e-12)
assert compute_mase(y_train, y_test, med, seasonal_period=1) > 0.0
taus = np.linspace(0.1, 0.9, 9)
q_calibrated = np.tile(np.quantile(y_test, taus), (y_test.size, 1))
q_overconfident = np.tile(np.quantile(20.0 + rng.normal(0.0, 0.3, size=500), taus), (y_test.size, 1))
assert compute_crps_from_quantiles(y_test, q_calibrated, taus) < compute_crps_from_quantiles(
y_test, q_overconfident, taus
)
# Smoke check reconcile_sample_paths API directly
s_mat = np.array([[1, 1], [1, 0], [0, 1]], dtype=np.float64)
rec = MinTReconciler(s_mat, MinTConfig(method="mint_ols")).fit()
draws = np.column_stack([rng.normal(20, 4, 200), rng.normal(10, 3, 200), rng.normal(10, 3, 200)])
sp = reconcile_sample_paths(rec, draws, tau=0.90)
assert sp["coherent_quantiles"].shape == (3,)
# ---------------------------------------------------------------------------
# Test 15: CLI Runner Execution & Workbench JSON Schema Validation
# ---------------------------------------------------------------------------
def test_15_cli_demo_execution_and_workbench_json_schema(tmp_path: Path) -> None:
out_json = tmp_path / "lab06_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed: {proc.stderr}"
payload = json.loads(out_json.read_text(encoding="utf-8"))
wb = payload["workbench_panels"]
assert len(wb["kpis"]) == 6
assert len(wb["bars"]) == 4
assert len(wb["tables"]) == 4
nv = payload["newsvendor_backtest"]
assert nv["cost_reduction_pct"] >= 12.0
assert nv["asof_violations"] == 0
assert payload["conformal_aci"]["aci_err_abs"] < 0.03
assert payload["hierarchical_mint"]["methods"]["mint_shrink"]["coherence_err"] < 1e-9
# ---------------------------------------------------------------------------
# Test 16: Security AST Guard — Ban Unsafe Deserialization Imports Only
# ---------------------------------------------------------------------------
def test_16_security_only_ast_deserialization_guard() -> None:
py_files = sorted(
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
violations: list[str] = []
for fpath in py_files:
tree = ast.parse(fpath.read_text(encoding="utf-8"), filename=str(fpath))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: import {alias.name}")
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".", 1)[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{fpath.name}: from {node.module} import ...")
assert violations == [], f"Unsafe deserialization imports found: {violations}"
ADF + KPSS và biến đổi phương sai bằng log / Box-Cox \(\lambda_{\text{bc}} < 1\), phát biểu nào ĐÚNG?ADF kiểm định \(H_0\) nghiệm đơn vị còn KPSS kiểm định \(H_0\) dừng xu hướng; AICc không so sánh được giữa hai bậc sai phân \(d\) khác nhau; còn phân vị bất biến dưới biến đổi đơn điệu trong khi kỳ vọng bị lệch Jensen (Test 02, Test 03).
Lab 06 (mape_traps), trên phân phối {1, 10} đồng xác suất (trung bình 5.5) và chuỗi nhu cầu gián đoạn có 71.5% ngày bằng 0 (trung bình 1.55), điều gì xảy ra với MAPE, MAE, Croston-SBA và Tweedie?Croston lệch dương; SBA nhân \((1 - \alpha_p/2)\) triệt tiêu lệch bậc đầu (Test 05). MAPE phạt nặng mẫu nhỏ nên kéo dự báo xuống 1.0 (-81.8%), còn MAE sụp về 0.0 (Test 04).
Pinball Loss vượt trội dự báo trung bình MSE trong Lab 06 (giảm -39.5% chi phí toàn danh mục, -42.2% ở SKU_HI, -37.3% ở SKU_PER)?< 1e-12 (Test 06), đem lại mức giảm -39.5% >= 12% trong Lab 06 (Test 07), và cắt bỏ toàn bộ 159 -> 0 giao cắt phân vị qua sắp xếp đơn điệu Chernozhukov.
Lab 06 với thời gian giao hàng L = 4 ngày, một kỹ sư dùng K-Fold ngẫu nhiên kèm cột giảm giá đột xuất chưa công bố (unannounced_flash_L) đạt Offline RMSE = 22.21 so với Purged Rolling-Origin RMSE = 35.02, nhưng khi chạy thật bị vọt lên 44.72. Nguyên nhân cốt lõi là gì?t0, chỉ thông tin thỏa \(\tau_{\text{avail}} \le t_0\) và \(\tau_{\text{announced}} \le t_0\) mới hợp lệ, đồng thời cửa sổ huấn luyện phải thanh lọc đủ L ngày để không chồng lấn mục tiêu \(Y_{t}^{(L)}\) (Test 08).
sales = min(demand, on_hand))
Lab 06, vì sao việc đưa trực tiếp doanh số POS bị cắt cụt lúc hết hàng vào biến trễ làm tỷ lệ đứt hàng vọt lên 79.3% với độ lệch trung bình -49.2%, và giải pháp nào phá vỡ vòng xoáy này?Lab 06 (Test 09), vòng xoáy này dìm lượng bán xuống 11.11 (so với 21.86 thật) và tăng chi phí lên 24,363.2 -> 9,136.1 (-62.5%) sau khi phục hồi OSA.
GIFT-Eval, fev-bench) và cẩm nang ra quyết định trong Chương 13, khi nào nên ưu tiên Global LightGBM (Quantile/Tweedie) và khi nào dùng Foundation Time Series (Chronos-2, TimesFM 2.5, Moirai 2.0)?LightGBM đặt Hessian giả bằng 1 khi tách nhánh và tối ưu trực tiếp phân vị có trọng số tại lá; fev-bench chứng minh TSFM đơn biến đời đầu thua mô hình có biến ngoại sinh, còn Chronos-2 bổ sung Group Attention cho cold-start.
MinT-Shrink (S·G·S = S) & Sample-Path Quantiles
Total -> 2 Regions -> 4 Stores (Lab 06) có hiệu ứng thay thế giữa các cửa hàng trong cùng vùng (\(\rho < 0\)), nhận định nào ĐÚNG về kết quả hòa giải?MinT-Shrink dùng co cụm Schäfer–Strimmer bảo đảm \(\hat{\mathbf{W}}_1^{\text{shrink}} \succ 0\) và đạt Top RMSE thấp nhất (Test 10).
Lab 06 (Test 11) với mục tiêu bao phủ 90.0% (\(\alpha = 0.10\)) khi biến động khuyến mãi bất ngờ tăng 2.8x, vì sao Static Split Conformal sụp đổ và Online ACI khắc phục thế nào?NeurIPS 2021), \(\alpha_{t+1} = \alpha_t + \gamma(\alpha - \operatorname{err}_t)\) bị chặn trong \([-\gamma, 1+\gamma]\), cho sai lệch trung bình \(\mathcal{O}(1/(\gamma T))\) bất chấp dịch chuyển phân phối bất kỳ (Test 11).
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Phân tích Tính dừng (ADF/KPSS), Lệch Jensen Box-Cox & Bẫy MAPE/MAE 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết phương trình hồi quy ADF (\(H_0: \gamma_{\text{adf}}=0\)) và thống kê KPSS (\(H_0: \sigma_u^2=0\)); giải thích vì sao AICc không so sánh được hai mô hình có bậc sai phân \(d\) khác nhau.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy check_stationarity_adf_kpss, boxcox_bias_corrected_mean, và audit_mape_and_mae_traps trên Y in {1, 10} và chuỗi thưa 71.5% số 0.
Tiêu chí Đáp án & Số đối chứng
ADF + KPSS phân loại chính xác bước ngẫu nhiên vs AR(1); MAPE lệch âm -81.8% (a*=1.0 vs 5.5); MAE sụp về 0.0 khi ngày bằng 0 > 50%, trong khi RMSSE giữ kỳ vọng dương (0.784 < 0.889).
Bài tập 2 — Chứng minh Croston Lệch Dương, SBA (2005), TSB & Tweedie Hessian Dương 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng bất đẳng thức Jensen cho \(g(u)=1/u\) và phương sai dừng \(\operatorname{Var}(\hat{p}_k) = \frac{\alpha_p}{2-\alpha_p}\sigma_p^2\) để thu được hệ số \((1 - \alpha_p/2)\) của SBA.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Tính đạo hàm bậc hai \(\frac{\partial^2 \ell_{\text{tw}}}{\partial \eta^2}\) cho \(1 < p_{\text{tw}} < 2\) và kiểm chứng trên CrostonSBAForecaster & tweedie_grad_hess.
Tiêu chí Đáp án & Số đối chứng
SBA = 1.88 triệt tiêu thiên lệch của Croston = 2.04 (sát trung bình 1.59); TSB suy giảm về < 5% SBA trên chuỗi 80 ngày bằng 0; tweedie_grad_hess cho Hessian dương chặt h > 0 tại mọi điểm.
Bài tập 3 — Chứng minh Tương đương Pinball <-> Newsvendor q* & Thực nghiệm Giảm >= 12% Chi phí 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thay \(c_u = (c_u+c_o)q^*\) và \(c_o = (c_u+c_o)(1-q^*)\) vào \(c_u(y-Q)^+ + c_o(Q-y)^+\), rồi lấy đạo hàm dưới dấu tích phân (hoặc đạo hàm trái/phải với CDF rời rạc).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng bất biến < 1e-12 qua pinball_loss vs newsvendor_cost, chạy GlobalLightGBMQuantileForecaster + rearrange_quantiles_monotonic.
Tiêu chí Đáp án & Số đối chứng
Đẳng thức điểm đúng tới < 1e-12; sắp xếp đơn điệu Chernozhukov xóa 159 -> 0 giao cắt phân vị; tổng chi phí danh mục giảm -39.5% (212.41 -> 128.52; HI -42.2%, PER -37.3%).
Bài tập 4 — Thiết kế Backtest Cuốn chiếu Thanh lọc Lead-Time (L), Kiểm toán ASOF & Uncensoring POS 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh bất biến \(t_{\text{train\_target\_end}} \le t_{\text{eval\_origin}}\) tương ứng khoảng thanh lọc \(L\) ngày, và tách rạch ròi bảng tau_avail <= t0 khỏi tau_announced <= t0.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy RollingOriginPurgedBacktester, audit_asof_and_leakage, và run_stockout_censoring_experiment.
Tiêu chí Đáp án & Số đối chứng
Kiểm thử thanh lọc \(L=4\) đạt 0 vi phạm ASOF (RMSE = 35.02) vs K-Fold rò rỉ 1,932 vi phạm (22.21 -> 44.72 live); phục hồi OSA hạ tỷ lệ đứt hàng từ 79.3% -> 0.0% và giảm -62.5% chi phí.
Bài tập 5 — Dẫn xuất Hòa giải Phân cấp MinT-Shrink & Bẫy Cộng Phân vị Biên 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dựng hàm Lagrange cực tiểu hóa \(\operatorname{tr}(\mathbf{S}\mathbf{G}\mathbf{W}_h\mathbf{G}^\top\mathbf{S}^\top)\) dưới ràng buộc \(\mathbf{G}\mathbf{S} = \mathbf{I}_{n_b}\) để thu được \(\mathbf{G}^* = (\mathbf{S}^\top\mathbf{W}_h^{-1}\mathbf{S})^{-1}\mathbf{S}^\top\mathbf{W}_h^{-1}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy MinTReconciler + reconcile_sample_paths trong run_hierarchical_mint_benchmark, kiểm tra co cụm Schäfer–Strimmer và sai số \(\mathbf{S}\mathbf{G}\mathbf{S} - \mathbf{S}\).
Tiêu chí Đáp án & Số đối chứng
MinT-Shrink (\(\lambda^* = 0.421\)) đạt sai số nhất quán 2.84e-14 < 1e-9, hạ Top RMSE từ 1.284 -> 1.054 (vượt Bottom-Up 5.266), và chiếu quỹ đạo mẫu giữ Top P90 = 85.00 < 104.61.
Bài tập 6 — Chứng minh Giới hạn Chặn ACI & Kiểm định Đầu-Cuối Lab 06 (16/16 Pytest) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh quy nạp \(\alpha_t \in [-\gamma, 1+\gamma]\) từ quy tắc đặt \(\hat{C}_t = \mathbb{R}\) khi \(\alpha_t \le 0\) và \(\emptyset\) khi \(\alpha_t \ge 1\), rồi dùng tổng lồng nhau (telescoping sum) thu được cận \(\mathcal{O}(1/(\gamma T))\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_aci_regime_shift_benchmark và thực thi toàn bộ pytest -p no:cacheprovider -v, ruff check, mypy src, và scripts/run_lab_demo.py.
Tiêu chí Đáp án & Số đối chứng
Online ACI-CQR giữ bao phủ 90.0% cả tổng thể lẫn vùng sốc (err = 0.00% < 3%, thắng Static 53.8% / 25.0%), và trọn bộ 16/16 pytest, 0 lỗi ruff/mypy, 0 import deserialization không an toàn.