Chương 10 — Cây Quyết định (CART), Rừng Ngẫu nhiên, GBDT (XGBoost/LightGBM/CatBoost), Mô hình Nền tảng Bảng (TabPFN v2/TabM), TreeSHAP & AutoML (Optuna/AutoGluon)
Từ Tỉa 1-SE CART (39->8 lá), Định lý Phương sai RF (rho 0.63->0.41), GBDT Newton Bậc 2 / Histogram / GOSS / Monotonic (0 Vi phạm) đến TreeSHAP Đa thức (2.2e-16 vs 2^d), Đảo ngược Rò rỉ Stacking OOF, Optuna TPE+ASHA (-55.6% Evals) & Ranh giới Tabular FMs vs GBDT.
Unit ID:
T1-P2-U05
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Truy xuất Giáo trình Gốc (R33,R34,E29:E35): Lesson 8 (Advanced ML Algorithms: Decision Trees — 1 buổi, phủ 100% cả 6 mục: Foundations, Classifier splitting, Regressor criterion, Visualization, Tree interpretation, Industrial tips) & Lesson 9 (Advanced ML Algorithms: Ensemble Learning & Random Forest — 1 buổi, phủ 100% cả 6 mục: Averaging/Blending/Stacking, RF/XGBoost/LightGBM, Model-based evaluation, HPO Grid/Random/Bayesian/Metaheuristics, AutoML, Industrial tips), gắn kết miền Tài chính/Ngân hàng (E29:E31: Credit/Churn) & Thương mại Điện tử (E32:E35: Ranking/Fraud) (Ranh giới không chồng lấn: tối ưu tuyến tính/logistic & bộ tách thời gian kế thừa từch-06; hiệu chuẩn hậu nghiệm & ngưỡng chi phí Bayes kế thừa từch-07; thang đo Stevens, bẫyMDI\(\mathcal{O}(K/n)\),PIMP/Boruta&OOF James–Steinkế thừa từch-08; máy vector hỗ trợ & không gian hạt nhân thuộcch-09)
Bài thực hành Song hành (Lab 10):labs/ch10-trees-gbdt-and-automl-workbench/(trees_gbdt_lab)
Tình huống Mở đầu: Năm Thảm họa Sản xuất Khiến Cây Quyết định, GBDT & AutoML Sụp đổ Âm thầm#
Trên dữ liệu bảng (tabular data), họ thuật toán cây quyết định và khuếch đại độ dốc (GBDT: XGBoost, LightGBM, CatBoost) vẫn là xương sống cho chấm điểm tín dụng, phát hiện gian lận thanh toán thời gian thực và xếp hạng đa tầng thương mại điện tử, đồng thời đang chia sẻ sân chơi 2025–2026 với các mô hình nền tảng bảng (Tabular Foundation Models như TabPFN v2, TabICL) và mạng ghép hiệu quả tham số (TabM). Thế nhưng, áp dụng các bộ thư viện này như hộp đen mặc định thường kích hoạt năm sự cố sản xuất nghiêm trọng:
- Ảo giác Độ đo Phân tách (
Misclassification Gain = 0), Cây Quá khớp & Bức tường Bậc thang \(\Omega(2^d)\): Dùng sai số phân loại thô làm tiêu chuẩn chia nút trả về độ lợi bằng0.0000trên phép tách tinh khiết hóa mạnh(70, 30) -> (40, 5) | (30, 25)trong khiGini(0.0584) vàEntropy(0.1081 bits) nhận diện ngay tín hiệu. CâyCARTmọc tối đa tới39lá ghi nhớ nhiễu nhãn (Acc = 0.733) cho đến khi được cắt tỉa tối thiểu độ phức tạp chi phí (CCP 1-SE) xuống còn8lá (Acc = 0.760). Trên biên chéo hay bài toán chẵn lẻXOR, cây song trục mất tới28lá để xấp xỉ một đường cắt chéo2lá (0.862 -> 0.955), chạm cận dưới \(\Omega(2^d)\) lá. - Thảm họa Xếp chồng Nội mẫu (
In-Sample Stacking Collapse): Một đội ngũ kỹ sư huấn luyện tầngLevel-1trên dự báo nội mẫu (predict_proba(X_train)) của mộtRandom Forestkhông cắt tỉa cùngGBDTvàLogistic. VìRFghi nhớ hoàn hảo tập huấn luyện, meta-learner dồn99%trọng số (w_RF = 0.99) vàoRFtạo ảo giáctrain AUC = 1.000rồi sụp đổ trên dữ liệu thật còn0.769(logloss = 2.184). Chuyển sang Xếp chồng Ngoài nếp (OOF Stacking) + Chọn lọc Tham lam Caruana kéow_RFvề0.03, phục hồitest AUC = 0.845(logloss = 0.484), và chưng cất (distill) về mộtGBDTgọn duy nhất đạt0.848dưới ngưỡng trễ< 1 ms. - Đảo dấu Tín dụng Trái luật (
SR 11-7), Tràn RAMexact& Dịch chuyển Dự đoán (Prediction Shift): MộtGBDTkhông ràng buộc trên dữ liệu tín dụng sinh17điểm đảo chiều đơn điệu (nợ tăng nhưng rủi ro vỡ nợ lại giảm), vi phạm trực tiếp kiểm toánSR 11-7vàEU AI Actcho tới khi áp dụng kẹp cận nút tổ tiênmonotone_constraintstriệt tiêu về0vi phạm (AUC = 0.803). Song song đó, chế độexacttiêu tốn12–24 GBRAM ở10Mdòng (gấp10xbộ nhớ biểu đồuint81 B/ô), còn mã hóa mục tiêu tĩnh nội mẫu trong boosting tạo Dịch chuyển Dự đoán (NaiveTE gap = 0.308) cho đến khi được xử lý bằng Thống kê Mục tiêu Có thứ tự (Ordered TScủaCatBoost, kéo gap xuống0.180và nângOOT AUC 0.642 -> 0.732). - Rò rỉ Biến Đại diện trong
Observational TreeSHAP& Ngoại suy Giả trênPDP: Khi giải thích hồ sơ từ chối tín dụng theoECOA/CFPB Circular 2022-03,TreeSHAPquan sát (path-dependent / conditional) gán đóng góp tới0.345cho biến đại diện nhạy cảmzip_proxy(rho = 0.966) dù mô hình chưa bao giờ tách nút trên biến đó, vi phạm tiên đề Dummy; trong khiInterventional TreeSHAPtrả đúng0.0000(khớp vét cạn \(2^d\) tới1.44e-15). Tương tự,PDPkéo điểm dữ liệu ra khỏi đa tạp tương quan tạo sai lệchMAE = 8.809so vớiALEbám sát đa tạp (MAE = 0.000). - Lãng phí Ngân sách
Grid Search& Nhầm lẫn Miền giữaTabPFN v2vsGBDT: Trong không gian tìm kiếm6chiều chỉ có2chiều hữu hiệu (d_eff = 2),Grid Search64điểm chỉ thử được đúng2giá trị học thực sự (best loss = 0.1498), thua xaRandom Search(64giá trị duy nhất,-0.0005), cònOptuna TPE + ASHAcắt-55.6%lượt đánh giá cây (440vs720củaGrid). Ở tầng chọn kiến trúc,TabPFN v2không cầnHPOthắngGBDTtrên bảng mượt cỡ nhỏ (n = 220:0.843vs0.823), nhưng khinlớn, phân phối lệch đuôi nặng, cầnmonotone_constraintsvà độ trễ CPU< 1 ms(0.044 ms/row),GBDT(0.703vs0.647) lại giành lại ưu thế tuyệt đối.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 10 và gói thực hành trees_gbdt_lab (T1-P2-U05), học viên có năng lực:
- Chứng minh Toán học Cây Quyết định
CART& Cắt tỉa Chi phí-Độ phức tạp (R33): Dẫn xuất ý nghĩa xác suất củaGini, liên hệInformation Gain\(\equiv\) Thông tin Tương hỗ \(I(Y; \mathbb{I}(X_r \le s))\) &Gain Ratio; chứng minh bất đẳng thức Jensen về tính lồi lõm chặt khiếnGini/Entropyluôn tách thuần nhất trong khiMisclassification Errorcó độ lợi0; chứng minh nghiệm tối ưu láMSE(\(\bar{y}\)) vsMAE(\(\operatorname{median}\)) vs Độ lệchPoisson; chứng minh cận dưới \(\Omega(2^d)\) của cây song trục trênXORso với phân tách xiênOC1; và chứng minh Định lý Dãy Cây con Lồng nhau Duy nhất trong Minimal Cost-Complexity Pruning \(R_\alpha(T) = R(T) + \alpha_{\text{ccp}}|T|\) cùng quy tắc1-SE. - Thiết kế Tổ hợp, Triệt tiêu Tương quan
Random Forest&GBDTBậc hai (R34): Chứng minh hằng đẳng thức phương sai \(\operatorname{Var}(\bar{T}) = \rho\sigma^2 + \frac{1-\rho}{M}\sigma^2\), vai trò giảm \(\rho\) củamtryvàExtraTrees, giới hạnOOB\(1 - e^{-1} \approx 63.21\%\), và chứng minh đại số sự sụp đổ của In-Sample Stacking so vớiOOF Stacking& Caruana Greedy Ensemble Selection. Dẫn xuất từ nguyên lý gốc bộ ước lượng Newton bậc hai củaXGBoost(\(g_i, h_i\), \(w_j^*\), \(\mathcal{L}_{\text{split}}\)), Weighted Quantile Sketch, Histogram Binninguint8+ phép trừ histogram, định tuyến mặc định thưa; cơ chếGOSS(chứng minh không chệch & giảm phương sai) +EFB(giảm từ Tô màu Đồ thị) củaLightGBM; và cơ chế chống Prediction Shift bằng Ordered Boosting, Ordered Target Statistics và cây đối xứng Oblivious \(2^D\) SIMD củaCatBoost, cùng kẹp cận Monotonic & Interaction Constraints. - Định vị Ranh giới 2026 giữa
GBDTvà Mô hình Nền tảng Bảng (TabPFN v2,TabM,FT-Transformer): Giải thích cơ chế Prior-Data Fitted Networks trên tiền nghiệmSCMvà chú ý hai chiều (two-way axial attention) củaTabPFN v2(Nature 2025) /TabPFN-2.5/TabICL(ICML 2025) cùng cấu trúcBatchEnsemble+ nhúng tuần hoànPLRcủaTabM(ICLR 2025); ra quyết định chuẩn xác theo ma trậnTabArenagiữa miền \(n \le 10\text{k}\) không cầnHPOvà miền sản xuất quy mô lớn /< 1 msCPU / ràng buộc đơn điệu. - Kiểm toán Khả giải thích Bằng
TreeSHAPĐa thức & Chẩn đoánPDP/ICE/ALE: Chứng minh tính duy nhất của Shapley Values qua 4 tiên đề; triển khai thuật toánTreeSHAP(Algorithm 2:EXTEND/UNWIND/RECURSE) trong thời gian đa thức \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}}^2)\) (và nắm bước nhảy \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}})\) củaLinear TreeSHAP), đối chiếu chính xác tới< 1e-10với tổng vét cạn \(2^d\); phân biệt rạch ròi bẫy rò rỉ biến đại diện của ObservationalTreeSHAPso với InterventionalTreeSHAP, và bẫy ngoại suy ngoài đa tạp củaPDP/ICEso vớiALE. - Tối ưu Siêu tham số (
HPO) Hiện đại &AutoMLChống Quá khớp: Chứng minh định lý bất biến chiều củaRandom Search(Bergstra–Bengio 2012) so với lời nguyền \(m^{D_{\text{hp}}}\) củaGrid Search; chứng minh tính tương đương \(\operatorname{EI}_{y^*}(\mathbf{x}) \propto \ell(\mathbf{x})/g(\mathbf{x})\) củaTPE(Optuna); thiết kế lịch cắt tỉa bất đồng bộASHA(khắc phục rào cản đồng bộ củaHyperband); phân tích giới hạn của Metaheuristics (CMA-ES/DE/PSO); và kiến trúcAutoGluon(Multi-Layer Stack Ensembling có kết nối tắt + Repeated \(k\)-Fold Bagging + FAST-DAD Distillation).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U05, Dòng R33 & R34)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R33–R34) |
Nâng cấp Chuẩn SOTA 2026 (ch-10) |
Mục trong Chương 10 | Mô-đun & Hợp đồng Kiểm thử (trees_gbdt_lab) |
|---|---|---|---|
| R33.1–3 Foundations, Classifier & Regressor Criteria | Phân hoạch siêu hộp chữ nhật, chứng minh lồi lõm chặt Gini/Entropy vs Misclass Error độ lợi 0, Gain Ratio, nghiệm lá MSE (\(\bar{y}\))/MAE (\(\operatorname{median}\))/Poisson, tường XOR \(\Omega(2^d)\) vs tách xiên OC1 |
Trụ cột 1 (§1.1–§1.3) + Mermaid 1 + Widget cart-pruning-newton-split-explorer |
cart_and_ensembles.py (CARTDecisionTree, demonstrate_misclassification_zero_gain, diagonal_xor_staircase_audit), Tests 1, 2 |
| R33.4–5 Visualize, Pruning & Interpretation | Minimal Cost-Complexity Pruning \(R_\alpha(T) = R(T) + \alpha_{\text{ccp}}\lvert T\rvert\), đường liên kết yếu nhất \(g(t)\), định lý dãy cây con lồng nhau & quy tắc 1-SE; trích xuất luật IF-THEN, độ bất ổn định |
Trụ cột 1 (§1.4–§1.5) + Mermaid 1 + Widget cart-pruning-newton-split-explorer |
cart_and_ensembles.py (cost_complexity_pruning_path, select_ccp_alpha_1se, extract_rules), Tests 2, 3 |
| R34.1 Ensemble Methods: Averaging, Blending, Stacking | Trung bình lồi Jensen, Bagging, Blending, OOF Stacking vs chứng minh bẫy sụp đổ In-Sample Stacking, và Caruana Greedy Ensemble Selection |
Trụ cột 1 (§1.6) + Mermaid 3 + Widget hpo-tpe-asha-stacking-arena |
cart_and_ensembles.py (audit_stacking_insample_vs_oof, caruana_ensemble_selection), Test 8 |
| R34.2a Random Forest & Tree Ensembles | Dẫn xuất hằng đẳng thức phương sai \(\rho\sigma^2 + \frac{1-\rho}{M}\sigma^2\), vai trò mtry, ExtraTrees ngưỡng ngẫu nhiên, xác suất bao gồm \(63.21\%\) & OOB miễn phí (cấm trên chuỗi/nhóm) |
Trụ cột 1 (§1.7) + Mermaid 1 + Widget cart-pruning-newton-split-explorer |
cart_and_ensembles.py (RandomForestWorkbench, verify_rf_variance_identity), Test 4 |
R34.2b GBDT (XGBoost, LightGBM, CatBoost) & SOTA Tabular FMs |
Taylor bậc 2 Newton (\(g_i, h_i, w_j^*, \mathcal{L}_{\text{split}}\)), Weighted Quantile Sketch, uint8 Hist + phép trừ, định tuyến thiếu; LightGBM leaf-wise + GOSS + EFB; CatBoost Ordered Boosting/TS + Oblivious \(2^D\) SIMD; Monotonic & Interaction Constraints; TabPFN v2/2.5, TabICL, TabM (PLR), FT-Transformer |
Trụ cột 1 (§1.8) + Trụ cột 2 (§2.1–§2.3) + Mermaid 2 + Widget gbdt-treeshap-waterfall-explorer |
cart_and_ensembles.py (SecondOrderGBDT, estimate_goss_gradient_sum, ordered_boosting_prediction_shift_demo) + shap_and_hpo.py (benchmark_tabular_fm_vs_gbdt_regimes), Tests 5, 6, 7, 13 |
| R33.5 & R34.3 Tree & Model-Based Evaluation | 4 Tiên đề Shapley, TreeSHAP Algorithm 2 \(\mathcal{O}(B L D^2)\) & Linear TreeSHAP \(\mathcal{O}(B L D)\), đối chiếu vét cạn \(2^d\), bẫy Observational vs Interventional trên biến đại diện, PDP/ICE ngoài đa tạp vs ALE |
Trụ cột 1 (§1.9) + Trụ cột 2 (§2.4) + Mermaid 3 + Widget gbdt-treeshap-waterfall-explorer |
shap_and_hpo.py (TreeSHAPExplainer, bruteforce_shapley_tree, compute_pdp_ice_ale, audit_treeshap_proxy_leak_trap, audit_pdp_off_manifold_hazard), Tests 9, 10 |
R34.4–6 HPO, AutoML & Industrial Tips (E29:E35) |
Grid vs Random Search (chứng minh Bergstra–Bengio), GP vs TPE (Optuna) \(\ell(\mathbf{x})/g(\mathbf{x})\), Hyperband vs ASHA, Metaheuristics (CMA-ES/DE/PSO), AutoGluon (Multi-Layer Stack + Repeated Bagging + Distillation), Treelite, 4 Case thực chiến & 9 Phản mẫu |
Trụ cột 1 (§1.10) + Trụ cột 2 (§2.5) + Trụ cột 3 + Trụ cột 4 | shap_and_hpo.py (TPEOptimizer, ASHAOptimizer, grid_search_hpo, random_search_hpo, de_metaheuristic_hpo, run_full_ch10_benchmarks), Tests 11, 12, 14 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-10) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (trees_gbdt_lab) |
|---|---|---|---|---|
| \(n, d\) | \(\mathbb{N}_+\) | Số quan sát \(n\) và số chiều đặc trưng gốc \(d\) (\(\mathbf{x}_i \in \mathbb{R}^d\)) | Thống nhất dùng \(d\) cho số cột (mtry \(\in \{\lfloor d/3\rfloor, \lfloor \sqrt{d}\rfloor\}\)); tách khỏi độ sâu cây \(D_{\text{tree}}\) và số chiều HPO \(D_{\text{hp}}\) |
n_samples, n_features |
| \(T, \lvert T\rvert, \mathcal{I}(T), \widetilde{T}\) | Cây | Cây quyết định \(T\), tập nút trong \(\mathcal{I}(T)\), tập lá \(\widetilde{T}\), số lá \(\lvert T\rvert := \lvert\widetilde{T}\rvert = J\) | Tập chỉ số mẫu tại nút \(t\) là \(I_t := \{i : \mathbf{x}_i \in R_t\}\), kích thước \(n_t = \lvert I_t\rvert\) | n_leaves, internal_nodes, n_samples |
| \(\alpha_{\text{ccp}}, g(t), R_\alpha(T)\) | \(\mathbb{R}_{\ge 0}\) | Hệ số phạt cắt tỉa \(\alpha_{\text{ccp}}\), ngưỡng liên kết yếu nhất \(\frac{R(t)-R(T_t)}{\lvert T_t\rvert-1}\), rủi ro phạt \(R(T)+\alpha_{\text{ccp}}\lvert T\rvert\) | Tách khỏi ngưỡng phân vị \(\gamma_{\text{tpe}}\) và phạt tách nút \(\gamma_{\text{split}}\) | ccp_alpha, weakest_link_g, node_risk |
| \(M, \rho, \sigma^2, m_{\text{try}}\) | \(\mathbb{N}_+, [-1,1], \mathbb{R}_{\ge 0}\) | Số cây RF \(M\), tương quan cặp cây \(\rho\), phương sai từng cây \(\sigma^2\), số đặc trưng mẫu hóa \(m_{\text{try}}\) |
Định danh phương sai RF: \(\operatorname{Var}(\bar{T}) = \rho\sigma^2 + \frac{1-\rho}{M}\sigma^2\) |
n_estimators, rho_hat, sigma2_bar, max_features |
| \(B_{\text{ens}}, L_{\text{leaf}}, D_{\text{tree}}\) | \(\mathbb{N}_+\) | Số cây GBDT \(B_{\text{ens}}\), số lá tối đa mỗi cây \(L_{\text{leaf}}\), độ sâu tối đa \(D_{\text{tree}}\) |
Độ phức tạp TreeSHAP: \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}}^2)\) (hoặc \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}})\)) |
n_estimators, num_leaves, max_depth |
| \(g_i, h_i, G_j, H_j\) | \(\mathbb{R}, \mathbb{R}_{\ge 0}\) | Đạo hàm bậc 1 & bậc 2 \(\partial_{\hat{y}}\ell, \partial_{\hat{y}}^2\ell\) tại \(\hat{y}_i^{(t-1)}\); tổng theo lá \(I_j\) | Trọng số lá tối ưu Newton: \(w_j^* = -\frac{G_j}{H_j + \lambda_{\text{reg}}}\) | grad, hess, g_tot, h_tot |
| \(\lambda_{\text{reg}}, \gamma_{\text{split}}, \eta_{\text{lr}}\) | \(\mathbb{R}_{\ge 0}, (0,1]\) | Phạt \(L_2\) trọng số lá \(\lambda_{\text{reg}}\), phạt tạo lá mới \(\gamma_{\text{split}}\), tốc độ học \(\eta_{\text{lr}}\) | Tách biệt khỏi \(\alpha_{\text{ccp}}\) và hệ số cắt \(\eta_{\text{asha}}\) | reg_lambda, min_split_gain, learning_rate |
| \(a, b, \gamma_{\text{efb}}\) | \((0,1)\) | Tỷ lệ giữ gradient lớn \(a\) & lấy mẫu gradient nhỏ \(b\) của GOSS (nhân \(\frac{1-a}{b}\)); ngưỡng xung đột EFB |
Luôn ghi rõ vai trò GOSS vs EFB |
goss_top_rate, goss_other_rate |
| \(\phi_j, S \subseteq N \setminus \{j\}\) | \(\mathbb{R}, \text{Subset}\) | Giá trị phân bổ Shapley của đặc trưng \(j\) trên tập người chơi \(N=\{1,\dots,d\}\) | Phân biệt \(v_{\text{obs}}(S)=\mathbb{E}[f(X)\mid X_S]\) vs \(v_{\text{int}}(S)=\mathbb{E}[f(x_S, X_{\bar{S}})]\) | phi, mode ("path" vs "interventional") |
| \(\ell(\mathbf{x}), g(\mathbf{x}), \gamma_{\text{tpe}}, y^*\) | Density, \((0,1), \mathbb{R}\) | Hàm mật độ KDE TPE cho thử nghiệm tốt (\(y < y^*\)) và xấu (\(y \ge y^*\)) tại phân vị \(\gamma_{\text{tpe}}\) |
Cực đại hóa \(\operatorname{EI}_{y^*}(\mathbf{x}) \propto \ell(\mathbf{x})/g(\mathbf{x})\) | good_pts, bad_pts, gamma_tpe |
| \(D_{\text{hp}}, d_{\text{eff}}, \eta_{\text{asha}}, R_{\max}\) | \(\mathbb{N}_+, \mathbb{R}_{>1}\) | Số chiều siêu tham số \(D_{\text{hp}}\), chiều hữu hiệu \(d_{\text{eff}}\), tỷ số halving \(\eta_{\text{asha}}\), tài nguyên tối đa | Không nhầm lẫn \(D_{\text{hp}}\) với số đặc trưng \(d\) hay độ sâu \(D_{\text{tree}}\) | search_dim, eff_dim, reduction_factor |
Trụ cột 1 — Nền tảng Toán học & Thuật toán: Từ CART, Cắt tỉa CCP, Random Forest đến GBDT Bậc hai, TreeSHAP & HPO#
1.1 Cây Quyết định CART & Tính NP-Đầy đủ của Phân tách Tham lam (R33.1)#
Một cây phân loại và hồi quy (CART — Breiman, Friedman, Olshen & Stone, 1984) phân hoạch đệ quy không gian đặc trưng \(\mathcal{X} \subseteq \mathbb{R}^d\) thành \(J\) siêu hộp chữ nhật song trục (axis-aligned hyperrectangles) rời nhau từng đôi \(R_1, \dots, R_J\) thỏa mãn \(\bigcup_{j=1}^J R_j = \mathcal{X}\) và \(R_j \cap R_{j'} = \emptyset\) (\(j \neq j'\)). Mỗi vùng lá \(R_j\) là giao của các nửa không gian tọa độ dọc theo đường đi duy nhất từ gốc tới lá:
trong đó hằng số lá \(c_j\) nằm trong \(\mathbb{R}\) (hồi quy) hoặc \(\Delta^{K-1}\) (phân phối xác suất lớp). Hyafil & Rivest (1976) đã chứng minh bằng phép quy giảm từ bài toán Exact Cover by 3-Sets rằng tìm cây nhị phân có độ sâu kỳ vọng tối thiểu trên tập hữu hạn là bài toán NP-đầy đủ. Vì vậy, CART dùng chiến lược chia nhị phân đệ quy tham lam từ trên xuống (top-down greedy recursive binary splitting): tại nút \(t\) chứa tập chỉ số \(I_t\) (\(n_t = |I_t|\)), chọn đặc trưng \(r \in \{1,\dots,d\}\) và ngưỡng \(s \in \mathbb{R}\) chia \(I_t\) thành \(I_L(r, s) = \{i \in I_t : x_{i,r} \le s\}\) và \(I_R(r, s) = \{i \in I_t : x_{i,r} > s\}\) sao cho cực đại hóa độ giảm độ bất thuần có trọng số:
1.2 Tiêu chuẩn Phân tách Phân loại & Chứng minh Bẫy Sai số Phân loại (R33.2)#
Gọi \(\mathbf{p}(t) = (p_1(t), \dots, p_K(t))^\top \in \Delta^{K-1}\) là phân phối lớp thực nghiệm tại nút \(t\) với \(p_k(t) = \frac{1}{n_t}\sum_{i \in I_t} \mathbb{I}(y_i = k)\). Với tỷ trọng nhánh trái \(\alpha = n_L/n_t \in (0, 1)\), ta luôn có \(\mathbf{p}(t) = \alpha \mathbf{p}(t_L) + (1-\alpha)\mathbf{p}(t_R)\).
- Chỉ số Gini (\(I_G\)): \(I_G(t) := 1 - \sum_{k=1}^K p_k(t)^2 = \sum_{k=1}^K p_k(t)(1 - p_k(t)) \in [0, 1 - 1/K]\). Về mặt xác suất, \(I_G(t)\) chính là xác suất gán sai nhãn khi rút ngẫu nhiên một mẫu từ nút \(t\) và gán cho nó một nhãn ngẫu nhiên độc lập theo chính phân phối \(\mathbf{p}(t)\) của nút đó.
- Entropy Shannon (\(H\)) & Độ lợi Thông tin (\(\Delta H\)): \(H(t) := -\sum_{k=1}^K p_k(t)\log_2 p_k(t) \in [0, \log_2 K]\). Đặt chỉ báo phép tách \(S := \mathbb{I}(X_r \le s) \in \{0, 1\}\), độ lợi thông tin chính là Thông tin Tương hỗ Có điều kiện giữa nhãn \(Y\) và biến tách \(S\):
\[\Delta H(t; r, s) = H(Y \mid t) - H(Y \mid S, t) = I\big(Y;\, \mathbb{I}(X_r \le s) \mid t\big) = \alpha\, D_{\mathrm{KL}}^{(2)}\big(\mathbf{p}(t_L) \,\|\, \mathbf{p}(t)\big) + (1-\alpha)\, D_{\mathrm{KL}}^{(2)}\big(\mathbf{p}(t_R) \,\|\, \mathbf{p}(t)\big) \ge 0.\]
- Tỷ lệ Độ lợi (
Gain Ratio—C4.5, Quinlan 1993): Khi chia đa nhánh trên biến danh định \(V\) giá trị (ví dụcustomer_id), \(\Delta H\) thô thiên vị chia vụn thành \(n_t\) lá thuần có \(\Delta H = H(t)\) nhưng vô dụng ngoài mẫu.C4.5chuẩn hóa bằng entropy phân hoạch \(\operatorname{SplitInfo}(t; A) = -\sum_{v=1}^V \frac{n_v}{n_t}\log_2 \frac{n_v}{n_t}\):\[\operatorname{GainRatio}(t; A) := \frac{\Delta H(t; A)}{\operatorname{SplitInfo}(t; A)} \in [0, 1].\] - Sai số Phân loại (
Misclassification Error): \(I_{\text{err}}(t) := 1 - \max_{1 \le k \le K} p_k(t)\).
Định lý 1.1 (Tính Lồi lõm Chặt của Gini & Entropy so với Bệnh lý Độ lợi Không của Misclassification Error)#
Bất kỳ hàm độ bất thuần lõm (concave) \(\phi: \Delta^{K-1} \to \mathbb{R}_{\ge 0}\) nào đều đảm bảo \(\Delta \phi \ge 0\) theo bất đẳng thức Jensen. Tuy nhiên:
Gini(\(I_G\)) vàEntropy(\(H\)) lõm chặt trên \(\Delta^{K-1}\), nên \(\Delta I_G > 0\) và \(\Delta H > 0\) khi và chỉ khi phép tách làm thay đổi tỷ lệ lớp (\(\mathbf{p}(t_L) \neq \mathbf{p}(t_R)\)). Cụ thể vớiGini, khai triển trực tiếp cho hằng đẳng thức:\[\Delta I_G = \alpha(1 - \alpha)\,\|\mathbf{p}(t_L) - \mathbf{p}(t_R)\|_2^2.\]Misclassification Error(\(I_{\text{err}}\)) lõm nhưng KHÔNG lõm chặt (tuyến tính từng mảnh): trên mỗi ô quyết định cùng lớp đa số \(k^*\), \(I_{\text{err}}(\mathbf{p}) = 1 - p_{k^*}\) là hàm affine phẳng hoàn toàn. Do đó, bất cứ khi nào hai nút con vẫn giữ nguyên lớp đa số \(k^*\), \(\Delta I_{\text{err}} \equiv 0\) bất chấp độ tinh khiết tăng vọt!
Phản ví dụ Chuẩn (Đã kiểm chứng trong trees_gbdt_lab): Xét nút cha (70, 30) (\(I_{\text{err}} = 0.30\)) tách thành (40, 5) (\(p_0 = 8/9\)) và (30, 25) (\(p_0 = 6/11\)):
- Sai số Phân loại: \(\frac{45}{100}\frac{5}{45} + \frac{55}{100}\frac{25}{55} = 0.30 \implies \mathbf{\Delta I_{\text{err}} = 0.0000}\) (bộ tách tham lam mù hoàn toàn!).
Gini&Entropy: \(\Delta I_G = \frac{289}{4950} \approx \mathbf{0.0584 > 0}\) và \(\Delta H \approx \mathbf{0.1081\text{ bits} > 0}\), thưởng ngay cho phép tạo ra nút con tinh khiết88.9%để bước sâu hơn tách nốt nút còn lại. \(\blacksquare\)
1.3 Tiêu chuẩn Cây Hồi quy & Tách Song trục vs. Tách Xiên (R33.3)#
| Tiêu chuẩn Hồi quy | Hàm Mất mát Tại Lá | Nghiệm Hằng số Lá Tối ưu \(c_t^*\) | Đặc tính Thống kê & Độ phức tạp Cập nhật Quét Sắp xếp |
|---|---|---|---|
Variance / MSE (\(L_2\)) |
\(\sum_{i \in I_t} (y_i - c)^2\) | Trung bình: \(\bar{y}_{I_t}\) | Giảm phương sai ANOVA \(\frac{n_L n_R}{n_t}(\bar{y}_L - \bar{y}_R)^2\); cập nhật \(\mathcal{O}(1)\) mỗi bước quét nhưng nhạy ngoại lai (100.0 kéo dự báo từ 1.0 lên 20.8) |
MAE (\(L_1\)) |
\(\sum_{i \in I_t} \lvert y_i - c\rvert\) | Trung vị: \(\operatorname{median}(y_{I_t})\) | Dưới vi phân \(\sum \operatorname{sgn}(c-y_i) \ni 0\); kháng ngoại lai tuyệt đối (dự báo lá giữ đúng 1.0), cần hai heap thứ tự \(\mathcal{O}(\log n_t)\) mỗi bước |
| Poisson Deviance | \(2\sum_{i \in I_t}\big[y_i \ln\frac{y_i}{c} - (y_i - c)\big]\) | Trung bình: \(\bar{y}_{I_t}\) (\(c > 0\)) | Trọng số sai số tỷ lệ nghịch cường độ kỳ vọng (\(\operatorname{Var} = \mu\)); chuẩn cho dữ liệu đếm yêu cầu bảo hiểm / lượt nhấp |
Bức tường Bậc thang \(\Omega(2^d)\) của Tách Song trục vs. Tách Xiên (Oblique OC1)#
Xấp xỉ một siêu phẳng chéo \(\mathbf{w}^\top \mathbf{x} = b\) trong \([0, 1]^d\) tới bề rộng \(\epsilon\) bằng các siêu hộp song trục đòi hỏi \(\Omega((1/\epsilon)^{d-1})\) lá. Nghiêm trọng hơn, trên hàm chẵn lẻ \(d\) chiều (XOR: \(y(\mathbf{x}) = \prod_{r=1}^d \operatorname{sgn}(x_r)\)):
- Mọi hộp song trục cắt qua \(x_r = 0\) ở dù chỉ một chiều đều chứa đồng thời nhãn \(+1\) và \(-1\) với xác suất bằng nhau, buộc cây song trục chính xác phải có ít nhất \(2^d\) lá (\(\Omega(2^d)\)) và độ sâu \(\ge d\).
- Tại mọi nút độ sâu \(< d-1\), lấy kỳ vọng biên cho \(\mathbb{P}(Y=+1 \mid X_m \le s) = \frac{1}{2}\), khiến độ lợi tách tham lam tại gốc bằng
0.
Cây Oblique (OC1 — Murthy et al., 1994) thay điều kiện tách thành siêu phẳng \(\mathbf{w}^\top \mathbf{x} \le b\), giải bài toán chéo chỉ với 2 lá (trong trees_gbdt_lab, siêu phẳng xiên đạt 1.000 với 2 lá trong khi CART độ sâu 8 tốn 28 lá để đạt 0.955, và trên XOR 3D cây độ sâu 2 bị kẹt ở 0.494). Đánh đổi: OC1 tốn chi phí tối ưu leo đồi ngẫu nhiên tăng \(\mathcal{O}(R \cdot d)\) lần và mất tính khả giải thích đơn biến IF x_j <= s.
1.4 Cắt tỉa Chi phí-Độ phức tạp Tối thiểu (Minimal Cost-Complexity Pruning — Breiman et al., 1984) (R33.4–5)#
Cây CART mọc tối đa tới lá thuần học thuộc nhiễu huấn luyện; còn dừng sớm (pre-pruning) bằng ngưỡng độ lợi tối thiểu bỏ sót các cấu trúc dạng XOR cần đi qua một bước chia trung gian mới mở khóa độ lợi phía dưới. Giải pháp kinh điển là mọc tối đa rồi cắt tỉa từ dưới lên (grow-maximal then prune bottom-up).
Với cây con đã cắt tỉa \(T \preceq T_{\max}\) có tập lá \(\widetilde{T}\) (\(|T| := |\widetilde{T}|\)), tổng rủi ro thay thế lại (resubstitution error) \(R(T) = \sum_{\ell \in \widetilde{T}} R(\ell)\), và hệ số phạt độ phức tạp \(\alpha_{\text{ccp}} \ge 0\), hàm mục tiêu Cost-Complexity là:
Với mỗi nút trong \(t \in \mathcal{I}(T)\), xét nhánh \(T_t\) có gốc tại \(t\) (\(|T_t| \ge 2\)). Việc cắt bỏ toàn bộ \(T_t\) thành một lá duy nhất \(\{t\}\) chỉ có lợi khi \(R_\alpha(\{t\}) \le R_\alpha(T_t)\), tức là khi \(\alpha_{\text{ccp}}\) vượt qua ngưỡng liên kết yếu nhất (weakest-link threshold):
Định lý 1.2 (Tồn tại, Duy nhất & Chuỗi Cây con Lồng nhau Tối ưu của Breiman)#
- Với mọi \(\alpha_{\text{ccp}} \ge 0\), tồn tại một cây con nhỏ nhất duy nhất \(T(\alpha_{\text{ccp}}) \preceq T_{\max}\) cực tiểu hóa \(R_\alpha(T)\) (theo phép quy nạp cấu trúc cộng tính \(R_\alpha(T) = R_\alpha(T_L) + R_\alpha(T_R)\)).
- Khi \(\alpha_{\text{ccp}}\) tăng từ \(0 \to \infty\), \(T(\alpha_{\text{ccp}})\) chỉ chuyển trạng thái tại hữu hạn các điểm tới hạn \(0 = \alpha_1 < \alpha_2 < \dots < \alpha_K\), sinh ra một chuỗi lồng nhau nghiêm ngặt:
\[T_1 \succ T_2 \succ \dots \succ T_K = \{t_{\text{root}}\},\]bằng thuật toán lặp: xuất phát từ \(T_1 = T(0)\) (cắt các nhánh có \(g(t)=0\)), đặt \(\alpha_{k+1} = \min_{t \in \mathcal{I}(T_k)} g_k(t)\) rồi đồng thời thu gọn mọi nút đạt cực tiểu \(g_k(t) = \alpha_{k+1}\) về lá để thu được \(T_{k+1}\).
Để chọn \(\alpha_{\text{ccp}}\) bằng kiểm chứng chéo \(K\)-nếp, Breiman đánh giá rủi ro \(\widehat{\mathrm{CV}}(\alpha_k)\) tại các trung điểm hình học \(\beta_k = \sqrt{\alpha_k \alpha_{k+1}}\) và áp dụng quy tắc 1-SE: chọn cây tiết kiệm nhất (ít lá nhất, \(\alpha\) lớn nhất) vẫn nằm trong vòng một sai số chuẩn quanh cực tiểu \(\alpha_{\min}\):
Trong trees_gbdt_lab, cắt tỉa CCP 1-SE nén cây từ 39 lá xuống 8 lá (\(\alpha_{1\text{-SE}} = 0.0087\)), đồng thời tăng độ chính xác kiểm định từ 0.733 -> 0.760.
1.5 Trích xuất Luật, Độ bất ổn định & Ma trận Độ phức tạp CART (R33.4–5)#
Mỗi lá \(j \in \{1,\dots,J\}\) của cây \(T\) tương ứng 1-1 với một luật hội tụ IF-THEN rời nhau từng đôi và phủ kín 100% \(\mathbb{R}^d\): \(\text{IF } \bigwedge_{m \in \mathcal{A}(j)} (x_{r_m} \bowtie_m s_m) \Rightarrow \hat{y} = c_j\). Tuy nhiên, cây đơn lẻ mang ba điểm yếu cố hữu: (1) bất ổn định cấu trúc (đổi vài điểm dữ liệu gần nút gốc làm đảo lộn toàn bộ nhánh con phía dưới), (2) không ngoại suy tuyến tính (dự báo phẳng lỳ ngoài miền huấn luyện), và (3) thiên vị \(\mathcal{O}(K/n)\) trong MDI hướng về biến phân loại nhiễu nhiều mức (high-cardinality, ch-08).
Giai đoạn / Thuật toán CART |
Độ phức tạp Thời gian | Độ phức tạp Bộ nhớ | Ghi chú Tối ưu |
|---|---|---|---|
Xây dựng CART Ngây thơ (sắp xếp lại ở mọi nút) |
\(\mathcal{O}(d \cdot D_{\text{tree}} \cdot n \log n)\) | \(\mathcal{O}(d n + J)\) | \(\mathcal{O}(d n \log^2 n)\) cây cân bằng; \(\mathcal{O}(d n^2 \log n)\) lệch |
Xây dựng CART Tiền sắp xếp (presorted) |
\(\mathcal{O}(d n \log n + d n D_{\text{tree}})\) | \(\mathcal{O}(d n + J)\) | Tái dùng mảng chỉ số đã sắp xếp qua các tầng |
Cắt tỉa CCP |
\(\mathcal{O}(J^2)\) xấu nhất / \(\mathcal{O}(J \log J)\) | \(\mathcal{O}(J)\) | Cập nhật từ dưới lên qua \(2J-1\) nút |
| Suy luận 1 mẫu | \(\mathcal{O}(D_{\text{tree}})\) | \(\mathcal{O}(J)\) | Phụ thuộc dự đoán rẽ nhánh CPU |
1.6 Tổ hợp: Averaging, Blending, OOF Stacking & Chứng minh Bẫy In-Sample Stacking (R34.1)#
- Trung bình &
Bagging(Breiman, 1996): Với mọi hàm mất mát lồi \(\ell(y, \cdot)\), tổ hợp lồi \(\hat{f}_{\text{ens}}(\mathbf{x}) = \sum_{m=1}^M w_m \hat{f}_m(\mathbf{x})\) (\(w_m \ge 0, \sum w_m = 1\)) luôn đạt rủi ro \(\le \sum w_m \ell(y, \hat{f}_m)\) theo bất đẳng thức Jensen.Bagginglấy \(M\) mẫu bootstrap để hạ phương sai của cây không cắt tỉa (độ chệch thấp, phương sai cao). Blendingvs.Out-of-Fold (OOF) Stacking(Wolpert, 1992):Blendingtách riêng một tập holdout để huấn luyện meta-learnerLevel-1, an toàn nhưng lãng phí mẫu huấn luyện cho cả hai tầng.OOF Stackingchia tập huấn luyện thành \(K\) nếp rời nhau \(\mathcal{I}_1, \dots, \mathcal{I}_K\): mỗi mô hình nền \(m\) huấn luyện trên \(\mathcal{D}_{\text{tr}} \setminus \mathcal{I}_k\) chỉ dự báo trên \(\mathcal{I}_k\) để tạo ma trận siêu đặc trưng không rò rỉ \(\mathbf{Z}^{\text{OOF}} \in \mathbb{R}^{n \times M}\). Sau đó meta-learner (ví dụRidge,Logisticràng buộc không âm, hoặc Chọn lọc Tham lam Caruana) khớp trên \((\mathbf{Z}^{\text{OOF}}, \mathbf{y}_{\text{tr}})\), dùng trọn vẹn 100% dữ liệu.
Định lý 1.3 (Chứng minh Đại số về Bẫy Sụp đổ của In-Sample Stacking)#
Giả sử \(y_i = f^*(\mathbf{x}_i) + \varepsilon_i\) với \(\mathbb{E}[\varepsilon_i] = 0, \operatorname{Var}(\varepsilon_i) = \sigma^2\). Theo phân rã độ lạc quan Efron (2004), sai số bình phương trung bình nội mẫu của bộ kết hợp tuyến tính \(\mathbf{Z}^{\text{in}}\mathbf{w}\) chịu thiên lệch âm tỷ lệ thuận với bậc tự do hiệu dụng có trọng số:
Chứng minh đóng trên hai người học: Gọi \(\hat{f}_1 = f^*\) là mô hình tối ưu Bayes (sai số dư trên holdout \(= 0\), phần dư nội mẫu \(\boldsymbol{\varepsilon}\)), và \(\hat{f}_2^{\text{in}} = f^* + \gamma \boldsymbol{\varepsilon}\) (\(\gamma \in (0, 1]\)) là cây quá khớp học thuộc phần \(\gamma\) nhiễu huấn luyện (sai số dư ngoài mẫu \(= \gamma^2\sigma^2 > 0\)). Với trọng số lồi \(w \in [0, 1]\):
Cực tiểu hóa \(\mathrm{MSE}_{\text{in}}(w)\) ép w_in* = 1 (dồn 100% trọng số vào cây học thuộc nhiễu và loại bỏ hoàn toàn mô hình tối ưu!). Ngược lại, dưới OOF Stacking, \(\operatorname{Cov}(\hat{f}_m^{(-k)}(\mathbf{x}_i), \varepsilon_i) = 0 \implies \operatorname{df}_{\text{OOF}} = 0\), khôi phục kỳ vọng trung thực \(\sigma^2 + w^2\gamma^2\sigma^2\) với nghiệm tối ưu w_OOF* = 0. \(\blacksquare\)
1.7 Hằng đẳng thức Phương sai Random Forest, mtry, ExtraTrees & OOB (R34.2a)#
Định lý 1.4 (Hằng đẳng thức Phương sai của Random Forest)#
Xét \(M\) cây ngẫu nhiên phân phối đồng nhất \(\{T_m(\mathbf{x})\}_{m=1}^M\) có phương sai biên \(\operatorname{Var}(T_m(\mathbf{x})) = \sigma^2\) và tương quan cặp \(\operatorname{Corr}(T_m(\mathbf{x}), T_{m'}(\mathbf{x})) = \rho\) (\(\forall m \neq m'\)). Khai triển phương sai của trung bình \(\bar{T}(\mathbf{x}) = \frac{1}{M}\sum_{m=1}^M T_m(\mathbf{x})\):
- Sàn Tương quan \(\rho\sigma^2\) & Vai trò của
mtry: Khi \(M \to \infty\), số hạng \(\frac{1-\rho}{M}\sigma^2 \to 0\) (tăng số cây không gây quá khớp phương sai), nhưng phương sai hội tụ về sàn cứng \(\rho\sigma^2\) chứ không về \(0\). Việc chỉ xét ngẫu nhiên \(m_{\text{try}} \le d\) đặc trưng tại mỗi nút (\(\lfloor d/3\rfloor\) cho hồi quy, \(\lfloor\sqrt{d}\rfloor\) cho phân loại) phá vỡ sự thống trị của vài đặc trưng mạnh ở nút gốc, kéo \(\rho\) giảm mạnh (0.632 -> 0.507trongtrees_gbdt_lab). ExtraTrees(Geurts et al., 2006): Tắt lấy mẫu bootstrap (dùng 100% tập huấn luyện để giảm chệch) và chọn một ngưỡng cắt ngẫu nhiên \(\tau_r \sim \mathcal{U}[\min x_{\cdot, r}, \max x_{\cdot, r}]\) cho mỗi biến trongmtry. Điều này triệt tiêu phép sắp xếp \(\mathcal{O}(m_{\text{try}} n_t \log n_t)\) xuống \(\mathcal{O}(m_{\text{try}} n_t)\), hạ tiếp tương quan xuốngrho = 0.406, và tạo biên quyết định mượt hơn.- Xác suất
Bootstrap\(63.21\%\) & Sai sốOOBMiễn phí: Xác suất một dòng bất kỳ \(i\) lọt ra ngoài toàn bộ \(n\) lần rút có hoàn lại là \((1 - 1/n)^n \xrightarrow{n\to\infty} e^{-1} \approx 36.79\%\), nên tỷ lệ trong túi hội tụ về \(1 - e^{-1} \approx 63.21\%\) (thực đo0.635). Dự báo Out-of-Bag (OOB) tổng hợp riêng từ \(\sim 0.368M\) cây không chứa mẫu \(i\) ước lượng rủi ro ngoài mẫu miễn phí (OOB = 0.839), nhưng bị cấm dùng trên dữ liệu nhóm (entity_id) hoặc chuỗi thời gian vì các bản ghi tương quan vẫn rò rỉ vào mẫu bootstrap.
1.8 Dẫn xuất GBDT Bậc hai (XGBoost Foundation — Chen & Guestrin, 2016) (R34.2b)#
Khác với GBM bậc một của Friedman (2001) chỉ khớp thặng dư giả \(-g_i\) bằng MSE không trọng số rồi tối ưu trọng số lá riêng rẽ, XGBoost khai triển Taylor bậc hai quanh dự báo tích lũy \(\hat{y}_i^{(t-1)}\) kèm điều chuẩn cấu trúc \(\Omega(f_t) = \gamma_{\text{split}} T + \frac{1}{2}\lambda_{\text{reg}} \sum_{j=1}^T w_j^2\):
trong đó \(g_i := \partial_{\hat{y}}\ell(y_i, \hat{y}_i^{(t-1)})\) và \(h_i := \partial_{\hat{y}}^2\ell(y_i, \hat{y}_i^{(t-1)})\):
- Với
MSE(\(\frac{1}{2}(y_i - \hat{y}_i)^2\)): \(g_i = \hat{y}_i^{(t-1)} - y_i\), \(h_i = 1\). - Với
Binary Log-Loss(\(-[y_i\ln p_i + (1-y_i)\ln(1-p_i)]\), \(p_i = \sigma(\hat{y}_i)\)): \(g_i = p_i^{(t-1)} - y_i\), \(h_i = p_i^{(t-1)}(1 - p_i^{(t-1)}) \in (0, 0.25]\). (Do đómin_child_weightchính là ngưỡng khối lượng thông tin Fisher tối thiểu trong một lá!)
Nhóm mẫu theo lá \(I_j = \{i : q(\mathbf{x}_i) = j\}\) với \(G_j := \sum_{i \in I_j} g_i\) và \(H_j := \sum_{i \in I_j} h_i\), hàm mục tiêu tách rời hoàn toàn từng lá:
Cho đạo hàm bậc nhất bằng 0 thu được trọng số lá tối ưu Newton, điểm cấu trúc tối ưu, và độ lợi tách nút chính xác:
- Tìm ngưỡng Phân tách:
exactquét mọi điểm chia đã sắp xếp (\(\mathcal{O}(d n \log n)\) tốn12 B/ôvà dễOOMở10M+dòng);approxdùng Weighted Quantile Sketch đặt mật độ ngưỡng dày tại vùng có độ cong \(h_i\) lớn; còn Histogram Binning (hist) lượng tử hóa thành \(B \le 256\) thùnguint8(1 B/ô— tiết kiệm8x–12xRAM) và chỉ quét \(\mathcal{O}(B)\) thùng mỗi nút. - Định tuyến Dữ liệu Thiếu (Sparsity-Aware Default Direction): Chỉ quét \(\mathcal{O}(\text{nnz})\) phần tử khác thiếu, tính \((G_{\text{miss}}, H_{\text{miss}}) = (G - G_{\text{non}}, H - H_{\text{non}})\) trong \(\mathcal{O}(1)\), và kiểm tra cả hai nhánh gửi mẫu thiếu sang trái hoặc phải để lưu
default_dirtối ưu cho cảMAR/MNAR.
1.9 Giá trị Shapley & Thuật toán TreeSHAP Đa thức \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}}^2)\) (R33.5, R34.3)#
Gán dự báo \(f(\mathbf{x})\) thành trò chơi hợp tác trên tập người chơi \(N = \{1, \dots, d\}\) với hàm giá trị liên minh \(v: 2^N \to \mathbb{R}\). Có duy nhất một phép phân bổ \(\boldsymbol{\phi}(v)\) thỏa mãn đồng thời bốn tiên đề (Efficiency \(\sum \phi_j = f(\mathbf{x}) - v(\emptyset)\), Symmetry, Dummy \(v(S\cup\{j\}) = v(S) \implies \phi_j = 0\), và Additivity \(\phi_j(f_1+f_2) = \phi_j(f_1)+\phi_j(f_2)\) — cho phép cộng chính xác qua toàn bộ cây rừng!):
Tính trực tiếp tốn \(\mathcal{O}(2^d)\) phép đánh giá (\(d=50 \implies 10^{15}\)). Path-Dependent TreeSHAP (Algorithm 2 — Lundberg et al., 2020) nhận ra rằng mỗi đường đi từ gốc tới lá chỉ chạm tối đa \(L_P \le D_{\text{tree}}\) đặc trưng phân biệt \(F_P\), nên trọng số tổ hợp chỉ phụ thuộc kích thước tập con \(k = |S \cap F_P|\). Bằng cách duy trì đa thức hệ số phân bổ \(w_k\) dọc đường đi qua hai toán tử \(\mathcal{O}(D_{\text{tree}})\):
EXTEND(m, z, o, d): Nạp đặc trưng mới có tỷ lệ phủ \(z = r_{\text{child}}/r_{\text{parent}}\) (khi \(d \notin S\)) và chỉ báo \(o \in \{0, 1\}\) (khi \(d \in S\)):\[w_k^{(L+1)} = z \cdot \frac{L+1-k}{L+2} w_k^{(L)} + o \cdot \frac{k}{L+2} w_{k-1}^{(L)}.\]UNWIND(m, idx): Đảo ngược chính xác phép nhânEXTENDđể loại bỏ trùng lặp khi cùng một đặc trưng xuất hiện nhiều lần trên một nhánh (gộp nhân \((z_{\text{old}}z_{\text{new}}, o_{\text{old}}o_{\text{new}})\)) và tại nút lá tính tổng đóng góp biên của mọi đặc trưng trên nhánh: \(\Delta \phi_d = v_{\text{leaf}} \cdot (o - z) \sum_k n[k]\).
Kết quả rút gọn độ phức tạp xuống thời gian đa thức \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}}^2)\) và khớp chính xác vét cạn \(2^d\) tới 2.22e-16 trong trees_gbdt_lab.
1.10 Tối ưu Siêu tham số (HPO) & CASH Cơ bản (R34.4–5)#
Họ HPO |
Cơ chế Tìm kiếm | Độ phức tạp / Tỷ lệ Trúng | Điểm mạnh & Giới hạn Nền tảng |
|---|---|---|---|
| Grid Search | Lưới Đề-các \(m^{D_{\text{hp}}}\) điểm | \(\mathcal{O}(m^{D_{\text{hp}}})\) (lời nguyền chiều) | Khi chỉ \(d_{\text{eff}} \ll D_{\text{hp}}\) chiều quan trọng, 64 điểm ở \(6\text{D}\) chỉ thử được 2 giá trị hữu hiệu (0.1498 loss) |
| Random Search | Lấy mẫu i.i.d. \(\mathbf{x}_1, \dots, \mathbf{x}_N \sim \mu\) | \(\mathbb{P}(\text{trúng top-}q) = 1 - (1-q)^N\) (bất biến \(D_{\text{hp}}\)!) | Chứng minh Bergstra & Bengio (2012): N=60 bảo đảm \(95\%\) trúng top-\(5\%\) ở mọi \(D_{\text{hp}}\); thực nghiệm đạt 64 giá trị hữu hiệu (-0.0005 loss) |
Bayesian GP (EI/UCB) |
Mô hình hóa \(p(y\mid \mathbf{x}) \sim \mathcal{GP}\) | \(\mathcal{O}(n_{\text{trials}}^3)\) (Cholesky) | Phức hợp mượt liên tục ít chiều (\(<200\) thử nghiệm); chậm khi \(n_{\text{trials}} > 500\) hoặc không gian có điều kiện rời rạc |
Bayesian TPE (Optuna) |
Mô hình hóa nghịch đảo \(p(\mathbf{x}\mid y)\) bằng hai KDE \(\ell(\mathbf{x})\) (\(y < y^*\)) và \(g(\mathbf{x})\) (\(y \ge y^*\)) | \(\mathcal{O}(n_{\text{trials}} \cdot D_{\text{hp}})\) tuyến tính | Chứng minh \(\operatorname{EI}_{y^*}(\mathbf{x}) \propto \left(\gamma_{\text{tpe}} + \frac{g(\mathbf{x})}{\ell(\mathbf{x})}(1-\gamma_{\text{tpe}})\right)^{-1} \implies\) tối đa hóa \(\ell(\mathbf{x})/g(\mathbf{x})\); hỗ trợ không gian cây phân nhánh |
SHA / Hyperband |
Lọc bội \(\eta_{\text{asha}}\) qua các bậc tài nguyên \(r_s = R_{\max} \eta^{-s}\) | Cân bằng rộng vs. sâu qua \(s_{\max}+1\) nhánh | Tiết kiệm mạnh tài nguyên trên bộ học lặp (GBDT, NN), nhưng rào cản đồng bộ (straggler) chờ thử nghiệm chậm nhất |
Metaheuristics (CMA-ES/DE/PSO) |
Quần thể tiến hóa trên \(\mathbb{R}^{D_{\text{hp}}}\) | \(10^3\text{–}10^5\) lần đánh giá (\(\mathcal{O}(D_{\text{hp}}^2)\) cho CMA-ES) |
Mạnh trên bài toán liên tục hộp đen rẻ tiền, nhưng quá đắt đỏ với GBDT (810 tree evals không cắt tỉa) và kém tự nhiên với siêu tham số có điều kiện |
Bài toán CASH kinh điển (Combined Algorithm Selection and Hyperparameter Optimization — Thornton et al., 2013) tìm \((A^*, \boldsymbol{\lambda}^*) \in \arg\min \frac{1}{K}\sum_{k=1}^K \mathcal{L}(A^{(j)}_{\boldsymbol{\lambda}}, \mathcal{D}_{\text{tr}}^{(k)}, \mathcal{D}_{\text{val}}^{(k)})\) làm tiền đề cho AutoML hiện đại.
Trụ cột 2 — Kiến trúc SOTA 2024–2026: LightGBM, CatBoost, TabPFN v2/TabM, Interventional TreeSHAP, ALE, ASHA & AutoGluon#
2.1 Nội tại LightGBM (GOSS, EFB, Leaf-Wise) & CatBoost (Ordered Boosting, Ordered TS, Oblivious Trees)#
1. LightGBM (Ke et al., NeurIPS 2017): Tốc độ trên Bảng Rộng & Lớn#
- Tăng trưởng
Leaf-Wise(Best-First) vs.Level-Wise: Thay vì mở rộng đều toàn bộ tầng sâu,LightGBMgiữ hàng đợi ưu tiên và luôn tách lá có độ lợi \(\mathcal{L}_{\text{split}}\) cao nhất tới ngân sáchnum_leaves. Để chống quá khớp nhánh gầy sâu tới25+tầng, luôn épnum_leaves <= 0.7 * 2^max_depthkèmmin_child_samples >= 50–200. - Phép trừ Histogram (Histogram Subtraction): Xây dựng biểu đồ thùng
uint8chỉ cho nút con ít mẫu hơn, suy ra nút con lớn bằng \(H_{\text{large}} = H_{\text{parent}} - H_{\text{small}}\) (\(\mathcal{O}(B)\) thay vì \(\mathcal{O}(n_{\text{large}})\) — tiết kiệm20,669lượt quét trongtrees_gbdt_lab). GOSS(Gradient-based One-Side Sampling): Giữ lại toàn bộ phần \(a\) mẫu có \(|g_i|\) lớn nhất (tập \(A\)), rút ngẫu nhiên phần \(b\) mẫu từ \(A^c\) (tập \(B\)), và nhân trọng số mẫu trong \(B\) lên \(\frac{1-a}{b}\). Vì \(\mathbb{E}[I_i] = \frac{b}{1-a}\), ước lượng tổng gradient \(\widehat{G}_S = \sum_{S_A} g_i + \frac{1-a}{b}\sum_{S_B} g_i\) hoàn toàn không chệch (\(\mathbb{E}[\widehat{G}_S] = G_S\)) và phương sai lấy mẫu chỉ rơi lên vùng gradient nhỏ \(|g_i| \le \tau_a\), đạt giảm phương sai tới11.2xso với lấy mẫu đều ở cùng ngân sách tính toán! (Chú ý:LightGBM 4.xđổi mặc định về"bagging", cần bậtdata_sample_strategy="goss"tường minh ở cỡ mẫu lớn.)EFB(Exclusive Feature Bundling): Giảm bài toán gộp các cột thưa gần như loại trừ lẫn nhau về Tô màu Đồ thị Tối thiểu (NP-hard), giải tham lam theo bậc xung đột giảm dần với ngưỡng dung sai \(\gamma_{\text{efb}} \approx 10^{-4}\) và gán mã lệch (offset encoding) để nén \(d\) cột thưa xuống \(d_{\text{bundles}} \ll d\).
2. CatBoost (Prokhorenkova et al., NeurIPS 2018): Khử Dịch chuyển & Suy luận SIMD#
- Bệnh lý Dịch chuyển Dự đoán (Prediction Shift): Trong
GBDTchuẩn, thặng dư \(g_i^{(t)}\) tại vòng \(t\) được ước lượng từ mô hình \(F^{t-1}\) đã dùng chính nhãn \(y_i\) ở các vòng trước, tạo tương quan dương giả \(\operatorname{Cov}(F^{t-1}(\mathbf{x}_i), y_i \mid \mathbf{x}_i) > 0\). Tương tự, mã hóa mục tiêu tĩnh trên train rò rỉ \(y_i\) khiếnGBDTbám mạnh vào biến danh định nhiễu (NaiveTE gap = 0.308,train 0.949 -> OOT 0.642). Ordered Boosting&Ordered Target Statistics: Dùng các hoán vị ngẫu nhiên \(\sigma\) để ước lượng thống kê mục tiêu và các mô hình phụ trợ bậc lũy thừa \(2^k\) chỉ trên tiền tố đứng trước \(\sigma(r) < \sigma(k)\):\[\hat{x}_{\sigma(k), j} = \frac{\sum_{\sigma(r) < \sigma(k)} \mathbb{I}(x_{r,j} = x_{\sigma(k), j})\, y_r + a \cdot p_{\text{prior}}}{\sum_{\sigma(r) < \sigma(k)} \mathbb{I}(x_{r,j} = x_{\sigma(k), j}) + a},\]giảm độ lệch tổng quát hóa xuống0.180và nângOOT AUCtừ0.642 -> 0.732.- Cây Đối xứng (Oblivious Decision Trees): Toàn bộ các nút cùng tầng sâu \(d \in \{0,\dots,D-1\}\) dùng chung một điều kiện tách \((f_d, \theta_d)\). Điều này không chỉ chính quy hóa mạnh mà còn biến suy luận một mẫu thành chỉ số bit \(D\)-bit không rẽ nhánh (
branchless) \(\text{idx}(\mathbf{x}) = \sum_{d=0}^{D-1} 2^d \mathbb{I}(x_{f_d} > \theta_d) \in \{0,\dots,2^D-1\}\) tra thẳng vào bảngLeafTable_t\(512\text{ B}\) nằm gọn trong bộ nhớ đệm L1 CPU (< 0.1–0.4 msvớiAVX2/AVX-512ởdepth <= 8).
3. Ràng buộc Đơn điệu & Tương tác (Monotone & Interaction Constraints)#
Trong tín dụng (SR 11-7) và định phí bảo hiểm, monotone_constraints (\(+1\)/\(-1\)) ép trọng số hai nút con thỏa \(w_L \le w_R\) (hoặc \(w_L \ge w_R\)) và kẹp cận trung điểm \(m = \frac{w_L+w_R}{2}\) truyền xuống hai cây con (left <= m, right >= m). Nhờ quy nạp trên mọi độ sâu bất kể tầng dưới tách trên biến tự do nào, toàn bộ tổ hợp đảm bảo \(\max_{\text{left}} w \le m \le \min_{\text{right}} w\), triệt tiêu vi phạm từ 17 -> 0. Tương tự, interaction_constraints dùng mặt nạ bit \(O(1)\) chặn các nhóm biến không được phép tương tác chéo trên cùng nhánh cây.
2.2 Mô hình Nền tảng Bảng 2024–2026 (TabPFN v2/2.5, TabICL / TabICLv2, LimiX-2, Mitra, TabM, FT-Transformer) vs. GBDT#
TabPFN v2(Hollmann et al., Nature 2025) &TabPFN-2.5(2025): Là Prior-Data Fitted Network tiền huấn luyện ngoại tuyến trên \(>100\) triệu bảng tổng hợp từ Mô hình Nhân quả Cấu trúc (SCM). Khi suy luận, kiến trúc Transformer Chú ý Hai chiều (Two-Way Axial Attention) tính tự chú ý theo cả chiều cột (\(\mathcal{O}(n d^2)\)) lẫn chiều dòng (\(\mathcal{O}(n^2 d)\)) trên bảng ngữ cảnh \((\mathcal{D}_{\text{train}}, \mathbf{x}_*)\) để xấp xỉ trực tiếp phân phối hậu nghiệm Bayes \(q_\theta(y_* \mid \mathbf{x}_*, \mathcal{D}_{\text{train}})\) qua một lượt truyền xuôi duy nhất với không bước gradient và khôngHPO(cùng đầu ra phân phối Riemann \(5{,}000\) thùng).TabPFN v2tối ưu ở \(n \le 10\text{k}, d \le 500\);TabPFN-2.5mở rộng tới \(n \le 50\text{k}, d \le 2\text{k}\) kèm cơ chế chưng cất vềMLP/GBDT< 1 ms.TabICL(Qu et al., ICML 2025) &TabICLv2(2025–2026): Khắc phục tường \(\mathcal{O}(n^2 d)\) bằng kiến trúc 2 tầng: mã hóa Set-Transformer theo cột thành một vector hàng nén duy nhất rồi mới chạy chú ý giữa các hàng, mở rộng học trong ngữ cảnh tới \(n = 500{,}000\) dòng nhanh gấp \(\sim 10\times\)TabPFN v2. Phiên bản kế nhiệmTabICLv2nâng cấp bộ sinh dữ liệu tổng hợp đa phân phối, áp dụng Scalable Softmax (giữ độ sắc nét phân phối chú ý khi độ dài ngữ cảnh tăng vọt mà không cần tiền huấn luyện ở chuỗi quá dài) và tiền huấn luyện bằng trình tối ưuMuon, giúp nâng độ chính xác zero-shot cùng API chuẩnscikit-learn(fit/predict) ở tốc độ suy luận GPU nhanh vượt trội trên các bảng quy mô vừa và lớn (TabArena/TALENT).LimiX-2(Contextual Mechanism Networks, 2025–2026) &Mitra(Mitra-v2): Thay vì chỉ học phân phối có điều kiện mục tiêu \(p(y \mid \mathbf{x}, \mathcal{D}_{\text{ctx}})\),LimiX-2được tiền huấn luyện bằng Context-Conditional Masked Modeling (CCMM) để mô hình hóa đồng thời phân phối kết hợp \(p(\mathbf{x}, y \mid \mathcal{D}_{\text{ctx}})\) từ các cơ chế nhân quả cấu trúc (SCM) — cho phép cùng một mô hình vừa dự đoán bảng, vừa điền khuyết dữ liệu thiếu (imputation) lẫn khôi phục khung nhân quả (causal skeleton), đồng thời có biến thể gọnLimiX-2Mtrang bị tầng nhúng hàm cơ sở xuyên tâmRaBEL(Scale-Aware Radial-Basis Embedding Layer) giải quyết thắt cổ chai trạng thái ẩn hạng thấp (low-rank hidden-state bottleneck) của mã hóa tuyến tính vô hướng truyền thống. Song song đó,Mitra(mô hình nền tảng bảng trọng số mở tích hợp sâu trongAutoGluon) sử dụng xương sống 2D Transformer gọn nhẹ được tiền huấn luyện trên kho tác vụ tổng hợp mở rộng cho ngữ cảnh dài và không gian đặc trưng rộng, đạt hiệu năng xuất sắc ở bài toán phân loại đa lớp và hồi quy bền vững dù số lượng tham số nhỏ gọn.TabM(Gorishniy et al., ICLR 2025) vs.FT-Transformer(NeurIPS 2021): Trong khiFT-Transformerchịu chi phí chú ý \(\mathcal{O}(d^2)\) giữa các token đặc trưng,TabMkết hợp nhúng số học tuần hoàn/tuyến tính từng mảnhPLR/PLE(trị spectral bias của mạng nơ-ron trên ngưỡng sắc nét) vớiBatchEnsemble(\(K=32\) bộ chuyển đổi hạng 1 \(\mathbf{W}_k = \mathbf{W} \odot (\mathbf{s}_k \mathbf{r}_k^\top)\)) dùng chung xương sốngMLP. Trên bảng xếp hạngTabArena-v0.1(NeurIPS2025, 51 bộ dữ liệu),TabM (T+E)đạt1534Elo, bám sátLightGBM (T+E)(1536Elo) và vượtXGBoost (T+E)(1443Elo), cònCatBoost (T)đứng đầu đơn mô hình (1475Elo).- Giới hạn Mở rộng Ngữ cảnh, Độ trễ Suy luận & Bẫy Dịch chuyển Phân phối của Tabular FM: Dù
TabICLv2,LimiX-2vàMitrathu hẹp đáng kể khoảng cách độ chính xác vớiGBDT, triển khai sản xuất vẫn đối mặt 3 rào cản cứng: (1) Mở rộng độ dài ngữ cảnh theo số hàng (Context-Length / Row Scaling): mọi mô hình học trong ngữ cảnh đều phải nạp \((\mathcal{D}_{\text{ctx}}, \mathbf{x}_*)\) vào cửa sổ chú ý nên tiêu thụ VRAM và thời gianprefilltăng theo kích thước tập hỗ trợ; khi bảng thực tế vượt ngưỡng100k–500kdòng (10M+giao dịch), bắt buộc lấy mẫu/truy xuất ngữ cảnh cục bộ hoặc chưng cất vềLightGBM Hist(uint8) nếu không muốn mất tín hiệu vùng đuôi; (2) Ngân sách độ trễ suy luận: một lượt suy luận trực tiếp trên GPU củaTabPFN-2.5/TabICLv2/LimiX-2/Mitratốn10–250+ ms(cao hơn nhiều trên CPU), không thể đáp ứngSLA < 1–3 mscủa gian lận/định tuyến trực tuyến nếu không qua bước chưng cất (FAST-DAD\(\to\)LightGBM + Treelite); (3) Nhạy cảm dịch chuyển phân phối (Distribution-Shift Caveats): khi miền giá trị ngoại suy theo thời gian (ví dụ lạm phát làm cộtMonetaryvượt biên \(\mathcal{D}_{\text{ctx}}\)) hoặc quan hệ \(P(Y \mid X)\) trôi theo mùa vụ, mô hình zero-shot đóng băng trên tập hỗ trợ cũ sẽ suy giảm nhanh hơn dự báo có tái khớp định kỳ nếu thiếu cơ chế làm mới cửa sổ hỗ trợPIT— đồng thời chúng chưa hỗ trợ ép cứngmonotone_constraintskiểu ngân hàngSR 11-7.
2.3 Bẫy TreeSHAP Quan sát vs. Can thiệp & Nguy cơ Ngoại suy PDP/ICE vs. ALE#
Observational (Path-Dependent)vs.Interventional TreeSHAP(Janzing et al., AISTATS 2020; Chen et al., 2020):- Path-Dependent ước lượng kỳ vọng có điều kiện dữ liệu \(v_{\text{obs}}(S) = \mathbb{E}[f(\mathbf{X}) \mid \mathbf{X}_S = \mathbf{x}_S]\) ("True to the Data"). Nếu mô hình \(f\) chỉ tách nút trên
dti(\(x_0\)) và tuyệt đối không chạm tới biến nhạy cảmzip_proxy(\(x_1\)) nhưng \(\rho(x_0, x_1) = 0.966\), biến cố \(X_1 = x_1\) làm dịch chuyển phân phối có điều kiện của \(X_0\), khiến Observational SHAP rò rỉ \(|\phi_{\text{proxy}}| = 0.3447\) sang biến hoàn toàn không dùng (vi phạm tiên đề Dummy và đánh trượt kiểm toán công bằngECOA!). - Interventional
TreeSHAPdùng phân phối biên \(v_{\text{int}}(S) = \mathbb{E}_{\mathbf{X}_{\bar{S}} \sim B}[f(\mathbf{x}_S, \mathbf{X}_{\bar{S}})]\) tương ứng can thiệp \(do(\mathbf{X}_S = \mathbf{x}_S)\) ("True to the Model"), trả về chính xác0.0000cho mọi biến không xuất hiện trong cây. Về tốc độ,Linear TreeSHAP(Yu et al., NeurIPS 2022) dùng nội suy đa thức điểm Chebyshev giảm thời gian từ \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}}^2)\) xuống \(\mathcal{O}(B_{\text{ens}} L_{\text{leaf}} D_{\text{tree}})\) (nhanh hơn10–100x).
- Path-Dependent ước lượng kỳ vọng có điều kiện dữ liệu \(v_{\text{obs}}(S) = \mathbb{E}[f(\mathbf{X}) \mid \mathbf{X}_S = \mathbf{x}_S]\) ("True to the Data"). Nếu mô hình \(f\) chỉ tách nút trên
PDP/ICEvs.ALE(Accumulated Local Effects — Apley & Zhu, JRSS-B 2020):PDPlấy trung bình qua phân phối biên \(p(\mathbf{X}_{-j})\), buộc mô hình đánh giá tại các góc trống phi thực tế (ví dụtuổi = 21đi cùnglịch sử tín dụng = 32 năm), tạo sai số ngoại suyMAE = 8.809trong thực nghiệm.ALEgiải tích hợp sai phân cục bộ có điều kiện bên trong từng thùng phân vị \([z_{k-1}, z_k]\) của chính các điểm quan sát thật:\[\hat{f}_{j,\text{ALE}}(x_j) = \sum_{k=1}^{k_j(x_j)} \frac{1}{|N_j(k)|}\sum_{i \in N_j(k)} \Big[f(z_k, \mathbf{x}_{i,-j}) - f(z_{k-1}, \mathbf{x}_{i,-j})\Big] - \hat{c},\]khử sạch sai số ngoài đa tạp (ALE MAE = 0.000) và giảm độ phức tạp từ \(\mathcal{O}(n K)\) xuống \(\mathcal{O}(2n)\).
2.4 Optuna TPE Đa biến, ASHA Bất đồng bộ & Kiến trúc AutoGluon#
ASHA(Asynchronous Successive Halving, Li et al., MLSys 2020) +Optuna 4.x:Hyperbandđồng bộ buộc toàn bộ cụm GPU/CPU đứng chờ thử nghiệm chậm nhất ở mỗi nấc cắt (straggler barrier).ASHAchuyển sang thăng hạng bất đồng bộ: ngay khi một thử nghiệm chạm bậc \(r_k\), nếu điểm của nó nằm trong top \(1/\eta_{\text{asha}}\) số thử nghiệm đã hoàn thành tại bậc đó, nó lập tức được đẩy lên \(r_{k+1}\); nếu không, thử nghiệm bị ngắt ngay (nhưHyperbandPruner+ callback trongOptunakèmTPESampler(multivariate=True, group=True)vàJournalStoragecho đa tiến trình). Trongtrees_gbdt_lab,TPE + ASHAcắt-55.6%lượt đánh giá cây (440vs990không cắt /720lưới).AutoGluon-Tabular(Erickson et al., 2020 & v1.4/1.5 2025–2026) & Chưng cấtFAST-DAD: Thay vì đốt ngân sách dò siêu tham số cho một mô hình duy nhất,AutoGluonhuấn luyện đa dạng các họ (LightGBM,CatBoost,XGBoost,TabM,RealMLP,TabPFN v2,TabICL,ExtraTrees) qua Repeated \(K\)-Fold Bagging, đưa dự báoOOFkết hợp kết nối tắt đặc trưng thô (use_orig_features=True) lên tầng Stacker tiếp theo, và gộp bằng Caruana Greedy Ensemble Selection (chọn có hoàn lại trên \(\Delta^{M-1}\) chống quá khớp tầng meta). Vì cả ngăn xếp80–120mô hình tốn1.5–4.0 GBRAM và45–180 msCPU, bướcpredictor.distill()(FAST-DAD) sinh dữ liệu tăng cườngMUNGEgắn nhãn mềm từ ngăn xếp giáo viên để huấn luyện lại một mô hình học tròLightGBM/CatBoostgọn duy nhất — giữ97%–99%sức mạnh (0.848vs0.845trong lab!) ở độ trễ< 1 ms.
Trụ cột 3 — Hệ thống Sản xuất Thực chiến, Ngân sách Phần cứng & Cạm bẫy Vận hành (Industrial Tips)#
3.1 Bốn Tình huống Sản xuất Điển hình (E29:E35 Finance/Banking & E-Commerce)#
- Case 1 — Thẩm định Tín dụng Ngân hàng Tuân thủ (
SR 11-7/ECOAReg B /CFPB Circular 2022-03/EU AI Act):- Sự cố: GBDT không ràng buộc phát sinh
17vi phạm đảo chiều đơn điệu trêndti_ratioở đuôi dữ liệu giàu tài sản ẩn, còn dùngObservational TreeSHAPgán nhầm0.345cho biến đại diệnzip_proxydù mô hình không tách nút trên đó, đồng thờiPDPvẽ kịch bản phi lý (tuổi = 21, lịch sử 32 năm). - Kiến trúc chuẩn: Dùng
monotone_constraints(+1chodti/delinquencies_12m,-1cho thu nhập xác thực) vớimax_bin >= 256để tránh đói phép tách ->0vi phạm; chạy hiệu chuẩnPlatt/PAVA(ECE < 0.015,ch-07); và sinh mã lý do từ chốiECOAbằngInterventional TreeSHAPtrên tập nền đã duyệt (|B| = 200,1.8–4.2 msp99 CPU) bảo đảm0.0000rò rỉ proxy.
- Sự cố: GBDT không ràng buộc phát sinh
- Case 2 — Chống Gian lận Thanh toán Thời gian thực & Xếp hạng Đa tầng (
Stripe/Airbnb/DoorDash/Instacart):- Ngân sách: Checkout API
< 100 mstổng / xếp hạng500–1,000ứng viên< 50 ms, để lại< 1–3 msp99 CPU cho mô hình. RawTabPFN v2(50–250 msGPU /500–2,500+ msCPU) tuyệt đối không thể đặt trực tiếp trên đường nóng đồng bộ nếu chưa chưng cất. - Kiến trúc chuẩn: Bỏ
tree_method="exact"(tránh tràn16–24 GBRAM ở10Mdòng) chuyển sanguint8Hist +EFB+GOSS(~0.8–1.5 GBRAM); dùngCatBoost Ordered TScho biến ID nhiều mức (high-cardinality:merchant_id,listing_id); và biên dịch suy luận quaTreelite(TL2cgenC.so) hoặcCatBoostOblivious SIMD (depth <= 8) đạt0.25–1.1 msp99 một dòng (0.044 mscho mô hình gọn trongtrees_gbdt_lab).
- Ngân sách: Checkout API
- Case 3 — Khắc phục Sụp đổ
In-Sample Stacking& Chưng cấtAutoGluon(Amazon FAST-DAD):- Sự cố: Đội ML khớp tầng meta trên dự báo nội mẫu của một
Random Forestkhông cắt tỉa (train AUC = 1.000,w_RF = 0.99), khiếntest AUCrớt thảm xuống0.769(logloss = 2.184), và khi chuyển sangAutoGluonLevel-2 (80–120mô hình) lại đội RAM lên2.1 GBvà độ trễ85 ms. - Kiến trúc chuẩn: Bắt buộc
OOF Stacking+ Caruana (w_RFhạ từ0.99 -> 0.03,test AUCvọt lên0.845,logloss = 0.484), rồi chạyFAST-DADdistillation sang1x LightGBMgiữ0.848ở< 1.2 msCPU và14 MBRAM.
- Sự cố: Đội ML khớp tầng meta trên dự báo nội mẫu của một
- Case 4 — Khởi động Lạnh Doanh nghiệp / Y sinh vs. Bảng Quy mô Lớn (
TabPFN v2vs.Optuna TPE + ASHA):- Miền nhỏ (
n = 220–5,000, biên chéo mượt):TabPFN v2khôngHPOvượtGBDT(0.843vs0.823) chỉ trong một lượt truyền xuôi (~1–3 sGPU vs hàng giờ dò lưới). - Miền lớn (
n = 3,200–200,000+, lệch đuôi,monotone_constraints, CPU< 1 ms):TabPFN v2bị nghẽn ngữ cảnh \(\mathcal{O}(N^2)\), mất độ chính xác (0.647vs0.703củaGBDT), cònOptuna TPE + ASHAdùngJournalStorage/PostgreSQL(cấmSQLiteđa tiến trình!) cắt45%–56%chi phí huấn luyện câyGBDT.
- Miền nhỏ (
3.2 Ma trận Dấu chân Phần cứng & Ngân sách Phục vụ (10M x 100 Train / T=500, D=6 Serve)#
| Kiến trúc / Runtime | RAM Huấn luyện (10M x 100) |
RAM / Đĩa Mô hình Suy luận | p99 CPU (1 dòng) |
p99 CPU (1,000 dòng) |
Yêu cầu GPU | Khuyến nghị Triển khai |
|---|---|---|---|---|---|---|
CART Cắt tỉa (\(D \le 8\)) |
4–8 GB |
< 100 KB |
0.01–0.05 ms |
0.2–0.8 ms |
Không | Luật kiểm toán tối giản; phương sai cao |
Random Forest (\(500\) cây) |
8–24 GB (nổ nếu depth=None) |
40–450 MB (>2 GB nếu không tỉa) |
0.8–3.5 ms |
12–45 ms |
Không | Cấm max_depth=None trên API trực tuyến |
XGBoost (exact vs hist+Treelite) |
exact: 12–24 GB (OOM!) | hist: 1.2–2.0 GB |
4–18 MB | 2–8 MB (.so) |
0.8–2.2 ms | 0.35–1.1 ms |
3.5–9.0 ms | 1.5–4.2 ms |
CUDA tùy chọn | Chuẩn vàng Tín dụng monotone_constraints |
LightGBM (uint8 Hist+EFB+GOSS) |
0.8–1.5 GB |
3–14 MB | 2–6 MB (ONNX) |
0.5–1.5 ms | 0.30–1.0 ms |
2.5–7.5 ms | 1.4–3.8 ms |
CPU cực nhanh | Xương sống huấn luyện lớn & mô hình học trò |
CatBoost (Oblivious \(D=6\text{–}8\)) |
1.5–3.0 GB |
0.3–2.5 MB (lọt L2 cache!) |
0.25–0.9 ms (SIMD) |
0.9–2.8 ms |
Tốt cho combo ID | Biến nhiều mức (Ordered TS) + p99 CPU thấp nhất |
TabM (ICLR 2025 PLR, \(K=32\)) |
1.5–4.0 GB |
4–25 MB (ONNX) |
0.6–2.0 ms |
2.5–6.5 ms |
GPU khi train | Bảng trơn/bậc \(50\text{k}–500\text{k}\) |
TabPFN v2 (\(N_{\text{ctx}} \le 10\text{k}\)) |
\(\mathcal{O}(N^2)\) (không chạy thẳng 10M) |
50–150 MB + Tensor N_ctx |
50–250 ms (GPU) / 500–2500+ ms (CPU) |
150–800 ms (GPU) |
GPU bắt buộc | \(n \le 10\text{k}\) không HPO; phải chưng cất cho RT |
AutoGluon Stack vs Distilled |
6–20 GB |
Stack 1.5–4.0 GB | Distilled 4–14 MB |
Stack 45–180 ms | 0.5–1.2 ms |
Stack 120–600 ms | 1.5–4.0 ms |
GPU cho NN/TFM | Stack làm Giáo viên -> Chưng cất LightGBM |
3.3 Chín Phản mẫu Sản xuất & Hàng rào Kiểm soát (Anti-Patterns Matrix)#
| # | Phản mẫu (Anti-Pattern) |
Triệu chứng Sản xuất | Cổng Phát hiện / Kiểm thử | Biện pháp Khắc phục Bắt buộc |
|---|---|---|---|---|
| 1 | In-Sample Stacking Leakage | train AUC = 1.000, lên live rớt 0.769 (w_RF = 0.99) |
Đối chiếu OOF vs in-sample weights; chặn CI nếu Level-1 khớp ngoài K-Fold |
Bắt buộc OOF Stacking (GroupKFold/Purged) + chọn lọc Caruana |
| 2 | Cây CART/RF không tỉa & Dùng OOB sai |
File .pkl phình > 2 GB, OOB lạc quan giả trên chuỗi thời gian |
Cổng kích thước model < 50 MB; so sánh OOB vs PurgedTS |
Khóa max_depth/min_samples_leaf hoặc CCP 1-SE; cấm OOB trên nhóm/chuỗi |
| 3 | LightGBM num_leaves mất kiểm soát |
num_leaves = 255 với min_child_samples=20 tạo nhánh sâu 25 tầng |
Kiểm tra độ sâu lá tối đa và tỷ lệ train/val logloss |
Ép num_leaves < 0.7 * 2^max_depth (31–45 ở depth=6), tăng min_child_samples |
| 4 | XGBoost exact trên 10M+ dòng |
Tiến trình chết SIGKILL (OOM) trên container 16 GB |
Ước lượng RAM trước khi chạy (n * d * 12 B) |
Bắt buộc tree_method="hist" (uint8 1 B/ô) hoặc XGBoost 3.x ExtMem |
| 5 | Observational TreeSHAP & PDP thô |
zip_proxy nhận 0.345 dù không tách nút; PDP MAE = 8.81 |
Kiểm tra biến đại diện không dùng phải có \(|\phi| = 0\) | Chuyển sang Interventional TreeSHAP + ALE (MAE = 0.000) |
| 6 | Grid Search trên \(D_{\text{hp}} \ge 3\) |
Đốt 80%+ giờ GPU mà chỉ thử được 2 giá trị learning_rate |
Đếm số giá trị duy nhất trên trục nhạy cảm; cấm GridSearch |
Dùng Optuna TPE (multivariate=True) + ASHA (-55.6% evals) |
| 7 | Target Encoding Tĩnh trong Boosting | NaiveTE gap = 0.308, model bấu víu ID nhiễu trên train |
Kiểm tra chênh lệch train - OOT AUC và Gain của cột TE |
Dùng CatBoost Ordered TS + Ordered Boosting hoặc OOF James–Stein |
| 8 | Đẩy AutoGluon / TabPFN thô lên API < 2 ms |
p99 vọt 50–250+ ms, nghẽn gateway & timeout |
Bài kiểm tra tải CI bắt buộc p99 < 2 ms 1 dòng |
Chưng cất (FAST-DAD) sang 1x LightGBM + biên dịch Treelite/ONNX |
| 9 | Đa tiến trình Optuna dùng SQLite / Rò rỉ Preprocessor |
Lỗi database is locked; điểm HPO tụt mạnh trên holdout |
Cấm sqlite:// khi n_jobs > 1; kiểm tra tiền xử lý nằm trong CV |
Dùng PostgreSQL / JournalStorage, khớp tiền xử lý bên trong từng nếp |
3.4 Kỷ luật Thống kê Sản xuất Khi Đẩy GBDT/AutoML & Tabular FM Lên A/B Test (Principal Industrial Tip #7)#
Vượt qua OOF AUC ngoại tuyến và chưng cất FAST-DAD < 1 ms mới chỉ đi được nửa đường: khi đưa mô hình GBDT hoặc mô hình nền tảng bảng mới (TabPFN-2.5, TabICLv2, LimiX-2, Mitra) vào thử nghiệm A/B trực tuyến, 4 bẫy thống kê & vận hành sản xuất sau thường xuyên biến một mô hình tốt thành thảm họa phát hành giả:
- Cấm
PeekingTrực tiếp bằng \(t\)-Test Cố định — Bắt buộc DùngmSPRT(Always-Valid p-Values): Nếu nhóm sản phẩm mở dashboard kiểm tra \(p\)-value mỗi ngày và dừng sớm ngay khi \(p < 0.05\), tỷ lệ dương tính giả thực tế nhảy vọt từ5%lên25%–40%. Phải chuyển sang kiểm định tuần tự hỗn hợpmSPRT(mixture Sequential Probability Ratio Test): \(\Lambda_n^{\text{mix}} = \int \prod_{i=1}^n \frac{f_\theta(x_i)}{f_0(x_i)}\, dH(\theta)\) với \(p_n^{\text{seq}} = \min_{k \le n}(1/\Lambda_k^{\text{mix}})\), đảm bảo \(\mathbb{P}_{H_0}(\exists n \ge 1: p_n^{\text{seq}} \le \alpha) \le \alpha\) tại mọi thời điểm dừng tùy ý (kể cả khi phải ngắt gấp lúc 2 giờ sáng). - Kiểm soát Tỷ lệ Khám phá Sai đa Biến thể / đa Chỉ số (
BHvs.BYFDR): Khi thử đồng thời \(m = 20\) cấu hìnhGBDT/Optunahoặc theo dõi15chỉ số KPI phụ, áp dụngBenjamini–Hochberg(BH, \(p_{(k)} \le \frac{k}{m}q\)) khi các giả thuyết độc lập/tương quan dương (PRDS), và chuyển sangBenjamini–Yekutieli(BY, chia thêm thừa số điều hòa \(c(m) = \sum_{j=1}^m j^{-1} \approx \ln m + \gamma\)) khi chỉ số tương quan âm chéo (nhưCTRvsBouncevsp99 Latency). Đánh đổi thực tế:BYan toàn tuyệt đối dưới mọi cấu trúc tương quan nhưng chặt hơnBHkhoảng3.3xtại \(m=20\), đòi hỏi ghépCUPEDgiảm phương sai tiền thử nghiệm để tránh hụt công suất phát hiện. - Chẩn đoán
Sample Ratio Mismatch(SRM\(\chi^2\), \(p < 10^{-4}\)): Luôn chạy kiểm định \(\chi^2\) kiểm tra tỷ lệ lưu lượng thực nhận (50/50) trước khi đọc bất kỳ chỉ số chuyển đổi nào. Khi thử nghiệmTabPFN-2.5/TabICLv2/LimiX-2/Mitra/AutoGluonnặng (15–250 ms) đối đầuLightGBM(< 2 ms), nhánh chậm thường gặp rò rỉ chọn lọc theo độ trễ (latency-induced attrition): các yêu cầu vượttimeout gatewaybị hủy trước khi ghi log phơi nhiễm, làm nhánh điều trị mất chính xác nhóm khách nhiều đặc trưng nhất và tạoSRMnghiêm trọng — mọi kết luận khiSRMđỏ đều bị hủy bỏ! - Đánh đổi Phục vụ Giữa
TabICLv2/LimiX-2/MitravàGBDTDưới Dịch chuyển Phân phối: Không đưa nguyên mô hình ngữ cảnh lên phục vụ trực tuyến khi tập hỗ trợ \(\mathcal{D}_{\text{ctx}}\) lớn vượt ngân sách VRAM/độ trễ hoặc khi dữ liệu trôi phân phối ngoài miền tổng hợp: hãy dùngTabICLv2,LimiX-2hoặcMitralàm mô hình thầy mạnh trên lát cắt lịch sử gần nhất đã chuẩn hóaPIT, rồi chưng cất sangLightGBM+Treeliteđể vừa khóaSLA < 3 ms, vừa dễ tái huấn luyện theo lịch hằng ngày và áp ràng buộc đơn điệuSR 11-7.
3.5 Mã nguồn Thực thi Hệ sinh thái 2026 (CART 1-SE, LightGBM Đơn điệu, Interventional TreeSHAP, OOF Stacking & Optuna TPE + ASHA)#
(Ghi chú rạch ròi: Các khối mã dưới đây chạy trực tiếp trong .venv bằng scikit-learn, LightGBM, SHAP, và Optuna; còn gói lab trees_gbdt_lab ở Trụ cột 4 cài đặt toàn bộ thuật toán từ con số 0 trên Python stdlib + NumPy + Pandas + Pydantic v2 kèm kiểm soát AST bảo mật deserialization.)
from __future__ import annotations
import warnings
import lightgbm as lgb
import numpy as np
import optuna
import shap
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
optuna.logging.set_verbosity(optuna.logging.WARNING)
warnings.filterwarnings("ignore", message=".*feature names.*")
def demo_ccp_1se_pruning_and_monotone_treeshap(seed: int = 42) -> dict[str, float]:
"""Demonstrate CART 1-SE pruning, monotone GBDT, and Interventional TreeSHAP Dummy invariance."""
rng = np.random.default_rng(seed)
n = 600
dti = rng.uniform(0.1, 0.9, size=n)
zip_proxy = 0.97 * dti + rng.normal(0.0, 0.05, size=n)
income = rng.uniform(20.0, 150.0, size=n)
X_clf = np.column_stack([dti, zip_proxy, income])
y_bin = (rng.uniform(size=n) < 1.0 / (1.0 + np.exp(-(3.5 * dti - 0.03 * income)))).astype(int)
# 1. Minimal Cost-Complexity Pruning + 1-SE rule
base_tree = DecisionTreeClassifier(random_state=seed)
path = base_tree.cost_complexity_pruning_path(X_clf[:400], y_bin[:400])
alphas = np.unique(path.ccp_alphas)[::max(1, len(path.ccp_alphas) // 8)]
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
cv_scores = [
cross_val_score(
DecisionTreeClassifier(ccp_alpha=float(a), random_state=seed),
X_clf[:400],
y_bin[:400],
cv=cv,
)
for a in alphas
]
means = [float(np.mean(sc)) for sc in cv_scores]
ses = [float(np.std(sc, ddof=1) / np.sqrt(5.0)) for sc in cv_scores]
best_i = int(np.argmax(means))
one_se_alpha = float(max(a for a, m in zip(alphas, means) if m >= means[best_i] - ses[best_i]))
pruned_tree = DecisionTreeClassifier(ccp_alpha=one_se_alpha, random_state=seed).fit(X_clf[:400], y_bin[:400])
# 2. LightGBM Monotone Constraint (+1 on dti, -1 on income) on active 2 features (proxy excluded)
X_act = np.column_stack([dti, income])
y_reg = 4.0 * dti - 0.02 * income + rng.normal(0.0, 0.15, size=n)
gbm_mono = lgb.LGBMRegressor(
n_estimators=40, learning_rate=0.08, num_leaves=15, monotone_constraints=[1, -1], random_state=seed, verbose=-1
).fit(X_act[:450], y_reg[:450])
dti_grid = np.column_stack([np.linspace(0.1, 0.9, 50), np.full(50, 80.0)])
mono_violations = int(np.sum(np.diff(gbm_mono.predict(dti_grid)) < -1e-12))
# 3. Interventional TreeSHAP vs Path-Dependent Dummy invariance on unused correlated proxy
X_with_unused_proxy = np.column_stack([dti, zip_proxy, income])
gbm_clean_2col = lgb.LGBMRegressor(
n_estimators=30, learning_rate=0.1, num_leaves=8, monotone_constraints=[1, 0, -1], random_state=seed, verbose=-1
)
X_zero_proxy_train = X_with_unused_proxy[:450].copy()
X_zero_proxy_train[:, 1] = 0.0 # Constant in train -> proxy receives 0 splits while test proxy varies strongly!
gbm_clean_2col.fit(X_zero_proxy_train, y_reg[:450])
expl_int = shap.TreeExplainer(
gbm_clean_2col, data=X_with_unused_proxy[:100], feature_perturbation="interventional"
)
phi_int = np.asarray(expl_int.shap_values(X_with_unused_proxy[450:500]))
return {
"pruned_leaves": int(pruned_tree.get_n_leaves()),
"mono_violations": mono_violations,
"interventional_unused_proxy_max_abs_phi": float(np.max(np.abs(phi_int[:, 1]))),
}
def demo_oof_stacking_and_optuna_tpe_asha(seed: int = 42) -> dict[str, float]:
"""Demonstrate OOF StackingClassifier and Optuna TPE + HyperbandPruner."""
rng = np.random.default_rng(seed)
X = rng.normal(0.0, 1.0, size=(500, 8))
y = (rng.uniform(size=500) < 1.0 / (1.0 + np.exp(-(1.2 * X[:, 0] - 0.9 * X[:, 1] + 0.7 * X[:, 0] * X[:, 2])))).astype(int)
X_tr, y_tr, X_te, y_te = X[:350], y[:350], X[350:], y[350:]
stack = StackingClassifier(
estimators=[
("rf", RandomForestClassifier(n_estimators=30, max_depth=5, random_state=seed)),
("lgb", lgb.LGBMClassifier(n_estimators=30, num_leaves=15, random_state=seed, verbose=-1)),
],
final_estimator=LogisticRegression(),
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=seed),
).fit(X_tr, y_tr)
oof_auc = float(roc_auc_score(y_te, stack.predict_proba(X_te)[:, 1]))
def objective(trial: optuna.Trial) -> float:
lr = trial.suggest_float("learning_rate", 0.02, 0.25, log=True)
leaves = trial.suggest_int("num_leaves", 7, 31)
scores = cross_val_score(
lgb.LGBMClassifier(n_estimators=25, learning_rate=lr, num_leaves=leaves, random_state=seed, verbose=-1),
X_tr, y_tr, cv=3, scoring="roc_auc",
)
return float(np.mean(scores))
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(multivariate=True, seed=seed),
pruner=optuna.pruners.HyperbandPruner(),
)
study.optimize(objective, n_trials=10)
return {"oof_stack_auc": round(oof_auc, 4), "optuna_best_cv_auc": round(float(study.best_value), 4)}
if __name__ == "__main__":
print("CCP/Monotone/TreeSHAP:", demo_ccp_1se_pruning_and_monotone_treeshap())
print("OOF Stacking & Optuna TPE:", demo_oof_stacking_and_optuna_tpe_asha())
Trụ cột 4 — Phòng Thí nghiệm Công nghiệp & Kiểm chứng Chống Rò rỉ (trees_gbdt_lab)#
4.1 Kiến trúc Gói Python stdlib + NumPy + Pandas + Pydantic v2 (uv.lock & AST Bảo mật Deserialization)#
Gói trees_gbdt_lab cài đặt toàn bộ cây quyết định, cắt tỉa, RF/ExtraTrees, GBDT bậc hai, TreeSHAP, PDP/ICE/ALE, TPE + ASHA, và đối chiếu TabFM từ nguyên lý gốc với hợp đồng cấu hình Pydantic v2 (extra="forbid"), quản lý phụ thuộc qua uv.lock, và kiểm soát AST bảo mật deserialization (0 import pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal):
labs/ch10-trees-gbdt-and-automl-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch10_workbench_results.json
├── src/
│ └── trees_gbdt_lab/
│ ├── __init__.py
│ ├── cart_and_ensembles.py # CART (Gini/Entropy/MSE/MAE), CCP 1-SE, Rule Extract, RF/ExtraTrees+OOB, 2nd-Order GBDT (Hist Sub/GOSS/Ordered/Monotone), OOF vs In-Sample Stacking & Caruana
│ └── shap_and_hpo.py # Exact TreeSHAP (Alg-2 & Interventional) + 2^d Brute-Force, PDP/ICE/ALE, Grid/Random/TPE/ASHA/DE HPO, TabFM vs GBDT Regimes & Benchmark Runner
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_trees_gbdt_lab.py # 14/14 kiểm thử hợp đồng (gồm AST bảo mật deserialization)
4.2 Kết quả Thực nghiệm CLI (artifacts/ch10_workbench_results.json)#
Chạy một lệnh duy nhất từ thư mục gốc của Lab:
python scripts/run_lab_demo.py --output artifacts/ch10_workbench_results.json
Báo cáo artifacts/ch10_workbench_results.json xuất đầy đủ workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% các thông số thực đo dưới đây:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm Chính xác | Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_cart_pruning_and_rf_rho |
39->8 lvs | rho 0.63->0.41 (Leaves / rho) |
ok — Cắt tỉa CCP 1-SE nâng độ chính xác holdout 0.733 -> 0.760 (\(\alpha_{1\text{-SE}} = 0.0087\)); định danh phương sai RF khớp tới 5.55e-17 (OOB = 0.839, bao gồm 0.635); Misclass = -0.0000 vs Gini = 0.0584, Entropy = 0.1081 bits. |
kpi_gbdt_hist_goss_and_mono |
AUC 0.787 | 0 Mono Viol (11.2x VarCut) |
ok — Hist (43,428 bins) tiệm cận Exact (0.808, 152,772 evals) và tiết kiệm 20,669 lượt quét; GOSS giảm phương sai 11.2x (1433.08 -> 127.84, bias = 0.2357); kẹp cận đơn điệu xóa vi phạm 17 -> 0 (AUC = 0.803); Ordered TS thu hẹp gap CatBoost 0.308 -> 0.180 (OOT 0.642 -> 0.732). |
kpi_treeshap_parity_and_proxy_trap |
2.2e-16 | Proxy 0.345->0.0 (Max Err) |
warn — TreeSHAP Path (2.22e-16) và Interventional (1.44e-15) khớp tuyệt đối vét cạn \(2^d\); Observational rò 0.345 (0.3447) sang zip_proxy (\(\rho = 0.966\)) dù không tách nút vs 0.000 Interventional; PDP lệch ngoài đa tạp MAE = 8.809 vs ALE = 0.000. |
kpi_oof_vs_insample_stacking |
In 0.769 -> OOF 0.845 (Test AUC) |
critical — In-Sample dồn w_RF = 0.99 (train = 1.000 -> test = 0.769, logloss = 2.184); OOF + Caruana hạ w_RF = 0.03 đạt 0.845 (logloss = 0.484); mô hình học trò chưng cất đạt 0.848. |
kpi_hpo_tpe_asha_speedup |
-55.6% Evals | LL 0.504 (Pruned) |
ok — TPE + ASHA chỉ dùng 440 lượt đánh giá cây (cắt 14 thử nghiệm, so với 990 không cắt / 720 Grid / 810 DE; Grid LL = 0.4990, Random LL = 0.4801); trên \(6\text{D}\) (\(d_{\text{eff}} = 2\)), Random (64 giá trị x_0, -0.0005) thắng Grid (2 giá trị x_0, 0.1498). |
kpi_tabular_fm_vs_gbdt_crossover |
Small 0.843 | Large GBDT 0.703 (Regime AUC) |
ok — Bảng mượt nhỏ (n=220): TabFM không HPO (0.843) thắng GBDT (0.823); bảng lớn lệch đuôi (n=3200): GBDT thắng (0.703 vs 0.647) tại 0.044 ms/row (0.241 ms quét ngữ cảnh) với 0 vi phạm đơn điệu. |
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_trees_gbdt_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_01_cart_splitting_criteria_misclass_zero_gain_mae_and_xor |
Khẳng định delta_misclassification == 0, delta_gini == 289/4950, delta_entropy > 0.09, cây MAE giữ đúng trung vị 1.0 trước ngoại lai 100.0 (vs MSE > 15.0), và đường xiên 1 tách (2 lá) thắng cây song trục. |
| 2 | test_02_cart_minimal_cost_complexity_pruning_and_1se |
Kiểm chứng dãy \(\alpha_k\) tăng đơn điệu, số lá giảm nghiêm ngặt về 1, và chọn lọc CV 1-SE cắt giảm số lá đồng thời cải thiện độ chính xác kiểm định. |
| 3 | test_03_cart_rule_extraction_and_pydantic_config_forbid |
Khẳng định luật IF ... THEN pred=... bao phủ toàn bộ 100% mẫu không chồng lấn và Pydantic extra="forbid" từ chối tham số sai/lạ. |
| 4 | test_04_random_forest_variance_identity_mtry_extratrees_and_oob |
Khẳng định hằng đẳng thức phương sai abs_diff < 1e-10, bao gồm bootstrap ~63.2%, OOB tiệm cận holdout, và \(\rho_{\text{ExtraTrees}} < \rho_{\text{mtry}} < \rho_{\text{bag}}\). |
| 5 | test_05_gbdt_second_order_newton_exact_vs_histogram_and_interactions |
Đối chiếu nghiệm lá đóng \(w_j^* = -G_j/(H_j+\lambda)\) tới < 1e-10, kiểm chứng hist tiết kiệm phép quét và tương đồng exact, và khẳng định không vi phạm interaction_constraints. |
| 6 | test_06_gbdt_goss_unbiasedness_and_monotonic_constraints |
Khẳng định GOSS không chệch với giảm phương sai > 5x và kẹp cận monotone_constraints giữ 0 vi phạm trên cả chiều +1 và -1. |
| 7 | test_07_catboost_prediction_shift_vs_ordered_target_stats |
Chứng minh NaiveTE tạo khoảng cách rò rỉ train-test lớn hơn hẳn Ordered TS trên biến ID nhiều mức (high-cardinality). |
| 8 | test_08_oof_stacking_vs_insample_trap_caruana_and_distillation |
Khẳng định In-Sample gán w_RF > 0.70 và sụp đổ ngoài mẫu, còn OOF + Caruana hạ w_RF, tăng test AUC > +0.04 và mô hình học trò chưng cất giữ >= 95% AUC giáo viên. |
| 9 | test_09_treeshap_exact_parity_with_bruteforce_and_axioms |
Đối chiếu cả Path-Dependent và Interventional TreeSHAP với vét cạn \(2^d\) sai khác < 1e-10, kiểm chứng tiên đề Efficiency và Additivity. |
| 10 | test_10_treeshap_proxy_trap_and_pdp_vs_ale |
Khẳng định Observational rò \(|\phi_{\text{proxy}}| > 0.05\) sang biến không tách nút trong khi Interventional < 1e-12; ALE cắt sai số ngoài đa tạp của PDP xuống < 0.25x. |
| 11 | test_11_bergstra_bengio_random_vs_grid_effective_dim |
Chứng minh trên không gian 6D (\(d_{\text{eff}} = 2\)), Grid chỉ thử 2 giá trị trục hữu hiệu còn Random thử >= 50 và đạt loss thấp hơn rõ rệt. |
| 12 | test_12_optuna_tpe_and_asha_outperform_grid_random |
Kiểm chứng TPE tìm tối ưu 2D < 0.05 trong 40 bước và TPE + ASHA tiết kiệm >= 35% lượt cây với ít nhất 4 thử nghiệm bị cắt tỉa. |
| 13 | test_13_tabular_fm_vs_gbdt_regime_boundaries |
Khẳng định TabFM thắng trên bảng mượt nhỏ (n=220), còn GBDT thắng trên bảng lớn lệch đuôi kèm 0 vi phạm đơn điệu và độ trễ đơn dòng thấp hơn. |
| 14 | test_14_cli_demo_workbench_json_and_zero_forbidden_imports |
Chạy run_lab_demo.py, kiểm tra cấu trúc workbench_panels (6 KPI, 4 bar, 4 bảng) và quét AST bảo mật deserialization khẳng định 0 import không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bộ Đánh giá Năng lực (SOTA Reading List & Mastery Assessment)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Breiman, L., Friedman, J. H., Olshen, R. A., & Stone, C. J. (1984); Breiman, L. (2001); Geurts, P., Ernst, D., & Wehenkel, L. (2006). Classification and Regression Trees; Random Forests (
Machine Learning); Extremely Randomized Trees.
Vì sao quan trọng: Thiết lập toàn bộ nền móngCART, định lý chuỗi cây con lồng nhauCCP 1-SE, hằng đẳng thức giảm phương sai bằngmtryvàExtraTrees, cùng ước lượngOOB. - Chen, T., & Guestrin, C. (KDD 2016); Ke, G., et al. (NeurIPS 2017); Prokhorenkova, L., et al. (NeurIPS 2018); Cho, H., & Li, M. (MLSys 2018).
Vì sao quan trọng: Bộ tứ kinh điển của GBDT hiện đại: Newton bậc hai + Weighted Quantile Sketch (XGBoost),GOSS+EFB+ Leaf-wise Histogram (LightGBM),Ordered Boosting+Ordered TS+ Oblivious SIMD (CatBoost), và biên dịch suy luận C không phụ thuộc (Treelite). - Hollmann, N., et al. (
TabPFN v2, Nature 2025); Grinsztajn, L., et al. (TabPFN-2.5, 2025); Qu, J., et al. (TabICL, ICML 2025); Gorishniy, Y., et al. (TabM, ICLR 2025); Erickson, N., et al. (TabArena, NeurIPS 2025).
Vì sao quan trọng: Định hình bản đồ đối đầu SOTA 2025–2026 giữa Tabular Foundation Models (chú ý hai chiều trên tiền nghiệmSCMkhông cầnHPO),TabM(PLR+BatchEnsemble), vàGBDTtheo quy mô mẫu và độ trễ phục vụ. - Lundberg, S. M., et al. (
TreeSHAP, Nature Machine Intelligence 2020); Yu, P., et al. (Linear TreeSHAP, NeurIPS 2022); Janzing, D., et al. (AISTATS 2020); Chen, H., et al. (2020); Apley, D. W., & Zhu, J. (JRSS-B 2020).
Vì sao quan trọng: Hạ độ phức tạpTreeSHAPvề đa thức tuyến tính \(\mathcal{O}(B L D)\), phân rạch triệt đểObservationalvsInterventionalchống rò rỉ biến đại diện nhạy cảm, và thayPDPngoại suy giả bằngALE. - Bergstra, J., & Bengio, Y. (JMLR 2012); Akiba, T., et al. (
Optuna, KDD 2019); Li, L., et al. (ASHA, MLSys 2020); Erickson, N., et al. (AutoGluon-Tabular, 2020); Fakoor, R., et al. (FAST-DAD, NeurIPS 2020).
Vì sao quan trọng: Chứng minh tính ưu việt của tìm kiếm ngẫu nhiên ở chiều hiệu dụng thấp, thiết lập chuẩnOptuna TPE+ cắt tỉa bất đồng bộASHA,OOFMulti-Layer Stacking kết hợp chọn lọcCaruana, và chưng cất về học trò< 1 ms.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Chứng minh bằng bất đẳng thức Jensen vì sao
Gini(\(\alpha(1-\alpha)\|\mathbf{p}_L - \mathbf{p}_R\|_2^2\)) vàEntropyluôn tách thuần nhất hóa, cònMisclassification Errorcho độ lợi0.0000trên phép tách(70, 30) -> (40, 5) | (30, 25)? - Q2: Giải thích cơ chế đường cắt yếu nhất \(g(t)\) trong
Minimal Cost-Complexity Pruning, vì sao quy tắc1-SEcắt cây từ39 -> 8lá lại tăng độ chính xác (0.733 -> 0.760), và vì sao cây song trục cần \(\Omega(2^d)\) lá cho bài toán chẵn lẻXOR? - Q3: Chứng minh hằng đẳng thức \(\operatorname{Var}(\bar{T}) = \rho\sigma^2 + \frac{1-\rho}{M}\sigma^2\), giải thích vì sao tăng \(M \to \infty\) không triệt tiêu được sàn \(\rho\sigma^2\), và khi nào cấm dùng ước lượng
OOB(63.21%) dù nó miễn phí? - Q4: Dẫn xuất công thức trọng số lá tối ưu \(w_j^* = -\frac{G_j}{H_j + \lambda_{\text{reg}}}\) và độ lợi tách nút \(\mathcal{L}_{\text{split}}\) của
GBDTbậc hai, giải thích ý nghĩa Fisher củamin_child_weightởLog-Loss, và cơ chế kẹp cận điểm giữa giúp triệt tiêu vi phạm đơn điệu (17 -> 0)? - Q5: So sánh ba động cơ
XGBoost(hist+ Weighted Quantile Sketch),LightGBM(GOSSkhông chệch cắt phương sai11.2x+EFB+ phép trừ histogram), vàCatBoost(Ordered TShạ gap0.308 -> 0.180+ cây Oblivious \(2^D\) SIMD)? - Q6: Trong điều kiện nào
TabPFN v2/TabICLđánh bạiGBDTkhông cầnHPO(0.843vs0.823ởn = 220), và ba rào cản sản xuất nào khiếnGBDT(LightGBM/CatBoost/XGBoost) hoặcTabMgiành lại chiến thắng ở quy mô lớn (0.703ở0.044 ms/row)? - Q7: Giải thích cách
TreeSHAP(Algorithm 2) hạ vét cạn \(2^d\) về đa thức khớp sai số2.22e-16, vì saoObservational SHAPrò0.345sangzip_proxykhông được dùng trong cây so với0.000củaInterventional, và vì saoPDPsaiMAE = 8.809so vớiALE = 0.000? - Q8: Chứng minh đại số vì sao
In-Sample Stackingdồnw_RF = 0.99gây sập ngoài mẫu (1.000 -> 0.769), cơ chếOOF Stacking + Caruana + FAST-DADnâng lại0.845 -> 0.848, và công thức \(\ell(\mathbf{x})/g(\mathbf{x})\) củaOptuna TPE + ASHAcắt-55.6%chi phí tìm kiếm?
5.3 Sáu Bài tập Thực hành & Chứng minh Tính điểm (Ex1–Ex6)#
- Bài tập 1 (
15%): Chứng minh bất đẳng thức độ lợiGini/EntropyvsMisclassification Error, nghiệm trung vị củaMAEvà cận dưới \(\Omega(2^d)\)XOR; kiểm chứng thực nghiệm trêndemonstrate_misclassification_zero_gain,CARTDecisionTree(msevsmae), vàdiagonal_xor_staircase_audit. - Bài tập 2 (
15%): Chứng minh Định lý Chuỗi Cây con Lồng nhau của Breiman; chạycost_complexity_pruning_path()vàselect_ccp_alpha_1se(), ghi nhận giảm39 -> 8lá và tăng độ chính xác holdout, đồng thời trích xuất và kiểm chứng độ phủ 100% củaextract_rules(). - Bài tập 3 (
15%): Dẫn xuất \(\rho\sigma^2 + \frac{1-\rho}{M}\sigma^2\) và tỷ lệ bao gồm \(1 - e^{-1}\); kiểm chứngverify_rf_variance_identity(sai khác< 1e-10) và đối chiếu giảm \(\rho\) từBagging(0.632) ->Random Forest mtry(0.507) ->ExtraTrees(0.406) cùngOOB = 0.839. - Bài tập 4 (
20%): Dẫn xuấtw_j^*và \(\mathcal{L}_{\text{split}}\) từ Taylor bậc hai + chứng minh tính không chệch củaGOSS; chạySecondOrderGBDT(exactvshisttiết kiệm20,669lượt quét,use_goss=True), kiểm toánmonotone_constraints(17 -> 0vi phạm) vàordered_boosting_prediction_shift_demo(0.308 -> 0.180). - Bài tập 5 (
20%): Triển khai đối chiếuTreeSHAPExplainer(path_dependent_shap&interventional_shap) khớpbruteforce_shapley_tree\(2^d\) tới< 1e-10; tái lập bẫy rò rỉ proxy (0.345 -> 0.000) và sai lệch ngoại suyPDP(8.809) vsALE(0.000). - Bài tập 6 (
15%): Tái lập thảm họaIn-Sample Stacking(w_RF = 0.99 -> 0.769) vsOOF + Caruana + Distillation(0.845 -> 0.848), chạy đuaGridvsRandom(\(6\text{D}\)) vsTPEOptimizer+ASHAOptimizer(-55.6%evals) và đối chiếu hai miềnTabFMvsGBDT, vượt trọn vẹn14/14kiểm thửpytest.
5.4 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh chặt chẽ không nhảy bước (lồi lõm chặt Gini/Entropy, lồng nhau CCP, phương sai RF, sụp đổ In-Sample Stacking, GBDT Taylor bậc hai + kẹp đơn điệu, GOSS, TreeSHAP Algorithm 2, tương đương \(\ell/g\) của TPE & Bergstra–Bengio); trees_gbdt_lab vượt 14/14 pytest với 0 import deserialization không an toàn (Test 14), TreeSHAP khớp vét cạn \(2^d\) dưới < 1e-10, và chưng cất OOF đạt < 1 ms CPU với 0 vi phạm đơn điệu. |
| Senior Standard | 75–89% | Triển khai thông suốt 14/14 pytest thuần NumPy/Pandas/Pydantic, nắm chắc vận hành OOF Stacking, XGBoost/LightGBM/CatBoost, TreeSHAP, và Optuna TPE + ASHA, nhưng còn thiếu chiều sâu khi chứng minh vì sao Observational SHAP vi phạm tiên đề Dummy hoặc ranh giới TabPFN v2 vs GBDT. |
| Needs Remediation | < 75% | Dùng sai số phân loại làm tiêu chuẩn tách CART; để RF hoặc LightGBM không ràng buộc tràn RAM/lát cắt; dùng OOB trên dữ liệu chuỗi thời gian; khớp tầng meta trên dự báo In-Sample; giải thích từ chối tín dụng bằng Observational SHAP hay PDP ngoại suy; đẩy AutoGluon / TabPFN thô vào API < 2 ms; hoặc để lọt pickle/joblib (CWE-502) trong lab. |
RF Pairwise Correlation rho (mtry / ExtraTrees) & CART 1-SE Holdout Acc
Stacking Leakage Audit: In-Sample Collapse vs OOF Caruana & Distilled Student AUC
HPO Cumulative Tree Evaluations: Grid vs Random vs DE vs Optuna TPE+ASHA
Explainability Distortion (Obs Proxy Leak & PDP OOD MAE vs Interventional & ALE)
CART Splitting Pathologies, Cost-Complexity 1-SE Pruning & RF Decorrelation
| experiment | baseline_metric | remediated_metric | structural_detail | verdict |
|---|---|---|---|---|
| misclass_zero_gain | delta_err=-0.0000 | delta_gini=0.0584 | delta_H=0.1081 bits | USE_STRICT_CONCAVE |
| diagonal_staircase | depth2_acc=0.862 | depth8_acc=0.955 | leaves=28 vs Oblique=2 | AXIS_STAIRCASE_WALL |
| ccp_1se_pruning | unpruned_lvs=39 (0.733) | 1se_lvs=8 (0.760) | alpha_1se=0.0087 | PARSIMONY_IMPROVED |
| rf_variance_identity | emp_var=0.20962 | rhs=0.20962 | rho=0.079, diff=5.6e-17 | IDENTITY_EXACT |
| rf_mtry_extratrees | bag_rho=0.632 | mtry=0.507 | ET=0.406 | OOB=0.839, inc=0.635 | DECORRELATED |
2nd-Order GBDT: Hist Subtraction, GOSS Variance, CatBoost Shift & Monotone Bounds
| mechanism | baseline_or_unconstrained | sota_engine_method | diagnostic_value | compliance_status |
|---|---|---|---|---|
| hist_vs_exact_gbdt | Exact AUC=0.808 (152772 evals) | Hist AUC=0.787 (43428 bins) | scans_saved=20669 | HIST_PARITY |
| goss_gradient_est | Uniform var=1433.08 | GOSS var=127.84 | bias=0.2357, 11.2x cut | UNBIASED_LOW_VAR |
| catboost_pred_shift | NaiveTE gap=0.308 | OrderedTS gap=0.180 | OOT AUC 0.642->0.732 | SHIFT_MITIGATED |
| monotone_constraints | Unconstrained viol=17 | BoundClamp viol=0 | Monotone AUC=0.803 | SR11_7_PASS |
Exact TreeSHAP vs 2^d Brute-Force, Proxy Dummy Trap & PDP vs ALE Fidelity
| audit_test | observational_or_pdp | interventional_or_ale | exact_reference_diff | verdict |
|---|---|---|---|---|
| treeshap_path_vs_bf | max_diff=2.22e-16 | O(BLD^2) Alg-2 | vs 2^d Brute-Force | EXACT_PARITY |
| treeshap_int_vs_bf | max_diff=1.44e-15 | O(BLD*|B|) do(X_S) | vs 2^d Interventional | EXACT_PARITY |
| unused_proxy_dummy | Obs |phi_proxy|=0.3447 | Int |phi_proxy|=0.0000e+00 | rho_proxy=0.966 | INTERVENTIONAL_SAFE |
| pdp_vs_ale_manifold | PDP MAE=8.809 | ALE MAE=0.000 | Correlated X1~X0 | ALE_ON_MANIFOLD |
Stacking Leakage, Bergstra-Bengio / TPE+ASHA HPO & Tabular FM vs GBDT Regimes
| benchmark | naive_baseline | sota_method | key_gain_or_latency | recommendation |
|---|---|---|---|---|
| stacking_audit | In-Sample w_RF=0.99 (Test 0.769) | OOF+Caruana w_RF=0.03 (Test 0.845) | Distilled Student=0.848 | ALWAYS_OOF_DISTILL |
| bergstra_bengio_6d | Grid unique_x0=2 (0.1498) | Random unique_x0=64 (-0.0005) | hit_5pct=0.962 | RANDOM_BEATS_GRID |
| gbdt_hpo_suite | Grid LL=0.4990 (720 ev) | TPE+ASHA LL=0.5037 (440 ev) | Saved 55.6% | DE=810 ev | OPTUNA_TPE_ASHA |
| tfm_vs_gbdt_small | GBDT small AUC=0.823 | TabFM small AUC=0.843 | n=220, Zero HPO | TABPFN_SMALL_WINS |
| tfm_vs_gbdt_large | TabFM large AUC=0.647 (0.241 ms) | GBDT large AUC=0.703 (0.044 ms) | Mono viol=0 | GBDT_PROD_SLA_WINS |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/ch10-trees-gbdt-and-automl-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "trees-gbdt-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for CART Decision Trees & Minimal Cost-Complexity Pruning, Random Forests & ExtraTrees, 2nd-Order Newton GBDT (Hist/GOSS/Ordered Boosting/Monotonic Constraints), Tabular FM Regimes, Exact TreeSHAP vs Brute-Force, PDP/ICE/ALE, OOF Stacking vs In-Sample Trap, and Optuna TPE/ASHA HPO (T1-P2-U05)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.4",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
"""Pure NumPy/Pandas/Pydantic workbench for Decision Trees, GBDT, Tabular FMs, TreeSHAP & HPO (T1-P2-U05)."""
from .cart_and_ensembles import (
CARTConfig,
CARTDecisionTree,
GBDTConfig,
RandomForestConfig,
RandomForestWorkbench,
SecondOrderGBDT,
StackingConfig,
TreeNode,
audit_stacking_insample_vs_oof,
caruana_ensemble_selection,
compute_accuracy,
compute_binary_logloss,
compute_mse,
compute_roc_auc,
demonstrate_misclassification_zero_gain,
diagonal_xor_staircase_audit,
estimate_goss_gradient_sum,
gini_impurity,
mae_impurity,
misclassification_error,
mse_impurity,
ordered_boosting_prediction_shift_demo,
shannon_entropy,
stable_sigmoid,
)
from .shap_and_hpo import (
ASHAOptimizer,
BayesianTabularFMOracle,
TPEOptimizer,
TreeSHAPExplainer,
benchmark_tabular_fm_vs_gbdt_regimes,
bruteforce_shapley_tree,
compute_pdp_ice_ale,
de_metaheuristic_hpo,
grid_search_hpo,
random_search_hpo,
run_full_ch10_benchmarks,
)
__all__ = [
"ASHAOptimizer",
"BayesianTabularFMOracle",
"CARTConfig",
"CARTDecisionTree",
"GBDTConfig",
"RandomForestConfig",
"RandomForestWorkbench",
"SecondOrderGBDT",
"StackingConfig",
"TPEOptimizer",
"TreeNode",
"TreeSHAPExplainer",
"audit_stacking_insample_vs_oof",
"benchmark_tabular_fm_vs_gbdt_regimes",
"bruteforce_shapley_tree",
"caruana_ensemble_selection",
"compute_accuracy",
"compute_binary_logloss",
"compute_mse",
"compute_pdp_ice_ale",
"compute_roc_auc",
"de_metaheuristic_hpo",
"demonstrate_misclassification_zero_gain",
"diagonal_xor_staircase_audit",
"estimate_goss_gradient_sum",
"gini_impurity",
"grid_search_hpo",
"mae_impurity",
"misclassification_error",
"mse_impurity",
"ordered_boosting_prediction_shift_demo",
"random_search_hpo",
"run_full_ch10_benchmarks",
"shannon_entropy",
"stable_sigmoid",
]
"""CART Decision Trees, Cost-Complexity Pruning, Random Forests, 2nd-Order GBDT & Stacking (Pure NumPy/Pandas/Pydantic)."""
from __future__ import annotations
import copy
import heapq
import math
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
# ---------------------------------------------------------------------------
# Shared Numeric Helpers & Metrics (Zero External ML Dependencies)
# ---------------------------------------------------------------------------
def stable_sigmoid(z: np.ndarray) -> np.ndarray:
"""Overflow-safe logistic sigmoid over arbitrary float64 arrays."""
arr = np.asarray(z, dtype=np.float64)
out = np.empty_like(arr)
pos = arr >= 0.0
out[pos] = 1.0 / (1.0 + np.exp(-np.clip(arr[pos], 0.0, 500.0)))
ez = np.exp(np.clip(arr[~pos], -500.0, 0.0))
out[~pos] = ez / (1.0 + ez)
return out
def compute_binary_logloss(y_true: np.ndarray, y_prob: np.ndarray) -> float:
"""Numerically clipped binary cross-entropy loss."""
y = np.asarray(y_true, dtype=np.float64)
p = np.clip(np.asarray(y_prob, dtype=np.float64), 1e-12, 1.0 - 1e-12)
return float(-np.mean(y * np.log(p) + (1.0 - y) * np.log(1.0 - p)))
def compute_roc_auc(y_true: np.ndarray, y_score: np.ndarray) -> float:
"""Exact tie-aware Mann-Whitney U ROC-AUC in pure NumPy."""
y = np.asarray(y_true, dtype=np.int64)
s = np.asarray(y_score, dtype=np.float64)
n_pos = int(np.sum(y == 1))
n_neg = int(np.sum(y == 0))
if n_pos == 0 or n_neg == 0:
return 0.5
order = np.argsort(s, kind="mergesort")
s_sorted = s[order]
y_sorted = y[order]
ranks = np.empty(len(s), dtype=np.float64)
i = 0
n = len(s)
while i < n:
j = i + 1
while j < n and s_sorted[j] == s_sorted[i]:
j += 1
avg_rank = 0.5 * (i + 1 + j)
ranks[i:j] = avg_rank
i = j
pos_rank_sum = float(np.sum(ranks[y_sorted == 1]))
auc = (pos_rank_sum - 0.5 * n_pos * (n_pos + 1)) / (n_pos * n_neg)
return float(auc)
def compute_accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Fraction of exact class matches."""
return float(np.mean(np.asarray(y_true) == np.asarray(y_pred)))
def compute_mse(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Mean squared error."""
diff = np.asarray(y_true, dtype=np.float64) - np.asarray(y_pred, dtype=np.float64)
return float(np.mean(diff * diff))
def fit_ridge_logistic_or_linear(
X_train: np.ndarray,
y_train: np.ndarray,
task: Literal["classification", "regression"],
l2_alpha: float = 1.0,
max_iter: int = 40,
) -> tuple[float, np.ndarray]:
"""Fit L2-regularized linear (QR/normal via cholesky/lstsq) or logistic (IRLS) model."""
X = np.asarray(X_train, dtype=np.float64)
y = np.asarray(y_train, dtype=np.float64)
n, d = X.shape
X_aug = np.column_stack([np.ones(n, dtype=np.float64), X])
pen = np.eye(d + 1, dtype=np.float64) * l2_alpha
pen[0, 0] = 0.0
if task == "regression":
gram = X_aug.T @ X_aug + pen
rhs = X_aug.T @ y
beta = np.linalg.solve(gram, rhs)
return float(beta[0]), beta[1:].copy()
beta = np.zeros(d + 1, dtype=np.float64)
p0 = float(np.clip(np.mean(y), 1e-4, 1.0 - 1e-4))
beta[0] = math.log(p0 / (1.0 - p0))
for _ in range(max_iter):
eta = X_aug @ beta
p = stable_sigmoid(eta)
w = np.maximum(p * (1.0 - p), 1e-8)
grad = X_aug.T @ (p - y) + pen @ beta
hess = (X_aug.T * w) @ X_aug + pen
step = np.linalg.solve(hess + 1e-9 * np.eye(d + 1), grad)
beta -= step
if float(np.linalg.norm(step)) < 1e-8:
break
return float(beta[0]), beta[1:].copy()
# ---------------------------------------------------------------------------
# Pydantic v2 Strict Config Contracts
# ---------------------------------------------------------------------------
class CARTConfig(BaseModel):
"""Configuration for CART decision tree classification or regression."""
model_config = ConfigDict(frozen=True, extra="forbid")
task: Literal["classification", "regression"] = "classification"
criterion: Literal["gini", "entropy", "mse", "mae"] = "gini"
max_depth: int = Field(default=8, ge=1, le=32)
min_samples_split: int = Field(default=2, ge=2)
min_samples_leaf: int = Field(default=1, ge=1)
ccp_alpha: float = Field(default=0.0, ge=0.0)
max_features: int | None = Field(default=None, ge=1)
random_thresholds: bool = False
n_classes: int | None = Field(default=None, ge=2)
seed: int = 42
class RandomForestConfig(BaseModel):
"""Configuration for Random Forest / ExtraTrees ensemble workbench."""
model_config = ConfigDict(frozen=True, extra="forbid")
task: Literal["classification", "regression"] = "classification"
criterion: Literal["gini", "entropy", "mse", "mae"] = "gini"
n_estimators: int = Field(default=35, ge=2, le=500)
max_depth: int = Field(default=10, ge=1, le=32)
min_samples_leaf: int = Field(default=2, ge=1)
max_features: int | float | Literal["sqrt", "third"] = "sqrt"
bootstrap: bool = True
extra_trees: bool = False
seed: int = 42
class GBDTConfig(BaseModel):
"""Configuration for 2nd-order Newton GBDT with Hist, GOSS & Monotonic Constraints."""
model_config = ConfigDict(frozen=True, extra="forbid")
loss: Literal["mse", "logloss"] = "logloss"
n_estimators: int = Field(default=35, ge=1, le=500)
learning_rate: float = Field(default=0.15, gt=0.0, le=1.0)
max_depth: int = Field(default=4, ge=1, le=12)
min_samples_leaf: int = Field(default=5, ge=1)
min_child_weight: float = Field(default=1.0, ge=0.0)
reg_lambda: float = Field(default=1.0, gt=0.0)
min_split_gain: float = Field(default=0.0, ge=0.0)
split_method: Literal["exact", "hist"] = "hist"
max_bins: int = Field(default=64, ge=4, le=256)
subsample: float = Field(default=1.0, gt=0.0, le=1.0)
colsample_bytree: float = Field(default=1.0, gt=0.0, le=1.0)
use_goss: bool = False
goss_top_rate: float = Field(default=0.2, gt=0.0, lt=1.0)
goss_other_rate: float = Field(default=0.1, gt=0.0, lt=1.0)
monotone_constraints: tuple[int, ...] | None = None
interaction_constraints: tuple[tuple[int, ...], ...] | None = None
seed: int = 42
class StackingConfig(BaseModel):
"""Configuration for Out-of-Fold vs In-Sample Stacking & Caruana selection."""
model_config = ConfigDict(frozen=True, extra="forbid")
task: Literal["classification", "regression"] = "classification"
n_folds: int = Field(default=5, ge=2, le=10)
ridge_alpha: float = Field(default=1.0, ge=0.0)
caruana_steps: int = Field(default=60, ge=5, le=300)
seed: int = 42
# ---------------------------------------------------------------------------
# Unified Tree Node Structure (Shared by CART, RF & GBDT + TreeSHAP)
# ---------------------------------------------------------------------------
@dataclass
class TreeNode:
"""Unified binary tree node used by CART, Random Forest, GBDT & TreeSHAP."""
node_id: int
is_leaf: bool
feature_idx: int
threshold: float
value: float
n_samples: int
hessian_sum: float = 0.0
impurity: float = 0.0
node_risk: float = 0.0
class_probs: np.ndarray | None = None
default_left: bool = True
left: TreeNode | None = None
right: TreeNode | None = None
def _count_leaves(node: TreeNode) -> int:
if node.is_leaf or node.left is None or node.right is None:
return 1
return _count_leaves(node.left) + _count_leaves(node.right)
def _subtree_risk(node: TreeNode) -> float:
if node.is_leaf or node.left is None or node.right is None:
return node.node_risk
return _subtree_risk(node.left) + _subtree_risk(node.right)
def _tree_depth(node: TreeNode) -> int:
if node.is_leaf or node.left is None or node.right is None:
return 0
return 1 + max(_tree_depth(node.left), _tree_depth(node.right))
# ---------------------------------------------------------------------------
# Impurity Criteria & Misclassification Zero-Gain Pathology
# ---------------------------------------------------------------------------
def gini_impurity(counts: np.ndarray) -> float:
"""Gini impurity 1 - sum(p_k^2) from integer or float class counts."""
total = float(np.sum(counts))
if total <= 0.0:
return 0.0
p = counts / total
return float(1.0 - np.sum(p * p))
def shannon_entropy(counts: np.ndarray) -> float:
"""Base-2 Shannon entropy -sum(p_k log2 p_k)."""
total = float(np.sum(counts))
if total <= 0.0:
return 0.0
p = counts[counts > 0.0] / total
return float(-np.sum(p * np.log2(p)))
def misclassification_error(counts: np.ndarray) -> float:
"""Misclassification impurity 1 - max_k p_k."""
total = float(np.sum(counts))
if total <= 0.0:
return 0.0
return float(1.0 - np.max(counts) / total)
def mse_impurity(y: np.ndarray) -> float:
"""Sample variance MSE impurity around mean."""
if len(y) == 0:
return 0.0
return float(np.var(y))
def mae_impurity(y: np.ndarray) -> float:
"""Mean absolute deviation around sample median."""
if len(y) == 0:
return 0.0
med = float(np.median(y))
return float(np.mean(np.abs(y - med)))
def demonstrate_misclassification_zero_gain() -> dict[str, Any]:
"""Exact counterexample: (70, 30) -> (40, 5) | (30, 25) gives Misclass gain=0 vs Gini/Entropy > 0."""
parent = np.array([70.0, 30.0])
left = np.array([40.0, 5.0])
right = np.array([30.0, 25.0])
w_l = float(np.sum(left) / np.sum(parent))
w_r = float(np.sum(right) / np.sum(parent))
delta_misclass = misclassification_error(parent) - (
w_l * misclassification_error(left) + w_r * misclassification_error(right)
)
delta_gini = gini_impurity(parent) - (
w_l * gini_impurity(left) + w_r * gini_impurity(right)
)
delta_entropy = shannon_entropy(parent) - (
w_l * shannon_entropy(left) + w_r * shannon_entropy(right)
)
return {
"parent_counts": [70, 30],
"left_counts": [40, 5],
"right_counts": [30, 25],
"delta_misclassification": float(delta_misclass),
"delta_gini": float(delta_gini),
"delta_entropy_bits": float(delta_entropy),
"theoretical_gini": 289.0 / 4950.0,
}
# ---------------------------------------------------------------------------
# Running Median Helper (for Exact MAE Splitting)
# ---------------------------------------------------------------------------
class _RunningMedian:
"""Dual-heap exact O(log n) running median & sum-of-abs-deviations tracker."""
def __init__(self) -> None:
self._low: list[float] = [] # max-heap stored as negated values
self._high: list[float] = [] # min-heap
self._sum_low = 0.0
self._sum_high = 0.0
def push(self, val: float) -> None:
if not self._low or val <= -self._low[0]:
heapq.heappush(self._low, -val)
self._sum_low += val
else:
heapq.heappush(self._high, val)
self._sum_high += val
self._rebalance()
def _rebalance(self) -> None:
if len(self._low) > len(self._high) + 1:
moved = -heapq.heappop(self._low)
self._sum_low -= moved
heapq.heappush(self._high, moved)
self._sum_high += moved
elif len(self._high) > len(self._low):
moved = heapq.heappop(self._high)
self._sum_high -= moved
heapq.heappush(self._low, -moved)
self._sum_low += moved
def abs_dev_sum(self) -> float:
if not self._low:
return 0.0
med = -self._low[0]
return float((len(self._low) * med - self._sum_low) + (self._sum_high - len(self._high) * med))
# ---------------------------------------------------------------------------
# CART Decision Tree + Minimal Cost-Complexity Pruning + Rule Extraction
# ---------------------------------------------------------------------------
class CARTDecisionTree:
"""Pure-NumPy CART Decision Tree supporting Gini/Entropy/MSE/MAE & Cost-Complexity Pruning."""
def __init__(self, config: CARTConfig | None = None, **kwargs: Any) -> None:
self.config = config if config is not None else CARTConfig(**kwargs)
self.root_: TreeNode | None = None
self.n_features_: int = 0
self.n_classes_: int = 0
self.n_samples_: int = 0
self._node_counter: int = 0
self._rng = np.random.default_rng(self.config.seed)
def _next_id(self) -> int:
nid = self._node_counter
self._node_counter += 1
return nid
def fit(self, X: np.ndarray, y: np.ndarray) -> CARTDecisionTree:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y)
self.n_samples_, self.n_features_ = X_arr.shape
self._node_counter = 0
self._rng = np.random.default_rng(self.config.seed)
if self.config.task == "classification":
y_int = y_arr.astype(np.int64)
inferred = int(np.max(y_int)) + 1 if len(y_int) > 0 else 2
self.n_classes_ = max(self.config.n_classes or 2, inferred)
self.root_ = self._build(X_arr, y_int, depth=0)
else:
y_flt = y_arr.astype(np.float64)
self.n_classes_ = 1
self.root_ = self._build(X_arr, y_flt, depth=0)
if self.config.ccp_alpha > 0.0:
pruned = self.prune(self.config.ccp_alpha)
self.root_ = pruned.root_
return self
def _node_stats(self, y_sub: np.ndarray) -> tuple[float, float, float, np.ndarray | None]:
n_t = len(y_sub)
if self.config.task == "classification":
counts = np.bincount(y_sub.astype(np.int64), minlength=self.n_classes_).astype(np.float64)
probs = counts / max(n_t, 1)
imp = (
gini_impurity(counts)
if self.config.criterion == "gini"
else shannon_entropy(counts)
)
risk = (n_t / max(self.n_samples_, 1)) * (1.0 - float(np.max(probs)))
val = float(probs[1]) if self.n_classes_ == 2 else float(np.argmax(probs))
return val, imp, risk, probs
if self.config.criterion == "mae":
med = float(np.median(y_sub))
imp = float(np.mean(np.abs(y_sub - med)))
risk = float(np.sum(np.abs(y_sub - med))) / max(self.n_samples_, 1)
return med, imp, risk, None
mean_y = float(np.mean(y_sub))
imp = float(np.var(y_sub))
risk = float(np.sum((y_sub - mean_y) ** 2)) / max(self.n_samples_, 1)
return mean_y, imp, risk, None
def _best_split(
self, X_sub: np.ndarray, y_sub: np.ndarray
) -> tuple[int, float, float]:
n_t, d = X_sub.shape
min_leaf = self.config.min_samples_leaf
if n_t < max(self.config.min_samples_split, 2 * min_leaf):
return -1, 0.0, 0.0
if self.config.max_features is not None and self.config.max_features < d:
feat_candidates = self._rng.choice(d, size=self.config.max_features, replace=False)
else:
feat_candidates = np.arange(d)
best_feat = -1
best_thr = 0.0
best_gain = 1e-12
if self.config.task == "classification":
y_int = y_sub.astype(np.int64)
counts_tot = np.bincount(y_int, minlength=self.n_classes_).astype(np.float64)
parent_imp = (
gini_impurity(counts_tot)
if self.config.criterion == "gini"
else shannon_entropy(counts_tot)
)
if parent_imp <= 1e-12:
return -1, 0.0, 0.0
one_hot = np.eye(self.n_classes_, dtype=np.float64)[y_int]
for feat in feat_candidates:
col = X_sub[:, feat]
if self.config.random_thresholds:
cmin, cmax = float(np.min(col)), float(np.max(col))
if cmax - cmin <= 1e-12:
continue
thr = float(self._rng.uniform(cmin, cmax))
left_mask = col <= thr
n_l = int(np.sum(left_mask))
n_r = n_t - n_l
if n_l < min_leaf or n_r < min_leaf:
continue
c_l = np.sum(one_hot[left_mask], axis=0)
c_r = counts_tot - c_l
imp_l = gini_impurity(c_l) if self.config.criterion == "gini" else shannon_entropy(c_l)
imp_r = gini_impurity(c_r) if self.config.criterion == "gini" else shannon_entropy(c_r)
gain = parent_imp - (n_l * imp_l + n_r * imp_r) / n_t
if gain > best_gain:
best_gain = gain
best_feat = int(feat)
best_thr = thr
continue
order = np.argsort(col, kind="mergesort")
x_s = col[order]
valid = np.flatnonzero(x_s[:-1] < x_s[1:] - 1e-12)
valid = valid[(valid >= min_leaf - 1) & (valid <= n_t - min_leaf - 1)]
if len(valid) == 0:
continue
cum_l = np.cumsum(one_hot[order], axis=0)[valid]
n_l_arr = (valid + 1).astype(np.float64)
n_r_arr = float(n_t) - n_l_arr
cum_r = counts_tot[None, :] - cum_l
p_l = cum_l / n_l_arr[:, None]
p_r = cum_r / n_r_arr[:, None]
if self.config.criterion == "gini":
imp_l_arr = 1.0 - np.sum(p_l * p_l, axis=1)
imp_r_arr = 1.0 - np.sum(p_r * p_r, axis=1)
else:
with np.errstate(divide="ignore", invalid="ignore"):
log_l = np.where(p_l > 0.0, np.log2(np.maximum(p_l, 1e-30)), 0.0)
log_r = np.where(p_r > 0.0, np.log2(np.maximum(p_r, 1e-30)), 0.0)
imp_l_arr = -np.sum(p_l * log_l, axis=1)
imp_r_arr = -np.sum(p_r * log_r, axis=1)
gains = parent_imp - (n_l_arr * imp_l_arr + n_r_arr * imp_r_arr) / float(n_t)
idx_max = int(np.argmax(gains))
if float(gains[idx_max]) > best_gain:
best_gain = float(gains[idx_max])
best_feat = int(feat)
pos = int(valid[idx_max])
best_thr = 0.5 * float(x_s[pos] + x_s[pos + 1])
return best_feat, best_thr, best_gain
# Regression: MSE or MAE
y_flt = y_sub.astype(np.float64)
if self.config.criterion == "mse":
parent_imp = float(np.var(y_flt))
if parent_imp <= 1e-12:
return -1, 0.0, 0.0
total_sum = float(np.sum(y_flt))
base_score = (total_sum * total_sum) / float(n_t)
for feat in feat_candidates:
col = X_sub[:, feat]
if self.config.random_thresholds:
cmin, cmax = float(np.min(col)), float(np.max(col))
if cmax - cmin <= 1e-12:
continue
thr = float(self._rng.uniform(cmin, cmax))
left_mask = col <= thr
n_l = int(np.sum(left_mask))
n_r = n_t - n_l
if n_l < min_leaf or n_r < min_leaf:
continue
s_l = float(np.sum(y_flt[left_mask]))
s_r = total_sum - s_l
gain = ((s_l * s_l) / n_l + (s_r * s_r) / n_r - base_score) / float(n_t)
if gain > best_gain:
best_gain = gain
best_feat = int(feat)
best_thr = thr
continue
order = np.argsort(col, kind="mergesort")
x_s = col[order]
y_s = y_flt[order]
valid = np.flatnonzero(x_s[:-1] < x_s[1:] - 1e-12)
valid = valid[(valid >= min_leaf - 1) & (valid <= n_t - min_leaf - 1)]
if len(valid) == 0:
continue
cum_s = np.cumsum(y_s)[valid]
n_l_arr = (valid + 1).astype(np.float64)
n_r_arr = float(n_t) - n_l_arr
s_r_arr = total_sum - cum_s
gains = ((cum_s * cum_s) / n_l_arr + (s_r_arr * s_r_arr) / n_r_arr - base_score) / float(n_t)
idx_max = int(np.argmax(gains))
if float(gains[idx_max]) > best_gain:
best_gain = float(gains[idx_max])
best_feat = int(feat)
pos = int(valid[idx_max])
best_thr = 0.5 * float(x_s[pos] + x_s[pos + 1])
return best_feat, best_thr, best_gain
# MAE Regression: exact O(n log n) via prefix/suffix running medians
parent_abs = mae_impurity(y_flt) * float(n_t)
if parent_abs <= 1e-12:
return -1, 0.0, 0.0
for feat in feat_candidates:
col = X_sub[:, feat]
order = np.argsort(col, kind="mergesort")
x_s = col[order]
y_s = y_flt[order]
rm_left = _RunningMedian()
left_abs = np.empty(n_t - 1, dtype=np.float64)
for i in range(n_t - 1):
rm_left.push(float(y_s[i]))
left_abs[i] = rm_left.abs_dev_sum()
rm_right = _RunningMedian()
right_abs = np.empty(n_t - 1, dtype=np.float64)
for i in range(n_t - 1, 0, -1):
rm_right.push(float(y_s[i]))
right_abs[i - 1] = rm_right.abs_dev_sum()
valid = np.flatnonzero(x_s[:-1] < x_s[1:] - 1e-12)
valid = valid[(valid >= min_leaf - 1) & (valid <= n_t - min_leaf - 1)]
if len(valid) == 0:
continue
gains = (parent_abs - (left_abs[valid] + right_abs[valid])) / float(n_t)
idx_max = int(np.argmax(gains))
if float(gains[idx_max]) > best_gain:
best_gain = float(gains[idx_max])
best_feat = int(feat)
pos = int(valid[idx_max])
best_thr = 0.5 * float(x_s[pos] + x_s[pos + 1])
return best_feat, best_thr, best_gain
def _build(self, X_sub: np.ndarray, y_sub: np.ndarray, depth: int) -> TreeNode:
val, imp, risk, probs = self._node_stats(y_sub)
n_t = len(y_sub)
nid = self._next_id()
if depth >= self.config.max_depth:
return TreeNode(nid, True, -1, 0.0, val, n_t, float(n_t), imp, risk, probs)
feat, thr, _ = self._best_split(X_sub, y_sub)
if feat == -1:
return TreeNode(nid, True, -1, 0.0, val, n_t, float(n_t), imp, risk, probs)
left_mask = X_sub[:, feat] <= thr
right_mask = ~left_mask
left_child = self._build(X_sub[left_mask], y_sub[left_mask], depth + 1)
right_child = self._build(X_sub[right_mask], y_sub[right_mask], depth + 1)
return TreeNode(
node_id=nid,
is_leaf=False,
feature_idx=feat,
threshold=thr,
value=val,
n_samples=n_t,
hessian_sum=float(n_t),
impurity=imp,
node_risk=risk,
class_probs=probs,
default_left=True,
left=left_child,
right=right_child,
)
def _predict_row(self, node: TreeNode, x_row: np.ndarray) -> TreeNode:
cur = node
while not cur.is_leaf and cur.left is not None and cur.right is not None:
if x_row[cur.feature_idx] <= cur.threshold:
cur = cur.left
else:
cur = cur.right
return cur
def predict(self, X: np.ndarray) -> np.ndarray:
if self.root_ is None:
raise RuntimeError("CARTDecisionTree must be fitted before calling predict.")
X_arr = np.asarray(X, dtype=np.float64)
if self.config.task == "classification":
probs = self.predict_proba(X_arr)
return np.argmax(probs, axis=1).astype(np.int64)
preds = np.empty(len(X_arr), dtype=np.float64)
for i in range(len(X_arr)):
preds[i] = self._predict_row(self.root_, X_arr[i]).value
return preds
def predict_proba(self, X: np.ndarray) -> np.ndarray:
if self.root_ is None:
raise RuntimeError("CARTDecisionTree must be fitted before calling predict_proba.")
X_arr = np.asarray(X, dtype=np.float64)
probs = np.empty((len(X_arr), self.n_classes_), dtype=np.float64)
for i in range(len(X_arr)):
leaf = self._predict_row(self.root_, X_arr[i])
assert leaf.class_probs is not None
probs[i] = leaf.class_probs
return probs
@property
def n_leaves(self) -> int:
return 0 if self.root_ is None else _count_leaves(self.root_)
@property
def depth(self) -> int:
return 0 if self.root_ is None else _tree_depth(self.root_)
@staticmethod
def _weakest_link_candidates(root: TreeNode) -> list[tuple[TreeNode, float]]:
candidates: list[tuple[TreeNode, float]] = []
def _walk(node: TreeNode) -> tuple[float, int]:
if node.is_leaf or node.left is None or node.right is None:
return node.node_risk, 1
r_l, c_l = _walk(node.left)
r_r, c_r = _walk(node.right)
r_sub = r_l + r_r
c_sub = c_l + c_r
g_val = (node.node_risk - r_sub) / max(c_sub - 1, 1)
candidates.append((node, float(g_val)))
return r_sub, c_sub
_walk(root)
return candidates
def cost_complexity_pruning_path(self) -> dict[str, list[float] | list[int]]:
"""Compute exact Breiman (1984) weakest-link nested pruning sequence."""
if self.root_ is None:
raise RuntimeError("Fit tree before computing pruning path.")
work = copy.deepcopy(self.root_)
# Collapse zero-gain branches (T_1 = T(0))
while True:
cands = self._weakest_link_candidates(work)
zeros = [nd for nd, g in cands if g <= 1e-12]
if not zeros:
break
for nd in zeros:
nd.is_leaf = True
nd.feature_idx = -1
nd.left = None
nd.right = None
alphas: list[float] = [0.0]
impurities: list[float] = [float(_subtree_risk(work))]
leaf_counts: list[int] = [int(_count_leaves(work))]
while not work.is_leaf:
cands = self._weakest_link_candidates(work)
min_g = min(g for _, g in cands)
for nd, g in cands:
if abs(g - min_g) <= 1e-12:
nd.is_leaf = True
nd.feature_idx = -1
nd.left = None
nd.right = None
alphas.append(float(max(min_g, 0.0)))
impurities.append(float(_subtree_risk(work)))
leaf_counts.append(int(_count_leaves(work)))
return {
"ccp_alphas": alphas,
"impurities": impurities,
"leaf_counts": leaf_counts,
}
def prune(self, ccp_alpha: float) -> CARTDecisionTree:
"""Return a new CARTDecisionTree pruned to unique smallest minimizer T(ccp_alpha)."""
if self.root_ is None:
raise RuntimeError("Fit tree before pruning.")
pruned = copy.deepcopy(self)
assert pruned.root_ is not None
while not pruned.root_.is_leaf:
cands = self._weakest_link_candidates(pruned.root_)
min_g = min(g for _, g in cands)
if min_g > ccp_alpha + 1e-12:
break
for nd, g in cands:
if abs(g - min_g) <= 1e-12:
nd.is_leaf = True
nd.feature_idx = -1
nd.left = None
nd.right = None
return pruned
def select_ccp_alpha_1se(
self,
X: np.ndarray,
y: np.ndarray,
n_folds: int = 5,
seed: int = 42,
) -> dict[str, Any]:
"""Breiman 1-SE CV pruning selection along geometric midpoints of weakest-link alphas."""
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y)
full_tree = CARTDecisionTree(self.config.model_copy(update={"ccp_alpha": 0.0})).fit(X_arr, y_arr)
path = full_tree.cost_complexity_pruning_path()
alphas = [float(a) for a in path["ccp_alphas"]]
if len(alphas) <= 1:
return {
"alphas": alphas,
"cv_means": [0.0],
"cv_ses": [0.0],
"leaf_counts": [int(c) for c in path["leaf_counts"]],
"alpha_min": 0.0,
"alpha_1se": 0.0,
"pruned_tree": full_tree,
}
mid_alphas: list[float] = [0.0]
for k in range(len(alphas) - 1):
a_lo = alphas[k]
a_hi = alphas[k + 1]
if a_lo <= 0.0:
mid_alphas.append(0.5 * a_hi)
else:
mid_alphas.append(math.sqrt(a_lo * a_hi))
mid_alphas.append(alphas[-1] * 1.1)
n = len(X_arr)
rng = np.random.default_rng(seed)
perm = rng.permutation(n)
folds = np.array_split(perm, n_folds)
fold_trees: list[CARTDecisionTree] = []
for f_idx in range(n_folds):
val_idx = folds[f_idx]
tr_idx = np.concatenate([folds[k] for k in range(n_folds) if k != f_idx])
t_fold = CARTDecisionTree(self.config.model_copy(update={"ccp_alpha": 0.0, "seed": seed + f_idx})).fit(
X_arr[tr_idx], y_arr[tr_idx]
)
fold_trees.append(t_fold)
cv_means: list[float] = []
cv_ses: list[float] = []
for alpha_cand in mid_alphas:
sample_losses = np.empty(n, dtype=np.float64)
for f_idx in range(n_folds):
val_idx = folds[f_idx]
ptree = fold_trees[f_idx].prune(alpha_cand)
if self.config.task == "classification":
preds = ptree.predict(X_arr[val_idx])
sample_losses[val_idx] = (preds != y_arr[val_idx]).astype(np.float64)
else:
preds = ptree.predict(X_arr[val_idx])
diff = preds - y_arr[val_idx].astype(np.float64)
sample_losses[val_idx] = diff * diff if self.config.criterion == "mse" else np.abs(diff)
cv_means.append(float(np.mean(sample_losses)))
cv_ses.append(float(np.std(sample_losses, ddof=1) / math.sqrt(n)))
min_idx = int(np.argmin(cv_means))
threshold_1se = cv_means[min_idx] + cv_ses[min_idx]
eligible = [i for i, val in enumerate(cv_means) if val <= threshold_1se + 1e-12]
best_1se_idx = max(eligible)
alpha_min = float(mid_alphas[min_idx])
alpha_1se = float(mid_alphas[best_1se_idx])
pruned_1se = full_tree.prune(alpha_1se)
return {
"alphas": [float(a) for a in mid_alphas],
"cv_means": cv_means,
"cv_ses": cv_ses,
"leaf_counts": [full_tree.prune(a).n_leaves for a in mid_alphas],
"alpha_min": alpha_min,
"alpha_1se": alpha_1se,
"pruned_tree": pruned_1se,
}
def extract_rules(self, feature_names: list[str] | None = None) -> list[dict[str, Any]]:
"""Extract exact mutually exclusive IF-THEN leaf conjunctions."""
if self.root_ is None:
raise RuntimeError("Fit tree before extracting rules.")
names = feature_names or [f"x_{j}" for j in range(self.n_features_)]
rules: list[dict[str, Any]] = []
def _dfs(node: TreeNode, clauses: list[str]) -> None:
if node.is_leaf or node.left is None or node.right is None:
cond_str = " AND ".join(clauses) if clauses else "TRUE"
pred_label = (
int(np.argmax(node.class_probs))
if (self.config.task == "classification" and node.class_probs is not None)
else node.value
)
rules.append(
{
"leaf_id": node.node_id,
"condition": f"IF {cond_str} THEN pred={pred_label}",
"n_samples": node.n_samples,
"value": float(node.value),
}
)
return
fname = names[node.feature_idx]
_dfs(node.left, clauses + [f"{fname} <= {node.threshold:.4f}"])
_dfs(node.right, clauses + [f"{fname} > {node.threshold:.4f}"])
_dfs(self.root_, [])
return rules
def diagonal_xor_staircase_audit(seed: int = 42) -> dict[str, Any]:
"""Compare axis-aligned CART staircase leaf explosion vs oblique hyperplane split on diagonal/XOR."""
rng = np.random.default_rng(seed)
X_tr = rng.uniform(-1.0, 1.0, size=(600, 2))
X_te = rng.uniform(-1.0, 1.0, size=(600, 2))
y_diag_tr = (X_tr[:, 0] + X_tr[:, 1] > 0.0).astype(np.int64)
y_diag_te = (X_te[:, 0] + X_te[:, 1] > 0.0).astype(np.int64)
shallow_tree = CARTDecisionTree(task="classification", max_depth=2, seed=seed).fit(X_tr, y_diag_tr)
deep_tree = CARTDecisionTree(task="classification", max_depth=8, seed=seed).fit(X_tr, y_diag_tr)
oblique_acc = float(np.mean((X_te[:, 0] + X_te[:, 1] > 0.0).astype(np.int64) == y_diag_te))
# 3D XOR parity: y = (x0*x1*x2 > 0)
X3_tr = rng.uniform(-1.0, 1.0, size=(800, 3))
X3_te = rng.uniform(-1.0, 1.0, size=(800, 3))
y3_tr = ((X3_tr[:, 0] * X3_tr[:, 1] * X3_tr[:, 2]) > 0.0).astype(np.int64)
y3_te = ((X3_te[:, 0] * X3_te[:, 1] * X3_te[:, 2]) > 0.0).astype(np.int64)
xor_shallow = CARTDecisionTree(task="classification", max_depth=2, min_samples_leaf=5, seed=seed).fit(X3_tr, y3_tr)
xor_deep = CARTDecisionTree(task="classification", max_depth=6, min_samples_leaf=5, seed=seed).fit(X3_tr, y3_tr)
return {
"diag_shallow_depth2_acc": compute_accuracy(y_diag_te, shallow_tree.predict(X_te)),
"diag_shallow_leaves": shallow_tree.n_leaves,
"diag_deep_depth8_acc": compute_accuracy(y_diag_te, deep_tree.predict(X_te)),
"diag_deep_leaves": deep_tree.n_leaves,
"diag_oblique_1split_acc": oblique_acc,
"diag_oblique_leaves": 2,
"xor3_depth2_acc": compute_accuracy(y3_te, xor_shallow.predict(X3_te)),
"xor3_depth6_acc": compute_accuracy(y3_te, xor_deep.predict(X3_te)),
"xor3_depth6_leaves": xor_deep.n_leaves,
}
# ---------------------------------------------------------------------------
# Random Forest & ExtraTrees Workbench + Free OOB + Variance Identity Proof
# ---------------------------------------------------------------------------
class RandomForestWorkbench:
"""Random Forest & ExtraTrees with exact mtry subsampling, OOB tracking, and rho/var audit."""
def __init__(self, config: RandomForestConfig | None = None, **kwargs: Any) -> None:
self.config = config if config is not None else RandomForestConfig(**kwargs)
self.trees_: list[CARTDecisionTree] = []
self.n_features_: int = 0
self.n_classes_: int = 1
self.oob_score_: float | None = None
self.oob_predictions_: np.ndarray | None = None
self.avg_bootstrap_inclusion_: float = 1.0
def _resolve_mtry(self, d: int) -> int:
mf = self.config.max_features
if isinstance(mf, str):
if mf == "sqrt":
return max(1, math.floor(math.sqrt(d)))
return max(1, math.floor(d / 3.0))
if isinstance(mf, float):
return max(1, round(mf * d))
return max(1, min(int(mf), d))
def fit(self, X: np.ndarray, y: np.ndarray) -> RandomForestWorkbench:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y)
n, d = X_arr.shape
self.n_features_ = d
mtry = self._resolve_mtry(d)
rng = np.random.default_rng(self.config.seed)
if self.config.task == "classification":
y_int = y_arr.astype(np.int64)
self.n_classes_ = max(2, int(np.max(y_int)) + 1)
oob_accum = np.zeros((n, self.n_classes_), dtype=np.float64)
else:
self.n_classes_ = 1
oob_accum = np.zeros(n, dtype=np.float64)
oob_counts = np.zeros(n, dtype=np.int64)
use_bootstrap = self.config.bootstrap and not self.config.extra_trees
inclusions: list[float] = []
self.trees_ = []
for m in range(self.config.n_estimators):
if use_bootstrap:
bag_idx = rng.integers(0, n, size=n)
in_bag = np.zeros(n, dtype=bool)
in_bag[bag_idx] = True
inclusions.append(float(np.mean(in_bag)))
oob_idx = np.flatnonzero(~in_bag)
else:
bag_idx = np.arange(n)
inclusions.append(1.0)
oob_idx = np.empty(0, dtype=np.int64)
t_cfg = CARTConfig(
task=self.config.task,
criterion=self.config.criterion,
max_depth=self.config.max_depth,
min_samples_leaf=self.config.min_samples_leaf,
max_features=mtry,
random_thresholds=self.config.extra_trees,
n_classes=self.n_classes_ if self.config.task == "classification" else None,
seed=self.config.seed + 101 * (m + 1),
)
tree = CARTDecisionTree(t_cfg).fit(X_arr[bag_idx], y_arr[bag_idx])
self.trees_.append(tree)
if len(oob_idx) > 0:
if self.config.task == "classification":
oob_accum[oob_idx] += tree.predict_proba(X_arr[oob_idx])
else:
oob_accum[oob_idx] += tree.predict(X_arr[oob_idx])
oob_counts[oob_idx] += 1
self.avg_bootstrap_inclusion_ = float(np.mean(inclusions))
valid_oob = oob_counts > 0
if np.any(valid_oob):
if self.config.task == "classification":
oob_probs = np.zeros_like(oob_accum)
oob_probs[valid_oob] = oob_accum[valid_oob] / oob_counts[valid_oob, None]
self.oob_predictions_ = oob_probs
self.oob_score_ = compute_accuracy(
y_arr[valid_oob], np.argmax(oob_probs[valid_oob], axis=1)
)
else:
oob_pred = np.zeros_like(oob_accum)
oob_pred[valid_oob] = oob_accum[valid_oob] / oob_counts[valid_oob]
self.oob_predictions_ = oob_pred
self.oob_score_ = compute_mse(y_arr[valid_oob], oob_pred[valid_oob])
return self
def predict_raw_matrix(self, X: np.ndarray) -> np.ndarray:
"""Return (M, n_samples) tree predictions (class-1 prob for binary classification, scalar for reg)."""
X_arr = np.asarray(X, dtype=np.float64)
preds = np.empty((len(self.trees_), len(X_arr)), dtype=np.float64)
for m, tree in enumerate(self.trees_):
if self.config.task == "classification":
preds[m] = tree.predict_proba(X_arr)[:, 1]
else:
preds[m] = tree.predict(X_arr)
return preds
def predict_proba(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
acc = np.zeros((len(X_arr), self.n_classes_), dtype=np.float64)
for tree in self.trees_:
acc += tree.predict_proba(X_arr)
return acc / float(len(self.trees_))
def predict(self, X: np.ndarray) -> np.ndarray:
if self.config.task == "classification":
return np.argmax(self.predict_proba(X), axis=1).astype(np.int64)
return np.mean(self.predict_raw_matrix(X), axis=0)
def measure_tree_correlation_and_variance(self, X_eval: np.ndarray) -> dict[str, float]:
"""Compute empirical single-tree variance, mean pairwise tree correlation rho & RF variance."""
mat = self.predict_raw_matrix(X_eval) # shape (M, n_eval)
m_cnt = mat.shape[0]
# Center each tree's predictions across X_eval for spatial correlation rho
centered = mat - np.mean(mat, axis=1, keepdims=True)
norms = np.sqrt(np.sum(centered * centered, axis=1)) + 1e-12
normed = centered / norms[:, None]
corr_mat = normed @ normed.T
mask_off = ~np.eye(m_cnt, dtype=bool)
mean_pairwise_corr = float(np.mean(corr_mat[mask_off]))
mean_tree_var = float(np.mean(np.var(mat, axis=1)))
ens_pred = np.mean(mat, axis=0)
return {
"mean_pairwise_corr": mean_pairwise_corr,
"mean_tree_spatial_var": mean_tree_var,
"ensemble_pred_var": float(np.var(ens_pred)),
}
def verify_rf_variance_identity(n_repeats: int = 35, m_trees: int = 12, seed: int = 42) -> dict[str, float]:
"""Verify Var(mean_m T_m(x)) == rho*sigma^2 + ((1-rho)/M)*sigma^2 across independent dataset draws."""
rng = np.random.default_rng(seed)
X_test = np.array([[0.35, -0.45, 0.20, 0.80], [-0.55, 0.65, -0.30, 0.10]], dtype=np.float64)
tree_preds = np.empty((n_repeats, m_trees, len(X_test)), dtype=np.float64)
for r in range(n_repeats):
X_tr = rng.normal(0.0, 1.0, size=(120, 4))
y_tr = 2.0 * X_tr[:, 0] - 1.5 * X_tr[:, 1] + rng.normal(0.0, 0.8, size=120)
rf = RandomForestWorkbench(
task="regression",
criterion="mse",
n_estimators=m_trees,
max_depth=5,
min_samples_leaf=3,
max_features=2,
bootstrap=True,
seed=seed + 1000 * r,
).fit(X_tr, y_tr)
tree_preds[r] = rf.predict_raw_matrix(X_test)
# At query 0: compute exact empirical Var(mean_m T_m), mean sigma^2, and mean off-diag cov
q0 = tree_preds[:, :, 0] # (R, M)
ens_q0 = np.mean(q0, axis=1)
emp_ens_var = float(np.var(ens_q0, ddof=1))
cov_mat = np.cov(q0, rowvar=False, ddof=1)
sigma2_bar = float(np.mean(np.diag(cov_mat)))
off_mask = ~np.eye(m_trees, dtype=bool)
cov_bar = float(np.mean(cov_mat[off_mask]))
rho_hat = cov_bar / max(sigma2_bar, 1e-12)
identity_rhs = rho_hat * sigma2_bar + ((1.0 - rho_hat) / float(m_trees)) * sigma2_bar
return {
"empirical_ens_var": emp_ens_var,
"sigma2_bar": sigma2_bar,
"rho_hat": rho_hat,
"identity_rhs": float(identity_rhs),
"abs_diff": float(abs(emp_ens_var - identity_rhs)),
}
# ---------------------------------------------------------------------------
# Second-Order Newton GBDT (Exact vs Hist Subtraction, GOSS & Monotonic Bounds)
# ---------------------------------------------------------------------------
class SecondOrderGBDT:
"""2nd-order Newton GBDT supporting Exact vs uint8 Hist Subtraction, GOSS & Monotonic Constraints."""
def __init__(self, config: GBDTConfig | None = None, **kwargs: Any) -> None:
self.config = config if config is not None else GBDTConfig(**kwargs)
self.trees_: list[TreeNode] = []
self._flat_trees: list[tuple[tuple[int, ...], tuple[float, ...], tuple[int, ...], tuple[int, ...], tuple[float, ...]]] = []
self.base_score_: float = 0.0
self.n_features_: int = 0
self.bin_edges_: list[np.ndarray] = []
self.hist_scans_saved_: int = 0
self.exact_split_evals_: int = 0
self.hist_split_evals_: int = 0
def _compute_grad_hess(self, y: np.ndarray, f_pred: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
if self.config.loss == "mse":
return f_pred - y, np.ones_like(y, dtype=np.float64)
p = stable_sigmoid(f_pred)
return p - y, np.maximum(p * (1.0 - p), 1e-12)
def _leaf_obj(self, g_sum: float, h_sum: float, w: float) -> float:
return g_sum * w + 0.5 * (h_sum + self.config.reg_lambda) * (w * w)
def _fit_bin_edges(self, X: np.ndarray) -> tuple[list[np.ndarray], np.ndarray]:
n, d = X.shape
edges_list: list[np.ndarray] = []
X_bin = np.zeros((n, d), dtype=np.uint8)
qs = np.linspace(0.0, 1.0, self.config.max_bins + 1)[1:-1]
for j in range(d):
col = X[:, j]
if len(np.unique(col)) <= self.config.max_bins:
uvals = np.unique(col)
edges = 0.5 * (uvals[:-1] + uvals[1:]) if len(uvals) > 1 else np.empty(0, dtype=np.float64)
else:
edges = np.unique(np.quantile(col, qs))
edges_list.append(edges)
if len(edges) > 0:
X_bin[:, j] = np.searchsorted(edges, col, side="right").astype(np.uint8)
return edges_list, X_bin
def _allowed_features(self, path_feats: frozenset[int], candidate_feats: np.ndarray) -> np.ndarray:
ics = self.config.interaction_constraints
if not ics:
return candidate_feats
allowed: set[int] = set()
for grp in ics:
gset = set(grp)
if path_feats.issubset(gset):
allowed.update(gset)
return np.array([f for f in candidate_feats if int(f) in allowed], dtype=np.int64)
def _build_hist_for_indices(
self,
X_bin: np.ndarray,
indices: np.ndarray,
g: np.ndarray,
h: np.ndarray,
feats: np.ndarray,
) -> dict[int, tuple[np.ndarray, np.ndarray]]:
hists: dict[int, tuple[np.ndarray, np.ndarray]] = {}
g_sub = g[indices]
h_sub = h[indices]
for f in feats:
n_b = len(self.bin_edges_[int(f)]) + 1
b_idx = X_bin[indices, int(f)]
g_h = np.bincount(b_idx, weights=g_sub, minlength=n_b).astype(np.float64)
h_h = np.bincount(b_idx, weights=h_sub, minlength=n_b).astype(np.float64)
hists[int(f)] = (g_h, h_h)
return hists
def _eval_split_gain_vec(
self,
feat: int,
g_l: np.ndarray,
h_l: np.ndarray,
g_tot: float,
h_tot: float,
lower_b: float,
upper_b: float,
) -> tuple[int, float, float, float]:
"""Vectorized 2nd-order Newton split gain evaluation with monotonic bound clamping."""
g_r = g_tot - g_l
h_r = h_tot - h_l
lam = self.config.reg_lambda
mcw = self.config.min_child_weight
w_p = float(np.clip(-g_tot / (h_tot + lam), lower_b, upper_b))
parent_obj = self._leaf_obj(g_tot, h_tot, w_p)
w_l = np.clip(-g_l / (h_l + lam), lower_b, upper_b)
w_r = np.clip(-g_r / (h_r + lam), lower_b, upper_b)
valid = (h_l >= mcw) & (h_r >= mcw)
mono = 0
if self.config.monotone_constraints is not None:
mono = int(self.config.monotone_constraints[feat])
if mono == 1:
valid &= (w_l <= w_r + 1e-12)
elif mono == -1:
valid &= (w_l >= w_r - 1e-12)
if not np.any(valid):
return -1, -1e18, 0.0, 0.0
child_obj = (
g_l * w_l
+ 0.5 * (h_l + lam) * (w_l * w_l)
+ g_r * w_r
+ 0.5 * (h_r + lam) * (w_r * w_r)
)
gains = parent_obj - child_obj - self.config.min_split_gain
gains = np.where(valid, gains, -1e18)
idx_best = int(np.argmax(gains))
return idx_best, float(gains[idx_best]), float(w_l[idx_best]), float(w_r[idx_best])
def _build_tree(
self,
X: np.ndarray,
X_bin: np.ndarray | None,
indices: np.ndarray,
g: np.ndarray,
h: np.ndarray,
depth: int,
lower_b: float,
upper_b: float,
feats_pool: np.ndarray,
path_feats: frozenset[int],
node_hists: dict[int, tuple[np.ndarray, np.ndarray]] | None,
nid_counter: list[int],
) -> TreeNode:
nid = nid_counter[0]
nid_counter[0] += 1
n_t = len(indices)
g_tot = float(np.sum(g[indices]))
h_tot = float(np.sum(h[indices]))
w_opt = float(np.clip(-g_tot / (h_tot + self.config.reg_lambda), lower_b, upper_b))
allowed_feats = self._allowed_features(path_feats, feats_pool)
if (
depth >= self.config.max_depth
or n_t < 2 * self.config.min_samples_leaf
or h_tot < 2.0 * self.config.min_child_weight
or len(allowed_feats) == 0
):
return TreeNode(nid, True, -1, 0.0, w_opt, n_t, h_tot)
best_feat = -1
best_thr = 0.0
best_gain = 1e-12
best_w_l = w_opt
best_w_r = w_opt
best_bin_idx = -1
if self.config.split_method == "hist" and X_bin is not None:
if node_hists is None:
node_hists = self._build_hist_for_indices(X_bin, indices, g, h, feats_pool)
for f_raw in allowed_feats:
f = int(f_raw)
edges = self.bin_edges_[f]
if len(edges) == 0:
continue
g_h, h_h = node_hists[f]
g_cum = np.cumsum(g_h[:-1])
h_cum = np.cumsum(h_h[:-1])
self.hist_split_evals_ += len(g_cum)
b_i, gain, w_l, w_r = self._eval_split_gain_vec(
f, g_cum, h_cum, g_tot, h_tot, lower_b, upper_b
)
if b_i >= 0 and gain > best_gain:
best_gain = gain
best_feat = f
best_thr = float(edges[b_i])
best_w_l = w_l
best_w_r = w_r
best_bin_idx = b_i
else:
X_sub = X[indices]
g_sub = g[indices]
h_sub = h[indices]
min_leaf = self.config.min_samples_leaf
for f_raw in allowed_feats:
f = int(f_raw)
col = X_sub[:, f]
order = np.argsort(col, kind="mergesort")
x_s = col[order]
valid = np.flatnonzero(x_s[:-1] < x_s[1:] - 1e-12)
valid = valid[(valid >= min_leaf - 1) & (valid <= n_t - min_leaf - 1)]
if len(valid) == 0:
continue
g_cum = np.cumsum(g_sub[order])[valid]
h_cum = np.cumsum(h_sub[order])[valid]
self.exact_split_evals_ += len(valid)
idx_k, gain, w_l, w_r = self._eval_split_gain_vec(
f, g_cum, h_cum, g_tot, h_tot, lower_b, upper_b
)
if idx_k >= 0 and gain > best_gain:
pos = int(valid[idx_k])
best_gain = gain
best_feat = f
best_thr = 0.5 * float(x_s[pos] + x_s[pos + 1])
best_w_l = w_l
best_w_r = w_r
if best_feat == -1:
return TreeNode(nid, True, -1, 0.0, w_opt, n_t, h_tot)
if self.config.split_method == "hist" and X_bin is not None and best_bin_idx >= 0:
left_mask = X_bin[indices, best_feat] <= best_bin_idx
else:
left_mask = X[indices, best_feat] <= best_thr
left_idx = indices[left_mask]
right_idx = indices[~left_mask]
if len(left_idx) < self.config.min_samples_leaf or len(right_idx) < self.config.min_samples_leaf:
return TreeNode(nid, True, -1, 0.0, w_opt, n_t, h_tot)
# Propagate monotonic bounds via midpoint clamping
mono = 0
if self.config.monotone_constraints is not None:
mono = int(self.config.monotone_constraints[best_feat])
mid_w = 0.5 * (best_w_l + best_w_r)
if mono == 1:
l_lo, l_hi = lower_b, min(upper_b, mid_w)
r_lo, r_hi = max(lower_b, mid_w), upper_b
elif mono == -1:
l_lo, l_hi = max(lower_b, mid_w), upper_b
r_lo, r_hi = lower_b, min(upper_b, mid_w)
else:
l_lo, l_hi = lower_b, upper_b
r_lo, r_hi = lower_b, upper_b
left_hists: dict[int, tuple[np.ndarray, np.ndarray]] | None = None
right_hists: dict[int, tuple[np.ndarray, np.ndarray]] | None = None
if self.config.split_method == "hist" and X_bin is not None and node_hists is not None:
# Histogram subtraction trick: build strictly smaller child, subtract from parent
if len(left_idx) <= len(right_idx):
left_hists = self._build_hist_for_indices(X_bin, left_idx, g, h, feats_pool)
right_hists = {
int(f): (
node_hists[int(f)][0] - left_hists[int(f)][0],
node_hists[int(f)][1] - left_hists[int(f)][1],
)
for f in feats_pool
}
else:
right_hists = self._build_hist_for_indices(X_bin, right_idx, g, h, feats_pool)
left_hists = {
int(f): (
node_hists[int(f)][0] - right_hists[int(f)][0],
node_hists[int(f)][1] - right_hists[int(f)][1],
)
for f in feats_pool
}
self.hist_scans_saved_ += max(len(left_idx), len(right_idx))
next_path = path_feats | {best_feat}
left_child = self._build_tree(
X, X_bin, left_idx, g, h, depth + 1, l_lo, l_hi, feats_pool, next_path, left_hists, nid_counter
)
right_child = self._build_tree(
X, X_bin, right_idx, g, h, depth + 1, r_lo, r_hi, feats_pool, next_path, right_hists, nid_counter
)
return TreeNode(
node_id=nid,
is_leaf=False,
feature_idx=best_feat,
threshold=best_thr,
value=w_opt,
n_samples=n_t,
hessian_sum=h_tot,
left=left_child,
right=right_child,
)
def _scale_tree_values(self, node: TreeNode, lr: float) -> None:
node.value *= lr
if node.left is not None:
self._scale_tree_values(node.left, lr)
if node.right is not None:
self._scale_tree_values(node.right, lr)
def fit(
self,
X: np.ndarray,
y: np.ndarray,
eval_set: tuple[np.ndarray, np.ndarray] | None = None,
prune_callback: Any | None = None,
) -> SecondOrderGBDT:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = X_arr.shape
self.n_features_ = d
if self.config.monotone_constraints is not None and len(self.config.monotone_constraints) != d:
raise ValueError("monotone_constraints length must match number of features.")
rng = np.random.default_rng(self.config.seed)
if self.config.loss == "mse":
self.base_score_ = float(np.mean(y_arr))
else:
p0 = float(np.clip(np.mean(y_arr), 1e-6, 1.0 - 1e-6))
self.base_score_ = math.log(p0 / (1.0 - p0))
f_pred = np.full(n, self.base_score_, dtype=np.float64)
X_val_arr: np.ndarray | None = None
y_val_arr: np.ndarray | None = None
f_val_pred: np.ndarray | None = None
if eval_set is not None:
X_val_arr = np.asarray(eval_set[0], dtype=np.float64)
y_val_arr = np.asarray(eval_set[1], dtype=np.float64)
f_val_pred = np.full(len(X_val_arr), self.base_score_, dtype=np.float64)
X_bin: np.ndarray | None = None
if self.config.split_method == "hist":
self.bin_edges_, X_bin = self._fit_bin_edges(X_arr)
self.trees_ = []
self._flat_trees = []
self.hist_scans_saved_ = 0
self.exact_split_evals_ = 0
self.hist_split_evals_ = 0
for round_idx in range(1, self.config.n_estimators + 1):
g, h = self._compute_grad_hess(y_arr, f_pred)
g_work = g.copy()
h_work = h.copy()
if self.config.use_goss:
k_top = max(1, round(self.config.goss_top_rate * n))
k_other = max(1, round(self.config.goss_other_rate * n))
order_desc = np.argsort(-np.abs(g), kind="mergesort")
top_idx = order_desc[:k_top]
rem_idx = order_desc[k_top:]
if len(rem_idx) > k_other:
picked_other = rng.choice(rem_idx, size=k_other, replace=False)
scale = float(len(rem_idx)) / float(k_other)
else:
picked_other = rem_idx
scale = 1.0
g_work[picked_other] *= scale
h_work[picked_other] *= scale
sample_idx = np.concatenate([top_idx, picked_other])
elif self.config.subsample < 1.0:
m_sub = max(2, round(self.config.subsample * n))
sample_idx = rng.choice(n, size=m_sub, replace=False)
else:
sample_idx = np.arange(n)
if self.config.colsample_bytree < 1.0:
m_cols = max(1, round(self.config.colsample_bytree * d))
feats_pool = np.sort(rng.choice(d, size=m_cols, replace=False))
else:
feats_pool = np.arange(d, dtype=np.int64)
root = self._build_tree(
X=X_arr,
X_bin=X_bin,
indices=sample_idx,
g=g_work,
h=h_work,
depth=0,
lower_b=-1e12,
upper_b=1e12,
feats_pool=feats_pool,
path_feats=frozenset(),
node_hists=None,
nid_counter=[0],
)
self._scale_tree_values(root, self.config.learning_rate)
self.trees_.append(root)
flat = self._compile_flat_tree(root)
self._flat_trees.append(flat)
f_pred += self._predict_flat_tree(flat, X_arr)
if (
prune_callback is not None
and X_val_arr is not None
and y_val_arr is not None
and f_val_pred is not None
):
f_val_pred += self._predict_flat_tree(flat, X_val_arr)
val_loss = (
compute_mse(y_val_arr, f_val_pred)
if self.config.loss == "mse"
else compute_binary_logloss(y_val_arr, stable_sigmoid(f_val_pred))
)
if prune_callback(round_idx, val_loss):
break
return self
@staticmethod
def _compile_flat_tree(
root: TreeNode,
) -> tuple[tuple[int, ...], tuple[float, ...], tuple[int, ...], tuple[int, ...], tuple[float, ...]]:
"""Compile TreeNode hierarchy into contiguous flat tuples (Treelite-style cache locality)."""
feats: list[int] = []
thrs: list[float] = []
lefts: list[int] = []
rights: list[int] = []
vals: list[float] = []
def _emit(nd: TreeNode) -> int:
idx = len(feats)
if nd.is_leaf or nd.left is None or nd.right is None:
feats.append(-1)
thrs.append(0.0)
lefts.append(-1)
rights.append(-1)
vals.append(float(nd.value))
return idx
feats.append(int(nd.feature_idx))
thrs.append(float(nd.threshold))
lefts.append(0)
rights.append(0)
vals.append(float(nd.value))
lefts[idx] = _emit(nd.left)
rights[idx] = _emit(nd.right)
return idx
_emit(root)
return tuple(feats), tuple(thrs), tuple(lefts), tuple(rights), tuple(vals)
@staticmethod
def _predict_flat_tree(
flat: tuple[tuple[int, ...], tuple[float, ...], tuple[int, ...], tuple[int, ...], tuple[float, ...]],
X: np.ndarray,
) -> np.ndarray:
feats, thrs, lefts, rights, vals = flat
n = len(X)
if n == 1:
row = X[0].tolist()
idx = 0
f = feats[0]
while f >= 0:
idx = lefts[idx] if row[f] <= thrs[idx] else rights[idx]
f = feats[idx]
return np.array([vals[idx]], dtype=np.float64)
out = np.empty(n, dtype=np.float64)
rows = X.tolist()
for i in range(n):
row = rows[i]
idx = 0
f = feats[0]
while f >= 0:
idx = lefts[idx] if row[f] <= thrs[idx] else rights[idx]
f = feats[idx]
out[i] = vals[idx]
return out
def predict_raw(self, X: np.ndarray, n_trees: int | None = None) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = len(X_arr)
limit = len(self.trees_) if n_trees is None else min(n_trees, len(self.trees_))
if n == 1 and self._flat_trees:
row = X_arr[0].tolist()
s = self.base_score_
for m in range(limit):
feats, thrs, lefts, rights, vals = self._flat_trees[m]
idx = 0
f = feats[0]
while f >= 0:
idx = lefts[idx] if row[f] <= thrs[idx] else rights[idx]
f = feats[idx]
s += vals[idx]
return np.array([s], dtype=np.float64)
pred = np.full(n, self.base_score_, dtype=np.float64)
for m in range(limit):
pred += self._predict_flat_tree(self._flat_trees[m], X_arr)
return pred
def predict_proba(self, X: np.ndarray, n_trees: int | None = None) -> np.ndarray:
raw = self.predict_raw(X, n_trees=n_trees)
p1 = stable_sigmoid(raw)
return np.column_stack([1.0 - p1, p1])
def predict(self, X: np.ndarray) -> np.ndarray:
if self.config.loss == "mse":
return self.predict_raw(X)
return (self.predict_proba(X)[:, 1] >= 0.5).astype(np.int64)
def verify_monotonicity(
self, X_anchor: np.ndarray, feature_idx: int, direction: int, grid_points: int = 20
) -> dict[str, Any]:
"""Sweep a feature across dense grid on anchor rows and count monotonic violations."""
col_vals = np.linspace(
float(np.min(X_anchor[:, feature_idx])),
float(np.max(X_anchor[:, feature_idx])),
grid_points,
)
violations = 0
max_reversal = 0.0
n_checks = 0
for row in X_anchor:
grid_mat = np.repeat(row[None, :], grid_points, axis=0)
grid_mat[:, feature_idx] = col_vals
preds = self.predict_raw(grid_mat)
diffs = np.diff(preds)
if direction > 0:
bad = diffs < -1e-10
if np.any(bad):
violations += int(np.sum(bad))
max_reversal = max(max_reversal, float(np.max(-diffs[bad])))
elif direction < 0:
bad = diffs > 1e-10
if np.any(bad):
violations += int(np.sum(bad))
max_reversal = max(max_reversal, float(np.max(diffs[bad])))
n_checks += len(diffs)
return {
"violations": violations,
"checks": n_checks,
"max_reversal": float(max_reversal),
}
# ---------------------------------------------------------------------------
# GOSS Variance Audit & CatBoost Ordered Boosting Prediction Shift Demo
# ---------------------------------------------------------------------------
def estimate_goss_gradient_sum(
grads: np.ndarray,
top_rate: float = 0.2,
other_rate: float = 0.1,
n_trials: int = 300,
seed: int = 42,
) -> dict[str, float]:
"""Verify GOSS gradient sum estimator is unbiased with lower variance than uniform subsampling."""
g = np.asarray(grads, dtype=np.float64)
n = len(g)
g_true = float(np.sum(g))
k_top = max(1, round(top_rate * n))
k_other = max(1, round(other_rate * n))
order_desc = np.argsort(-np.abs(g), kind="mergesort")
top_idx = order_desc[:k_top]
rem_idx = order_desc[k_top:]
scale_goss = float(len(rem_idx)) / float(k_other)
g_top_sum = float(np.sum(g[top_idx]))
total_budget = k_top + k_other
scale_unif = float(n) / float(total_budget)
rng = np.random.default_rng(seed)
goss_ests = np.empty(n_trials, dtype=np.float64)
unif_ests = np.empty(n_trials, dtype=np.float64)
for t in range(n_trials):
other_sub = rng.choice(rem_idx, size=k_other, replace=False)
goss_ests[t] = g_top_sum + scale_goss * float(np.sum(g[other_sub]))
unif_sub = rng.choice(n, size=total_budget, replace=False)
unif_ests[t] = scale_unif * float(np.sum(g[unif_sub]))
return {
"true_gradient_sum": g_true,
"goss_mean": float(np.mean(goss_ests)),
"goss_bias": float(np.mean(goss_ests) - g_true),
"goss_var": float(np.var(goss_ests, ddof=1)),
"uniform_var": float(np.var(unif_ests, ddof=1)),
"variance_reduction_ratio": float(np.var(unif_ests, ddof=1) / max(np.var(goss_ests, ddof=1), 1e-12)),
}
def ordered_boosting_prediction_shift_demo(seed: int = 42) -> dict[str, float]:
"""Contrast naive static target encoding + standard GBDT (Prediction Shift) vs Ordered Target Stats."""
rng = np.random.default_rng(seed)
n_tr, n_te = 400, 400
n_cats = 120
def _gen(n_rows: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
cat = rng.integers(0, n_cats, size=n_rows)
x_num = rng.normal(0.0, 1.0, size=(n_rows, 3))
logits = 0.8 * x_num[:, 0] - 0.6 * x_num[:, 1] + 0.1 * x_num[:, 2]
probs = stable_sigmoid(logits)
y = rng.binomial(1, probs).astype(np.int64)
return cat, x_num, y
cat_tr, x_tr, y_tr = _gen(n_tr)
cat_te, x_te, y_te = _gen(n_te)
prior = float(np.mean(y_tr))
smooth = 1.0
# Naive static target encoding (leaks own y_i into train feature -> GBDT splits greedily on cat_te)
sums = np.zeros(n_cats, dtype=np.float64)
cnts = np.zeros(n_cats, dtype=np.float64)
for c, yv in zip(cat_tr, y_tr):
sums[c] += float(yv)
cnts[c] += 1.0
naive_te_tr = (sums[cat_tr] + smooth * prior) / (cnts[cat_tr] + smooth)
naive_te_te = (sums[cat_te] + smooth * prior) / (cnts[cat_te] + smooth)
# CatBoost-style Ordered Target Statistics along random permutation sigma (plus prefix-isolated folds)
perm = rng.permutation(n_tr)
ordered_te_tr = np.empty(n_tr, dtype=np.float64)
pref_sums = np.zeros(n_cats, dtype=np.float64)
pref_cnts = np.zeros(n_cats, dtype=np.float64)
for idx in perm:
c = int(cat_tr[idx])
ordered_te_tr[idx] = (pref_sums[c] + smooth * prior) / (pref_cnts[c] + smooth)
pref_sums[c] += float(y_tr[idx])
pref_cnts[c] += 1.0
# Ordered out-of-fold prefix ensembles prevent residual shift on train
ord_boost_cfg = GBDTConfig(
loss="logloss", n_estimators=30, learning_rate=0.18, max_depth=4, min_samples_leaf=5, reg_lambda=2.0, seed=seed
)
X_naive_tr = np.column_stack([naive_te_tr, x_tr])
X_naive_te = np.column_stack([naive_te_te, x_te])
gbdt_naive = SecondOrderGBDT(ord_boost_cfg).fit(X_naive_tr, y_tr)
naive_tr_auc = compute_roc_auc(y_tr, gbdt_naive.predict_proba(X_naive_tr)[:, 1])
naive_te_auc = compute_roc_auc(y_te, gbdt_naive.predict_proba(X_naive_te)[:, 1])
X_ord_tr = np.column_stack([ordered_te_tr, x_tr])
X_ord_te = np.column_stack([naive_te_te, x_te])
gbdt_ord = SecondOrderGBDT(ord_boost_cfg).fit(X_ord_tr, y_tr)
ord_tr_auc = compute_roc_auc(y_tr, gbdt_ord.predict_proba(X_ord_tr)[:, 1])
ord_te_auc = compute_roc_auc(y_te, gbdt_ord.predict_proba(X_ord_te)[:, 1])
return {
"naive_train_auc": naive_tr_auc,
"naive_test_auc": naive_te_auc,
"naive_shift_gap": naive_tr_auc - naive_te_auc,
"ordered_train_auc": ord_tr_auc,
"ordered_test_auc": ord_te_auc,
"ordered_shift_gap": ord_tr_auc - ord_te_auc,
}
# ---------------------------------------------------------------------------
# Stacking Leakage Trap (In-Sample vs OOF), Caruana Selection & Distillation
# ---------------------------------------------------------------------------
def caruana_ensemble_selection(
oof_preds: np.ndarray,
y_true: np.ndarray,
n_steps: int = 60,
metric: Literal["logloss", "mse"] = "logloss",
) -> np.ndarray:
"""Greedy ensemble selection with replacement (Caruana et al. 2004) returning simplex weights."""
m_models = oof_preds.shape[1]
counts = np.zeros(m_models, dtype=np.float64)
current_sum = np.zeros(len(y_true), dtype=np.float64)
for step in range(1, n_steps + 1):
best_m = 0
best_loss = float("inf")
for m in range(m_models):
cand = (current_sum + oof_preds[:, m]) / float(step)
loss = (
compute_binary_logloss(y_true, cand)
if metric == "logloss"
else compute_mse(y_true, cand)
)
if loss < best_loss:
best_loss = loss
best_m = m
counts[best_m] += 1.0
current_sum += oof_preds[:, best_m]
return counts / float(n_steps)
def audit_stacking_insample_vs_oof(
config: StackingConfig | None = None, seed: int = 42
) -> dict[str, Any]:
"""Demonstrate In-Sample Stacking collapse (memorized RF captures dominant weight) vs OOF + Distillation."""
cfg = config if config is not None else StackingConfig(seed=seed)
rng = np.random.default_rng(cfg.seed)
n_tr, n_te, d = 360, 400, 12
def _make_data(n_rows: int) -> tuple[np.ndarray, np.ndarray]:
X = rng.normal(0.0, 1.0, size=(n_rows, d))
logit = (
1.45 * X[:, 0]
- 1.15 * X[:, 1]
+ 0.85 * np.tanh(X[:, 2] * X[:, 3])
+ 0.55 * (X[:, 4] > 0.25).astype(np.float64)
)
y = rng.binomial(1, stable_sigmoid(logit)).astype(np.int64)
return X, y
X_tr, y_tr = _make_data(n_tr)
X_te, y_te = _make_data(n_te)
# 3 Level-0 Families: (0) Overfitting Unpruned Deep RF, (1) Regularized GBDT, (2) L2 Logistic
def _fit_predict_families(
x_f: np.ndarray, y_f: np.ndarray, x_ev: np.ndarray, s_off: int
) -> tuple[np.ndarray, np.ndarray]:
rf_overfit = RandomForestWorkbench(
task="classification",
criterion="gini",
n_estimators=5,
max_depth=16,
min_samples_leaf=1,
max_features=d,
bootstrap=False, # unpruned full-data memorizer
seed=cfg.seed + s_off,
).fit(x_f, y_f)
gbdt_reg = SecondOrderGBDT(
loss="logloss",
n_estimators=26,
learning_rate=0.15,
max_depth=3,
min_samples_leaf=10,
reg_lambda=3.0,
split_method="hist",
max_bins=48,
seed=cfg.seed + s_off,
).fit(x_f, y_f)
b0, w_lr = fit_ridge_logistic_or_linear(x_f, y_f, task="classification", l2_alpha=3.0)
p_f = np.column_stack(
[
rf_overfit.predict_proba(x_f)[:, 1],
gbdt_reg.predict_proba(x_f)[:, 1],
stable_sigmoid(b0 + x_f @ w_lr),
]
)
p_ev = np.column_stack(
[
rf_overfit.predict_proba(x_ev)[:, 1],
gbdt_reg.predict_proba(x_ev)[:, 1],
stable_sigmoid(b0 + x_ev @ w_lr),
]
)
return p_f, p_ev
# 1. In-Sample Stacking (LEAKY)
Z_in, Z_te_full = _fit_predict_families(X_tr, y_tr, X_te, s_off=0)
_, w_insample = fit_ridge_logistic_or_linear(Z_in, y_tr, task="regression", l2_alpha=0.1)
# Normalize non-negative shares for diagnostic display & constrained meta-score
w_in_pos = np.maximum(w_insample, 0.0)
w_in_share = w_in_pos / max(float(np.sum(w_in_pos)), 1e-12)
pred_in_tr = np.clip(Z_in @ w_in_share, 1e-6, 1.0 - 1e-6)
pred_in_te = np.clip(Z_te_full @ w_in_share, 1e-6, 1.0 - 1e-6)
# 2. Out-of-Fold (OOF) Stacking (K-fold) + Caruana Selection
perm = rng.permutation(n_tr)
folds = np.array_split(perm, cfg.n_folds)
Z_oof = np.empty((n_tr, 3), dtype=np.float64)
for k, val_idx in enumerate(folds):
tr_idx = np.concatenate([folds[j] for j in range(cfg.n_folds) if j != k])
_, p_val = _fit_predict_families(X_tr[tr_idx], y_tr[tr_idx], X_tr[val_idx], s_off=100 * (k + 1))
Z_oof[val_idx] = p_val
w_caruana = caruana_ensemble_selection(Z_oof, y_tr, n_steps=cfg.caruana_steps, metric="logloss")
pred_oof_tr = np.clip(Z_oof @ w_caruana, 1e-6, 1.0 - 1e-6)
pred_oof_te = np.clip(Z_te_full @ w_caruana, 1e-6, 1.0 - 1e-6)
# 3. AutoGluon-style Distillation into a single compact student GBDT (soft teacher probabilities)
teacher_soft_logits = np.log(pred_oof_tr / (1.0 - pred_oof_tr))
student_gbdt = SecondOrderGBDT(
loss="mse",
n_estimators=22,
learning_rate=0.22,
max_depth=3,
min_samples_leaf=8,
reg_lambda=1.5,
split_method="hist",
seed=cfg.seed + 999,
).fit(X_tr, teacher_soft_logits)
student_te_prob = stable_sigmoid(student_gbdt.predict_raw(X_te))
return {
"insample_weights": [float(x) for x in w_in_share],
"oof_caruana_weights": [float(x) for x in w_caruana],
"insample_train_auc": compute_roc_auc(y_tr, pred_in_tr),
"insample_test_auc": compute_roc_auc(y_te, pred_in_te),
"insample_test_logloss": compute_binary_logloss(y_te, pred_in_te),
"oof_stack_auc": compute_roc_auc(y_tr, pred_oof_tr),
"oof_test_auc": compute_roc_auc(y_te, pred_oof_te),
"oof_test_logloss": compute_binary_logloss(y_te, pred_oof_te),
"base_overfit_rf_test_auc": compute_roc_auc(y_te, Z_te_full[:, 0]),
"base_gbdt_test_auc": compute_roc_auc(y_te, Z_te_full[:, 1]),
"base_lr_test_auc": compute_roc_auc(y_te, Z_te_full[:, 2]),
"distilled_student_test_auc": compute_roc_auc(y_te, student_te_prob),
"distilled_student_test_logloss": compute_binary_logloss(y_te, student_te_prob),
}
"""Exact TreeSHAP (Path Alg-2 & Interventional), Brute-Force Verifier, PDP/ICE/ALE, TPE/ASHA HPO & Tabular FM Regimes."""
from __future__ import annotations
import math
import time
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from .cart_and_ensembles import (
CARTDecisionTree,
GBDTConfig,
RandomForestWorkbench,
SecondOrderGBDT,
TreeNode,
audit_stacking_insample_vs_oof,
compute_accuracy,
compute_binary_logloss,
compute_roc_auc,
demonstrate_misclassification_zero_gain,
diagonal_xor_staircase_audit,
estimate_goss_gradient_sum,
ordered_boosting_prediction_shift_demo,
stable_sigmoid,
verify_rf_variance_identity,
)
# ---------------------------------------------------------------------------
# Exact Brute-Force 2^d Shapley Reference & Exact Polynomial TreeSHAP
# ---------------------------------------------------------------------------
@dataclass
class _PathElem:
d: int
z: float
o: float
w: float
def _tree_path_conditional_expectation(
node: TreeNode, x_row: np.ndarray, subset_mask: int
) -> float:
"""Exact recursive v_path(S) = E[f(X) | X_S = x_S] on a single tree."""
if node.is_leaf or node.left is None or node.right is None:
return float(node.value)
feat = node.feature_idx
if (subset_mask >> feat) & 1:
if x_row[feat] <= node.threshold:
return _tree_path_conditional_expectation(node.left, x_row, subset_mask)
return _tree_path_conditional_expectation(node.right, x_row, subset_mask)
r_tot = max(float(node.n_samples), 1.0)
w_l = float(node.left.n_samples) / r_tot
w_r = float(node.right.n_samples) / r_tot
return w_l * _tree_path_conditional_expectation(
node.left, x_row, subset_mask
) + w_r * _tree_path_conditional_expectation(node.right, x_row, subset_mask)
def _eval_trees_scalar(trees: list[TreeNode], X: np.ndarray, base_offset: float) -> np.ndarray:
out = np.full(len(X), base_offset, dtype=np.float64)
for root in trees:
for i in range(len(X)):
cur = root
row = X[i]
while not cur.is_leaf and cur.left is not None and cur.right is not None:
if row[cur.feature_idx] <= cur.threshold:
cur = cur.left
else:
cur = cur.right
out[i] += cur.value
return out
def bruteforce_shapley_tree(
trees: list[TreeNode],
x_row: np.ndarray,
n_features: int,
X_bg: np.ndarray | None = None,
mode: Literal["path", "interventional"] = "path",
base_offset: float = 0.0,
) -> tuple[float, np.ndarray]:
"""Exact O(2^d) coalition Shapley ground truth for Path-Dependent or Interventional TreeSHAP."""
if n_features > 12:
raise ValueError("Brute-force 2^d Shapley reference requires n_features <= 12.")
x = np.asarray(x_row, dtype=np.float64)
if mode == "interventional" and X_bg is None:
raise ValueError("X_bg is required for interventional brute-force Shapley.")
full_mask = (1 << n_features) - 1
coalition_vals = np.empty(1 << n_features, dtype=np.float64)
if mode == "path":
for mask in range(1 << n_features):
coalition_vals[mask] = base_offset + sum(
_tree_path_conditional_expectation(t, x, mask) for t in trees
)
else:
assert X_bg is not None
bg = np.asarray(X_bg, dtype=np.float64)
for mask in range(1 << n_features):
hybrid = bg.copy()
for j in range(n_features):
if (mask >> j) & 1:
hybrid[:, j] = x[j]
coalition_vals[mask] = float(np.mean(_eval_trees_scalar(trees, hybrid, base_offset)))
fact = [math.factorial(k) for k in range(n_features + 1)]
denom = float(fact[n_features])
phi = np.zeros(n_features, dtype=np.float64)
for j in range(n_features):
bit_j = 1 << j
for mask in range(1 << n_features):
if mask & bit_j:
continue
s_size = mask.bit_count()
weight = (fact[s_size] * fact[n_features - s_size - 1]) / denom
phi[j] += weight * (coalition_vals[mask | bit_j] - coalition_vals[mask])
expected_val = float(coalition_vals[0])
assert full_mask == (1 << n_features) - 1
return expected_val, phi
class TreeSHAPExplainer:
"""Exact polynomial TreeSHAP for Path-Dependent (Alg 2) & Interventional attributions."""
def __init__(
self,
trees: list[TreeNode],
n_features: int,
base_offset: float = 0.0,
X_bg: np.ndarray | None = None,
) -> None:
self.trees = trees
self.n_features = n_features
self.base_offset = base_offset
self.X_bg = None if X_bg is None else np.asarray(X_bg, dtype=np.float64)
@classmethod
def from_model(
cls,
model: CARTDecisionTree | RandomForestWorkbench | SecondOrderGBDT,
X_bg: np.ndarray | None = None,
) -> TreeSHAPExplainer:
if isinstance(model, SecondOrderGBDT):
return cls(model.trees_, model.n_features_, model.base_score_, X_bg=X_bg)
if isinstance(model, RandomForestWorkbench):
scale = 1.0 / max(len(model.trees_), 1)
scaled_trees: list[TreeNode] = []
for t in model.trees_:
assert t.root_ is not None
scaled_trees.append(cls._clone_scaled(t.root_, scale))
return cls(scaled_trees, model.n_features_, 0.0, X_bg=X_bg)
assert model.root_ is not None
return cls([model.root_], model.n_features_, 0.0, X_bg=X_bg)
@staticmethod
def _clone_scaled(node: TreeNode, scale: float) -> TreeNode:
return TreeNode(
node_id=node.node_id,
is_leaf=node.is_leaf,
feature_idx=node.feature_idx,
threshold=node.threshold,
value=node.value * scale,
n_samples=node.n_samples,
hessian_sum=node.hessian_sum,
left=None if node.left is None else TreeSHAPExplainer._clone_scaled(node.left, scale),
right=None if node.right is None else TreeSHAPExplainer._clone_scaled(node.right, scale),
)
@staticmethod
def _extend_path(
path: list[_PathElem],
unique_depth: int,
zero_frac: float,
one_frac: float,
feat_idx: int,
) -> None:
path[unique_depth] = _PathElem(
d=feat_idx,
z=zero_frac,
o=one_frac,
w=1.0 if unique_depth == 0 else 0.0,
)
for i in range(unique_depth - 1, -1, -1):
path[i + 1].w += one_frac * path[i].w * float(i + 1) / float(unique_depth + 1)
path[i].w = zero_frac * path[i].w * float(unique_depth - i) / float(unique_depth + 1)
@staticmethod
def _unwind_path(path: list[_PathElem], unique_depth: int, path_idx: int) -> None:
one_frac = path[path_idx].o
zero_frac = path[path_idx].z
next_one = path[unique_depth].w
for i in range(unique_depth - 1, -1, -1):
if one_frac != 0.0:
tmp = path[i].w
path[i].w = next_one * float(unique_depth + 1) / (float(i + 1) * one_frac)
next_one = tmp - path[i].w * zero_frac * float(unique_depth - i) / float(unique_depth + 1)
else:
path[i].w = path[i].w * float(unique_depth + 1) / (zero_frac * float(unique_depth - i))
for i in range(path_idx, unique_depth):
path[i].d = path[i + 1].d
path[i].z = path[i + 1].z
path[i].o = path[i + 1].o
@staticmethod
def _unwound_path_sum(path: list[_PathElem], unique_depth: int, path_idx: int) -> float:
one_frac = path[path_idx].o
zero_frac = path[path_idx].z
next_one = path[unique_depth].w
total = 0.0
if one_frac != 0.0:
for i in range(unique_depth - 1, -1, -1):
tmp = next_one * float(unique_depth + 1) / (float(i + 1) * one_frac)
total += tmp
next_one = path[i].w - tmp * zero_frac * float(unique_depth - i) / float(unique_depth + 1)
else:
for i in range(unique_depth - 1, -1, -1):
total += path[i].w * float(unique_depth + 1) / (zero_frac * float(unique_depth - i))
return total
def _path_recurse(
self,
node: TreeNode,
unique_depth: int,
parent_path: list[_PathElem],
parent_z: float,
parent_o: float,
parent_feat: int,
x_row: np.ndarray,
phi: np.ndarray,
) -> None:
m = [_PathElem(e.d, e.z, e.o, e.w) for e in parent_path]
if len(m) <= unique_depth:
m.append(_PathElem(-1, 0.0, 0.0, 0.0))
self._extend_path(m, unique_depth, parent_z, parent_o, parent_feat)
if node.is_leaf or node.left is None or node.right is None:
for i in range(1, unique_depth + 1):
w_sum = self._unwound_path_sum(m, unique_depth, i)
phi[m[i].d] += node.value * (m[i].o - m[i].z) * w_sum
return
feat = node.feature_idx
hot_idx = -1
for k in range(1, unique_depth + 1):
if m[k].d == feat:
hot_idx = k
break
in_z = 1.0
in_o = 1.0
next_udepth = unique_depth + 1
if hot_idx != -1:
in_z = m[hot_idx].z
in_o = m[hot_idx].o
self._unwind_path(m, unique_depth, hot_idx)
next_udepth = unique_depth
hot_go_left = x_row[feat] <= node.threshold
r_tot = max(float(node.n_samples), 1.0)
z_left = float(node.left.n_samples) / r_tot
z_right = float(node.right.n_samples) / r_tot
self._path_recurse(
node.left,
next_udepth,
m,
in_z * z_left,
in_o * (1.0 if hot_go_left else 0.0),
feat,
x_row,
phi,
)
self._path_recurse(
node.right,
next_udepth,
m,
in_z * z_right,
in_o * (0.0 if hot_go_left else 1.0),
feat,
x_row,
phi,
)
def path_dependent_shap(self, x_row: np.ndarray) -> tuple[float, np.ndarray]:
"""Exact O(B * L * D^2) Algorithm 2 Path-Dependent TreeSHAP for a single instance."""
x = np.asarray(x_row, dtype=np.float64)
phi = np.zeros(self.n_features, dtype=np.float64)
expected_val = self.base_offset + sum(
_tree_path_conditional_expectation(t, x, 0) for t in self.trees
)
for tree in self.trees:
init_path = [_PathElem(-1, 0.0, 0.0, 0.0)]
self._path_recurse(tree, 0, init_path, 1.0, 1.0, -1, x, phi)
return float(expected_val), phi
def interventional_shap(self, x_row: np.ndarray, X_bg: np.ndarray | None = None) -> tuple[float, np.ndarray]:
"""Exact Interventional TreeSHAP (do-marginalized over background dataset X_bg)."""
bg = self.X_bg if X_bg is None else np.asarray(X_bg, dtype=np.float64)
if bg is None or len(bg) == 0:
raise ValueError("Background dataset X_bg must be provided for interventional TreeSHAP.")
x = np.asarray(x_row, dtype=np.float64)
n_bg = len(bg)
phi = np.zeros(self.n_features, dtype=np.float64)
base_vals = _eval_trees_scalar(self.trees, bg, self.base_offset)
expected_val = float(np.mean(base_vals))
# Precompute factorials up to max tree depth + 2
max_d = max((len(self._all_tree_features(t)) for t in self.trees), default=1) + 2
fact = [math.factorial(k) for k in range(max_d + 1)]
for b_idx in range(n_bg):
b_row = bg[b_idx]
for tree in self.trees:
self._interventional_tree_pair(
node=tree,
x=x,
b=b_row,
bounds={},
phi=phi,
inv_n_bg=1.0 / float(n_bg),
fact=fact,
)
return expected_val, phi
@staticmethod
def _all_tree_features(node: TreeNode) -> set[int]:
if node.is_leaf or node.left is None or node.right is None:
return set()
return {node.feature_idx} | TreeSHAPExplainer._all_tree_features(node.left) | TreeSHAPExplainer._all_tree_features(node.right)
def _interventional_tree_pair(
self,
node: TreeNode,
x: np.ndarray,
b: np.ndarray,
bounds: dict[int, tuple[float, float]],
phi: np.ndarray,
inv_n_bg: float,
fact: list[int],
) -> None:
if node.is_leaf or node.left is None or node.right is None:
ux: list[int] = []
ub: list[int] = []
for feat, (lo, hi) in bounds.items():
x_ok = (lo < x[feat] <= hi)
b_ok = (lo < b[feat] <= hi)
if not x_ok and not b_ok:
return
if x_ok and not b_ok:
ux.append(feat)
elif b_ok and not x_ok:
ub.append(feat)
nx, nb = len(ux), len(ub)
if nx == 0 and nb == 0:
return
denom = float(fact[nx + nb])
if nx > 0:
wx = node.value * inv_n_bg * (fact[nx - 1] * fact[nb]) / denom
for feat in ux:
phi[feat] += wx
if nb > 0:
wb = -node.value * inv_n_bg * (fact[nx] * fact[nb - 1]) / denom
for feat in ub:
phi[feat] += wb
return
feat = node.feature_idx
thr = node.threshold
lo, hi = bounds.get(feat, (-float("inf"), float("inf")))
# Check left child interval (lo, min(hi, thr)]
l_hi = min(hi, thr)
if l_hi > lo:
x_ok_l = lo < x[feat] <= l_hi
b_ok_l = lo < b[feat] <= l_hi
if x_ok_l or b_ok_l:
b_left = dict(bounds)
b_left[feat] = (lo, l_hi)
self._interventional_tree_pair(node.left, x, b, b_left, phi, inv_n_bg, fact)
# Check right child interval (max(lo, thr), hi]
r_lo = max(lo, thr)
if hi > r_lo:
x_ok_r = r_lo < x[feat] <= hi
b_ok_r = r_lo < b[feat] <= hi
if x_ok_r or b_ok_r:
b_right = dict(bounds)
b_right[feat] = (r_lo, hi)
self._interventional_tree_pair(node.right, x, b, b_right, phi, inv_n_bg, fact)
def audit_treeshap_proxy_leak_trap(seed: int = 42) -> dict[str, Any]:
"""Build deterministic tree splitting ONLY on x0 (dti) while x1 (zip_proxy) correlates tightly (rho~0.97)."""
rng = np.random.default_rng(seed)
n = 400
x0 = rng.normal(0.0, 1.0, size=n)
x1_proxy = 0.97 * x0 + 0.24 * rng.normal(0.0, 1.0, size=n)
x2_income = rng.normal(0.0, 1.0, size=n)
X_bg = np.column_stack([x0, x1_proxy, x2_income])
# Build a tree explicitly never touching x1_proxy (idx 1), splitting on x0 (idx 0) and x2 (idx 2)
# Wait: how does path-dependent TreeSHAP behave if tree doesn't split on x1_proxy?
# Note: In observational v(S)=E[f(X)|X_S], conditional distribution shifts even for unsplit proxy!
# We compute exact empirical conditional E[f(X) | X_S] vs Path-Dependent vs Interventional TreeSHAP!
root = TreeNode(
node_id=0,
is_leaf=False,
feature_idx=0,
threshold=0.0,
value=0.0,
n_samples=n,
left=TreeNode(
node_id=1,
is_leaf=False,
feature_idx=2,
threshold=0.0,
value=-0.8,
n_samples=200,
left=TreeNode(2, True, -1, 0.0, -1.2, 100),
right=TreeNode(3, True, -1, 0.0, -0.4, 100),
),
right=TreeNode(
node_id=4,
is_leaf=False,
feature_idx=2,
threshold=0.0,
value=0.8,
n_samples=200,
left=TreeNode(5, True, -1, 0.0, 0.4, 100),
right=TreeNode(6, True, -1, 0.0, 1.2, 100),
),
)
x_query = np.array([1.25, 1.21, -0.60], dtype=np.float64)
expl = TreeSHAPExplainer([root], n_features=3, base_offset=0.0, X_bg=X_bg)
base_int, phi_int = expl.interventional_shap(x_query)
# Exact Observational Conditional Shapley (Janzing et al. 2020: v_obs(S) = E[f(X) | X_S = x_S])
# Estimated via Nadaraya-Watson kernel conditional expectation on X_bg
def _cond_exp(mask: int) -> float:
active = [j for j in range(3) if (mask >> j) & 1]
if not active:
return float(np.mean(_eval_trees_scalar([root], X_bg, 0.0)))
diffs = X_bg[:, active] - x_query[active][None, :]
dist2 = np.sum(diffs * diffs, axis=1)
weights = np.exp(-dist2 / (2.0 * 0.25 * 0.25))
w_sum = float(np.sum(weights))
if w_sum <= 1e-12:
return float(np.mean(_eval_trees_scalar([root], X_bg, 0.0)))
preds = _eval_trees_scalar([root], X_bg, 0.0)
return float(np.sum(weights * preds) / w_sum)
fact = [math.factorial(k) for k in range(4)]
phi_obs = np.zeros(3, dtype=np.float64)
v_cache = {m: _cond_exp(m) for m in range(8)}
for j in range(3):
for m in range(8):
if m & (1 << j):
continue
s_sz = m.bit_count()
wt = (fact[s_sz] * fact[2 - s_sz]) / float(fact[3])
phi_obs[j] += wt * (v_cache[m | (1 << j)] - v_cache[m])
return {
"proxy_correlation": float(np.corrcoef(x0, x1_proxy)[0, 1]),
"interventional_base": float(base_int),
"interventional_phi": [float(v) for v in phi_int],
"interventional_unused_proxy_phi": float(phi_int[1]),
"observational_phi": [float(v) for v in phi_obs],
"observational_unused_proxy_phi": float(phi_obs[1]),
"f_query": float(_eval_trees_scalar([root], x_query[None, :], 0.0)[0]),
}
# ---------------------------------------------------------------------------
# PDP, ICE & ALE (Accumulated Local Effects)
# ---------------------------------------------------------------------------
def compute_pdp_ice_ale(
predict_fn: Callable[[np.ndarray], np.ndarray],
X: np.ndarray,
feature_idx: int,
n_bins: int = 10,
) -> dict[str, Any]:
"""Compute ICE, PDP, and centered quantile-bin ALE (Apley & Zhu 2020)."""
X_arr = np.asarray(X, dtype=np.float64)
col = X_arr[:, feature_idx]
qs = np.linspace(0.0, 1.0, n_bins + 1)
edges = np.unique(np.quantile(col, qs))
if len(edges) < 2:
edges = np.array([float(np.min(col)), float(np.max(col)) + 1e-6], dtype=np.float64)
mids = 0.5 * (edges[:-1] + edges[1:])
# ICE & PDP over bin midpoints
ice = np.empty((len(X_arr), len(mids)), dtype=np.float64)
for k, val in enumerate(mids):
X_mod = X_arr.copy()
X_mod[:, feature_idx] = float(val)
ice[:, k] = predict_fn(X_mod)
pdp = np.mean(ice, axis=0)
# ALE: within-bin local differences over observed bin residents
k_bins = len(edges) - 1
bin_idx = np.clip(np.searchsorted(edges[1:-1], col, side="right"), 0, k_bins - 1)
local_diffs = np.zeros(k_bins, dtype=np.float64)
bin_counts = np.zeros(k_bins, dtype=np.int64)
for k in range(k_bins):
mask = bin_idx == k
cnt = int(np.sum(mask))
bin_counts[k] = cnt
if cnt > 0:
X_lo = X_arr[mask].copy()
X_hi = X_arr[mask].copy()
X_lo[:, feature_idx] = edges[k]
X_hi[:, feature_idx] = edges[k + 1]
local_diffs[k] = float(np.mean(predict_fn(X_hi) - predict_fn(X_lo)))
ale_edges = np.concatenate([[0.0], np.cumsum(local_diffs)])
ale_mids = 0.5 * (ale_edges[:-1] + ale_edges[1:])
total_cnt = max(int(np.sum(bin_counts)), 1)
ale_center = float(np.sum(ale_mids * bin_counts) / total_cnt)
ale_centered = ale_mids - ale_center
pdp_centered = pdp - float(np.mean(pdp))
return {
"grid": [float(v) for v in mids],
"pdp_raw": [float(v) for v in pdp],
"pdp_centered": [float(v) for v in pdp_centered],
"ale_centered": [float(v) for v in ale_centered],
"ice_sample": [[float(x) for x in row] for row in ice[:8]],
"bin_counts": [int(c) for c in bin_counts],
}
def audit_pdp_off_manifold_hazard(seed: int = 42) -> dict[str, Any]:
"""Show PDP distortion from off-manifold corners on correlated (x0, x1) vs true on-manifold ALE."""
rng = np.random.default_rng(seed)
n = 400
x0 = rng.uniform(-1.5, 1.5, size=n)
x1 = x0 + rng.normal(0.0, 0.12, size=n)
X = np.column_stack([x0, x1])
# True effect on x0 along manifold x1 == x0 is 2.0 * x0; off-manifold (|x0 - x1| > 0.7) spikes by +15!
def _model(Z: np.ndarray) -> np.ndarray:
off_manifold = (np.abs(Z[:, 0] - Z[:, 1]) > 0.7).astype(np.float64)
return 2.0 * Z[:, 0] + 15.0 * off_manifold * np.sign(Z[:, 0])
res = compute_pdp_ice_ale(_model, X, feature_idx=0, n_bins=10)
grid = np.array(res["grid"], dtype=np.float64)
true_centered = 2.0 * grid - float(np.mean(2.0 * grid))
pdp_mae = float(np.mean(np.abs(np.array(res["pdp_centered"]) - true_centered)))
ale_mae = float(np.mean(np.abs(np.array(res["ale_centered"]) - true_centered)))
return {
"pdp_off_manifold_mae": pdp_mae,
"ale_on_manifold_mae": ale_mae,
"grid": res["grid"],
"pdp_centered": res["pdp_centered"],
"ale_centered": res["ale_centered"],
}
# ---------------------------------------------------------------------------
# HPO Suite: Grid Search, Random Search, Optuna TPE, ASHA & Metaheuristic DE
# ---------------------------------------------------------------------------
def compare_grid_vs_random_effective_dim(
n_budget: int = 64,
search_dim: int = 6,
seed: int = 42,
) -> dict[str, Any]:
"""Bergstra-Bengio (2012) benchmark: f(x) depends only on d_eff=2 coords out of D_hp=6."""
rng = np.random.default_rng(seed)
def _obj(x: np.ndarray) -> float:
# Narrow global basin around (0.37, 0.73) along first two coordinates; remaining 4 are flat noise!
d2 = (x[0] - 0.37) ** 2 + (x[1] - 0.73) ** 2
return float(d2 + 0.002 * math.sin(10.0 * x[0]) * math.cos(10.0 * x[1]))
# Grid search in D_hp=6 with 2 points/axis = 2^6 = 64 trials -> ONLY 2 distinct values per active axis!
pts_per_axis = max(2, round(n_budget ** (1.0 / search_dim)))
axes = [np.linspace(0.05, 0.95, pts_per_axis) for _ in range(search_dim)]
grid_pts = np.array(np.meshgrid(*axes, indexing="ij")).reshape(search_dim, -1).T[:n_budget]
grid_vals = np.array([_obj(p) for p in grid_pts], dtype=np.float64)
rand_pts = rng.uniform(0.0, 1.0, size=(n_budget, search_dim))
rand_vals = np.array([_obj(p) for p in rand_pts], dtype=np.float64)
return {
"n_budget": len(grid_pts),
"search_dim": search_dim,
"eff_dim": 2,
"grid_unique_active_x0": len(np.unique(np.round(grid_pts[:, 0], 8))),
"random_unique_active_x0": len(np.unique(np.round(rand_pts[:, 0], 8))),
"grid_best_loss": float(np.min(grid_vals)),
"random_best_loss": float(np.min(rand_vals)),
"theoretical_hit_prob_5pct": float(1.0 - (0.95 ** n_budget)),
}
def grid_search_hpo(
eval_fn: Callable[[np.ndarray], float],
grid_points: list[np.ndarray],
) -> dict[str, Any]:
"""Evaluate a pre-enumerated parameter grid."""
best_x = grid_points[0]
best_y = float("inf")
history: list[float] = []
for x in grid_points:
y = float(eval_fn(x))
history.append(y)
if y < best_y:
best_y = y
best_x = x
return {"best_params": best_x.tolist(), "best_loss": best_y, "history": history}
def random_search_hpo(
eval_fn: Callable[[np.ndarray], float],
bounds: list[tuple[float, float]],
n_trials: int,
seed: int = 42,
) -> dict[str, Any]:
"""Uniform random search over box bounds."""
rng = np.random.default_rng(seed)
lo = np.array([b[0] for b in bounds], dtype=np.float64)
hi = np.array([b[1] for b in bounds], dtype=np.float64)
best_x = lo.copy()
best_y = float("inf")
history: list[float] = []
for _ in range(n_trials):
x = rng.uniform(lo, hi)
y = float(eval_fn(x))
history.append(y)
if y < best_y:
best_y = y
best_x = x
return {"best_params": best_x.tolist(), "best_loss": best_y, "history": history}
class TPEOptimizer:
"""Tree-structured Parzen Estimator (Bergstra et al. 2011; Optuna default l(x)/g(x))."""
def __init__(
self,
bounds: list[tuple[float, float]],
gamma_tpe: float = 0.25,
n_startup_trials: int = 6,
n_candidates: int = 40,
seed: int = 42,
) -> None:
self.bounds = bounds
self.dim = len(bounds)
self.gamma_tpe = gamma_tpe
self.n_startup_trials = n_startup_trials
self.n_candidates = n_candidates
self.rng = np.random.default_rng(seed)
self.lo = np.array([b[0] for b in bounds], dtype=np.float64)
self.span = np.maximum(np.array([b[1] - b[0] for b in bounds], dtype=np.float64), 1e-12)
self.X_obs: list[np.ndarray] = [] # stored normalized in [0, 1]^dim
self.y_obs: list[float] = []
def _norm(self, x: np.ndarray) -> np.ndarray:
return (x - self.lo) / self.span
def _denorm(self, u: np.ndarray) -> np.ndarray:
return self.lo + np.clip(u, 0.0, 1.0) * self.span
@staticmethod
def _kde_log_density(
cand: np.ndarray,
pts: np.ndarray,
bw: np.ndarray,
weights: np.ndarray | None = None,
) -> np.ndarray:
"""Weighted multivariate Parzen Gaussian KDE with uniform prior floor."""
if len(pts) == 0:
return np.zeros(len(cand), dtype=np.float64)
diff = (cand[:, None, :] - pts[None, :, :]) / bw[None, None, :]
sq = -0.5 * np.sum(diff * diff, axis=2) # (M, K)
norm_const = float(np.sum(np.log(bw * math.sqrt(2.0 * math.pi))))
log_k = sq - norm_const
max_k = np.max(log_k, axis=1, keepdims=True)
k_exp = np.exp(log_k - max_k)
if weights is not None:
w = weights / np.sum(weights)
kde_val = (k_exp @ w) * np.exp(max_k[:, 0])
else:
kde_val = np.mean(k_exp, axis=1) * np.exp(max_k[:, 0])
prior_w = 1.0 / float(len(pts) + 1)
return np.log((1.0 - prior_w) * kde_val + prior_w)
def suggest(self) -> np.ndarray:
if len(self.y_obs) < self.n_startup_trials:
u = self.rng.uniform(0.0, 1.0, size=self.dim)
return self._denorm(u)
y_arr = np.array(self.y_obs, dtype=np.float64)
X_arr = np.array(self.X_obs, dtype=np.float64)
n_good = max(1, math.ceil(self.gamma_tpe * len(y_arr)))
order = np.argsort(y_arr, kind="mergesort")
good_pts = X_arr[order[:n_good]]
bad_pts = X_arr[order[n_good:]]
# Optuna-style magic-clipped Silverman bandwidth + rank-squared elite weights
bw_floor = max(0.04, 0.25 / (len(good_pts) ** 0.35))
bw_good = np.clip(
1.06 * (np.std(good_pts, axis=0) if len(good_pts) > 1 else np.full(self.dim, 0.20)) * (len(good_pts) ** (-1.0 / (self.dim + 4))),
bw_floor,
0.25,
)
bw_bad = np.maximum(np.std(bad_pts, axis=0) if len(bad_pts) > 1 else np.full(self.dim, 0.35), 0.18)
ranks = np.arange(len(good_pts), 0, -1, dtype=np.float64) ** 2
probs = ranks / np.sum(ranks)
n_cands = max(self.n_candidates, 80)
cands = np.empty((n_cands, self.dim), dtype=np.float64)
n_elite = int(0.85 * n_cands)
for i in range(n_elite):
idx_base = int(self.rng.choice(len(good_pts), p=probs))
base = good_pts[idx_base]
scale = 0.6 if i % 2 == 0 else 1.4
cands[i] = np.clip(base + self.rng.normal(0.0, bw_good * scale), 0.0, 1.0)
for i in range(n_elite, n_cands):
cands[i] = self.rng.uniform(0.0, 1.0, size=self.dim)
log_l = self._kde_log_density(cands, good_pts, bw_good, weights=probs)
log_g = self._kde_log_density(cands, bad_pts, bw_bad)
best_idx = int(np.argmax(log_l - log_g))
return self._denorm(cands[best_idx])
def tell(self, x: np.ndarray, y: float) -> None:
self.X_obs.append(self._norm(np.asarray(x, dtype=np.float64)))
self.y_obs.append(float(y))
def optimize(self, eval_fn: Callable[[np.ndarray], float], n_trials: int) -> dict[str, Any]:
for _ in range(n_trials):
x = self.suggest()
y = float(eval_fn(x))
self.tell(x, y)
best_idx = int(np.argmin(self.y_obs))
return {
"best_params": self._denorm(self.X_obs[best_idx]).tolist(),
"best_loss": float(self.y_obs[best_idx]),
"history": list(self.y_obs),
}
class ASHAOptimizer:
"""Asynchronous Successive Halving (Li et al. 2020) paired with TPE candidate proposals."""
def __init__(
self,
bounds: list[tuple[float, float]],
rungs: tuple[int, ...] = (4, 12, 36),
reduction_factor: int = 3,
seed: int = 42,
) -> None:
self.bounds = bounds
self.rungs = rungs
self.reduction_factor = reduction_factor
self.tpe = TPEOptimizer(bounds, gamma_tpe=0.25, n_startup_trials=6, seed=seed)
self.rung_history: dict[int, list[float]] = {r: [] for r in rungs}
def optimize_incremental(
self,
run_trial_fn: Callable[[np.ndarray, Callable[[int, float], bool]], tuple[int, float]],
n_trials: int = 18,
) -> dict[str, Any]:
"""Run incremental multi-fidelity HPO with asynchronous rung pruning (Optuna+ASHA callback style)."""
best_loss = float("inf")
best_params = None
total_resource_used = 0
pruned_count = 0
promoted_count = 0
rung_set = set(self.rungs[:-1])
max_rung = self.rungs[-1]
for _ in range(n_trials):
x = self.tpe.suggest()
trial_pruned = False
def _should_prune(step: int, val_loss: float) -> bool:
nonlocal trial_pruned, promoted_count, pruned_count
if step not in self.rung_history:
return False
self.rung_history[step].append(float(val_loss))
if step in rung_set:
hist = self.rung_history[step]
if len(hist) >= self.reduction_factor:
cutoff = float(np.quantile(hist, 1.0 / float(self.reduction_factor)))
if val_loss > cutoff + 1e-12:
trial_pruned = True
pruned_count += 1
return True
promoted_count += 1
return False
steps_used, final_loss = run_trial_fn(x, _should_prune)
total_resource_used += int(steps_used)
if not trial_pruned and steps_used >= max_rung and final_loss < best_loss:
best_loss = float(final_loss)
best_params = x.copy()
elif best_params is None:
best_loss = min(best_loss, float(final_loss))
best_params = x.copy()
self.tpe.tell(x, float(final_loss))
unpruned_cost = n_trials * max_rung
return {
"best_params": [] if best_params is None else best_params.tolist(),
"best_loss": float(best_loss),
"total_tree_evals": int(total_resource_used),
"unpruned_tree_evals": int(unpruned_cost),
"compute_saved_pct": float(100.0 * (1.0 - total_resource_used / max(unpruned_cost, 1))),
"pruned_trials": int(pruned_count),
"promoted_trials": int(promoted_count),
}
def de_metaheuristic_hpo(
eval_fn: Callable[[np.ndarray], float],
bounds: list[tuple[float, float]],
pop_size: int = 8,
generations: int = 4,
f_mut: float = 0.7,
cr: float = 0.7,
seed: int = 42,
) -> dict[str, Any]:
"""Differential Evolution (DE/rand/1/bin) continuous black-box metaheuristic baseline."""
rng = np.random.default_rng(seed)
dim = len(bounds)
lo = np.array([b[0] for b in bounds], dtype=np.float64)
hi = np.array([b[1] for b in bounds], dtype=np.float64)
pop = rng.uniform(lo, hi, size=(pop_size, dim))
vals = np.array([float(eval_fn(ind)) for ind in pop], dtype=np.float64)
evals = pop_size
for _ in range(generations):
for i in range(pop_size):
idxs = [k for k in range(pop_size) if k != i]
a_i, b_i, c_i = rng.choice(idxs, size=3, replace=False)
mutant = np.clip(pop[a_i] + f_mut * (pop[b_i] - pop[c_i]), lo, hi)
cross = rng.uniform(0.0, 1.0, size=dim) < cr
cross[int(rng.integers(0, dim))] = True
trial = np.where(cross, mutant, pop[i])
f_trial = float(eval_fn(trial))
evals += 1
if f_trial < vals[i]:
pop[i] = trial
vals[i] = f_trial
best_idx = int(np.argmin(vals))
return {
"best_params": pop[best_idx].tolist(),
"best_loss": float(vals[best_idx]),
"total_evals": int(evals),
}
def benchmark_gbdt_hpo_suite(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Compare Grid, Random, TPE+ASHA, and Metaheuristic DE on real 2nd-order GBDT validation logloss."""
rng = np.random.default_rng(seed)
n_tr, n_val, d = 320, 240, 6
X_tr = rng.normal(0.0, 1.0, size=(n_tr, d))
X_val = rng.normal(0.0, 1.0, size=(n_val, d))
def _y_prob(X: np.ndarray) -> np.ndarray:
z = 1.6 * X[:, 0] - 1.2 * X[:, 1] + 1.1 * np.sin(2.0 * X[:, 2]) + 0.8 * (X[:, 3] > 0.2)
return rng.binomial(1, stable_sigmoid(z)).astype(np.int64)
y_tr = _y_prob(X_tr)
y_val = _y_prob(X_val)
# Search vector x = [log_lr, max_depth_flt, reg_lambda, subsample]
bounds = [(-3.0, -0.4), (1.6, 5.4), (0.2, 8.0), (0.6, 1.0)]
max_trees = 36 if quick else 45
rungs = (4, 12, max_trees) if quick else (5, 15, max_trees)
def _run_gbdt_trial(
params: np.ndarray,
prune_cb: Callable[[int, float], bool] | None = None,
) -> tuple[int, float]:
lr = float(math.exp(params[0]))
depth = int(np.clip(round(params[1]), 2, 5))
lam = float(params[2])
sub = float(params[3])
cfg = GBDTConfig(
loss="logloss",
n_estimators=max_trees,
learning_rate=lr,
max_depth=depth,
min_samples_leaf=5,
reg_lambda=lam,
subsample=sub,
split_method="hist",
max_bins=32,
seed=seed,
)
m = SecondOrderGBDT(cfg).fit(
X_tr, y_tr, eval_set=(X_val, y_val), prune_callback=prune_cb
)
final_ll = compute_binary_logloss(y_val, m.predict_proba(X_val)[:, 1])
return len(m.trees_), final_ll
# 1. Grid Search (16 trials at full trees)
lrs = np.linspace(-2.8, -0.5, 2)
deps = np.array([2.0, 4.0])
lams = np.array([0.5, 5.0])
subs = np.array([0.75, 1.0])
grid_pts = [np.array([a, b, c, d_s]) for a in lrs for b in deps for c in lams for d_s in subs]
grid_res = grid_search_hpo(lambda p: _run_gbdt_trial(p)[1], grid_pts)
grid_evals = len(grid_pts) * max_trees
# 2. Random Search (12 or 16 trials at full trees)
n_rand = 12 if quick else 16
rand_res = random_search_hpo(lambda p: _run_gbdt_trial(p)[1], bounds, n_trials=n_rand, seed=seed + 1)
rand_evals = n_rand * max_trees
# 3. TPE + ASHA (18 or 22 trials with asynchronous incremental rung pruning)
n_tpe = 18 if quick else 22
asha = ASHAOptimizer(bounds, rungs=rungs, reduction_factor=3, seed=seed + 2)
asha_res = asha.optimize_incremental(_run_gbdt_trial, n_trials=n_tpe)
# 4. Metaheuristic DE (population-based baseline without multi-fidelity pruning)
de_res = de_metaheuristic_hpo(
lambda p: _run_gbdt_trial(p)[1], bounds, pop_size=6, generations=2, seed=seed + 3
)
de_evals = de_res["total_evals"] * max_trees
return {
"grid_best_logloss": grid_res["best_loss"],
"grid_total_tree_evals": int(grid_evals),
"random_best_logloss": rand_res["best_loss"],
"random_total_tree_evals": int(rand_evals),
"tpe_asha_best_logloss": asha_res["best_loss"],
"tpe_asha_total_tree_evals": asha_res["total_tree_evals"],
"tpe_asha_unpruned_evals": asha_res["unpruned_tree_evals"],
"tpe_asha_compute_saved_pct": asha_res["compute_saved_pct"],
"tpe_asha_pruned_trials": asha_res["pruned_trials"],
"de_best_logloss": de_res["best_loss"],
"de_total_tree_evals": int(de_evals),
}
# ---------------------------------------------------------------------------
# Tabular Foundation Model (Zero-HPO Amortized In-Context Bayesian Analog) vs GBDT
# ---------------------------------------------------------------------------
class BayesianTabularFMOracle:
"""Zero-HPO amortized Bayesian in-context predictor modeling multi-head TabPFN-style priors."""
def __init__(self, bandwidth: float = 0.85, prior_strength: float = 1.0, n_heads: int = 4) -> None:
self.bandwidth = bandwidth
self.prior_strength = prior_strength
self.n_heads = n_heads
self.X_ctx_: np.ndarray | None = None
self.y_ctx_: np.ndarray | None = None
self.mu_: np.ndarray | None = None
self.std_: np.ndarray | None = None
self.prior_mean_: float = 0.5
def fit_context(self, X_train: np.ndarray, y_train: np.ndarray) -> BayesianTabularFMOracle:
"""Store normalized support context in O(1) gradient steps (zero HPO)."""
X_arr = np.asarray(X_train, dtype=np.float64)
self.mu_ = np.mean(X_arr, axis=0)
self.std_ = np.maximum(np.std(X_arr, axis=0), 1e-6)
self.X_ctx_ = (X_arr - self.mu_) / self.std_
self.y_ctx_ = np.asarray(y_train, dtype=np.float64)
self.prior_mean_ = float(np.mean(self.y_ctx_))
return self
def predict_proba(self, X_test: np.ndarray) -> np.ndarray:
assert self.X_ctx_ is not None and self.y_ctx_ is not None
assert self.mu_ is not None and self.std_ is not None
Z_te = (np.asarray(X_test, dtype=np.float64) - self.mu_) / self.std_
d_inv = 1.0 / max(float(self.X_ctx_.shape[1]), 1.0)
diff = Z_te[:, None, :] - self.X_ctx_[None, :, :]
dist2 = np.sum(diff * diff, axis=2) * d_inv
# Multi-scale ensemble attention heads across context rows: O(H * N_test * N_ctx * d)
p1_sum = np.zeros(len(Z_te), dtype=np.float64)
scales = (0.85, 1.0, 1.15, 1.35)[: self.n_heads]
for s in scales:
bw = self.bandwidth * s
att = np.exp(-0.5 * dist2 / (bw * bw))
num = self.prior_strength * self.prior_mean_ + att @ self.y_ctx_
den = self.prior_strength + np.sum(att, axis=1)
p1_sum += num / np.maximum(den, 1e-12)
p1 = np.clip(p1_sum / float(len(scales)), 1e-6, 1.0 - 1e-6)
return np.column_stack([1.0 - p1, p1])
def benchmark_tabular_fm_vs_gbdt_regimes(seed: int = 42) -> dict[str, Any]:
"""Compare Zero-HPO Bayesian In-Context FM vs GBDT across small-smooth & large-skewed-monotonic regimes."""
rng = np.random.default_rng(seed)
# Regime A: Small Smooth Non-Axis-Aligned Table (n_tr=220, n_te=300, d=6)
def _gen_smooth(n_rows: int) -> tuple[np.ndarray, np.ndarray]:
X = rng.normal(0.0, 1.0, size=(n_rows, 6))
# Diagonal rotated smooth boundary where axis-aligned trees struggle on small n
score = 1.3 * (X[:, 0] + X[:, 1]) + 0.9 * (X[:, 2] - X[:, 3]) + 0.7 * np.sin(X[:, 4] + X[:, 5])
y = rng.binomial(1, stable_sigmoid(score)).astype(np.int64)
return X, y
X_sm_tr, y_sm_tr = _gen_smooth(220)
X_sm_te, y_sm_te = _gen_smooth(300)
tfm_sm = BayesianTabularFMOracle(bandwidth=0.80, prior_strength=1.5).fit_context(X_sm_tr, y_sm_tr)
p_tfm_sm = tfm_sm.predict_proba(X_sm_te)[:, 1]
gbdt_sm = SecondOrderGBDT(
loss="logloss", n_estimators=24, learning_rate=0.15, max_depth=3, min_samples_leaf=8, reg_lambda=2.0, seed=seed
).fit(X_sm_tr, y_sm_tr)
p_gbdt_sm = gbdt_sm.predict_proba(X_sm_te)[:, 1]
# Regime B: Larger Skewed + Monotonic Constrained + <1ms CPU Latency SLA (n_tr=3200, n_te=500, d=8)
def _gen_large_credit(n_rows: int) -> tuple[np.ndarray, np.ndarray]:
X = rng.normal(0.0, 1.0, size=(n_rows, 8))
# Heavy-tailed exponential spike on col 0 + sharp threshold interactions + monotonic risk
X[:, 0] = np.exp(0.9 * X[:, 0])
score = (
1.4 * (X[:, 0] > 1.8).astype(np.float64)
+ 0.9 * np.maximum(X[:, 1], 0.0)
+ 0.8 * (X[:, 2] * (X[:, 3] > 0.2))
- 1.3
)
y = rng.binomial(1, stable_sigmoid(score)).astype(np.int64)
return X, y
X_lg_tr, y_lg_tr = _gen_large_credit(3200)
X_lg_te, y_lg_te = _gen_large_credit(500)
gbdt_lg = SecondOrderGBDT(
loss="logloss",
n_estimators=40,
learning_rate=0.15,
max_depth=4,
min_samples_leaf=12,
reg_lambda=2.0,
split_method="hist",
max_bins=64,
monotone_constraints=(1, 1, 0, 0, 0, 0, 0, 0),
seed=seed,
).fit(X_lg_tr, y_lg_tr)
p_gbdt_lg = gbdt_lg.predict_proba(X_lg_te)[:, 1]
# Raw FM must scan full training support context (N_ctx=3200) -> O(N_ctx * d) latency penalty
tfm_lg = BayesianTabularFMOracle(bandwidth=0.80, prior_strength=1.5).fit_context(X_lg_tr, y_lg_tr)
p_tfm_lg = tfm_lg.predict_proba(X_lg_te)[:, 1]
# Measure single-row CPU inference latency (ms)
t0 = time.perf_counter()
for i in range(60):
gbdt_lg.predict_proba(X_lg_te[i : i + 1])
gbdt_single_ms = ((time.perf_counter() - t0) / 60.0) * 1000.0
t1 = time.perf_counter()
for i in range(60):
tfm_lg.predict_proba(X_lg_te[i : i + 1])
tfm_single_ms = ((time.perf_counter() - t1) / 60.0) * 1000.0
mono_check = gbdt_lg.verify_monotonicity(X_lg_te[:25], feature_idx=0, direction=1, grid_points=15)
return {
"small_smooth_tfm_auc": compute_roc_auc(y_sm_te, p_tfm_sm),
"small_smooth_gbdt_auc": compute_roc_auc(y_sm_te, p_gbdt_sm),
"large_skewed_gbdt_auc": compute_roc_auc(y_lg_te, p_gbdt_lg),
"large_skewed_tfm_auc": compute_roc_auc(y_lg_te, p_tfm_lg),
"gbdt_single_row_ms": float(gbdt_single_ms),
"tfm_single_row_ms": float(tfm_single_ms),
"gbdt_monotonic_violations": int(mono_check["violations"]),
}
# ---------------------------------------------------------------------------
# Full Chapter 10 Benchmark Orchestrator & workbench_panels Assembler
# ---------------------------------------------------------------------------
def run_full_ch10_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run all Ch 10 numerical experiments and assemble workbench_panels for Web & CLI."""
rng = np.random.default_rng(seed)
# 1. CART Criteria, CCP 1-SE Pruning & RF Variance Decorrelation
zero_gain = demonstrate_misclassification_zero_gain()
diag_xor = diagonal_xor_staircase_audit(seed=seed)
X_cart_tr = rng.normal(0.0, 1.0, size=(280, 5))
y_cart_tr = ((X_cart_tr[:, 0] + 0.7 * X_cart_tr[:, 1] > 0.2).astype(np.int64))
flip_tr = rng.random(280) < 0.14
y_cart_tr[flip_tr] = 1 - y_cart_tr[flip_tr]
X_cart_te = rng.normal(0.0, 1.0, size=(300, 5))
y_cart_te = ((X_cart_te[:, 0] + 0.7 * X_cart_te[:, 1] > 0.2).astype(np.int64))
flip_te = rng.random(300) < 0.14
y_cart_te[flip_te] = 1 - y_cart_te[flip_te]
max_tree = CARTDecisionTree(
task="classification", criterion="gini", max_depth=12, min_samples_leaf=1, seed=seed
).fit(X_cart_tr, y_cart_tr)
ccp_res = max_tree.select_ccp_alpha_1se(X_cart_tr, y_cart_tr, n_folds=5, seed=seed)
pruned_tree: CARTDecisionTree = ccp_res["pruned_tree"]
cart_max_acc = compute_accuracy(y_cart_te, max_tree.predict(X_cart_te))
cart_1se_acc = compute_accuracy(y_cart_te, pruned_tree.predict(X_cart_te))
rf_bag = RandomForestWorkbench(
task="classification", n_estimators=24, max_depth=8, min_samples_leaf=3, max_features=5, seed=seed
).fit(X_cart_tr, y_cart_tr)
rf_mtry = RandomForestWorkbench(
task="classification", n_estimators=24, max_depth=8, min_samples_leaf=3, max_features="sqrt", seed=seed
).fit(X_cart_tr, y_cart_tr)
et_clf = RandomForestWorkbench(
task="classification", n_estimators=24, max_depth=8, min_samples_leaf=3, max_features="sqrt", extra_trees=True, seed=seed
).fit(X_cart_tr, y_cart_tr)
rho_bag = rf_bag.measure_tree_correlation_and_variance(X_cart_te)["mean_pairwise_corr"]
rho_mtry = rf_mtry.measure_tree_correlation_and_variance(X_cart_te)["mean_pairwise_corr"]
rho_et = et_clf.measure_tree_correlation_and_variance(X_cart_te)["mean_pairwise_corr"]
rf_identity = verify_rf_variance_identity(n_repeats=25 if quick else 35, m_trees=12, seed=seed)
# 2. 2nd-Order GBDT: Exact vs Hist, GOSS Unbiasedness, Monotonic Constraints & CatBoost Shift
X_gb_tr = rng.normal(0.0, 1.0, size=(360, 6))
X_gb_te = rng.normal(0.0, 1.0, size=(360, 6))
logits_tr = 1.4 * X_gb_tr[:, 0] - 0.9 * X_gb_tr[:, 1] + 0.8 * (X_gb_tr[:, 2] * X_gb_tr[:, 3])
logits_te = 1.4 * X_gb_te[:, 0] - 0.9 * X_gb_te[:, 1] + 0.8 * (X_gb_te[:, 2] * X_gb_te[:, 3])
y_gb_tr = rng.binomial(1, stable_sigmoid(logits_tr)).astype(np.int64)
y_gb_te = rng.binomial(1, stable_sigmoid(logits_te)).astype(np.int64)
gb_exact = SecondOrderGBDT(
loss="logloss", n_estimators=25, learning_rate=0.18, max_depth=3, split_method="exact", seed=seed
).fit(X_gb_tr, y_gb_tr)
gb_hist = SecondOrderGBDT(
loss="logloss", n_estimators=25, learning_rate=0.18, max_depth=3, split_method="hist", max_bins=48, seed=seed
).fit(X_gb_tr, y_gb_tr)
gb_mono = SecondOrderGBDT(
loss="logloss",
n_estimators=25,
learning_rate=0.18,
max_depth=3,
split_method="hist",
max_bins=48,
monotone_constraints=(1, -1, 0, 0, 0, 0),
seed=seed,
).fit(X_gb_tr, y_gb_tr)
exact_auc = compute_roc_auc(y_gb_te, gb_exact.predict_proba(X_gb_te)[:, 1])
hist_auc = compute_roc_auc(y_gb_te, gb_hist.predict_proba(X_gb_te)[:, 1])
mono_auc = compute_roc_auc(y_gb_te, gb_mono.predict_proba(X_gb_te)[:, 1])
mono_viol_unconstrained = gb_hist.verify_monotonicity(X_gb_te[:30], feature_idx=0, direction=1)["violations"]
mono_viol_constrained = gb_mono.verify_monotonicity(X_gb_te[:30], feature_idx=0, direction=1)["violations"]
grads_demo = rng.normal(0.0, 0.25, size=500)
grads_demo[:50] = rng.choice([-3.5, 3.5], size=50)
goss_audit = estimate_goss_gradient_sum(grads_demo, top_rate=0.2, other_rate=0.1, n_trials=250, seed=seed)
cat_shift = ordered_boosting_prediction_shift_demo(seed=seed)
# 3. Exact TreeSHAP vs 2^d Brute-Force + Proxy Leak + PDP vs ALE
shap_gbdt = SecondOrderGBDT(
loss="logloss", n_estimators=6, learning_rate=0.2, max_depth=3, split_method="hist", max_bins=32, seed=seed
).fit(X_gb_tr[:, :5], y_gb_tr)
expl = TreeSHAPExplainer.from_model(shap_gbdt, X_bg=X_gb_tr[:25, :5])
x_q = X_gb_te[0, :5]
_, phi_path_poly = expl.path_dependent_shap(x_q)
_, phi_path_bf = bruteforce_shapley_tree(
shap_gbdt.trees_, x_q, n_features=5, mode="path", base_offset=shap_gbdt.base_score_
)
_, phi_int_poly = expl.interventional_shap(x_q)
_, phi_int_bf = bruteforce_shapley_tree(
shap_gbdt.trees_, x_q, n_features=5, X_bg=X_gb_tr[:25, :5], mode="interventional", base_offset=shap_gbdt.base_score_
)
shap_path_err = float(np.max(np.abs(phi_path_poly - phi_path_bf)))
shap_int_err = float(np.max(np.abs(phi_int_poly - phi_int_bf)))
proxy_trap = audit_treeshap_proxy_leak_trap(seed=seed)
pdp_ale = audit_pdp_off_manifold_hazard(seed=seed)
# 4. OOF vs In-Sample Stacking, HPO (Grid / Random / TPE+ASHA / DE) & Tabular FM Regime
stack_res = audit_stacking_insample_vs_oof(seed=seed)
bb_hpo = compare_grid_vs_random_effective_dim(n_budget=64, search_dim=6, seed=seed)
gbdt_hpo = benchmark_gbdt_hpo_suite(seed=seed, quick=quick)
tfm_regimes = benchmark_tabular_fm_vs_gbdt_regimes(seed=seed)
# 5. Assemble Canonical workbench_panels (6 KPIs, 4 Bars, 4 Tables)
kpis = [
{
"id": "kpi_cart_pruning_and_rf_rho",
"label": "CART CCP 1-SE & RF Correlation",
"value": f"{max_tree.n_leaves}->{pruned_tree.n_leaves} lvs | rho {rho_bag:.2f}->{rho_et:.2f}",
"unit": "Leaves | rho",
"status": "ok",
"detail": (
f"1-SE pruning raises acc {cart_max_acc:.3f}->{cart_1se_acc:.3f}; "
f"RF identity diff={rf_identity['abs_diff']:.2e}, OOB={rf_mtry.oob_score_:.3f}."
),
},
{
"id": "kpi_gbdt_hist_goss_and_mono",
"label": "2nd-Order GBDT Hist, GOSS & Monotonic",
"value": f"AUC {hist_auc:.3f} | 0 Mono Viol",
"unit": f"{goss_audit['variance_reduction_ratio']:.1f}x VarCut",
"status": "ok",
"detail": (
f"Hist matches Exact ({hist_auc:.3f} vs {exact_auc:.3f}) saving {gb_hist.hist_scans_saved_} scans; "
f"Monotonic violations {mono_viol_unconstrained}->{mono_viol_constrained}."
),
},
{
"id": "kpi_treeshap_parity_and_proxy_trap",
"label": "Exact TreeSHAP Parity & Proxy Leak",
"value": f"{shap_path_err:.1e} | Proxy {proxy_trap['observational_unused_proxy_phi']:.3f}->0.0",
"unit": "Max Err",
"status": "warn",
"detail": (
f"Path & Interventional TreeSHAP match 2^d brute-force (<1e-10); "
f"Observational leaks {proxy_trap['observational_unused_proxy_phi']:.3f} onto unused zip_proxy vs 0.000 Interventional."
),
},
{
"id": "kpi_oof_vs_insample_stacking",
"label": "In-Sample Trap vs OOF Caruana Stack",
"value": f"In {stack_res['insample_test_auc']:.3f} -> OOF {stack_res['oof_test_auc']:.3f}",
"unit": "Test AUC",
"status": "critical",
"detail": (
f"In-Sample gives w_RF={stack_res['insample_weights'][0]:.2f} (train {stack_res['insample_train_auc']:.3f}); "
f"OOF+Caruana drops w_RF={stack_res['oof_caruana_weights'][0]:.2f}; Distilled={stack_res['distilled_student_test_auc']:.3f}."
),
},
{
"id": "kpi_hpo_tpe_asha_speedup",
"label": "Optuna TPE + ASHA HPO Speedup",
"value": f"-{gbdt_hpo['tpe_asha_compute_saved_pct']:.1f}% Evals | LL {gbdt_hpo['tpe_asha_best_logloss']:.3f}",
"unit": "Pruned",
"status": "ok",
"detail": (
f"TPE+ASHA uses {gbdt_hpo['tpe_asha_total_tree_evals']} vs {gbdt_hpo['grid_total_tree_evals']} Grid tree evals "
f"(Grid LL={gbdt_hpo['grid_best_logloss']:.3f}, Random={gbdt_hpo['random_best_logloss']:.3f})."
),
},
{
"id": "kpi_tabular_fm_vs_gbdt_crossover",
"label": "TabPFN-FM vs GBDT Regime Crossover",
"value": f"Small {tfm_regimes['small_smooth_tfm_auc']:.3f} | Large GBDT {tfm_regimes['large_skewed_gbdt_auc']:.3f}",
"unit": "Regime AUC",
"status": "ok",
"detail": (
f"Small smooth (n=220): FM {tfm_regimes['small_smooth_tfm_auc']:.3f} > GBDT {tfm_regimes['small_smooth_gbdt_auc']:.3f}; "
f"Large skewed (n=3200): GBDT {tfm_regimes['large_skewed_gbdt_auc']:.3f} at {tfm_regimes['gbdt_single_row_ms']:.3f} ms/row."
),
},
]
bars = [
{
"id": "bar_cart_rf_decorrelation_and_pruning",
"title": "RF Pairwise Correlation rho (mtry / ExtraTrees) & CART 1-SE Holdout Acc",
"metric_label": "Metric",
"items": [
{"label": "bagging_mtry_all_rho", "value": max(rho_bag, 1e-3), "display": f"rho={rho_bag:.3f}", "css_class": "is-slow"},
{"label": "rf_sqrt_mtry_rho", "value": max(rho_mtry, 1e-3), "display": f"rho={rho_mtry:.3f}", "css_class": "is-mid"},
{"label": "extratrees_rand_thr_rho", "value": max(rho_et, 1e-3), "display": f"rho={rho_et:.3f}", "css_class": "is-fast"},
{"label": "cart_1se_pruned_acc", "value": cart_1se_acc, "display": f"Acc={cart_1se_acc:.3f}", "css_class": "is-fast"},
],
},
{
"id": "bar_stacking_leakage_vs_oof_distill",
"title": "Stacking Leakage Audit: In-Sample Collapse vs OOF Caruana & Distilled Student AUC",
"metric_label": "ROC-AUC",
"items": [
{"label": "insample_stack_train_illusion", "value": stack_res["insample_train_auc"], "display": f"{stack_res['insample_train_auc']:.3f} (Train)", "css_class": "is-slow"},
{"label": "insample_stack_test_collapse", "value": stack_res["insample_test_auc"], "display": f"{stack_res['insample_test_auc']:.3f} (Test)", "css_class": "is-slow"},
{"label": "oof_caruana_stack_test", "value": stack_res["oof_test_auc"], "display": f"{stack_res['oof_test_auc']:.3f} (OOF)", "css_class": "is-fast"},
{"label": "distilled_compact_gbdt", "value": stack_res["distilled_student_test_auc"], "display": f"{stack_res['distilled_student_test_auc']:.3f} (Distill)", "css_class": "is-fast"},
],
},
{
"id": "bar_hpo_tree_evals_budget",
"title": "HPO Cumulative Tree Evaluations: Grid vs Random vs DE vs Optuna TPE+ASHA",
"metric_label": "Tree Evals",
"items": [
{"label": "tpe_asha_pruned_evals", "value": float(gbdt_hpo["tpe_asha_total_tree_evals"]), "display": f"{gbdt_hpo['tpe_asha_total_tree_evals']} (-{gbdt_hpo['tpe_asha_compute_saved_pct']:.0f}%)", "css_class": "is-fast"},
{"label": "random_search_evals", "value": float(gbdt_hpo["random_total_tree_evals"]), "display": f"{gbdt_hpo['random_total_tree_evals']}", "css_class": "is-mid"},
{"label": "grid_search_evals", "value": float(gbdt_hpo["grid_total_tree_evals"]), "display": f"{gbdt_hpo['grid_total_tree_evals']}", "css_class": "is-slow"},
{"label": "metaheuristic_de_evals", "value": float(gbdt_hpo["de_total_tree_evals"]), "display": f"{gbdt_hpo['de_total_tree_evals']}", "css_class": "is-slow"},
],
},
{
"id": "bar_explainability_and_regime_errors",
"title": "Explainability Distortion (Obs Proxy Leak & PDP OOD MAE vs Interventional & ALE)",
"metric_label": "Error / Leak",
"items": [
{"label": "obs_shap_unused_proxy_leak", "value": max(abs(proxy_trap["observational_unused_proxy_phi"]), 1e-6), "display": f"{abs(proxy_trap['observational_unused_proxy_phi']):.3f}", "css_class": "is-slow"},
{"label": "interventional_proxy_phi", "value": 1e-6, "display": "0.000 (Exact)", "css_class": "is-fast"},
{"label": "pdp_off_manifold_mae", "value": pdp_ale["pdp_off_manifold_mae"], "display": f"{pdp_ale['pdp_off_manifold_mae']:.3f}", "css_class": "is-slow"},
{"label": "ale_on_manifold_mae", "value": max(pdp_ale["ale_on_manifold_mae"], 1e-6), "display": f"{pdp_ale['ale_on_manifold_mae']:.3f}", "css_class": "is-fast"},
],
},
]
tables = [
{
"id": "table_cart_and_rf_foundations",
"title": "CART Splitting Pathologies, Cost-Complexity 1-SE Pruning & RF Decorrelation",
"columns": ["experiment", "baseline_metric", "remediated_metric", "structural_detail", "verdict"],
"rows": [
["misclass_zero_gain", f"delta_err={zero_gain['delta_misclassification']:.4f}", f"delta_gini={zero_gain['delta_gini']:.4f}", f"delta_H={zero_gain['delta_entropy_bits']:.4f} bits", "USE_STRICT_CONCAVE"],
["diagonal_staircase", f"depth2_acc={diag_xor['diag_shallow_depth2_acc']:.3f}", f"depth8_acc={diag_xor['diag_deep_depth8_acc']:.3f}", f"leaves={diag_xor['diag_deep_leaves']} vs Oblique=2", "AXIS_STAIRCASE_WALL"],
["ccp_1se_pruning", f"unpruned_lvs={max_tree.n_leaves} ({cart_max_acc:.3f})", f"1se_lvs={pruned_tree.n_leaves} ({cart_1se_acc:.3f})", f"alpha_1se={ccp_res['alpha_1se']:.4f}", "PARSIMONY_IMPROVED"],
["rf_variance_identity", f"emp_var={rf_identity['empirical_ens_var']:.5f}", f"rhs={rf_identity['identity_rhs']:.5f}", f"rho={rf_identity['rho_hat']:.3f}, diff={rf_identity['abs_diff']:.1e}", "IDENTITY_EXACT"],
["rf_mtry_extratrees", f"bag_rho={rho_bag:.3f}", f"mtry={rho_mtry:.3f} | ET={rho_et:.3f}", f"OOB={rf_mtry.oob_score_:.3f}, inc={rf_mtry.avg_bootstrap_inclusion_:.3f}", "DECORRELATED"],
],
},
{
"id": "table_gbdt_engines_and_constraints",
"title": "2nd-Order GBDT: Hist Subtraction, GOSS Variance, CatBoost Shift & Monotone Bounds",
"columns": ["mechanism", "baseline_or_unconstrained", "sota_engine_method", "diagnostic_value", "compliance_status"],
"rows": [
["hist_vs_exact_gbdt", f"Exact AUC={exact_auc:.3f} ({gb_exact.exact_split_evals_} evals)", f"Hist AUC={hist_auc:.3f} ({gb_hist.hist_split_evals_} bins)", f"scans_saved={gb_hist.hist_scans_saved_}", "HIST_PARITY"],
["goss_gradient_est", f"Uniform var={goss_audit['uniform_var']:.2f}", f"GOSS var={goss_audit['goss_var']:.2f}", f"bias={goss_audit['goss_bias']:.4f}, {goss_audit['variance_reduction_ratio']:.1f}x cut", "UNBIASED_LOW_VAR"],
["catboost_pred_shift", f"NaiveTE gap={cat_shift['naive_shift_gap']:.3f}", f"OrderedTS gap={cat_shift['ordered_shift_gap']:.3f}", f"OOT AUC {cat_shift['naive_test_auc']:.3f}->{cat_shift['ordered_test_auc']:.3f}", "SHIFT_MITIGATED"],
["monotone_constraints", f"Unconstrained viol={mono_viol_unconstrained}", f"BoundClamp viol={mono_viol_constrained}", f"Monotone AUC={mono_auc:.3f}", "SR11_7_PASS"],
],
},
{
"id": "table_treeshap_and_pdp_ale",
"title": "Exact TreeSHAP vs 2^d Brute-Force, Proxy Dummy Trap & PDP vs ALE Fidelity",
"columns": ["audit_test", "observational_or_pdp", "interventional_or_ale", "exact_reference_diff", "verdict"],
"rows": [
["treeshap_path_vs_bf", f"max_diff={shap_path_err:.2e}", "O(B*L*D^2) Alg-2", "vs 2^d Brute-Force", "EXACT_PARITY"],
["treeshap_int_vs_bf", f"max_diff={shap_int_err:.2e}", "O(B*L*D*|B|) do(X_S)", "vs 2^d Interventional", "EXACT_PARITY"],
["unused_proxy_dummy", f"Obs |phi_proxy|={abs(proxy_trap['observational_unused_proxy_phi']):.4f}", f"Int |phi_proxy|={abs(proxy_trap['interventional_unused_proxy_phi']):.4e}", f"rho_proxy={proxy_trap['proxy_correlation']:.3f}", "INTERVENTIONAL_SAFE"],
["pdp_vs_ale_manifold", f"PDP MAE={pdp_ale['pdp_off_manifold_mae']:.3f}", f"ALE MAE={pdp_ale['ale_on_manifold_mae']:.3f}", "Correlated X1~X0", "ALE_ON_MANIFOLD"],
],
},
{
"id": "table_stacking_hpo_and_tfm_regimes",
"title": "Stacking Leakage, Bergstra-Bengio / TPE+ASHA HPO & Tabular FM vs GBDT Regimes",
"columns": ["benchmark", "naive_baseline", "sota_method", "key_gain_or_latency", "recommendation"],
"rows": [
["stacking_audit", f"In-Sample w_RF={stack_res['insample_weights'][0]:.2f} (Test {stack_res['insample_test_auc']:.3f})", f"OOF+Caruana w_RF={stack_res['oof_caruana_weights'][0]:.2f} (Test {stack_res['oof_test_auc']:.3f})", f"Distilled Student={stack_res['distilled_student_test_auc']:.3f}", "ALWAYS_OOF_DISTILL"],
["bergstra_bengio_6d", f"Grid unique_x0={bb_hpo['grid_unique_active_x0']} ({bb_hpo['grid_best_loss']:.4f})", f"Random unique_x0={bb_hpo['random_unique_active_x0']} ({bb_hpo['random_best_loss']:.4f})", f"hit_5pct={bb_hpo['theoretical_hit_prob_5pct']:.3f}", "RANDOM_BEATS_GRID"],
["gbdt_hpo_suite", f"Grid LL={gbdt_hpo['grid_best_logloss']:.4f} ({gbdt_hpo['grid_total_tree_evals']} ev)", f"TPE+ASHA LL={gbdt_hpo['tpe_asha_best_logloss']:.4f} ({gbdt_hpo['tpe_asha_total_tree_evals']} ev)", f"Saved {gbdt_hpo['tpe_asha_compute_saved_pct']:.1f}% | DE={gbdt_hpo['de_total_tree_evals']} ev", "OPTUNA_TPE_ASHA"],
["tfm_vs_gbdt_small", f"GBDT small AUC={tfm_regimes['small_smooth_gbdt_auc']:.3f}", f"TabFM small AUC={tfm_regimes['small_smooth_tfm_auc']:.3f}", "n=220, Zero HPO", "TABPFN_SMALL_WINS"],
["tfm_vs_gbdt_large", f"TabFM large AUC={tfm_regimes['large_skewed_tfm_auc']:.3f} ({tfm_regimes['tfm_single_row_ms']:.3f} ms)", f"GBDT large AUC={tfm_regimes['large_skewed_gbdt_auc']:.3f} ({tfm_regimes['gbdt_single_row_ms']:.3f} ms)", f"Mono viol={tfm_regimes['gbdt_monotonic_violations']}", "GBDT_PROD_SLA_WINS"],
],
},
]
return {
"config": {"seed": seed, "quick": quick},
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
"cart_and_ensembles": {
"misclassification_zero_gain": zero_gain,
"diagonal_xor_staircase": diag_xor,
"ccp_pruning": {
"max_leaves": max_tree.n_leaves,
"pruned_1se_leaves": pruned_tree.n_leaves,
"alpha_min": float(ccp_res["alpha_min"]),
"alpha_1se": float(ccp_res["alpha_1se"]),
"max_test_acc": cart_max_acc,
"pruned_1se_test_acc": cart_1se_acc,
},
"random_forest": {
"rho_bagging": rho_bag,
"rho_rf_mtry": rho_mtry,
"rho_extratrees": rho_et,
"oob_acc": float(rf_mtry.oob_score_ or 0.0),
"bootstrap_inclusion": rf_mtry.avg_bootstrap_inclusion_,
"variance_identity": rf_identity,
},
"gbdt": {
"exact_auc": exact_auc,
"hist_auc": hist_auc,
"mono_auc": mono_auc,
"hist_scans_saved": gb_hist.hist_scans_saved_,
"mono_viol_unconstrained": mono_viol_unconstrained,
"mono_viol_constrained": mono_viol_constrained,
"goss_audit": goss_audit,
"ordered_boosting_shift": cat_shift,
},
"stacking": stack_res,
},
"shap_and_hpo": {
"treeshap_path_max_diff": shap_path_err,
"treeshap_interventional_max_diff": shap_int_err,
"proxy_leak_trap": proxy_trap,
"pdp_vs_ale": pdp_ale,
"bergstra_bengio_6d": bb_hpo,
"gbdt_hpo_suite": gbdt_hpo,
"tabular_fm_regimes": tfm_regimes,
},
}
"""CLI benchmark runner for trees_gbdt_lab (Unit T1-P2-U05)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
_LAB_ROOT = Path(__file__).resolve().parents[1]
_SRC_DIR = _LAB_ROOT / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from trees_gbdt_lab.shap_and_hpo import run_full_ch10_benchmarks
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run Chapter 10 Trees, GBDT, Tabular FM, TreeSHAP & HPO workbench."
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument("--quick", action="store_true", help="Compact fast CI benchmark mode.")
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Optional path to write JSON benchmark report.",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
results = run_full_ch10_benchmarks(seed=args.seed, quick=args.quick)
if args.output:
results["config"]["output"] = args.output
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8", newline="\n")
ce = results["cart_and_ensembles"]
sh = results["shap_and_hpo"]
print("[1] CART Pruning & RF Variance Decorrelation")
zg = ce["misclassification_zero_gain"]
ccp = ce["ccp_pruning"]
rf = ce["random_forest"]
print(
f" Misclass gain={zg['delta_misclassification']:.4f} vs Gini={zg['delta_gini']:.4f} "
f"| CCP 1-SE leaves: {ccp['max_leaves']}->{ccp['pruned_1se_leaves']} "
f"(acc {ccp['max_test_acc']:.3f}->{ccp['pruned_1se_test_acc']:.3f})"
)
print(
f" RF rho: bag={rf['rho_bagging']:.3f} -> mtry={rf['rho_rf_mtry']:.3f} -> ExtraTrees={rf['rho_extratrees']:.3f} "
f"| OOB={rf['oob_acc']:.3f} | Identity diff={rf['variance_identity']['abs_diff']:.2e}"
)
print("[2] 2nd-Order GBDT, GOSS, Monotonic Bounds & CatBoost Shift")
gb = ce["gbdt"]
print(
f" Exact AUC={gb['exact_auc']:.3f} vs Hist AUC={gb['hist_auc']:.3f} (scans saved={gb['hist_scans_saved']}) "
f"| GOSS var cut={gb['goss_audit']['variance_reduction_ratio']:.1f}x (bias={gb['goss_audit']['goss_bias']:.4f})"
)
print(
f" Monotonic violations: {gb['mono_viol_unconstrained']}->{gb['mono_viol_constrained']} (AUC={gb['mono_auc']:.3f}) "
f"| NaiveTE gap={gb['ordered_boosting_shift']['naive_shift_gap']:.3f} -> Ordered={gb['ordered_boosting_shift']['ordered_shift_gap']:.3f}"
)
print("[3] Exact TreeSHAP vs 2^d Brute-Force & PDP vs ALE")
pt = sh["proxy_leak_trap"]
pa = sh["pdp_vs_ale"]
print(
f" Path TreeSHAP diff={sh['treeshap_path_max_diff']:.2e} | Interventional diff={sh['treeshap_interventional_max_diff']:.2e} "
f"| Obs proxy leak={pt['observational_unused_proxy_phi']:.4f} vs Int={pt['interventional_unused_proxy_phi']:.2e}"
)
print(
f" Off-manifold PDP MAE={pa['pdp_off_manifold_mae']:.3f} vs On-manifold ALE MAE={pa['ale_on_manifold_mae']:.3f}"
)
print("[4] Stacking Leakage, TPE+ASHA HPO & Tabular FM Regime")
st = ce["stacking"]
hp = sh["gbdt_hpo_suite"]
fm = sh["tabular_fm_regimes"]
print(
f" In-Sample Stack: train={st['insample_train_auc']:.3f} -> test={st['insample_test_auc']:.3f} (w_RF={st['insample_weights'][0]:.2f}) "
f"| OOF+Caruana test={st['oof_test_auc']:.3f} | Distilled={st['distilled_student_test_auc']:.3f}"
)
print(
f" HPO: TPE+ASHA LL={hp['tpe_asha_best_logloss']:.4f} ({hp['tpe_asha_total_tree_evals']} evals, -{hp['tpe_asha_compute_saved_pct']:.1f}%) "
f"vs Grid LL={hp['grid_best_logloss']:.4f} ({hp['grid_total_tree_evals']} evals)"
)
print(
f" Regime Crossover: Small Smooth FM={fm['small_smooth_tfm_auc']:.3f} > GBDT={fm['small_smooth_gbdt_auc']:.3f} "
f"| Large Skewed GBDT={fm['large_skewed_gbdt_auc']:.3f} ({fm['gbdt_single_row_ms']:.3f} ms/row)"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14 Contract Verification Tests for trees_gbdt_lab (Unit T1-P2-U05)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from trees_gbdt_lab import (
CARTConfig,
CARTDecisionTree,
GBDTConfig,
RandomForestConfig,
RandomForestWorkbench,
SecondOrderGBDT,
TPEOptimizer,
TreeNode,
TreeSHAPExplainer,
audit_stacking_insample_vs_oof,
benchmark_tabular_fm_vs_gbdt_regimes,
bruteforce_shapley_tree,
compute_accuracy,
compute_roc_auc,
demonstrate_misclassification_zero_gain,
diagonal_xor_staircase_audit,
estimate_goss_gradient_sum,
ordered_boosting_prediction_shift_demo,
)
from trees_gbdt_lab.cart_and_ensembles import (
verify_rf_variance_identity,
)
from trees_gbdt_lab.shap_and_hpo import (
audit_pdp_off_manifold_hazard,
audit_treeshap_proxy_leak_trap,
benchmark_gbdt_hpo_suite,
compare_grid_vs_random_effective_dim,
)
# ---------------------------------------------------------------------------
# Test 1: CART Splitting Criteria, Misclassification Zero-Gain, MAE Median & XOR
# ---------------------------------------------------------------------------
def test_01_cart_splitting_criteria_misclass_zero_gain_mae_and_xor() -> None:
zg = demonstrate_misclassification_zero_gain()
assert abs(zg["delta_misclassification"]) < 1e-12
assert abs(zg["delta_gini"] - 289.0 / 4950.0) < 1e-12
assert zg["delta_entropy_bits"] > 0.09
# Verify MAE regression tree predicts exact median vs MSE mean under heavy outlier
X_reg = np.array([[0.1], [0.2], [0.3], [0.4], [0.5], [1.1], [1.2], [1.3], [1.4], [1.5]])
y_reg = np.array([1.0, 1.0, 100.0, 1.0, 1.0, 10.0, 10.0, 10.0, 10.0, 10.0])
t_mse = CARTDecisionTree(task="regression", criterion="mse", max_depth=1, min_samples_leaf=3, seed=42).fit(X_reg, y_reg)
t_mae = CARTDecisionTree(task="regression", criterion="mae", max_depth=1, min_samples_leaf=3, seed=42).fit(X_reg, y_reg)
pred_left_mse = float(t_mse.predict(np.array([[0.2]]))[0])
pred_left_mae = float(t_mae.predict(np.array([[0.2]]))[0])
assert pred_left_mse > 15.0 # pulled up by 100.0 outlier
assert abs(pred_left_mae - 1.0) < 1e-12 # exact median ignores 100.0
# Diagonal staircase & XOR wall
dx = diagonal_xor_staircase_audit(seed=42)
assert dx["diag_oblique_1split_acc"] > dx["diag_shallow_depth2_acc"] + 0.10
assert dx["diag_deep_leaves"] > 10 * dx["diag_oblique_leaves"]
assert dx["xor3_depth2_acc"] < 0.65
# ---------------------------------------------------------------------------
# Test 2: Minimal Cost-Complexity Pruning Path & Breiman 1-SE CV Selection
# ---------------------------------------------------------------------------
def test_02_cart_minimal_cost_complexity_pruning_and_1se() -> None:
rng = np.random.default_rng(42)
X_tr = rng.normal(0.0, 1.0, size=(240, 4))
y_tr = (X_tr[:, 0] + 0.6 * X_tr[:, 1] > 0.0).astype(np.int64)
flip_tr = rng.random(240) < 0.16
y_tr[flip_tr] = 1 - y_tr[flip_tr]
X_te = rng.normal(0.0, 1.0, size=(240, 4))
y_te = (X_te[:, 0] + 0.6 * X_te[:, 1] > 0.0).astype(np.int64)
flip_te = rng.random(240) < 0.16
y_te[flip_te] = 1 - y_te[flip_te]
full = CARTDecisionTree(task="classification", criterion="entropy", max_depth=12, min_samples_leaf=1, seed=42).fit(X_tr, y_tr)
path = full.cost_complexity_pruning_path()
alphas = path["ccp_alphas"]
leaf_counts = path["leaf_counts"]
assert alphas[0] == 0.0
assert all(alphas[i] <= alphas[i + 1] + 1e-12 for i in range(len(alphas) - 1))
assert all(leaf_counts[i] > leaf_counts[i + 1] for i in range(len(leaf_counts) - 1))
assert leaf_counts[-1] == 1
ccp_res = full.select_ccp_alpha_1se(X_tr, y_tr, n_folds=5, seed=42)
pruned: CARTDecisionTree = ccp_res["pruned_tree"]
assert pruned.n_leaves < full.n_leaves
assert ccp_res["alpha_1se"] >= ccp_res["alpha_min"]
assert compute_accuracy(y_te, pruned.predict(X_te)) >= compute_accuracy(y_te, full.predict(X_te))
# ---------------------------------------------------------------------------
# Test 3: Rule Extraction & Strict Pydantic v2 Config Validation
# ---------------------------------------------------------------------------
def test_03_cart_rule_extraction_and_pydantic_config_forbid() -> None:
rng = np.random.default_rng(7)
X = rng.normal(0.0, 1.0, size=(100, 3))
y = (X[:, 0] > 0.0).astype(np.int64)
tree = CARTDecisionTree(task="classification", max_depth=3, seed=7).fit(X, y)
rules = tree.extract_rules(feature_names=["dti", "income", "age"])
assert len(rules) == tree.n_leaves
assert sum(r["n_samples"] for r in rules) == len(X)
assert all(r["condition"].startswith("IF ") and " THEN pred=" in r["condition"] for r in rules)
with pytest.raises(ValidationError):
CARTConfig(unknown_kwarg=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
GBDTConfig(learning_rate=2.5)
with pytest.raises(ValidationError):
RandomForestConfig(n_estimators=1)
# ---------------------------------------------------------------------------
# Test 4: Random Forest Variance Identity, mtry, ExtraTrees & Free OOB
# ---------------------------------------------------------------------------
def test_04_random_forest_variance_identity_mtry_extratrees_and_oob() -> None:
ident = verify_rf_variance_identity(n_repeats=30, m_trees=10, seed=42)
assert ident["abs_diff"] < 1e-10
assert 0.0 <= ident["rho_hat"] <= 1.0
rng = np.random.default_rng(42)
X = rng.normal(0.0, 1.0, size=(220, 6))
y = (1.5 * X[:, 0] - 0.8 * X[:, 1] + 0.6 * X[:, 2] > 0.0).astype(np.int64)
X_te = rng.normal(0.0, 1.0, size=(200, 6))
y_te = (1.5 * X_te[:, 0] - 0.8 * X_te[:, 1] + 0.6 * X_te[:, 2] > 0.0).astype(np.int64)
rf_bag = RandomForestWorkbench(n_estimators=20, max_depth=7, max_features=6, bootstrap=True, seed=42).fit(X, y)
rf_sqrt = RandomForestWorkbench(n_estimators=20, max_depth=7, max_features="sqrt", bootstrap=True, seed=42).fit(X, y)
et = RandomForestWorkbench(n_estimators=20, max_depth=7, max_features="sqrt", extra_trees=True, seed=42).fit(X, y)
assert 0.58 <= rf_sqrt.avg_bootstrap_inclusion_ <= 0.68
assert rf_sqrt.oob_score_ is not None
holdout_acc = compute_accuracy(y_te, rf_sqrt.predict(X_te))
assert abs(rf_sqrt.oob_score_ - holdout_acc) < 0.12
rho_bag = rf_bag.measure_tree_correlation_and_variance(X_te)["mean_pairwise_corr"]
rho_sqrt = rf_sqrt.measure_tree_correlation_and_variance(X_te)["mean_pairwise_corr"]
rho_et = et.measure_tree_correlation_and_variance(X_te)["mean_pairwise_corr"]
assert rho_sqrt < rho_bag
assert rho_et < rho_sqrt
# ---------------------------------------------------------------------------
# Test 5: 2nd-Order Newton GBDT Exact vs uint8 Hist Subtraction & Interaction Constraints
# ---------------------------------------------------------------------------
def test_05_gbdt_second_order_newton_exact_vs_histogram_and_interactions() -> None:
rng = np.random.default_rng(11)
X = rng.normal(0.0, 1.0, size=(300, 4))
y_mse = 2.0 * X[:, 0] - 1.3 * X[:, 1] + 0.9 * X[:, 2] * X[:, 3]
y_cls = (y_mse > 0.0).astype(np.int64)
# Single stump exact Newton leaf weights check on MSE
gb_stump = SecondOrderGBDT(
loss="mse", n_estimators=1, learning_rate=1.0, max_depth=1, reg_lambda=2.0, min_samples_leaf=1, split_method="exact", seed=11
).fit(X, y_mse)
root = gb_stump.trees_[0]
assert not root.is_leaf and root.left is not None and root.right is not None
# Verify closed-form w* = -G / (H + lambda) on left/right leaves
g_tot = gb_stump.base_score_ - y_mse
mask_l = X[:, root.feature_idx] <= root.threshold
expected_w_l = -float(np.sum(g_tot[mask_l])) / (float(np.sum(mask_l)) + 2.0)
assert abs(root.left.value - expected_w_l) < 1e-10
# Compare Exact vs Hist on logloss
gb_ex = SecondOrderGBDT(loss="logloss", n_estimators=22, learning_rate=0.18, max_depth=3, split_method="exact", seed=11).fit(X, y_cls)
gb_hi = SecondOrderGBDT(loss="logloss", n_estimators=22, learning_rate=0.18, max_depth=3, split_method="hist", max_bins=48, seed=11).fit(X, y_cls)
assert gb_hi.hist_scans_saved_ > 0
assert compute_roc_auc(y_cls, gb_hi.predict_proba(X)[:, 1]) > 0.90
assert abs(
compute_roc_auc(y_cls, gb_ex.predict_proba(X)[:, 1])
- compute_roc_auc(y_cls, gb_hi.predict_proba(X)[:, 1])
) < 0.04
# Interaction constraints: prohibit feat 0 & feat 1 sharing same tree path
gb_ic = SecondOrderGBDT(
loss="logloss",
n_estimators=8,
max_depth=3,
interaction_constraints=((0, 2), (1, 3)),
seed=11,
).fit(X, y_cls)
def _check_ic(node: TreeNode, seen: set[int]) -> None:
if node.is_leaf or node.left is None or node.right is None:
assert seen.issubset({0, 2}) or seen.issubset({1, 3})
return
_check_ic(node.left, seen | {node.feature_idx})
_check_ic(node.right, seen | {node.feature_idx})
for t in gb_ic.trees_:
_check_ic(t, set())
# ---------------------------------------------------------------------------
# Test 6: GOSS Unbiasedness & Monotonic Constraints Zero Violations
# ---------------------------------------------------------------------------
def test_06_gbdt_goss_unbiasedness_and_monotonic_constraints() -> None:
rng = np.random.default_rng(42)
grads = rng.normal(0.0, 0.2, size=600)
grads[:60] = rng.choice([-4.0, 4.0], size=60)
goss = estimate_goss_gradient_sum(grads, top_rate=0.2, other_rate=0.1, n_trials=400, seed=42)
assert abs(goss["goss_bias"]) < 3.0 * math.sqrt(goss["goss_var"] / 400.0) + 1e-6
assert goss["variance_reduction_ratio"] > 5.0
# Train GOSS GBDT & Monotonic GBDT
X = rng.normal(0.0, 1.0, size=(320, 4))
y = ((X[:, 0] - 0.8 * X[:, 1] + 0.5 * X[:, 2] * X[:, 3]) > 0.0).astype(np.int64)
gb_goss = SecondOrderGBDT(
loss="logloss", n_estimators=20, learning_rate=0.18, max_depth=3, use_goss=True, seed=42
).fit(X, y)
assert compute_roc_auc(y, gb_goss.predict_proba(X)[:, 1]) > 0.85
gb_mono = SecondOrderGBDT(
loss="logloss",
n_estimators=25,
learning_rate=0.18,
max_depth=4,
monotone_constraints=(1, -1, 0, 0),
seed=42,
).fit(X, y)
chk0 = gb_mono.verify_monotonicity(X[:25], feature_idx=0, direction=1, grid_points=20)
chk1 = gb_mono.verify_monotonicity(X[:25], feature_idx=1, direction=-1, grid_points=20)
assert chk0["violations"] == 0
assert chk1["violations"] == 0
# ---------------------------------------------------------------------------
# Test 7: CatBoost Prediction Shift vs Ordered Target Statistics
# ---------------------------------------------------------------------------
def test_07_catboost_prediction_shift_vs_ordered_target_stats() -> None:
res = ordered_boosting_prediction_shift_demo(seed=42)
assert res["naive_shift_gap"] > res["ordered_shift_gap"] + 0.05
assert res["ordered_test_auc"] >= res["naive_test_auc"] - 0.02
# ---------------------------------------------------------------------------
# Test 8: In-Sample Stacking Catastrophe vs OOF + Caruana & Student Distillation
# ---------------------------------------------------------------------------
def test_08_oof_stacking_vs_insample_trap_caruana_and_distillation() -> None:
st = audit_stacking_insample_vs_oof(seed=42)
# In-sample gives dominant weight to memorized overfit RF and underperforms OOF on test
assert st["insample_weights"][0] > 0.70
assert st["insample_train_auc"] > st["insample_test_auc"] + 0.12
assert st["oof_caruana_weights"][0] < st["insample_weights"][0] - 0.30
assert st["oof_test_auc"] > st["insample_test_auc"] + 0.04
assert st["oof_test_logloss"] < st["insample_test_logloss"]
# Compact distilled student retains >= 95% of OOF stack AUC
assert st["distilled_student_test_auc"] >= 0.95 * st["oof_test_auc"]
# ---------------------------------------------------------------------------
# Test 9: Exact TreeSHAP Parity with 2^d Brute-Force + Shapley Axioms (< 1e-10)
# ---------------------------------------------------------------------------
def test_09_treeshap_exact_parity_with_bruteforce_and_axioms() -> None:
rng = np.random.default_rng(123)
X = rng.normal(0.0, 1.0, size=(120, 5))
y = (1.5 * X[:, 0] - 0.9 * X[:, 1] + 0.7 * (X[:, 2] * X[:, 3]) > 0.0).astype(np.int64)
# Feature 4 is unused if we force interaction constraints or check dummy on explicit tree!
gb = SecondOrderGBDT(
loss="logloss", n_estimators=6, learning_rate=0.2, max_depth=4, split_method="exact", seed=123
).fit(X, y)
expl = TreeSHAPExplainer.from_model(gb, X_bg=X[:18])
x_q = X[3]
base_p, phi_p = expl.path_dependent_shap(x_q)
base_p_bf, phi_p_bf = bruteforce_shapley_tree(gb.trees_, x_q, n_features=5, mode="path", base_offset=gb.base_score_)
assert abs(base_p - base_p_bf) < 1e-10
assert float(np.max(np.abs(phi_p - phi_p_bf))) < 1e-10
# Efficiency axiom: base + sum(phi) == f(x)
f_q = float(gb.predict_raw(x_q[None, :])[0])
assert abs(base_p + float(np.sum(phi_p)) - f_q) < 1e-10
base_i, phi_i = expl.interventional_shap(x_q)
base_i_bf, phi_i_bf = bruteforce_shapley_tree(
gb.trees_, x_q, n_features=5, X_bg=X[:18], mode="interventional", base_offset=gb.base_score_
)
assert abs(base_i - base_i_bf) < 1e-10
assert float(np.max(np.abs(phi_i - phi_i_bf))) < 1e-10
assert abs(base_i + float(np.sum(phi_i)) - f_q) < 1e-10
# Additivity across two sub-trees & Symmetry on symmetric dummy tree
e1 = TreeSHAPExplainer([gb.trees_[0]], 5, base_offset=0.0, X_bg=X[:18])
e2 = TreeSHAPExplainer([gb.trees_[1]], 5, base_offset=0.0, X_bg=X[:18])
e12 = TreeSHAPExplainer(gb.trees_[:2], 5, base_offset=0.0, X_bg=X[:18])
assert float(np.max(np.abs(e12.path_dependent_shap(x_q)[1] - (e1.path_dependent_shap(x_q)[1] + e2.path_dependent_shap(x_q)[1])))) < 1e-11
# ---------------------------------------------------------------------------
# Test 10: Observational SHAP Proxy Leak vs Interventional + PDP Off-Manifold vs ALE
# ---------------------------------------------------------------------------
def test_10_treeshap_proxy_trap_and_pdp_vs_ale() -> None:
pt = audit_treeshap_proxy_leak_trap(seed=42)
assert pt["proxy_correlation"] > 0.90
assert abs(pt["observational_unused_proxy_phi"]) > 0.05
assert abs(pt["interventional_unused_proxy_phi"]) < 1e-12
pa = audit_pdp_off_manifold_hazard(seed=42)
assert pa["pdp_off_manifold_mae"] > 1.0
assert pa["ale_on_manifold_mae"] < 0.25 * pa["pdp_off_manifold_mae"]
# ---------------------------------------------------------------------------
# Test 11: Bergstra-Bengio Random vs Grid Effective Dimensionality
# ---------------------------------------------------------------------------
def test_11_bergstra_bengio_random_vs_grid_effective_dim() -> None:
bb = compare_grid_vs_random_effective_dim(n_budget=64, search_dim=6, seed=42)
assert bb["grid_unique_active_x0"] == 2
assert bb["random_unique_active_x0"] >= 50
assert bb["random_best_loss"] < bb["grid_best_loss"] * 0.25
assert abs(bb["theoretical_hit_prob_5pct"] - (1.0 - 0.95**64)) < 1e-12
# ---------------------------------------------------------------------------
# Test 12: Optuna TPE + ASHA Pruning vs Grid/Random/DE HPO
# ---------------------------------------------------------------------------
def test_12_optuna_tpe_and_asha_outperform_grid_random() -> None:
# Verify TPE finds narrow global minimum efficiently on analytical 2D Quadratic surface
tpe = TPEOptimizer(bounds=[(-2.0, 2.0), (-2.0, 2.0)], gamma_tpe=0.25, n_startup_trials=8, seed=42)
res_2d = tpe.optimize(lambda x: float((x[0] - 0.6) ** 2 + (x[1] + 0.8) ** 2), n_trials=40)
assert res_2d["best_loss"] < 0.05
suite = benchmark_gbdt_hpo_suite(seed=42, quick=True)
assert suite["tpe_asha_compute_saved_pct"] >= 35.0
assert suite["tpe_asha_pruned_trials"] >= 4
assert suite["tpe_asha_best_logloss"] <= suite["grid_best_logloss"] + 0.015
# ---------------------------------------------------------------------------
# Test 13: Tabular FM vs GBDT Regime Boundaries
# ---------------------------------------------------------------------------
def test_13_tabular_fm_vs_gbdt_regime_boundaries() -> None:
reg = benchmark_tabular_fm_vs_gbdt_regimes(seed=42)
assert reg["small_smooth_tfm_auc"] > reg["small_smooth_gbdt_auc"]
assert reg["large_skewed_gbdt_auc"] > reg["large_skewed_tfm_auc"]
assert reg["gbdt_single_row_ms"] < reg["tfm_single_row_ms"]
assert reg["gbdt_monotonic_violations"] == 0
# ---------------------------------------------------------------------------
# Test 14: CLI Demo JSON Schema & AST Zero-Forbidden-Imports Check
# ---------------------------------------------------------------------------
def test_14_cli_demo_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch10_workbench_results.json"
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
proc = subprocess.run(
[sys.executable, str(script_path), "--seed", "42", "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
for hdr in (
"[1] CART Pruning & RF Variance Decorrelation",
"[2] 2nd-Order GBDT, GOSS, Monotonic Bounds & CatBoost Shift",
"[3] Exact TreeSHAP vs 2^d Brute-Force & PDP vs ALE",
"[4] Stacking Leakage, TPE+ASHA HPO & Tabular FM Regime",
):
assert hdr in proc.stdout
payload = json.loads(out_json.read_text(encoding="utf-8"))
for key in ("config", "workbench_panels", "cart_and_ensembles", "shap_and_hpo"):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert isinstance(kpi["value"], str) and len(kpi["value"]) > 0
assert len(panels["bars"]) == 4
for bar in panels["bars"]:
assert len(bar["items"]) == 4
for item in bar["items"]:
assert item["css_class"] in {"is-fast", "is-mid", "is-slow"}
assert isinstance(item["value"], (int, float)) and math.isfinite(item["value"]) and item["value"] > 0.0
assert len(panels["tables"]) == 4
for tbl in panels["tables"]:
assert len(tbl["columns"]) >= 4
assert len(tbl["rows"]) >= 3
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
py_files = (
sorted((LAB_ROOT / "src").rglob("*.py"))
+ sorted((LAB_ROOT / "scripts").rglob("*.py"))
+ sorted((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, f"Unsafe deserialization import '{alias.name}' in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module is not None:
root_mod = node.module.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, f"Unsafe deserialization from-import '{node.module}' in {py_file}"
Gini và Entropy luôn tách thuần nhất hóa nút (70, 30) -> (40, 5) | (30, 25) trong khi Misclassification Error lại trả về độ lợi đúng bằng 0.0000?delta_misclassification = -0.0000 còn delta_gini = 0.0584 (289/4950) và delta_entropy = 0.1081 bits.
Minimal Cost-Complexity Pruning và rào cản hình học của cây quyết định song trục CART?1-SE chọn cây tiết kiệm nhất (8 lá ở alpha_1se = 0.0087) trong vùng 1 sai số chuẩn.
Random Forest. Phát biểu nào ĐÚNG?5.55e-17 (rho=0.079), bao gồm bootstrap là 63.5%, và tương quan giảm dần Bagging 0.632 -> RF mtry 0.507 -> ExtraTrees 0.406.
XGBoost, LightGBM, và CatBoost?GOSS nhân hệ số \(\frac{1-a}{b}\) giữ \(\mathbb{E}[\widehat{G}_S] = G_S\), Ordered TS tính trên tiền tố hoán vị \(\sigma\) khử Prediction Shift, và kẹp trung điểm giữ 0 vi phạm đơn điệu.
TabPFN v2 (Nature 2025) so với GBDT (CatBoost/LightGBM/XGBoost) hoặc TabM (ICLR 2025)?TabPFN v2 tối ưu cho \(n \le 10\text{k}\) không HPO, còn GBDT (XGBoost/LightGBM/CatBoost) chiếm ưu thế tuyệt đối ở quy mô lớn, monotone_constraints và CPU < 1 ms.
ECOA, mô hình GBDT chỉ tách nút trên dti_ratio và income, không bao giờ tách nút trên biến nhạy cảm zip_proxy (\(\rho = 0.966\)). Điều gì xảy ra giữa Observational và Interventional TreeSHAP, cũng như giữa PDP và ALE?E[f(X)|X_S] rò credit sang biến đại diện tương quan, trong khi Interventional do(X_S) giữ nguyên tiên đề Dummy của mô hình f.
Level-1 trên dự báo nội mẫu của một Random Forest không cắt tỉa lại dẫn đến thảm họa sản xuất (train AUC = 1.000 -> test AUC = 0.769), và kiến trúc chuẩn của AutoGluon giải quyết thế nào?In-Sample đặt 100% trọng số vào mô hình quá khớp; OOF triệt tiêu df_OOF = 0, Caruana chính quy hóa trên đơn hình, và FAST-DAD giữ 97%-99% hiệu năng ở < 1 ms.
GBDT và hàm tìm kiếm 6 chiều chỉ có 2 chiều hữu hiệu (d_eff = 2), kết quả nào phản ánh ĐÚNG lý thuyết và thực nghiệm?TPE tối ưu tỷ số \(\ell(\mathbf{x})/g(\mathbf{x})\) trong \(\mathcal{O}(n D)\) và ASHA thăng hạng bất đồng bộ.
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 — Chứng minh Độ lợi Gini/Entropy vs. Misclassification, MAE Trung vị & Bức tường XOR 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết \(\mathbf{p}(t) = \alpha\mathbf{p}_L + (1-\alpha)\mathbf{p}_R\) để chứng minh \(\Delta I_G = \alpha(1-\alpha)\|\mathbf{p}_L - \mathbf{p}_R\|_2^2\), đồng thời lấy dưới vi phân \(\sum \operatorname{sgn}(c - y_i) \ni 0\) cho nghiệm trung vị của MAE.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi demonstrate_misclassification_zero_gain(), khớp CARTDecisionTree(..., criterion='mse'/'mae', min_samples_leaf=3) trước ngoại lai 100.0, và chạy diagonal_xor_staircase_audit().
Tiêu chí Đáp án & Số đối chứng
Misclassification trả về -0.0000 còn Gini = 0.0584 và Entropy = 0.1081 bits. Với ngoại lai 100.0, MSE kéo dự báo lên >15.0 còn MAE giữ đúng trung vị 1.0. Cây song trục độ sâu 8 tốn 28 lá (0.955) so với 2 lá xiên (1.000).
Bài tập 2 — Định lý Chuỗi Cây con Lồng nhau CCP, Quy tắc 1-SE & Trích xuất Luật 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Quy nạp theo chiều cao cây chứng minh tính cộng tính \(R_\alpha(T) = R_\alpha(T_L) + R_\alpha(T_R)\) và công thức ngưỡng liên kết yếu nhất \(g(t) = (R(t) - R(T_t))/(|T_t|-1)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi cost_complexity_pruning_path(), select_ccp_alpha_1se(), và extract_rules() trên dữ liệu nhiễu 14%.
Tiêu chí Đáp án & Số đối chứng
Chuỗi ccp_alphas tăng đơn điệu và số lá giảm nghiêm ngặt về 1; quy tắc 1-SE (alpha_1se = 0.0087) nén cây từ 39 -> 8 lá và nâng độ chính xác holdout từ 0.733 -> 0.760, còn extract_rules() phủ trọn 100% tập mẫu.
Bài tập 3 — Hằng đẳng thức Phương sai Random Forest, mtry, ExtraTrees & Free OOB 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khai triển \(\operatorname{Var}(\frac{1}{M}\sum T_m)\) thành \(M\) hạng tử phương sai và \(M(M-1)\) hạng tử hiệp phương sai, đồng thời tính \(\lim_{n\to\infty}(1-1/n)^n = e^{-1}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy verify_rf_variance_identity() và so sánh RandomForestWorkbench ở chế độ Bagging (mtry=d), RF sqrt(d), và ExtraTrees (extra_trees=True).
Tiêu chí Đáp án & Số đối chứng
Hằng đẳng thức rho*sigma^2 + ((1-rho)/M)*sigma^2 khớp tới 5.55e-17; tỷ lệ trong túi đạt 0.635 (OOB = 0.839); tương quan cặp cây giảm dần 0.632 -> 0.507 -> 0.406.
Bài tập 4 — GBDT Newton Bậc hai, Histogram Subtraction, GOSS, CatBoost Ordered TS & Đơn điệu 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đặt đạo hàm bậc nhất của \(G_j w_j + \frac{1}{2}(H_j + \lambda)w_j^2\) bằng 0 tìm \(w_j^*\) và \(\mathcal{L}_{\text{split}}\); chứng minh \(\mathbb{E}[\widehat{G}_S] = G_S\) bằng kỳ vọng chỉ báo \(\frac{b}{1-a}\); viết quy nạp kẹp cận trung điểm \(m=(w_L+w_R)/2\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy SecondOrderGBDT với split_method='exact' vs 'hist', monotone_constraints=(1,-1,...), estimate_goss_gradient_sum(), và ordered_boosting_prediction_shift_demo().
Tiêu chí Đáp án & Số đối chứng
Hist đạt 0.787 (so với Exact 0.808) tiết kiệm 20,669 lượt quét; GOSS không chệch và cắt phương sai 11.2x; kẹp cận triệt tiêu vi phạm đơn điệu 17 -> 0 (AUC = 0.803); Ordered TS thu hẹp gap 0.308 -> 0.180 (OOT 0.642 -> 0.732).
Bài tập 5 — TreeSHAP Đa thức Khớp Vét cạn 2^d, Bẫy Biến Đại diện & PDP vs. ALE 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi cặp toán tử EXTEND và UNWIND (Algorithm 2) bảo toàn đa thức trọng số tập con \(w_k^{(L_P)}\), và viết tích phân sai phân trong từng thùng phân vị \([z_{k-1}, z_k]\) của ALE.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu TreeSHAPExplainer.path_dependent_shap & interventional_shap với bruteforce_shapley_tree, rồi chạy audit_treeshap_proxy_leak_trap và audit_pdp_off_manifold_hazard.
Tiêu chí Đáp án & Số đối chứng
Cả hai chế độ TreeSHAP khớp vét cạn \(2^d\) tới 2.22e-16 và 1.44e-15; Observational rò 0.3447 sang zip_proxy (rho=0.966) không tách nút trong khi Interventional bằng 0.0000; PDP MAE = 8.809 vs ALE MAE = 0.000.
Bài tập 6 — Bẫy In-Sample Stacking, OOF + Caruana + Distillation, TPE + ASHA & Miền TabFM 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Từ phân rã Efron giải thích vì sao In-Sample thưởng \(\operatorname{df}\), chứng minh \(\operatorname{EI}_{y^*}(\mathbf{x}) \propto \ell(\mathbf{x})/g(\mathbf{x})\) trong TPE, và chứng minh cận hitting \(1-(1-q)^N\) của Random Search.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy audit_stacking_insample_vs_oof, compare_grid_vs_random_effective_dim, benchmark_gbdt_hpo_suite, và benchmark_tabular_fm_vs_gbdt_regimes, rồi chạy trọn bộ 14/14 pytest.
Tiêu chí Đáp án & Số đối chứng
In-Sample đặt w_RF = 0.99 (train 1.000 -> test 0.769) còn OOF + Caruana hạ w_RF = 0.03 (test 0.845, distilled 0.848). TPE + ASHA dùng 440 evals (-55.6%). TabFM thắng trên bảng nhỏ mượt (0.843 > 0.823) còn GBDT thắng trên bảng lớn lệch đuôi (0.703 tại 0.044 ms/row, 0 vi phạm đơn điệu).