Chương 07 — Đánh giá Chống Rò rỉ, Hiệu chuẩn Xác suất & Lý thuyết Quyết định Nhạy Chi phí
Hợp nhất Bài #1 (6 lớp Rò rỉ, Canary Hoán vị, C2ST Bậc hai, PIT ASOF) & Bài #2 (Proper Scoring Rules, Phân rã Murphy Brier, Platt/Isotonic PAVA/Temperature/Beta/Inductive Venn-Abers (p0, p1), Ngưỡng Bayes Phụ thuộc Mẫu & Phân bổ Năng lực Top-K).
Unit ID:
T1-P2-U02
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Tích hợp Chuyên sâu Đặc biệt (03-35-special-topics-extracted.md): Hợp nhất trọn vẹn Bài viết#1(Leakage-Proof Evaluation) và Bài viết#2(Calibration and Cost-Sensitive Decisions) theo chuẩn 4 phần Deep-Dive (Tình huống Thất bại->Mô hình Định lượng->Thực nghiệm Đối chứng->Cẩm nang Sản xuất), kế thừa hợp đồng tách tậpch-04(SplitContract) cùng phân tích mất cân bằngch-06(PR-AUC,MCC,PurgedTimeSeriesSplit) và chuyển giao Feature EngineeringWoEsangch-08.
Bài thực hành Song hành (Lab 07):labs/ch07-leakage-and-calibration-workbench/(eval_calibration_lab)
Tình huống Mở đầu: Bốn Thất bại Sản xuất Khi ROC-AUC = 0.99 Vẫn Đốt Cháy Ngân sách Kinh doanh#
Trong vận hành hệ thống máy học công nghiệp (gian lận thanh toán, cấp tín dụng tiêu dùng, cảnh báo nhiễm trùng huyết lâm sàng), phần lớn các mô hình sụp đổ ngoài thực địa không thất bại vì thiếu lớp ẩn mạng nơ-ron hay siêu tham số cây XGBoost, mà thất bại ngay ở giao thức đánh giá ngoại tuyến và chuyển đổi xác suất thành hành động kinh tế:
- Ảo ảnh
SMOTE-trước-CV(PR-AUC 0.952 -> 0.189) & Điểm mùC2STTrước Bản sao Trùng lặp: Áp dụng tăng mẫu thiểu sốSMOTEtrước khi chia5-Fold CVđể "cân bằng" tập nợ xấu3.9%tạo ra các bản sao nội suy \(k\)-láng giềng nằm xuyên ranh giới train–val với xác suất nhiễm chéo lên tới \(1 - 1/5^2 = \mathbf{96.0\%}\), thổi phồngPR-AUCcủa bộ phân loại7-NNlên0.952trong khi hiệu năng thật trên dữ liệu sạch chỉ đạt0.189(và kéo xác suất dự báo trung bình nhảy từ3.94%lên23.0%). Tương tự,35%hồ sơ trùng lặp hoặc nhiễu nhẹ chia ngẫu nhiên xuyên tập khiến1-NNnhảy từ0.593lên0.754trong khi Kiểm định Hai mẫu Đối nghịch (C2ST) hoàn toàn mù (AUC_adv = 0.500)! - Rò rỉ Hậu quả
SCD Type-1, Bẫy Nhãn Trễ0d(-30.8%Thiên lệch) & Mất Parity Feature Store: Đọc bảng chiều ghi đè tại chỗ (account_risk_tiersau khi sự cố đã nổ) hoặc giữ cờrefund_issued_proxychưa xuất hiện tại thời điểm quyết định \(t_{\text{obs}}\) đưaROC-AUCngoại tuyến lên0.989–1.000rồi rơi tự do xuống0.603–0.802khi chạy trực tiếp. Đồng thời, huấn luyện trên các giao dịch chưa qua chân trời đòi bồi hoàn60ngày (maturity_violation_rate = 66.7%) gắn nhầm nhãny = 0cho các ca gian lận mới phát sinh, kéo xác suất dự báo nền sụt-30.8%(0.0609so với tỷ lệ thật8.80%). - Ảo tưởng
ROC-AUC = 0.860Giữ Nguyên Nhưng Lợi nhuận Sụp đổ -$35,000 (DCA NB < 0): VìROC-AUCvàPR-AUCbất biến hoàn toàn dưới mọi phép biến đổi đơn điệu tăng, một mô hình bị lệch tiên nghiệm (+3.2logit do đào tạo cân bằng 50/50 quên bù log-odds) hay bị nén tự tin giữ nguyênROC-AUC = 0.860, nhưng khi cắt ngưỡng tại ngưỡng tối ưu Bayes \(t^* = 25/525 = 4.76\%\), lợi nhuận ròng sụp đổ từ +$28,725 xuống -$6,275 (-$35,000 thiệt hại!) và thậm chí gây hại ròng (DCA Net Benefit = -0.0042 < 0) so với không triển khai mô hình! - Cắt Ngưỡng
t = 0.50Hay Hàng đợiFIFOBão hòa Đánh rơi91%Giá trị Gian lận ($4,799 vs. $39,611): Trên luồng giao dịch từ $15 đến $5,000 với đội thẩm định chỉ xử lý tối đaK = 120ca/ngày, cắt ngưỡng tĩnht = 0.50bỏ lọt các lệnh gian lận $3,000+ có \(\hat{p} = 0.25\) (chỉ cứu được20.0%tổng tiền gian lận, thu ròng $13,739), còn dùng ngưỡng phụ thuộc mẫu không giới hạn làm tràn hàng đợi879ca (7.3xcông suất), đẩy chế độFIFOtụt xuống $4,799 (8.7%giá trị). Ngược lại, Hiệu chuẩnInductive Venn-Aberskết hợp tối ưu Ba-lô Lagrangian giá bóng \(\mu^* = 131.00\text{ USD/slot}\) nâng giá trị cứu vãn ròng lên $39,611 (+188.3%so vớit = 0.50, cứu57.8%dòng tiền gian lận!).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 07 và bài thực hành eval_calibration_lab (T1-P2-U02), học viên có đủ năng lực để:
- Hình thức hóa & Kiểm toán Trọn bộ 6 Lớp Rò rỉ Đánh giá (
Article #1): Định nghĩa rò rỉ qua không gian lọc nhân quả \(\mathcal{F}_{t_{\text{obs}}}\) và cô lập tách tập; chứng minh các định lý sụp đổ của Lớp 1 (Target Proxy), Lớp 2 (Temporal Look-Ahead & Label-Maturity Truncation), Lớp 3 (Preprocessing &SMOTE-before-CV \(1 - 1/K^2\)), Lớp 4 (Entity Overlap \(2\sigma_u^2\)), Lớp 5 (Duplicates vượt ngưỡng Bayes \(R^*\) & mùC2ST), và Lớp 6 (BitemporalASOFFeature Store Skew); đồng thời cài đặt trọn bộ 4 cổng canary tự động (Permutation Null,1D Dominance + Maturity,OOF C2ST / E-C2ST,SHA-256 + NNDR). - Chứng minh Quy tắc Tính điểm Chuẩn Nghiêm ngặt (
Strictly Proper Scoring Rules): Chứng minh tính chuẩn nghiêm ngặt qua biểu diễn phân kỳ Bregman củaLog-Loss(\(H(\mathbf{q}) + D_{\text{KL}}(\mathbf{q}\|\mathbf{p})\)),Brier Score(kèm chứng minh đại số trọn vẹn Phân rã Murphy 1973REL - RES + UNC), vàSpherical Score; đồng thời chứng minh phản ví dụ vì saoROC-AUC,Accuracy, và \(F_1\) không chuẩn nghiêm ngặt. - Chẩn đoán Hiệu chuẩn & Triển khai Các Bộ Hiệu chuẩn SOTA 2026 (
Article #2): Phân tách bẫy thiên lệch \(O(1/B)\) vs. phương sai \(O(\sqrt{B/n})\) củaECE; triển khaiACE(đồng khối lượng),Debiased L2-CE(triệt tiêu \(\frac{\bar{y}_b(1-\bar{y}_b)}{n_b-1}\)),SmoothECE(smECE^*) và hệ số dốc/dịch Cox; làm chủPlatt Scaling,PAVA Isotonic(\(O(n\log n)\) + chứng minh KKT),Temperature/Vector Scaling,Beta Calibration,Dirichlet + ODIR, và SOTAInductive/Cross Venn-Abers(IVAP/CVAP) với tiền tính bao lồi \(O(m \log m)\), truy vấn \(O(\log m)\), và công thức thu gọn minimax \(p_{\text{VA}} = \frac{p_1}{1 - p_0 + p_1}\). - Thiết kế Chính sách Quyết định Tối ưu Bayes & Hàng đợi Ràng buộc Năng lực: Dẫn xuất công thức ngưỡng tổng quát \(t^*\) dưới ma trận chi phí/lợi ích \(2 \times 2\), ngưỡng phụ thuộc mẫu \(t^*(\mathbf{x}_i)\), bài toán Ba-lô KKT với giá bóng \(\mu^*\) dịch ngưỡng thành \(t^*_{\mu^*}(\mathbf{x}_i)\), Định lý Sụp đổ Lợi nhuận Tích phân khi giữ nguyên
ROC-AUC, và Phân tích Đường cong Quyết định (DCA Net Benefit). - Tự động hóa Cổng Kiểm toán Không-
pickletrongeval_calibration_lab: Tuần tự hóa toàn bộ bộ hiệu chuẩn bằngJSON State-Dict, vận hành cổngCI/CD6bước, khóa phụ thuộc bằnguv.lock, và vượt qua toàn bộ14/14hợp đồngpytestcài đặt từ đầu bằngNumPy + Pandas + Pydantic v2(đạt chuẩn quét AST bảo mật deserialization).
Bảng Truy xuất Chuyên sâu Đặc biệt & Giáo trình (Articles #1 & #2 -> Ch 07)#
Thành phần Tích hợp (03-35-special-topics-extracted.md & Syllabus ch-07) |
Chuẩn SOTA 2026 & Mở rộng Toán học (ch-07) |
Vị trí trong Chương 07 | Mô-đun & Hợp đồng Kiểm thử (eval_calibration_lab) |
|---|---|---|---|
Bài viết #1: 6-Class Leakage Taxonomy |
Định nghĩa qua lọc nhân quả \(\mathcal{F}_{t_{\text{obs}}}\) & cô lập \(\mathcal{D}_{\text{tr}} \perp \mathcal{D}_{\text{te}}\); Chứng minh 6 lớp: (1) Target Proxy, (2) Temporal + Maturity Truncation \(F(c_i) < F(H)\), (3) Preprocessing + SMOTE-before-CV (\(1 - 1/K^2\)), (4) Group Overlap (\(2\sigma_u^2\)), (5) Exact/Near Duplicates (mù C2ST), (6) Bitemporal ASOF SCD-1 Skew |
Trụ cột 1 (§1.1–§1.2) + Mermaid 1 + Widget leakage-taxonomy-canary-explorer |
leakage_auditor.py (audit_class1..class6_*), Tests 1–5 |
Bài viết #1: Automated Canary Audits |
4 Cổng Canary: Permutation Null (Ojala–Garriga, Phipson–Smyth \(p\)-val), 1D Dominance + Maturity Slope, OOF Quadratic C2ST + Sequential E-C2ST Supermartingale (Pandeva 2024), SHA-256 + NNDR / Proximity + ASOF |
Trụ cột 1 (§1.3) + Trụ cột 3 (§3.1 Case 4, §3.2) | leakage_auditor.py (run_permutation_null_canary, probe_single_feature_dominance, run_oof_c2st_canary, compute_ec2st_supermartingale, run_duplicate_nndr_and_asof_canaries), Tests 1–5 |
Bài viết #2: Strictly Proper Scoring & Diagnostics |
Định lý Bregman (Savage–Gneiting–Raftery); Chứng minh Log-Loss, Brier + Phân rã Murphy 1973, Spherical; Phản chứng ROC-AUC/Acc/F1; Phân biệt ECE vs ACE vs Debiased L2-CE vs SmoothECE (smECE* 2024) & CITL/Slope |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1) | calibrators.py (compute_log_loss, compute_brier_and_murphy, compute_spherical_score, compute_calibration_diagnostics), Tests 6, 7 |
Bài viết #2: Post-Hoc & Distribution-Free Calibrators |
Kỷ luật tách \(\mathcal{D}_{\text{cal}}\); Temperature Scaling (chứng minh lồi \(\beta_{\text{inv}}\) & bất biến hạng), Platt (Lin–Lin–Weng Laplace smoothing), Beta (Kull 2017), PAVA Isotonic (stack \(O(n\log n)\) + chứng minh KKT), Dirichlet+ODIR (Kull 2019), và Inductive / Cross Venn-Abers (O(m log m) hai bao lồi + minimax \(\frac{p_1}{1-p_0+p_1}\) + CRC) |
Trụ cột 2 (§2.2) + Mermaid 2 + Widget calibration-reliability-venn-abers |
calibrators.py (TemperatureScalingCalibrator, PlattScalingCalibrator, BetaCalibrator, IsotonicPavaCalibrator, DirichletODIRCalibrator, InductiveVennAbersCalibrator, CrossVennAbersCalibrator), Tests 8–11 |
Bài viết #2: Cost-Sensitive & Capacity Triage |
Ngưỡng Bayes \(t^*\), Ngưỡng phụ thuộc mẫu \(t^*(\mathbf{x}_i)\) (Bahnsen 2015), Đảo ngược thứ tự dưới bất đồng nhất, Ba-lô KKT giá bóng \(\mu^*\) (\(t^*_{\mu^*}(\mathbf{x}_i)\)), Định lý sụp đổ lợi nhuận tích phân khi ROC-AUC không đổi, & DCA Net Benefit (Vickers–Elkin) |
Trụ cột 2 (§2.3) + Mermaid 3 + Widget bayes-cost-capacity-threshold-arena + Trụ cột 3 (§3.1 Cases 1–3) |
cost_decision_engine.py (compute_bayes_threshold, compute_instance_thresholds, solve_capacity_constrained_triage, compute_decision_curve_analysis, compute_miscalibration_profit_collapse), Tests 12, 13, 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-07) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (eval_calibration_lab) |
|---|---|---|---|---|
| \(n, m, N_{\text{te}}\) | \(\mathbb{N}_+\) | Cỡ tập huấn luyện \(n\), cỡ tập hiệu chuẩn \(m = \lvert\mathcal{D}_{\text{cal}}\rvert\), cỡ tập kiểm định \(N_{\text{te}}\) | Tách \(m\) hiệu chuẩn khỏi số lớp \(K_{\text{cls}}\) | n_train, n_cal, n_test |
| \(K_{\text{cls}}, K_{\text{fold}}, K_{\text{cap}}\) | \(\mathbb{N}_+\) | Số lớp phân loại, số nếp CV, ngân sách hàng đợi duyệt thủ công | Luôn gắn chỉ số dưới khi đồng xuất hiện | n_classes, n_folds, capacity_k |
| \(\mathcal{F}_{t_{\text{obs}}}, t_{\text{obs}}, \tau_{\text{event}}, \tau_{\text{avail}}\) | Filtration, \(\mathbb{R}_{\ge 0}\) | Tập thông tin hợp lệ tại \(t_{\text{obs}}\); thời điểm biến cố và thời điểm sẵn sàng vật lý | Phân biệt \(\tau_{\text{avail}}\) với ngưỡng \(t^*\) | obs_ts, event_ts, avail_ts |
| \(\Delta t_{\text{horizon}}, \Delta_{\text{mat}}, c_i\) | \(\mathbb{R}_{\ge 0}\) | Chân trời nhãn / độ trễ trưởng thành; tuổi kiểm duyệt \(c_i = t_{\text{cutoff}} - t_{\text{obs}, i}\) | Liên thông \(\Delta t_{\text{horizon}}\) từ ch-04, ch-06 |
label_horizon, maturity_age |
| \(q(\mathbf{x}), \hat{p}_i, \hat{q}_i, z_i\) | \([0,1], \mathbb{R}\) | Hậu nghiệm thật \(P(Y=1\mid\mathbf{x})\), xác suất thô, xác suất đã hiệu chuẩn, logit \(\ln\frac{\hat{p}_i}{1-\hat{p}_i}\) | Không dùng \(p\) làm tỷ lệ nền \(\pi_+\) | y_prob_raw, y_prob_cal, logits |
| \(\pi_+\) | \((0, 1)\) | Tỷ lệ nền lớp dương \(P(Y = 1)\) | Tách biệt khỏi \(\hat{p}_i\) từng mẫu | prevalence |
| \(B_{\text{bin}}, \mathcal{I}_b, n_b\) | \(\mathbb{N}_{\ge 2}, \text{Subset}\) | Số bin biểu đồ hiệu chuẩn, tập chỉ số bin \(b\), số mẫu \(n_b = |\mathcal{I}_b|\) | Phân biệt tuyệt đối \(B_{\text{bin}}\) với lợi ích \(B_{\text{TP}}, B_{\text{TN}}\) | n_bins, bin_counts |
| \(C_{\text{FP}}, C_{\text{FN}}, B_{\text{TP}}, B_{\text{TN}}\) | \(\mathbb{R}\) | Chi phí FP/FN; lợi ích TP/TN (\(C_{\text{TP}} = -B_{\text{TP}}\), \(C_{\text{TN}} = -B_{\text{TN}}\)) |
Khóa quy ước dấu giữa ma trận \(C\) và \(U = -C\) | cost_fp, cost_fn, benefit_tp, benefit_tn |
| \(t^*, t^*(\mathbf{x}_i), t^*_{\mu^*}(\mathbf{x}_i)\) | \((0, 1)\) | Ngưỡng Bayes toàn cục, ngưỡng phụ thuộc mẫu, ngưỡng sau nâng giá bóng \(\mu^*\) | Không dùng \(\tau\) làm ngưỡng quyết định | bayes_threshold, instance_thresholds |
| \((p_0, p_1), p_{\text{VA}}, \Delta p_{\text{VA}}\) | \([0, 1]^2, (0, 1)\) | Cặp cận dưới/trên Venn-Abers, điểm thu gọn \(\frac{p_1}{1 - p_0 + p_1}\), độ rộng \(p_1 - p_0\) | Luôn giữ \(0 \le p_0 < p_1 \le 1\) nghiêm ngặt | p0, p1, p_va, interval_width |
| \(T, \beta_{\text{inv}}, \alpha_{\text{CITL}}, \beta_{\text{cal}}\) | \(\mathbb{R}_{>0}, \mathbb{R}\) | Nhiệt độ \(T\) (\(\beta_{\text{inv}} = 1/T\)), độ lệch trung bình và độ dốc hiệu chuẩn Cox | Tách \(\beta_{\text{inv}}\) khỏi độ dốc \(\beta_{\text{cal}}\) | temperature, citl_alpha, cal_slope |
Trụ cột 1 — Lý thuyết Hình thức Rò rỉ Đánh giá, Phân loại 6 Lớp, Kiểm toán Canary & Quy tắc Tính điểm Chuẩn (Article #1 & Proper Scoring Foundations)#
1.1 Định nghĩa Hình thức Rò rỉ Đánh giá qua Lọc Nhân quả \(\mathcal{F}_{t_{\text{obs}}}\) (Article #1)#
Xét không gian xác suất \((\Omega, \mathcal{F}, \mathbb{P})\) của Quá trình Sinh Dữ liệu (DGP), trong đó mỗi sự kiện quyết định \(i\) phát sinh tại thời điểm quan sát \(t_{\text{obs}, i} \in \mathbb{R}_{\ge 0}\) gắn với thực thể \(g_i \in \mathcal{G}\) và độ trễ phục vụ trực tuyến \(\Delta_{\text{sla}} \ge 0\). Gọi \(\{\mathcal{F}_t\}_{t \ge 0}\) là bộ lọc nhân quả tự nhiên (causal observation filtration) chứa toàn bộ thông tin thực sự đã được sinh ra và vật chất hóa trong hệ thống phục vụ tại thời điểm \(\le t\). Một vector đặc trưng \(\mathbf{X}_i\) chỉ hợp lệ lúc suy luận khi thỏa mãn \(\sigma(\mathbf{X}_i) \subseteq \mathcal{F}_{t_{\text{obs}, i}}\).
Nếu một quy trình đánh giá huấn luyện bộ biến đổi \(\hat{T}\) và bộ dự báo \(\hat{f}_{\mathcal{D}_{\text{tr}}}\) trên tập \(\mathcal{D}_{\text{tr}}\) rồi đo rủi ro thực nghiệm \(\hat{R}(\hat{f}_{\mathcal{D}_{\text{tr}}}; \mathcal{D}_{\text{te}}) = \frac{1}{n_{\text{te}}}\sum_{j \in \mathcal{D}_{\text{te}}}\ell(y_j, \hat{f}_{\mathcal{D}_{\text{tr}}}(\tilde{\mathbf{x}}_j))\), đánh giá đó mắc Rò rỉ Đánh giá (Evaluation Leakage) bất cứ khi nào vi phạm ít nhất một trong hai bất biến nền tảng (Kaufman et al., ACM TKDD 2012):
- Điều kiện A — Vi phạm Đo được Nhân quả (Filtration Violation): Đặc trưng ngoại tuyến \(\tilde{\mathbf{X}}_i\) chứa biến không \(\mathcal{F}_{t_{\text{obs}, i}}\)-đo được (sinh sau \(t_{\text{obs}, i}\) hoặc là hậu duệ nhân quả của nhãn tương lai \(Y_i\)), khiến lượng thông tin tương hỗ ngoại tuyến vượt quá giới hạn khả dụng trực tuyến:
\[I(\tilde{\mathbf{X}}; Y) > I(\mathbf{X}_{\text{deploy}}; Y).\]
- Điều kiện B — Vi phạm Cô lập Tách tập (Split-Isolation Violation): Bộ tiền xử lý/mô hình phụ thuộc không tầm thường vào dữ liệu kiểm định (\(\sigma(\hat{T}), \sigma(\hat{f}) \not\subseteq \sigma(\mathcal{D}_{\text{tr}})\)), hoặc phân hoạch hai tập không độc lập có điều kiện dưới phân phối triển khai (\(\mathcal{D}_{\text{tr}} \not\perp\!\!\!\perp \mathcal{D}_{\text{te}} \mid P_{\text{deploy}}\) do chia sẻ hiệu ứng thực thể \(u_g\), tự tương quan tương lai, hoặc bản sao trùng lặp).
Hệ quả — Định lý Lạc quan Rò rỉ (Leakage Optimism Bias): Khi Điều kiện A hoặc B bị phá vỡ, ước lượng rủi ro ngoại tuyến mất tính không chệch với rủi ro triển khai thật \(R_{\text{deploy}}(\hat{f}_{\mathcal{D}_{\text{tr}}})\) và tạo ra khoảng hở lạc quan dương (hoặc thiên lệch âm giả tạo nếu tập kiểm định bị cắt cụt nhãn chưa trưởng thành ở Lớp 2):
1.2 Giải phẫu Toán học Toàn diện 6 Lớp Rò rỉ Đánh giá (6-Class Leakage Taxonomy)#
| Lớp Rò rỉ | Cơ chế Phát sinh | Bất biến Toán học Bị phá vỡ | Triệu chứng Ngoại tuyến vs. Sụp đổ Thực địa |
|---|---|---|---|
| Lớp 1: Rò rỉ Đích / Đại diện Hậu quả | Đặc trưng \(X_{\text{leak}}\) sinh ra sau \(Y\) hoặc từ cùng nguyên nhân hậu biến cố (refund_issued, collection_flag) |
\(Y \to X_{\text{leak}}\) hoặc \(X_{\text{leak}} \notin \mathcal{F}_{t_{\text{obs}}}\) | ROC-AUC = 0.989 ngoại tuyến nhờ X_leak; trực tuyến X_leak = 0 nên sụp về 0.802 |
| Lớp 2: Nhìn trước Thời gian & Cắt cụt Nhãn Trễ | Tách ngẫu nhiên nhãn \(H\)-ngày chồng lấn; hoặc giữ mẫu chưa đủ tuổi trưởng thành \(c_i < \Delta_{\text{mat}}\) thành \(Y=0\) | \(\operatorname{Corr}(Y_t, Y_{t+1}) = \frac{H-1}{H}\); \(\mathbb{E}[\tilde{Y}_i \mid c_i] = q(\mathbf{x}_i)F_{\text{delay}}(c_i) < q(\mathbf{x}_i)\) | Nhiễu trắng đạt AUC = 0.879 (Purged = 0.532); nhãn trễ 0d đẩy dự báo nền sụt -30.8% |
Lớp 3: Tiền xử lý / SMOTE-trước-CV |
StandardScaler, TargetEncoder hay SMOTE chạy trên toàn tập trước khi chia nếp K-Fold |
\(\operatorname{Corr}(\text{tr},\text{te}) = -1\); nhiễm chéo cha–con SMOTE: \(1 - 1/K^2 = 96\%\) (\(K=5\)); dịch log-odds \(+\ln(M+1)\) |
PR-AUC nhảy ảo lên 0.952 (thật 0.189), xác suất bị thổi từ 3.9% lên 23.0% |
| Lớp 4: Chồng lấn Thực thể / Nhóm | Cùng user_id / borrower_id / patient_id xuất hiện ở cả train và val trong bài toán dự báo thực thể mới |
\(\mathcal{G}(\mathcal{D}_{\text{tr}}) \cap \mathcal{G}(\mathcal{D}_{\text{te}}) \neq \emptyset\) với hiệu ứng ngẫu nhiên \(u_g \sim (0, \sigma_u^2)\) | Ghi nhớ dấu vân tay thực thể, che giấu \(2\sigma_u^2\) sai số (0.664 -> 0.486 khi GroupKFold) |
| Lớp 5: Trùng lặp Chính xác & Gần trùng lặp | Bản sao ETL nhân bản hoặc jitter tăng cường chia ngẫu nhiên xuyên hai tập (alpha_dup > 0) |
\((1-\alpha_{\text{dup}})\varepsilon_{\text{clean}} < R^*\) (vượt cả rủi ro Bayes!); làm mù C2ST (0.500) |
1-NN vọt 0.593 -> 0.754; C2ST mù tịt ở 0.500 trong khi SHA-256 & NNDR tóm gọn 100% |
Lớp 6: Hồi tố Feature Store (ASOF & SCD-1) |
Bảng chiều SCD-1 ghi đè không lưu lịch sử, hoặc nối không khóa \(\tau_{\text{avail}} \le t_{\text{obs}}\); xếp tầng in-sample |
\(\tau_{\text{avail}} > t_{\text{obs}}\) hoặc \(\mathbf{x}_{\text{offline}}(t_{\text{obs}}) \neq \mathbf{x}_{\text{online}}(t_{\text{obs}})\) | Ngoại tuyến đạt 1.000 rồi rớt xuống 0.603; chỉ Quadratic C2ST (0.961) và ASOF mới bắt được |
Chứng minh Điểm nhấn cho Các Lớp Khó Phát hiện Nhất:#
-
Lớp 2B — Định lý Thiên lệch Kiểm duyệt Phải của Nhãn Trễ (Label-Maturity Truncation): Gọi \(T_{\text{event}, i}\) là thời gian từ quyết định \(t_{\text{obs}, i}\) đến khi biến cố (đòi bồi hoàn/vỡ nợ) xảy ra, và nhãn đúng tại chân trời \(H = \Delta t_{\text{horizon}}\) là \(Y_i := \mathbb{I}[T_{\text{event}, i} \le H]\). Tại thời điểm chụp kho dữ liệu \(t_{\text{cutoff}}\), mỗi dòng chỉ mới trải qua tuổi kiểm duyệt (censoring age) \(c_i := t_{\text{cutoff}} - t_{\text{obs}, i}\). Nhãn thô trích xuất \(\tilde{Y}_i := \mathbb{I}[T_{\text{event}, i} \le \min(H, c_i)]\) có kỳ vọng:
\[\mathbb{E}[\tilde{Y}_i \mid \mathbf{x}_i, c_i] = q(\mathbf{x}_i)\cdot F_{\text{delay}}\big(\min(H, c_i) \mid \mathbf{x}_i, Y_i = 1\big) < q(\mathbf{x}_i) \quad (\forall c_i < H).\]Vì các giao dịch gần \(t_{\text{cutoff}}\) nhất có \(c_i \to 0\), chúng đồng loạt bị gắn nhãn giả \(\tilde{Y}_i = 0\) (chính là các ca gian lận chưa kịp khiếu nại!), buộc mô hình học nhầm rằng mọi đặc trưng gắn với thời điểm mới đều "an toàn" và làm tỷ lệ dự báo trung bình tụt
-30.8%trong thực nghiệm Lab 07 (6.18%vs.8.80%). Khắc phục bắt buộc: loại bỏ toàn bộ mẫuy = 0có \(c_i < \Delta_{\text{mat}}\) (chỉ giữc_i >= 60d, hạ sai lệch xuống-5.7%) hoặc áp trọng số nghịch đảo xác suất kiểm duyệtIPCW\(w_i = \mathbb{I}[c_i \ge H \text{ hoặc } \tilde{Y}_i = 1] / \hat{G}(\min(c_i, H))\). -
Lớp 3B — Chứng minh Nhiễm chéo
SMOTE-trước-CV& Dịch chuyển Log-Odds Tiên nghiệm: Khi chạySMOTEtrên toàn bộ \(\mathcal{D}\) trước chia \(K\)-Fold, mỗi điểm tổng hợp \(\mathbf{x}_{\text{syn}} = (1-u)\mathbf{x}_i + u\mathbf{x}_j\) (\(u \sim \mathcal{U}[0,1]\)) nối giữa hai điểm thiểu số gốc \(\mathbf{x}_i, \mathbf{x}_j\). Khi chia \(\mathcal{D}_{\text{aug}}\) vào \(K\) nếp ngẫu nhiên, xác suất để cả hai điểm cha mẹ rơi vào cùng tập kiểm định với \(\mathbf{x}_{\text{syn}}\) chỉ là \((1/K)^2\). Do đó, xác suất để ít nhất một cha mẹ nằm trong tập huấn luyện \(\mathcal{D}_{\text{tr}}\) lên tới:\[P\big(\{\mathbf{x}_i, \mathbf{x}_j\} \cap \mathcal{D}_{\text{tr}} \neq \emptyset \;\big|\; \mathbf{x}_{\text{syn}} \in \mathcal{D}_{\text{val}}\big) = 1 - \frac{1}{K^2} \quad \big(= \mathbf{96.0\%} \text{ với } K=5,\; \mathbf{99.0\%} \text{ với } K=10\big)!\]Thậm chí ngay cả khi đưa
SMOTEvào đúng bên trong từng nếp huấn luyện, việc nhân số ca dương lên \((M+1)\) lần đẩy tỷ lệ dương huấn luyện từ \(\pi_+\) sang \(\pi_+^{\text{SMOTE}}\), làm dịch chuyển toàn bộ log-odds đầu ra một lượng phân tích chính xác \(+\ln\!\left(\frac{\pi_+^{\text{SMOTE}}(1-\pi_+)}{(1-\pi_+^{\text{SMOTE}})\pi_+}\right) = +\ln(M+1)\), phá hỏng hoàn toàn hiệu chuẩn xác suất (mean_pred = 0.230so với thật0.0394) nếu không trừ ngược bù tiên nghiệm (Elkan 2001;Saerens et al. 2002). -
Lớp 4 & Lớp 5 — Khoảng hở \(2\sigma_u^2\) & Tại sao
C2STHoàn toàn Mù Trước Bản sao Trùng lặp:- Với mô hình phân cấp \(Y_{g, t} = f(\mathbf{x}_{g, t}) + u_g + \varepsilon_{g, t}\) (\(u_g \sim (0, \sigma_u^2)\)), nếu chia ngẫu nhiên sao cho thực thể \(g\) có ở cả hai tập, mô hình học thuộc hiệu ứng \(\hat{u}_g \approx u_g\); nhưng khi triển khai lên khách hàng mới \(g_{\text{new}}\), ảnh xạ sang \(\hat{u}_{\hat{g}}\) độc lập làm phương sai sai số bùng thêm \(\operatorname{Var}(u_{g_{\text{new}}} - \hat{u}_{\hat{g}}) \approx \mathbf{2\sigma_u^2}\).
- Với Lớp 5, giả sử một phần \(\alpha_{\text{dup}}\) bản ghi bị nhân bản rồi chia ngẫu nhiên vào \(\mathcal{D}_{\text{tr}}\) (
1 - p_te) và \(\mathcal{D}_{\text{te}}\) (p_te). Tại mọi vị trí trùng lặp \(\mathbf{x}\), xác suất có điều kiện thuộc tập kiểm định là hằng số \(P(Z = 1 \mid \mathbf{X} = \mathbf{x}) \equiv p_{\text{te}}\) đồng nhất ở mọi nơi, khiến bộ phân biệt đối nghịch tối ưu Bayes (C2ST) chỉ đạt đúng \(\operatorname{AUC}_{\text{adv}} = 0.500\)! Phải dùng băm mật mã dòngSHA-256và Tỷ lệ Khoảng cách Láng giềng Gần nhất (NNDR/ \(\rho_{\text{prox}}\)) để phát hiện.
-
Lớp 6 — Toán tử Kết nối Lưỡng thời điểm (
Bitemporal PIT ASOF Join): Mọi bảng đặc trưng trong Feature Store đều mang đồng thời thời điểm sự kiện \(\tau_{\text{event}}\) và thời điểm vật chất hóa sẵn sàng phục vụ \(\tau_{\text{avail}} \ge \tau_{\text{event}}\). Toán tửPIT ASOFhợp lệ duy nhất tại \(t_{\text{obs}}\) là:\[\mathbf{x}_e^{\text{PIT}}(t_{\text{obs}}) := \mathbf{z}_e\!\left(\arg\max\Big\{\tau_{\text{event}} \;\Big|\; \tau_{\text{event}} \le t_{\text{obs}} - \Delta_{\text{sla}} \;\wedge\; \tau_{\text{avail}} \le t_{\text{obs}}\Big\}\right).\]Nếu một quy trình hồi tố
SCD Type-1giữ nguyên trung bình0nhưng thổi phồng phương sai đặc trưng theo nhãn tương lai (Class 6), ngay cảLinear C2STcũng có thể bị đánh lừa (AUC = 0.523), buộc phải dùngQuadratic C2ST(AUC = 0.961) và khẳng định dấu thời gianASOF.
1.3 Cơ sở Toán học Bốn Cổng Kiểm toán Canary Tự động (Automated Canary Probes)#
| Cổng Canary | Quy tắc Kiểm định & Công thức Phân phối Vô hiệu (H_0: Không Rò rỉ) |
Chế độ Phá vỡ Mà Nó Bắt được & Ngưỡng Chặn |
|---|---|---|
Canary 1: Kiểm định Hoán vị Nhãn Toàn Pipeline (Ojala & Garriga 2010) |
Hoán vị ngẫu nhiên \(\mathbf{y}^{(\pi_b)}\) (\(b = 1 \dots B\)) trước toàn bộ tiền xử lý + TE + SMOTE + CV. Dưới \(H_0\): \(\mathbb{E}[\operatorname{AUC}_\pi] = 0.50\), \(\operatorname{Var}_{H_0} = \frac{n_+ + n_- + 1}{12 n_+ n_-}\), và \(\hat{p}_{\text{perm}} = \frac{1 + \sum \mathbb{I}[M_b \ge M_{\text{obs}}]}{B+1}\). |
Nếu trung bình \(\bar{M}_{\text{null}} > 0.55\) (ví dụ Full-TE đạt 0.880 trên nhãn nhiễu ngẫu nhiên vs. 0.496 ở OOF-TE), chứng minh 100% rò rỉ mã nguồn / tiền tách tập Lớp 3 hoặc Lớp 6. |
| Canary 2: Thăm dò Đơn biến 1D & Đảo ngược Thời gian / Độ dốc Nhãn Trễ | Tính \(\operatorname{AUC}_{1\text{D}}(j) = \max(\text{AUC}(X_j, Y), 1 - \text{AUC}(X_j, Y))\) và NMI trên từng cột; kiểm tra \(\tau_{\text{avail}} \le t_{\text{obs}} - \Delta_{\text{sla}}\) và tỷ lệ \(\mathbb{E}[\tilde{Y} \mid c_i < H] / \mathbb{E}[\tilde{Y} \mid c_i \ge H]\). |
Bắt tức thì refund_issued_proxy (1D AUC = 0.946), vi phạm ASOF (100%), và suy giảm tỷ lệ dương mẫu non (ratio = 0.62 < 0.75). |
Canary 3: Kiểm định Hai mẫu Đối nghịch Bậc hai OOF C2ST & E-C2ST (Pandeva 2024) |
Gán \(Z=0\) (train/offline) vs. \(Z=1\) (test/live), mở rộng đặc trưng bậc hai \([\tilde{\mathbf{x}}, \tilde{\mathbf{x}}^{\odot 2}]\), tính \(\operatorname{AUC}_{\text{adv}}\) (OOF) và thống kê chuẩn hóa \(z = \frac{\operatorname{AUC}_{\text{adv}}-0.5}{\sqrt{(n_0+n_1+1)/(12 n_0 n_1)}}\). Ở chế độ luồng tuần tự, tích lũy siêu martingale đặt cược \(M_t = \prod_{s=1}^t E_s\) (bác bỏ theo Bất đẳng thức Ville nếu \(M_t \ge 1/\alpha = 20\)). |
Bắt sai lệch phương sai có trung bình khớp 0 của SCD-1 backfill (Quad C2ST = 0.961 nơi Linear C2ST trượt ở 0.523, và E-C2ST đạt trần 1.0e+12 >= 20). |
Canary 4: Băm SHA-256 & Khoảng cách Láng giềng Chéo Tập NNDR / \(\rho_{\text{prox}}\) |
Băm SHA-256 trên từng dòng đặc trưng làm tròn chuẩn; tính chuẩn hóa \(\rho_{\text{prox}}(j) = d_{1,\text{cross}}(j) / \operatorname{Med}(d_{1,\text{intra}})\) và \(\operatorname{NNDR}(j) = d_{1,\text{cross}}(j) / d_{2,\text{cross}}(j)\) cùng \(\max \cos\). |
Chặn Lớp 4/Lớp 5 & SMOTE-trước-CV ngay tại điểm mù của C2ST: phát hiện 35.0% bản sao chính xác + 47.2% gần trùng lặp (p05 prox = 0.00 vs. 0.591 sạch). |
1.4 Quy tắc Tính điểm Chuẩn Nghiêm ngặt (Strictly Proper Scoring Rules — Article #2)#
Một hàm mất mát \(L : \Delta^{K_{\text{cls}}-1} \times \mathcal{Y} \to \mathbb{R} \cup \{+\infty\}\) (càng nhỏ càng tốt) là chuẩn (proper) nếu với mọi phân phối thật \(\mathbf{q}\) và mọi dự báo \(\mathbf{p}\), \(\mathbb{E}_{Y \sim \mathbf{q}}[L(\mathbf{q}, Y)] \le \mathbb{E}_{Y \sim \mathbf{q}}[L(\mathbf{p}, Y)]\), và là chuẩn nghiêm ngặt (strictly proper) nếu dấu bằng xảy ra khi và chỉ khi \(\mathbf{p} = \mathbf{q}\) (tức là nói thật xác suất hậu nghiệm \(\mathbf{q}\) là chiến lược tối ưu duy nhất). Theo Định lý Savage–Gneiting–Raftery (2007), mọi quy tắc chuẩn nghiêm ngặt đều tương ứng với một hàm thế entropy lồi chặt \(G(\mathbf{p})\) sao cho tổn thất dư kỳ vọng chính bằng Phân kỳ Bregman \(D_G(\mathbf{q}, \mathbf{p}) > 0\) (\(\forall \mathbf{p} \neq \mathbf{q}\)).
-
Log-Loss(Mất mát Chéo / Điểm Thiếu thông tin): \(L_{\log}(\mathbf{p}, y) := -\ln p_y\) (\(G(\mathbf{p}) = \sum_k p_k \ln p_k\)). Khai triển:\[\mathbb{E}_{Y \sim \mathbf{q}}[-\ln p_Y] = -\sum_{k=1}^{K_{\text{cls}}} q_k \ln q_k + \sum_{k=1}^{K_{\text{cls}}} q_k \ln\frac{q_k}{p_k} = H(\mathbf{q}) + D_{\text{KL}}(\mathbf{q} \,\|\, \mathbf{p}).\]Vì \(\ln u \le u - 1\) nghiêm ngặt trừ tại \(u = 1\), \(D_{\text{KL}}(\mathbf{q} \,\|\, \mathbf{p}) \ge 0\) và bằng \(0\) khi và chỉ khi \(\mathbf{p} = \mathbf{q}\). \(\blacksquare\) (Tính địa phương chặt và phạt vô hạn nếu gán \(p_y \to 0^+\) cho biến cố có thật.)
-
Brier Score& Chứng minh Trọn vẹn Phân rã Murphy (1973): Với \(\mathbf{e}_y\) là vector one-hot (\(\mathbb{E}_{Y\sim\mathbf{q}}[\mathbf{e}_Y] = \mathbf{q}\)), khai triển bình phương trực giao:\[\mathbb{E}_{Y\sim\mathbf{q}}\big[\|\mathbf{p} - \mathbf{e}_Y\|_2^2\big] = \|\mathbf{p} - \mathbf{q}\|_2^2 + 2(\mathbf{p} - \mathbf{q})^\top \underbrace{\mathbb{E}[\mathbf{q} - \mathbf{e}_Y]}_{=\mathbf{0}} + \sum_{k=1}^{K_{\text{cls}}} q_k(1 - q_k),\]đạt cực tiểu duy nhất tại \(\mathbf{p} = \mathbf{q}\) (trong nhị phân thường dùng nửa Brier \(\ell_{\text{BS}}(p, y) = (p - y)^2 \in [0, 1]\)). Gom \(n\) dự báo rời rạc theo \(B_{\text{bin}}\) nhóm \(\mathcal{I}_1, \dots, \mathcal{I}_{B_{\text{bin}}}\) (trung bình dự báo \(\bar{p}_b\), tần suất thực \(\bar{y}_b\), tỷ lệ chung \(\bar{y}\)), tách \(\bar{p}_b - y_i = (\bar{p}_b - \bar{y}_b) + (\bar{y}_b - y_i)\) làm số hạng chéo triệt tiêu từng bin, kết hợp đồng nhất thức ANOVA nhị phân \(n\bar{y}(1-\bar{y}) = \sum_b\sum_{i \in \mathcal{I}_b}(y_i - \bar{y}_b)^2 + \sum_b n_b(\bar{y}_b - \bar{y})^2\), thu được Phân rã Murphy chính xác:
\[\text{BS}_{\text{binned}} := \frac{1}{n}\sum_{b=1}^{B_{\text{bin}}}\sum_{i\in\mathcal{I}_b}(\bar{p}_b - y_i)^2 = \underbrace{\frac{1}{n}\sum_{b=1}^{B_{\text{bin}}} n_b(\bar{p}_b - \bar{y}_b)^2}_{\text{REL (Hiệu chuẩn } \downarrow\text{)}} - \underbrace{\frac{1}{n}\sum_{b=1}^{B_{\text{bin}}} n_b(\bar{y}_b - \bar{y})^2}_{\text{RES (Phân giải } \uparrow\text{)}} + \underbrace{\bar{y}(1 - \bar{y})}_{\text{UNC (Bất định nền)}}.\](Khi dự báo liên tục trên mỗi bin, \(\text{BS} = \text{BS}_{\text{binned}} + \text{Within-Bin Residual}\) như đã kiểm chứng tới
1e-12trong Test 6. Dự báo hằng \(\hat{p}_i \equiv \bar{y}\) cho \(\text{REL}=0\) nhưng \(\text{RES}=0\) nên vô dụng!) -
Spherical Score(Điểm Cầu, hướng dương — càng lớn càng tốt): \(S_{\text{sph}}(\mathbf{p}, y) := \frac{p_y}{\|\mathbf{p}\|_2}\). Theo bất đẳng thức Cauchy–Schwarz:\[\mathbb{E}_{Y\sim\mathbf{q}}\left[\frac{p_Y}{\|\mathbf{p}\|_2}\right] = \frac{\langle \mathbf{q}, \mathbf{p} \rangle}{\|\mathbf{p}\|_2} \le \frac{\|\mathbf{q}\|_2 \|\mathbf{p}\|_2}{\|\mathbf{p}\|_2} = \|\mathbf{q}\|_2 = \mathbb{E}_{Y\sim\mathbf{q}}\left[\frac{q_Y}{\|\mathbf{q}\|_2}\right],\]dấu bằng xảy ra khi và chỉ khi \(\mathbf{p} = c\mathbf{q}\) (\(c>0\)); ràng buộc đơn hình \(\sum p_k = \sum q_k = 1\) ép \(c = 1 \implies \mathbf{p} = \mathbf{q}\). \(\blacksquare\) (Bị chặn trong \([0, 1]\) nên bền vững trước điểm ngoại lai xác suất cực trị.)
-
Phản chứng Vì sao
ROC-AUC,Accuracy, và \(F_1\) KHÔNG Chuẩn Nghiêm ngặt:ROC-AUC: Theo thống kê Mann–Whitney, với mọi hàm tăng ngặt \(g : [0,1]\to[0,1]\) (ví dụ \(g(q) = \sigma(2.8\operatorname{logit}(q))\) hay \(\sigma(\operatorname{logit}(q)+3.2)\)), \(q_i > q_j \iff g(q_i) > g(q_j) \implies \text{ROC-AUC}(g \circ q) \equiv \text{ROC-AUC}(q)\) dù \(g(q) \neq q\)!Accuracy(ngưỡng0.5): Chỉ là quy tắc chuẩn yếu; mọi dự báo bóp méo chỉ cần giữ nguyên dấu so với0.5(ví dụ ép thành0.999khi \(q > 0.5\) và0.001khi \(q < 0.5\)) đều đạt đúng độ chính xác cực đại \(\max(q, 1-q)\) như \(q\) thật.- \(F_1\) Score (Lipton, Elkan & Naryanaswamy, ECML 2014): Nếu toàn bộ dân số có \(q(\mathbf{x}) \equiv 0.35 < 0.5\) tại ngưỡng cắt
0.50: nói thật \(\hat{p}_i = 0.35\) dự đoán toàn0(\(\text{TP}=0 \implies F_1 = \mathbf{0.000}\)), trong khi nói dối thổi phồng \(\hat{p}_i = 0.60 > 0.5\) cho kỳ vọng \(F_1 = \frac{2(0.35)}{2(0.35)+0.65} = \mathbf{0.519} > 0\)! Do đó \(F_1\) thậm chí không chuẩn (improper) vì chủ động thưởng cho sự gian dối thổi phồng xác suất!
Trụ cột 2 — Chẩn đoán Hiệu chuẩn, Thuật toán Hậu nghiệm SOTA (Venn-Abers) & Quyết định Tối ưu Bayes Dưới Chi phí và Năng lực (Article #2)#
2.1 Phân cấp Hiệu chuẩn & Giải phẫu Các Bộ Ước lượng ECE, ACE, Debiased & smECE*#
Theo phân cấp của Van Calster et al. (2019) và Kull et al. (2019), hiệu chuẩn trải qua ba cấp độ ngày càng chặt: (i) Hiệu chuẩn Trung bình (CITL: \(\bar{p} = \bar{y}\)), (ii) Hiệu chuẩn Yếu qua hồi quy Cox \(\operatorname{logit}(P(Y=1\mid z)) = \alpha_{\text{cal}} + \beta_{\text{cal}} z\) (\(\alpha=0, \beta=1\); với \(\beta_{\text{cal}} < 1\) báo hiệu mô hình quá tự tin như GBDT sâu/ReLU DNN, còn \(\beta_{\text{cal}} > 1\) báo thiếu tự tin như Random Forest), và (iii) Hiệu chuẩn Vừa / Mạnh (\(\mathbb{E}[\mathbf{e}_Y \mid \hat{\mathbf{p}}=\mathbf{p}] = \mathbf{p}\) trên đồ thị tin cậy \(45^\circ\)).
Khi ước lượng sai số hiệu chuẩn từ \(n\) mẫu hữu hạn:
- Bẫy Thiên lệch–Phương sai của
ECEĐều Chiều rộng (Naeini et al. 2015): Chia \([0, 1]\) thành \(B_{\text{bin}}\) đoạn rộng bằng nhau cho \(\widehat{\text{ECE}} = \sum_{b=1}^{B_{\text{bin}}} \frac{n_b}{n}|\bar{y}_b - \bar{p}_b|\). Ngay cả khi mô hình là tiên tri hoàn hảo (\(\mathbb{E}[\bar{y}_b] = \bar{p}_b\)), phép lấy trị tuyệt đối \(|\bar{y}_b - \bar{p}_b|\) trên biến động chuẩn bán chuẩn \(\mathbb{E}[|Z|] = \sqrt{2/\pi}\,\sigma\) tạo thiên lệch dương giả tạo \(O(\sqrt{B_{\text{bin}}/n})\), trong khi chia quá ít bin lại để lỗi \(+e\) và \(-e\) triệt tiêu nhau ở mức \(O(1/B_{\text{bin}})\)! Nguy hiểm hơn trên dữ liệu mất cân bằng (5%gian lận), hơn80%điểm dồn vào Bin 0[0.0, 0.067], che khuất hoàn toàn sai lệch cục bộ ở vùng đuôi thấp. - Hiệu chuẩn Thích ứng Đồng Khối lượng
ACE(Nixon et al., CVPRW 2019): Đặt biên bin theo các phân vị đều nhau (\(n_b \approx n / B_{\text{bin}}\)) sao cho \(\widehat{\text{ACE}} = \frac{1}{B_{\text{bin}}}\sum_{b=1}^{B_{\text{bin}}}|\bar{y}_b - \bar{p}_b|\) tập trung độ phân giải vào đúng vùng mật độ dự báo cao (trong thực nghiệm lâm sàng,ACEphát hiện sai lệch cao hơn4.4xso vớiECEbị che ở Bin 0; trong gian lận Lab 07 vớiIVAP,ACE = 0.0137đo nhạy hơnECE = 0.0176). - Ước lượng Không Chệch
Debiased L2-CE(Kumar, Liang & Ma, NeurIPS 2019): Trừ đúng phương sai mẫu Bessel trong từng bin có \(n_b \ge 2\):\[\widehat{\text{CE}}_{\text{debiased}}^2 := \sum_{b: n_b \ge 2}\frac{n_b}{n}\left[(\bar{y}_b - \bar{p}_b)^2 - \frac{\bar{y}_b(1-\bar{y}_b)}{n_b - 1}\right] \implies \mathbb{E}\big[\widehat{\text{CE}}_{\text{debiased}}^2\big] = \sum_b \frac{n_b}{n}(\mu_b - \bar{p}_b)^2\]triệt tiêu hoàn toàn thiên lệch dương hữu hạn mẫu (đạt trung bình \(\approx 0.000\) trên kiểm định Monte Carlo Test 7 trong khiECEbị thổi lên> 0.012). Đồng thời thuật toán Scaling-Binning chứng minh giảm độ phức tạp mẫu xuống chuẩn \(O(1/\varepsilon^2)\). - Chuẩn Vàng 2024
SmoothECE(smECE^*,Błasiok et al. STOC 2023;Błasiok & Nakkiran ICLR 2024): Loại bỏ hoàn toàn siêu tham số \(B_{\text{bin}}\) và bước nhảy gián đoạn ở rìa bin bằng nhân Gaussian phản xạ biên \(K_\sigma^{\text{refl}}(t, p_i) = \phi_\sigma(t - p_i) + \phi_\sigma(t + p_i) + \phi_\sigma(2 - t - p_i)\) giải phương trình điểm bất động duy nhất \(\operatorname{smECE}_{\sigma^*} = \sigma^*\), đảm bảo tương đương đa thức với khoảng cách chuẩn thật \(\Omega(\operatorname{dCE}^2) \le \operatorname{smCE} \le 2\operatorname{dCE}\).
2.2 Bộ Hiệu chuẩn Cổ điển & SOTA Phân phối Tự do Inductive / Cross Venn-Abers#
Kỷ luật Tuyệt đối về Tách tập Hiệu chuẩn (
Zero Double-Dipping): Tuyệt đối không khớp bộ hiệu chuẩn hậu nghiệm trên chính tập \(\mathcal{D}_{\text{tr}}\) đã huấn luyện mô hình gốc (XGBoost/DNN), vì phần dư nội mẫu đã bị bóp cực đại về0/1khiếnThoặcPlatt atrượt về1.0và bỏ sót quá tự tin ngoài mẫu. Bắt buộc dùng tập hiệu chuẩn tách rời \(\mathcal{D}_{\text{cal}}\) (FrozenEstimatortrongscikit-learn >= 1.6) hoặc dự đoán sạch Ngoài-nếp (OOF).
A. Bốn Bộ Hiệu chuẩn Tham số & Phi tham số Cổ điển#
Temperature Scaling(Guo et al., ICML 2017): Biến đổi \(\hat{\mathbf{q}}_i(T) = \operatorname{softmax}(\mathbf{z}_i / T)\) với đúng1tham số \(T > 0\) (\(\beta_{\text{inv}} = 1/T\)).- Chứng minh Lồi chặt & Bất biến Hạng: Đạo hàm bậc hai theo \(\beta_{\text{inv}}\) cho \(\mathcal{L}''(\beta_{\text{inv}}) = \frac{1}{m}\sum_{i=1}^m \operatorname{Var}_{\hat{\mathbf{q}}_i(\beta_{\text{inv}})}(z_{ic}) \ge 0\), đảm bảo cực tiểu duy nhất toàn cục qua Newton 1D. Đồng thời \(z \mapsto z/T\) tăng ngặt nên bảo toàn
100%Top-1 Accuracy đa lớp (55.87%) vàROC-AUCnhị phân (0.8645). Rất mạnh khi \(n_{\text{cal}}\) nhỏ (n=200,NLL = 0.6294thắng tuyệt đốiPAVA = 0.7313), nhưng mù trước dịch chuyển tiên nghiệm (\(\alpha_{\text{CITL}} \neq 0\), giữACE = 0.0229trên tập dịch chuyển!).
- Chứng minh Lồi chặt & Bất biến Hạng: Đạo hàm bậc hai theo \(\beta_{\text{inv}}\) cho \(\mathcal{L}''(\beta_{\text{inv}}) = \frac{1}{m}\sum_{i=1}^m \operatorname{Var}_{\hat{\mathbf{q}}_i(\beta_{\text{inv}})}(z_{ic}) \ge 0\), đảm bảo cực tiểu duy nhất toàn cục qua Newton 1D. Đồng thời \(z \mapsto z/T\) tăng ngặt nên bảo toàn
Platt Scaling(Lin, Lin & Weng 2007): Khớp hồi quy logistic 2 tham số \(\sigma(a z_i + b)\) trên logit với nhãn làm mượt Laplace Bayes \(t_+ = \frac{N_+ + 1}{N_+ + 2}\), \(t_- = \frac{1}{N_- + 2}\) tránh phân kỳ khi tách rời. Sửa đồng thời cả độ dốc quá tự tin lẫn dịch chuyển tỷ lệ nền (NLL 0.1716 -> 0.1646,ACE 0.0212 -> 0.0095,Murphy REL 0.00262 -> 0.00024), giả định Log-Likelihood Ratio tuyến tính (tương đương hai lớp Gauss cùng phương sai).Beta Calibration(Kull et al., AISTATS 2017) &Dirichlet + ODIR(Kull et al., NeurIPS 2019): Từ tỷ số mật độ hậu nghiệm của hai phân phối \(\operatorname{Beta}(\alpha_k, \beta_k)\), suy ra họ 3 tham số:\[\hat{q}_{\text{Beta}}(s; a, b, c) = \sigma\big(a \ln s - b \ln(1 - s) + c\big) \qquad (a \ge 0,\; b \ge 0).\]Vừa giữ nguyên bản sắc hàm đồng nhất tại \((a=1, b=1, c=0)\) (nơiPlatttrên xác suất thô bị bẻ cong thành chữ S!), vừa tách hai cực \(0\) và \(1\) để xử lý đuôi lệch bất đối xứng củaNaive Bayes/RF(cắtACEtừ0.0506xuống0.0323). Tổng quát hóa lên \(K_{\text{cls}}\) lớp trên vector \(\mathbf{u} = \ln\mathbf{p}\) cho Dirichlet Calibration với phạt chính quy hóaODIR(\(\lambda_1\|\operatorname{diag}(\mathbf{W}) - \mathbf{I}\|_F^2 + \lambda_2\|\mathbf{W}_{\text{off}}\|_F^2 + \mu\|\mathbf{b}\|_2^2\)), đưa3-class NLLtừ1.0234 -> 0.9188vượt cảTemperature Scaling(0.9270) mà không quá khớp \(O(K_{\text{cls}}^2)\).Isotonic Regressionqua Ngăn xếpPAVAChính xác (Barlow 1972;Zadrozny & Elkan 2002): Gộp trước các điểm trùng điểm số \(s_i\), rồi chạy 1 vòng lặp ngăn xếp giữ bất biến tăng đơn điệu \(\text{val}(\mathcal{B}_{t-1}) \le \text{val}(\mathcal{B}_t)\) trong tổng thời gian \(O(m \log m)\) (mỗi khối đẩy vào đúng1lần và gộp tối đa \(m-1\) lần \(\implies O(m)\) sau khi sắp xếp). Theo điều kiệnKKTđối ngẫu, mọi tiền tố bên trong từng khối gộp luôn có trung bình \(\ge\) giá trị khối (\(\lambda_k \ge 0\)), giúpPAVAđồng thời tối ưu hóa MỌI phân kỳ Bregman và quy tắc chuẩn trong lớp hàm tăng đơn điệu! Nhược điểm chí mạng: quá khớp hình bậc thang khi \(n_{\text{cal}}\) nhỏ (n=200\(\implies\)NLL = 0.7313) và gán0/1tuyệt đối ở hai đuôi khiếnLog-Losscó thể bùng \(+\infty\).
B. SOTA 2026 Phân phối Tự do: Inductive & Cross Venn-Abers Predictors (IVAP & CVAP)#
Để khắc phục hoàn toàn điểm yếu thiếu đảm bảo mẫu hữu hạn và cực 0/1 của PAVA, Vovk & Petej (UAI 2014) và Vovk, Petej & Fedorova (NeurIPS 2015) đưa ra Inductive Venn-Abers Predictor (IVAP): với mỗi điểm kiểm tra \(s^*\), chạy PAVA trên tập hiệu chuẩn mở rộng hai lần—một lần giả định nhãn \(y^* = 0\) để thu cận dưới \(p_0(s^*)\) và một lần giả định \(y^* = 1\) để thu cận trên \(p_1(s^*)\).
- Định lý Hiệu chuẩn Hữu hạn Mẫu (
Vovk & Petej 2014): Nếu \(\{(X_i, Y_i)\}_{i=1}^m \cup \{(X^*, Y^*)\}\) hoán đổi được (exchangeable), phép phân vùng khốiPAVAhoàn toàn bất biến theo hoán vị trên túi \((m+1)\) phần tử. Do đó xác suất hậu nghiệm chọn đúng nhánh nhãn thật \(P^*(X^*) := p_{Y^*}(s^*) \in \{p_0(s^*), p_1(s^*)\}\) được hiệu chuẩn chính xác ở MỌI cỡ mẫu \(m \ge 1\) không cần bất kỳ giả định phân phối nào: \(\mathbb{P}(Y^* = 1 \mid P^*(X^*) = p) = p\). Đồng thời theo định thức biến phân min-max Barlow:\[0 \le p_0(s^*) < p_1(s^*) \le 1, \qquad p_1(s^*) - p_0(s^*) \ge \frac{1}{m+1}, \qquad p_0 \le \frac{m}{m+1},\quad p_1 \ge \frac{1}{m+1}.\] - Chứng minh Công thức Thu gọn Điểm Minimax
Log-Loss: Để chọn một xác suất điểm duy nhất \(p \in (0, 1)\) tối thiểu hóa tổn thất hối tiếc cực đại \(\min_p \max_{y \in \{0,1\}} [L_{\log}(p, y) - L_{\log}(p_y, y)]\), đặt hai nhánh đối nghịch bằng nhau:\[\ln\frac{1 - p_0}{1 - p} = \ln\frac{p_1}{p} \iff p(1 - p_0) = p_1(1 - p) \iff \mathbf{p_{\text{VA}}(s^*) = \frac{p_1(s^*)}{1 - p_0(s^*) + p_1(s^*)}} \in [p_0, p_1].\]Tại biên đuôi nơiPAVAtrả về0hoặc1(\(p_0 = 0, p_1 = \frac{1}{m+1}\)), \(p_{\text{VA}} = \frac{1}{m+2} > 0\), tự động khôi phục đúng phép làm mượt Laplace cộng-một từ lý thuyết trò chơi! Độ rộng nhận thức \(\Delta p_{\text{VA}} := p_1 - p_0\) trực tiếp nối sang Dự báo Conformal và Kiểm soát Rủi ro Conformal (CRC, Angelopoulos et al. ICLR 2024) để định tuyến các hồ sơ có \(t^* \in [p_0, p_1]\) (3.4%trong Lab 07) hoặc \(\Delta p_{\text{VA}} \ge 0.03\) (4.8%) sang thẩm định viên con người. - Giải thuật Tiền tính Bao lồi \(O(m \log m)\) & Truy vấn \(O(\log m)\) (
Vovk, Petej & Fedorova 2015): Thay vì chạy lạiPAVA\(O(N_{\text{test}} \cdot m \log m)\) cho mỗi truy vấn, biểu diễn đồ thị tổng tích lũy \((W_r, V_r)\) qua cầu nối tiếp tuyến chung dưới giữa bao lồi dưới trái \(\{Q_0, \dots, Q_{i-1}\}\) (\(Q_a = (W_a - 1, V_a - 1)\)) và bao lồi dưới phải \(\{P_i, \dots, P_k\}\) (tính \(F_1[i]\) và đối ngẫu đảo nhãn \(F_0[i] = 1 - F_1^{\text{rev}}[k+1-i]\)) với một lần tiền tính \(O(m \log m)\), sau đó truy vấn cả triệu điểm kiểm định trong \(O(\log m)\) bằng hai lệnhnp.searchsorted(khớpPAVAvét cạn chính xác tới1.11e-16!). Với biến thểCross Venn-Abers(CVAP) khớp trên \(K_{\text{fold}}\) nếp chéo rời nhau hoàn toàn, gom bằng trung bình nhân tỷ số chênh (GM of Odds) trong không gian logarit \(\sigma\big(\frac{1}{K}\sum_{k=1}^K \ln\frac{p_1^{(k)}}{1 - p_0^{(k)}}\big)\) tận dụng100%dữ liệu hiệu chuẩn (NLL = 0.1705,Brier = 0.04615).
2.3 Lý thuyết Quyết định Tối ưu Bayes Dưới Chi phí Bất đối xứng & Ràng buộc Năng lực#
A. Khóa Quy ước Dấu Ma trận \(2 \times 2\) & Ngưỡng Phụ thuộc Mẫu \(t^*(\mathbf{x}_i)\)#
Đặt \(Y \in \{0, 1\}\) (1 = Gian lận / Vỡ nợ) và hành động \(a \in \{0, 1\}\) (1 = Chặn / Duyệt thủ công, 0 = Cho qua mặc định). Ký hiệu ma trận chi phí \(C(\hat{y}, y)\) tương đương ma trận lợi ích \(U(\hat{y}, y) = -C(\hat{y}, y)\) với \(B_{\text{TP}} := -C_{\text{TP}}\) và \(B_{\text{TN}} := -C_{\text{TN}}\) (tuyệt đối không cộng trùng biên lợi nhuận cho vay vào cả \(C_{\text{FP}}\) lẫn \(B_{\text{TN}}\)!). Đặt chi phí ròng dương giả \(\tilde{C}_{\text{FP}}(\mathbf{x}_i) := C_{\text{FP}}(\mathbf{x}_i) + B_{\text{TN}}(\mathbf{x}_i)\), chi phí ròng âm giả \(\tilde{C}_{\text{FN}}(\mathbf{x}_i) := C_{\text{FN}}(\mathbf{x}_i) + B_{\text{TP}}(\mathbf{x}_i)\), và tổng biên lợi ích quyết định \(\Delta B_i := \tilde{C}_{\text{FP}}(\mathbf{x}_i) + \tilde{C}_{\text{FN}}(\mathbf{x}_i)\):
dẫn xuất chính xác Ngưỡng Tối ưu Bayes (và phiên bản phụ thuộc từng giao dịch \(\mathbf{x}_i\), Elkan 2001; Bahnsen et al. 2015):
(Ví dụ thực tế gian lận thẻ với phí điều tra \(C_{\text{FP}} = 15\text{ USD}\), \(C_{\text{FN}}(\mathbf{x}_i) = A_i + 15\text{ USD}\), \(B_{\text{TP}} = B_{\text{TN}} = 0\) cho \(\Delta B_i = A_i + 30\): đơn hàng $15 cần \(\hat{p} > \frac{15}{45} = 33.3\%\), còn đơn hàng $5,000 chỉ cần \(\hat{p} > \frac{15}{5{,}030} = 0.298\%\)!)
B. Tối ưu Hàng đợi Ràng buộc Năng lực & Định lý KKT Giá Bóng Lagrangian \(\mu^*\)#
Khi đội thẩm định chỉ xử lý tối đa \(\sum_{i=1}^N w_i a_i \le K_{\text{cap}}\) ca mỗi ngày (giá trị ròng gia tăng \(\Delta u_i\) và trọng số tài nguyên \(w_i > 0\)), giải bài toán Ba-lô Lagrangian \(\max_{\mathbf{a} \in [0,1]^N} \sum_i a_i(\Delta u_i - \mu w_i) + \mu K_{\text{cap}}\) cho chính sách KKT tối ưu toàn cục:
- Loại mọi giao dịch có \(\Delta u_i \le 0\).
- Xếp hạng giảm dần theo Lợi ích Ròng Kỳ vọng trên mỗi đơn vị công suất \(\Delta u_i / w_i\) (tuyệt đối không xếp theo \(\hat{p}_i\) thô!), chọn tới khi chạm \(K_{\text{cap}}\).
- Nhân tử đối ngẫu giá bóng \(\mu^* \ge 0\) (chính là \(\Delta u / w\) tại điểm cắt \(K_{\text{cap}}+1\), đạt $131.00 / slot trong Lab 07) dịch chuyển ngưỡng hiệu dụng tăng thêm \(\frac{\mu^* w_i}{\Delta B_i}\):
\[p_i > t^*_{\mu^*}(\mathbf{x}_i) := t^*(\mathbf{x}_i) + \frac{\mu^* w_i}{\tilde{C}_{\text{FP}}(\mathbf{x}_i) + \tilde{C}_{\text{FN}}(\mathbf{x}_i)} = t^*(\mathbf{x}_i) + \frac{\mu^* w_i}{\Delta B_i}.\]Hệ quả trọng yếu: Vì so sánh \(\Delta u_1 > \Delta u_2 \iff p_1 \Delta B_1 - \tilde{C}_{\text{FP},1} > p_2 \Delta B_2 - \tilde{C}_{\text{FP},2}\) (tức \(p_1 A_1 - C_{\text{FP}} > p_2 A_2 - C_{\text{FP}}\) khi chỉ phí điều tra cố định) đòi hỏi hiệu chuẩn định lượng tuyệt đối (cardinal calibration) chính xác khi \(A_1 \neq A_2\), sai lệch hiệu chuẩn làm đảo lộn thứ tự xếp hạng giữa lệnh nhỏ xác suất cao ($100 với \(p=0.20\) nhưng \(\hat{p}=0.85\)) và lệnh lớn ($200 với \(p=0.35\) nhưng \(\hat{p}=0.40\)), làm thất thoát hàng nghìn USD mỗi ngày!
C. Định lý Sụp đổ Lợi nhuận Tích phân Khi ROC-AUC Không Đổi & DCA (Vickers & Elkin 2006)#
Nếu xác suất dự báo \(\hat{p}(\mathbf{x}) = g(q(\mathbf{x}))\) bị méo qua bất kỳ ánh xạ tăng ngặt \(g \neq \text{id}\) nào (giữ nguyên 100% ROC-AUC), quyết định ngưỡng \(t^*\) đổi ranh giới thành \(q_{\text{eff}} = g^{-1}(t^*) \neq t^*\), tạo ra vùng bất đồng \([\min(t^*, q_{\text{eff}}), \max(t^*, q_{\text{eff}})]\) chịu tổn thất kỳ vọng chính xác:
Quy chuẩn hóa theo \(\tilde{C}_{\text{FN}} = C_{\text{FN}} + B_{\text{TP}}\) cho đường cong Lợi ích Ròng Quyết định (DCA Net Benefit) \(\operatorname{NB}(t) := \frac{\text{TP}(t)}{N} - \frac{\text{FP}(t)}{N}\frac{t}{1-t}\). Bất cứ khi nào mô hình chưa hiệu chuẩn thổi phồng xác suất trên bài toán \(\pi_+ < t^*\), \(\operatorname{NB}(t^*)\) rơi xuống âm (-0.0042 trong Lab 07) — tức tệ hơn cả đường cơ sở không làm gì (\(\operatorname{NB}_{\text{none}} \equiv 0\))!
Trụ cột 3 — Kiến trúc Sản xuất 2026: Deep-Dive Chuyên sâu 4 Phần cho Bài viết #1 & #2#
Cấu trúc Chuẩn 4 Phần Deep-Dive: Mỗi bài chuyên sâu dưới đây tách bạch đầy đủ: (1) Tình huống Thất bại Cụ thể -> (2) Mô hình Hình thức / Định lượng -> (3) Thực nghiệm Đối chứng Chạy được (Python) -> (4) Cẩm nang Quyết định Sản xuất (
Playbook).
3.1 Bài viết Chuyên sâu #1: Đánh giá Chống Rò rỉ (Leakage-Proof Evaluation — 4 Phần Deep-Dive)#
- Tình huống Thất bại Cụ thể (
Concrete Failure Cases):- Tín dụng tiêu dùng (
3.9%nợ xấu) &SMOTE-trước-CV: Tăng mẫu thiểu sốSMOTEtrước5-Fold CVnhét \(1 - 1/5^2 = 96.0\%\) cặp cha–con vào hai phía tách tập (p05 prox = 0.519vs.0.909sạch), thổiPR-AUCcủa7-NNlên0.952trong khi dữ liệu sạch chỉ đạt0.189(Clean LogReg), đồng thời chia ngẫu nhiên nhiều kỳ sao kê của cùng khách hàng làm vọtROC-AUCtừ0.486(GroupKFold) lên0.664. - Thanh toán Gian lận (
Label-Maturity) &SCD Type-1Feature Store: Huấn luyện trên nhãn0dchưa qua chân trời đòi bồi hoàn60ngày biến gian lận mới thànhy=0, kéo tỷ lệ dự báo nền tụt-30.8%(0.0609vs.0.0880). Bên cạnh đó, ghi đè kho chiềuSCD-1(ASOF viol = 100%) giữ trung bình bằng0nhưng rò rỉ phương sai hậu quả tạoROC-AUC = 1.000ngoại tuyến rồi sụp về0.603trực tuyến (Linear C2STbị mù ở0.523!). - Bản sao Trùng lặp (
35%Duplicate Split): Chia ngẫu nhiên hồ sơ trùng lặp thổi1-NNtừ0.593 -> 0.754trong khi bộ phân biệt đối nghịchOOF C2SThoàn toàn mù (0.500)!
- Tín dụng tiêu dùng (
- Mô hình Hình thức & Kiểm định Định lượng (
Formal Model):- Khóa hai bất biến Kaufman–Kapoor: Đo được nhân quả \(\sigma(\mathbf{X}_i) \subseteq \mathcal{F}_{t_{\text{obs}, i}}\) với kết nối lưỡng thời điểm \(\tau_{\text{event}} \le t_{\text{obs}} - \Delta_{\text{sla}} \land \tau_{\text{avail}} \le t_{\text{obs}}\); và Cô lập tách tập \(\mathcal{D}_{\text{tr}} \perp\!\!\!\perp \mathcal{D}_{\text{te}}\) theo nhóm thực thể + độ tuổi kiểm duyệt \(c_i \ge \Delta_{\text{mat}}\).
- Khóa bộ tứ Canary định lượng trước khi đóng gói: (a)
1D Dominance(AUC >= 0.85), (b)Label-Permutation Null(Ojala–Garriga, ngưỡng \(\bar{M}_{\text{null}} \le 0.55\)), (c)OOF Quadratic C2ST&Sequential E-C2ST(M_t >= 20), và (d)SHA-256 Exact Hash + Cross-Split NNDR.
- Thực nghiệm Đối chứng Chạy được (
Runnable Controlled Ablation — 6-Class Leakage Canaries):
from __future__ import annotations
import hashlib
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import GroupKFold, StratifiedKFold, cross_val_predict
def run_6class_leakage_canary_ablation(seed: int = 42) -> dict[str, float]:
"""Controlled ablation across 6 leakage classes and automated canary probes."""
rng = np.random.default_rng(seed)
n = 1200
X_clean = rng.normal(0.0, 1.0, size=(n, 4))
y = (rng.uniform(size=n) < 1.0 / (1.0 + np.exp(-(-2.2 + 0.9 * X_clean[:, 0])))).astype(np.int64)
# Class 1: Target Proxy Leakage (post-outcome column) + 1D Dominance Canary
proxy_col = np.where(y == 1, rng.normal(2.5, 0.5, n), rng.normal(-0.5, 0.5, n))
auc_1d_proxy = float(roc_auc_score(y, proxy_col))
# Class 2: Label-Maturity Truncation (0d immature cohort treated as negative vs c_i >= 60d mature filter)
censored_age = np.linspace(0.0, 90.0, n)
maturity_mask = censored_age >= 60.0
y_trunc = np.where(censored_age < 60.0, 0, y)
bias_0d_rel = float((y_trunc.mean() - y.mean()) / y.mean())
bias_60d_rel = float((y[maturity_mask].mean() - y.mean()) / y.mean())
# Class 3: Pre-split Target Encoding Leakage caught by Label-Permutation Null Canary
cats = rng.integers(0, 80, size=n)
y_perm = rng.permutation(y)
# Leaky: compute target mean on ALL samples before CV split
global_means = np.array([y_perm[cats == c].mean() for c in cats])
auc_perm_leaky_te = float(roc_auc_score(y_perm, global_means))
# Clean OOF TE inside 5-Fold Stratified CV on permuted labels
oof_te = np.zeros(n, dtype=np.float64)
for tr, va in StratifiedKFold(n_splits=5, shuffle=True, random_state=seed).split(X_clean, y_perm):
prior = y_perm[tr].mean()
counts = np.bincount(cats[tr], minlength=80)
sums = np.bincount(cats[tr], weights=y_perm[tr], minlength=80)
enc = (sums + 10.0 * prior) / (counts + 10.0)
oof_te[va] = enc[cats[va]]
auc_perm_clean_te = float(roc_auc_score(y_perm, oof_te))
# Class 4: Entity Group Overlap (random CV memorization vs GroupKFold)
groups = np.repeat(np.arange(150), 8)
u_g = rng.normal(0.0, 1.8, size=150)[groups]
y_grp = (u_g + rng.normal(0.0, 0.5, size=n) > 0.0).astype(np.int64)
X_grp = np.column_stack([X_clean[:, :2], u_g + rng.normal(0.0, 0.1, size=n)]) # Entity fingerprint proxy
clf = LogisticRegression(max_iter=500)
p_rand = cross_val_predict(clf, X_grp, y_grp, cv=StratifiedKFold(5, shuffle=True, random_state=seed), method="predict_proba")[:, 1]
# Remove entity fingerprint in clean baseline -> GroupKFold measures true feature generalization
p_gkf = cross_val_predict(clf, X_clean[:, :2], y_grp, cv=GroupKFold(5), groups=groups, method="predict_proba")[:, 1]
# Class 5: Exact Duplicate Cross-Split -> OOF C2ST Blind (0.500) vs SHA-256 Hash Detector
n_uniq = 400
X_u = rng.normal(0.0, 1.0, size=(n_uniq, 4))
X_dup = np.vstack([X_u, X_u[:200]]) # 33.3% duplicated rows
idx = rng.permutation(len(X_dup))
X_tr_d, X_te_d = X_dup[idx[:400]], X_dup[idx[400:]]
Z_d = np.concatenate([np.zeros(400), np.ones(200)])
p_c2st_dup = cross_val_predict(
LogisticRegression(max_iter=500), np.vstack([X_tr_d, X_te_d]), Z_d, cv=5, method="predict_proba"
)[:, 1]
tr_hashes = {hashlib.sha256(np.round(row, 6).tobytes()).hexdigest() for row in X_tr_d}
dup_rate = float(np.mean([hashlib.sha256(np.round(row, 6).tobytes()).hexdigest() in tr_hashes for row in X_te_d]))
# Class 6: Mean-0 Variance-Skewed SCD-1 Backfill -> Linear C2ST Blind vs Quadratic C2ST Caught
X_off = rng.normal(0.0, 1.0, size=(600, 3))
X_live = np.column_stack([X_off[:, 0] * 1.9, X_off[:, 1], X_off[:, 2]]) # Same zero mean, inflated variance
X_z = np.vstack([X_off, X_live])
Z_s = np.concatenate([np.zeros(600), np.ones(600)])
p_lin = cross_val_predict(LogisticRegression(max_iter=500), X_z, Z_s, cv=5, method="predict_proba")[:, 1]
p_quad = cross_val_predict(LogisticRegression(max_iter=500), np.hstack([X_z, X_z ** 2]), Z_s, cv=5, method="predict_proba")[:, 1]
return {
"c1_1d_proxy_auc": round(auc_1d_proxy, 4),
"c2_bias_0d_pct": round(100.0 * bias_0d_rel, 1),
"c2_bias_60d_pct": round(100.0 * bias_60d_rel, 1),
"c3_perm_null_leaky_auc": round(auc_perm_leaky_te, 4),
"c3_perm_null_clean_auc": round(auc_perm_clean_te, 4),
"c4_random_pr_auc": round(float(average_precision_score(y_grp, p_rand)), 4),
"c4_groupkfold_pr_auc": round(float(average_precision_score(y_grp, p_gkf)), 4),
"c5_dup_c2st_auc": round(float(roc_auc_score(Z_d, p_c2st_dup)), 4),
"c5_dup_sha256_overlap_pct": round(100.0 * dup_rate, 1),
"c6_scd1_linear_c2st_auc": round(float(roc_auc_score(Z_s, p_lin)), 4),
"c6_scd1_quad_c2st_auc": round(float(roc_auc_score(Z_s, p_quad)), 4),
}
if __name__ == "__main__":
print("6-Class Leakage Canaries:", run_6class_leakage_canary_ablation())
- Cẩm nang Quyết định Sản xuất (
Production Decision Playbook— Article #1):
| Lớp Rò rỉ / Triệu chứng Ngoại tuyến | Hành động Đúng (Use X) |
Phản mẫu Cấm (Avoid Y) |
Ngưỡng Cổng CI/CD Bắt buộc |
|---|---|---|---|
| Lớp 1: Cột đơn biến thống trị vô lý | Chạy 1D Dominance Probe; xóa mọi đặc trưng \(\notin \mathcal{F}_{t_{\text{obs}}}\) |
Giữ cờ hậu nghiệm (refund_issued, collection_flag) |
Chặn build nếu cột bất kỳ đạt \(\text{AUC}_{1\text{D}} \ge 0.85\) |
| Lớp 2: Nhãn trễ & Chuỗi gối đầu | Lọc độ tuổi trưởng thành \(c_i \ge \Delta_{\text{mat}}\) (hoặc IPCW) + PurgedTS |
Huấn luyện trên nhãn 0d chưa trưởng thành thành y=0 |
ASOF viol == 0% và maturity_ratio >= 0.75 |
Lớp 3: Tiền xử lý / SMOTE trước CV |
Đặt toàn bộ Scaler, OOF-TE, SMOTE vào trong nếp + trừ \(\ln(M+1)\) |
fit_transform(X_all) hoặc SMOTE trước K-Fold; bỏ qua bù tiên nghiệm |
Perm-Null AUC <= 0.55 (50+ lượt xáo nhãn) |
| Lớp 4 & 5: Trùng thực thể / bản sao | Bắt buộc GroupKFold(entity_id) + băm dòng SHA-256 + NNDR |
Chia ngẫu nhiên hoặc chỉ tin mỗi C2ST (bị mù tại 0.500) |
Entity Overlap == 0, Exact Hash == 0%, p05 prox >= 0.40 |
Lớp 6: Feature Store SCD-1 Backfill |
Kết nối lưỡng thời điểm ASOF (tau_avail <= t_obs) + Quad C2ST / E-C2ST |
Tin tưởng Linear C2ST (0.523) hay bảng chiều ghi đè không lịch sử |
Quad C2ST < 0.55 và E-C2ST M_t < 20 |
3.2 Bài viết Chuyên sâu #2: Hiệu chuẩn Xác suất & Quyết định Chi phí Bayes (Calibration & Cost-Sensitive Decisions — 4 Phần Deep-Dive)#
- Tình huống Thất bại Cụ thể (
Concrete Failure Cases):- Giữ nguyên
ROC-AUC = 0.860Nhưng Đốt -$35,000 Lợi nhuận: Trên tập lệch tiên nghiệm hay thiếu tự tin, xác suất thô vẫn giữ thứ hạng y hệt (ROC-AUC = 0.860) nhưng khi cắt tại ngưỡng Bayes \(t^* = 25/525 = 4.76\%\), lợi nhuận ròng sụp từ +$28,725 xuống -$6,275 (mất $35,000 vàDCA Net Benefit = -0.0042 < 0!). - Hàng đợi Công suất Giới hạn
K = 120(Phơi nhiễm $69,952): Cắt ngưỡng cứngt = 0.50chỉ cứu được $13,739 (20.0%giá trị), còn mở ngưỡng không giới hạn làm tràn879ca đẩyFIFOxuống $4,799 (8.7%); chỉ Hiệu chuẩnIVAP+ Ba-lô Lagrangian (\(\mu^* = 131.00\text{ USD/slot}\)) mới kéo về $39,611 (+188.3%,57.8%giá trị). - Thảm họa Mẫu nhỏ
n_cal = 200& Lệch đuôi (Nixon/Kull): ChạyPAVA Isotonictại \(n_{\text{cal}} = 200\) làmLog-Lossnổ lên0.7313so với0.6294củaTemperature Scaling; còn trên tập mất cân bằng lệch về[0, 0.07],ECE-15che khuất lỗi cục bộ lớn hơn2–4.4xbịACE-15phát hiện.
- Giữ nguyên
- Mô hình Định lượng & Kiến trúc
< 10 ms(Formal Model & Systems Architecture):- Chuyển đánh giá sang bộ ba quy tắc chuẩn nghiêm ngặt Bregman (
Log-Loss, MurphyBrier,Spherical), chẩn đoánACE,Debiased L2-CE, vàSmoothECE(smECE*lưới thích nghi chống răng cưaNyquistở \(\sigma < 0.005\)). - Khớp hiệu chuẩn tách rời khỏi tập huấn luyện (\(\mathcal{D}_{\text{cal}}\) qua
FrozenEstimatorhoặcOOF), tuần tự hóa không-pickle(Zero-Pickle JSON State-Dict,CWE-502):Platt/Temperature/Betachỉ< 300 B(~2 usCPU), cònIVAPtiền tính hai bao lồi (O(m log m)) truy vấn quanp.searchsortedtrongO(log m)(< 0.20 msp99 FastAPI), vàCross Venn-Abers(CVAP) khớp trên K nếp OOF rời nhau hoàn toàn. - Kích hoạt Rollback / Căn lại hệ số chặn
Platttự động khi lô đã trưởng thành (\(\ge \Delta_{\text{mat}}\)) có \(|\bar{p} - \bar{y}| > \max(0.015, 0.20\,\bar{y})\),ACE-15 >= 0.05, hoặcDCA Net Benefit < 0liên tiếp3ngày.
- Chuyển đánh giá sang bộ ba quy tắc chuẩn nghiêm ngặt Bregman (
- Thực nghiệm Đối chứng Chạy được (
Runnable Controlled Ablation — Frozen Calibration, Profit Collapse & Capacity Triage):
from __future__ import annotations
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import FixedThresholdClassifier
def run_calibration_and_bayes_triage_ablation(seed: int = 42) -> dict[str, float]:
"""Demonstrate disjoint FrozenEstimator calibration, profit collapse at fixed AUC & K-queue triage."""
rng = np.random.default_rng(seed)
X = rng.normal(0.0, 1.0, size=(3600, 6))
logits_true = -2.7 + 1.4 * X[:, 0] - 0.9 * X[:, 1] + 0.6 * X[:, 2]
p_true = 1.0 / (1.0 + np.exp(-logits_true))
y = (rng.uniform(size=3600) < p_true).astype(np.int64)
amounts = rng.lognormal(mean=4.8, sigma=1.1, size=3600)
X_tr, y_tr = X[:1400], y[:1400]
X_cal, y_cal = X[1400:2200], y[1400:2200]
X_te, y_te, amt_te = X[2200:], y[2200:], amounts[2200:]
# Intentionally overconfident base score trained on 50/50 balanced subsample (forgetting prior offset)
pos_idx = np.flatnonzero(y_tr == 1)
neg_idx = rng.choice(np.flatnonzero(y_tr == 0), size=len(pos_idx), replace=False)
bal_idx = np.concatenate([pos_idx, neg_idx])
base_clf = LogisticRegression(C=100.0, max_iter=500).fit(X_tr[bal_idx], y_tr[bal_idx])
p_raw = base_clf.predict_proba(X_te)[:, 1]
# Disjoint post-hoc Platt calibration via FrozenEstimator (sklearn >= 1.6)
frozen = FrozenEstimator(base_clf)
cal_clf = CalibratedClassifierCV(estimator=frozen, method="sigmoid").fit(X_cal, y_cal)
p_cal = cal_clf.predict_proba(X_te)[:, 1]
# Bayes policy evaluation under fixed cost_fp=25, cost_fn=500 -> t*=25/525=0.0476
cost_fp, cost_fn = 25.0, 500.0
t_star = cost_fp / (cost_fp + cost_fn)
policy_cal = FixedThresholdClassifier(estimator=cal_clf, threshold=t_star)
act_raw = (p_raw >= t_star).astype(np.int64)
act_cal = policy_cal.predict(X_te)
def _net_savings(act: np.ndarray) -> float:
tp = float(np.sum((act == 1) & (y_te == 1)))
fp = float(np.sum((act == 1) & (y_te == 0)))
return tp * cost_fn - (tp + fp) * cost_fp
# Variable-amount K=100 daily review queue: capped t=0.50 FIFO vs calibrated Delta_u / 1.0 knapsack
k_cap = 100
t05_idx = np.flatnonzero(p_raw >= 0.5)[:k_cap]
net_raw_t05 = float(np.sum(np.where(y_te[t05_idx] == 1, amt_te[t05_idx], 0.0)) - 15.0 * len(t05_idx))
delta_u_cal = p_cal * (amt_te + 15.0) - 15.0
valid = np.flatnonzero(delta_u_cal > 0.0)
topk_idx = valid[np.argsort(-delta_u_cal[valid])[:k_cap]]
net_cal_topk = float(np.sum(np.where(y_te[topk_idx] == 1, amt_te[topk_idx], 0.0)) - 15.0 * len(topk_idx))
return {
"auc_raw": round(float(roc_auc_score(y_te, p_raw)), 4),
"auc_cal": round(float(roc_auc_score(y_te, p_cal)), 4),
"nll_raw": round(float(log_loss(y_te, p_raw)), 4),
"nll_cal": round(float(log_loss(y_te, p_cal)), 4),
"brier_raw": round(float(brier_score_loss(y_te, p_raw)), 5),
"brier_cal": round(float(brier_score_loss(y_te, p_cal)), 5),
"bayes_net_raw_usd": round(_net_savings(act_raw), 2),
"bayes_net_cal_usd": round(_net_savings(act_cal), 2),
"queue_t05_usd": round(net_raw_t05, 2),
"queue_cal_topk_usd": round(net_cal_topk, 2),
}
def _hull_cross(ox: float, oy: float, ax: float, ay: float, bx: float, by: float) -> float:
"""2D cross product (a - o) x (b - o); <= 0 implies clockwise or collinear."""
return (ax - ox) * (by - oy) - (ay - oy) * (bx - ox)
def _compute_f1_hull_values(u_weights: np.ndarray, u_sums: np.ndarray) -> np.ndarray:
"""Compute exact upper Venn-Abers F1[0..k-1] via two-hull lower common tangent."""
k = len(u_weights)
px = np.concatenate(([0.0], np.cumsum(u_weights)))
py = np.concatenate(([0.0], np.cumsum(u_sums)))
qx = px[:-1] - 1.0
qy = py[:-1] - 1.0
r_hull: list[int] = [k]
undo_pops: list[list[int]] = [[] for _ in range(k + 1)]
for i in range(k - 1, 0, -1):
popped: list[int] = []
xi, yi = float(px[i]), float(py[i])
while len(r_hull) >= 2:
j1, j2 = r_hull[-1], r_hull[-2]
if _hull_cross(xi, yi, float(px[j1]), float(py[j1]), float(px[j2]), float(py[j2])) <= 0.0:
popped.append(r_hull.pop())
else:
break
r_hull.append(i)
undo_pops[i] = popped
l_hull: list[int] = []
f1 = np.empty(k, dtype=np.float64)
def _max_slope_from_left(rx: float, ry: float) -> float:
lo_l, hi_l = 0, len(l_hull) - 1
while lo_l < hi_l:
mid_l = (lo_l + hi_l) // 2
a0, a1 = l_hull[mid_l], l_hull[mid_l + 1]
slope_to_r = (ry - float(qy[a0])) / (rx - float(qx[a0]))
edge_l = (float(qy[a1]) - float(qy[a0])) / (float(qx[a1]) - float(qx[a0]))
if slope_to_r > edge_l:
lo_l = mid_l + 1
else:
hi_l = mid_l
a_best = l_hull[lo_l]
return (ry - float(qy[a_best])) / (rx - float(qx[a_best]))
for i in range(1, k + 1):
q_idx = i - 1
xi, yi = float(qx[q_idx]), float(qy[q_idx])
while len(l_hull) >= 2:
a1, a2 = l_hull[-2], l_hull[-1]
if _hull_cross(float(qx[a1]), float(qy[a1]), float(qx[a2]), float(qy[a2]), xi, yi) <= 0.0:
l_hull.pop()
else:
break
l_hull.append(q_idx)
n_r = len(r_hull)
lo_p, hi_p = 0, n_r - 1
while lo_p < hi_p:
mid_p = (lo_p + hi_p) // 2
b0, b1 = r_hull[n_r - 1 - mid_p], r_hull[n_r - 2 - mid_p]
s_mid = _max_slope_from_left(float(px[b0]), float(py[b0]))
edge_r = (float(py[b1]) - float(py[b0])) / (float(px[b1]) - float(px[b0]))
if edge_r < s_mid:
lo_p = mid_p + 1
else:
hi_p = mid_p
b_best = r_hull[n_r - 1 - lo_p]
f1[i - 1] = float(np.clip(_max_slope_from_left(float(px[b_best]), float(py[b_best])), 0.0, 1.0))
if i < k:
r_hull.pop()
for restored in reversed(undo_pops[i]):
r_hull.append(restored)
return f1
class InductiveVennAbersCalibrator:
"""Tier 1 O(m log m) Inductive Venn-Abers Predictor with O(log m) (p0, p1) bounds."""
def __init__(self) -> None:
self.unique_scores_: np.ndarray = np.array([], dtype=np.float64)
self.f0_table_: np.ndarray = np.array([], dtype=np.float64)
self.f1_table_: np.ndarray = np.array([], dtype=np.float64)
def fit(self, scores: np.ndarray, y: np.ndarray) -> InductiveVennAbersCalibrator:
s_arr = np.asarray(scores, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
order = np.argsort(s_arr, kind="mergesort")
uniq_scores, inv = np.unique(s_arr[order], return_inverse=True)
u_weights = np.bincount(inv, minlength=len(uniq_scores)).astype(np.float64)
u_sums = np.bincount(inv, weights=y_arr[order], minlength=len(uniq_scores)).astype(np.float64)
f1_vals = _compute_f1_hull_values(u_weights, u_sums)
rev_weights = u_weights[::-1]
f1_rev = _compute_f1_hull_values(rev_weights, rev_weights - u_sums[::-1])
f0_vals = 1.0 - f1_rev[::-1]
self.unique_scores_ = uniq_scores
self.f0_table_ = np.concatenate(([0.0], np.clip(f0_vals, 0.0, 1.0)))
self.f1_table_ = np.concatenate((np.clip(f1_vals, 0.0, 1.0), [1.0]))
return self
def predict_p0_p1(self, scores: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
s = np.asarray(scores, dtype=np.float64)
p0 = self.f0_table_[np.searchsorted(self.unique_scores_, s, side="right")]
p1 = self.f1_table_[np.searchsorted(self.unique_scores_, s, side="left")]
return p0, p1
def predict_proba(self, scores: np.ndarray) -> np.ndarray:
p0, p1 = self.predict_p0_p1(scores)
return p1 / (1.0 - p0 + p1)
class CrossVennAbersCalibrator:
"""Tier 1 K-fold Cross Venn-Abers Predictor aggregating log-odds across disjoint folds."""
def __init__(self, n_folds: int = 5, seed: int = 42) -> None:
self.n_folds = n_folds
self.seed = seed
self.fold_calibrators_: list[InductiveVennAbersCalibrator] = []
def fit(self, scores: np.ndarray, y: np.ndarray) -> CrossVennAbersCalibrator:
s_arr = np.asarray(scores, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
rng = np.random.default_rng(self.seed)
folds: list[list[np.ndarray]] = [[] for _ in range(self.n_folds)]
for cls in np.unique(y_arr):
cls_idx = rng.permutation(np.flatnonzero(y_arr == cls))
for k, part in enumerate(np.array_split(cls_idx, self.n_folds)):
folds[k].append(part)
self.fold_calibrators_ = []
for parts in folds:
cal_idx = np.sort(np.concatenate(parts))
self.fold_calibrators_.append(
InductiveVennAbersCalibrator().fit(s_arr[cal_idx], y_arr[cal_idx])
)
return self
def predict_proba(self, scores: np.ndarray) -> np.ndarray:
s_arr = np.asarray(scores, dtype=np.float64)
log_odds = np.zeros(len(s_arr), dtype=np.float64)
for cal in self.fold_calibrators_:
p0, p1 = cal.predict_p0_p1(s_arr)
log_odds += np.log(np.maximum(p1, 1e-15)) - np.log(np.maximum(1.0 - p0, 1e-15))
mean_lo = log_odds / float(len(self.fold_calibrators_))
return np.asarray(1.0 / (1.0 + np.exp(-np.clip(mean_lo, -60.0, 60.0))), dtype=np.float64)
def predict_mean_bounds(self, scores: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
s_arr = np.asarray(scores, dtype=np.float64)
p0_all = np.zeros((len(self.fold_calibrators_), len(s_arr)), dtype=np.float64)
p1_all = np.zeros_like(p0_all)
for k, cal in enumerate(self.fold_calibrators_):
p0_all[k], p1_all[k] = cal.predict_p0_p1(s_arr)
return p0_all.mean(axis=0), p1_all.mean(axis=0)
def run_cross_venn_abers_verification(seed: int = 42) -> dict[str, float]:
"""Verify Tier 1 CrossVennAbersCalibrator multiprobability bounds and NLL reduction."""
rng = np.random.default_rng(seed)
X = rng.normal(0.0, 1.0, size=(1800, 4))
p_true = 1.0 / (1.0 + np.exp(-(-2.2 + 1.3 * X[:, 0] - 0.8 * X[:, 1])))
y = (rng.uniform(size=1800) < p_true).astype(np.int64)
# Resampled balanced base model produces overconfident raw probabilities
pos_tr = np.flatnonzero(y[:900] == 1)
neg_tr = rng.choice(np.flatnonzero(y[:900] == 0), size=len(pos_tr), replace=False)
bal_tr = np.concatenate([pos_tr, neg_tr])
clf = LogisticRegression(C=25.0, max_iter=500).fit(X[:900][bal_tr], y[:900][bal_tr])
s_cal, y_cal = clf.decision_function(X[900:1350]), y[900:1350]
s_te, y_te = clf.decision_function(X[1350:]), y[1350:]
p_raw = clf.predict_proba(X[1350:])[:, 1]
ivap = InductiveVennAbersCalibrator().fit(s_cal, y_cal)
p0_ivap, p1_ivap = ivap.predict_p0_p1(s_te)
p_ivap = ivap.predict_proba(s_te)
assert np.all((0.0 <= p0_ivap) & (p0_ivap <= p_ivap) & (p_ivap <= p1_ivap) & (p1_ivap <= 1.0))
cvap = CrossVennAbersCalibrator(n_folds=5, seed=seed).fit(s_cal, y_cal)
p_cvap = cvap.predict_proba(s_te)
p0_mean, p1_mean = cvap.predict_mean_bounds(s_te)
assert np.all((p0_mean >= 0.0) & (p0_mean <= p1_mean) & (p1_mean <= 1.0))
nll_raw = float(log_loss(y_te, p_raw))
nll_cvap = float(log_loss(y_te, p_cvap))
brier_raw = float(brier_score_loss(y_te, p_raw))
brier_cvap = float(brier_score_loss(y_te, p_cvap))
assert nll_cvap < nll_raw
assert brier_cvap < brier_raw
return {
"nll_raw": round(nll_raw, 4),
"nll_cvap": round(nll_cvap, 4),
"brier_raw": round(brier_raw, 5),
"brier_cvap": round(brier_cvap, 5),
"mean_interval_width": round(float(np.mean(p1_mean - p0_mean)), 4),
}
if __name__ == "__main__":
print("Calibration & Bayes Triage:", run_calibration_and_bayes_triage_ablation())
print("Cross Venn-Abers (Tier 1):", run_cross_venn_abers_verification())
- Cẩm nang Quyết định Sản xuất (
Production Decision Playbook— Article #2):
| Tiêu chí Chọn Bộ hiệu chuẩn & Quyết định | Khi nào Nên dùng (Use X) |
Phản mẫu Cấm (Avoid Y) |
Điều kiện Định lượng Kích hoạt |
|---|---|---|---|
| Ít mẫu hiệu chuẩn, không dịch chuyển nền | Temperature Scaling (1 tham số) |
PAVA Isotonic (NLL nổ vì bậc thang) |
\(n_{\text{cal}} < 500\) và \(\lvert\bar{p} - \bar{y}\rvert < 0.01\) |
| Có dịch chuyển tỷ lệ nền + độ dốc logit | Platt Scaling (a z + b) |
Temperature (thiếu hệ số chặn \(b\)) |
\(\lvert\bar{p} - \bar{y}\rvert \ge 0.01\) và \(\beta_{\text{cal}} \neq 1\) |
Điểm số lệch đuôi / chữ U (NB, RF) |
Beta Calibration (3 tham số) |
Platt trên xác suất thô [0,1] |
Đuôi 0/1 bất đối xứng hoặc Beta hạ ACE |
Đa lớp lệch theo từng lớp (K_cls <= 20) |
Dirichlet + ODIR |
Matrix Scaling không phạt (\(K^2+K\)) |
Cần hiệu chuẩn từng lớp (SCE), không chỉ Top-1 |
| Bảo chứng hữu hạn mẫu + phân luồng người | Inductive / Cross Venn-Abers |
Dự báo điểm đơn không cận \((p_0, p_1)\) | Cần \(\mathbb{P}(Y=1 \mid P^* = p) = p\) & \(t^* \in [p_0, p_1]\) |
Hàng đợi giới hạn công suất K_cap |
Ba-lô \(\Delta u_i / w_i\) + giá bóng \(\mu^*\) | Xếp theo \(\hat{p}_i\) thô, t = 0.50 hoặc FIFO |
Cần cardinal calibration khi giá trị \(A_i\) biến động |
Trụ cột 4 — Thực hành Lab 07 (eval_calibration_lab) & Kiểm định 14 Hợp đồng pytest#
Bài thực hành đồng hành tại labs/ch07-leakage-and-calibration-workbench/ hiện thực hóa trọn vẹn hai bài chuyên sâu #1 & #2 thành gói Python kiểm chứng độc lập eval_calibration_lab cài đặt từ đầu bằng Python stdlib + NumPy + Pandas + Pydantic v2 (quản lý phụ thuộc với uv.lock, kèm kiểm soát AST bảo mật deserialization cấm tuyệt đối pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal).
4.1 Kiến trúc Gói eval_calibration_lab#
labs/ch07-leakage-and-calibration-workbench/
├── pyproject.toml
├── uv.lock
├── README.md
├── artifacts/
│ └── ch07_workbench_results.json
├── src/
│ └── eval_calibration_lab/
│ ├── __init__.py
│ ├── leakage_auditor.py
│ ├── calibrators.py
│ └── cost_decision_engine.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_eval_calibration_lab.py
4.2 Đồng bộ Kết quả Thực nghiệm CLI (artifacts/ch07_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 --seed 42 --quick --output artifacts/ch07_workbench_results.json
Báo cáo artifacts/ch07_workbench_results.json xuất trọn bộ workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% các số đo kiểm chứng thực tế dưới đây:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm Chính xác (--seed 42 --quick) |
Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_smote_and_dup_leakage_gap |
0.952 -> 0.189 (PR-AUC) |
critical — SMOTE-trước-CV thổi PR-AUC lên 0.952 (Clean LogReg = 0.189); Perm-Null TE AUC = 0.880 vs. sạch 0.496; Dup C2ST mù tại 0.500 trong khi SHA-256 Hash = 35.0% (near_dup = 47.2%, 1-NN AUC 0.754 -> 0.593). |
kpi_maturity_truncation_and_asof |
-30.8% | Live 0.603 (Bias / AUC) |
warn — Huấn luyện 0d chưa trưởng thành kéo dự báo sụt -30.8% (60d purge rút về -5.7%); ASOF viol = 100% làm SCD-1 sụp từ 1.000 -> 0.603 và bị Quad C2ST = 0.961 (E-C2ST = 1.0e+12) bắt sống. |
kpi_ece_vs_ace_and_smoothece |
ACE 0.0212 | smECE 0.0211 (ECE 0.0203) |
warn — ACE/ECE = 1.04x; IVAP hạ ACE xuống 0.0137 và smECE* xuống 0.0179 (Slope = 0.66 -> 1.13); Platt hạ ACE xuống 0.0095, smECE* xuống 0.0111. |
kpi_ivap_calibration_and_brier |
NLL 0.172 -> 0.169 (REL 0.00138) |
ok — Brier 0.04760 -> 0.04647 (CVAP-5 = 0.1705, Platt = 0.1646); độ rộng trung bình IVAP = 0.0105, tự động chuyển 3.4% ca biên (\(t^*=0.08 \in [p_0, p_1]\)) và 4.8% ca bất định rộng (\(\ge 0.03\)) sang duyệt tay. |
kpi_miscalibration_profit_collapse |
AUC 0.860 | -35000 USD (Bayes Loss) |
critical — Cùng ROC-AUC = 0.860 nhưng Oracle Net = $28,725 sụp xuống Prior-Shifted Net = -$6,275 (Underconf Net = -$17,100, Overconf = $13,050; DCA NB = -0.0042 < 0 gây hại ròng!). |
kpi_capacity_triage_dollar_lift |
$13,739 -> $39,611 (+188.3% Lift) |
ok — Trên hàng đợi K = 120 (phơi nhiễm $69,952), cứu tiền gian lận vọt từ 20.0% -> 57.8% (FIFO bão hòa chỉ được $4,799 / 8.7%); giá bóng Lagrangian \(\mu^* = 131.00\text{ USD/slot}\) nâng ngưỡng hiệu dụng trung bình lên 0.723. |
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_eval_calibration_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_pydantic_strict_configs_and_class1_target_proxy_dominance_canary |
Kiểm chứng Pydantic extra="forbid"; Lớp 1 thổi AUC ngoại tuyến (> clean + 0.12) rồi sụp trực tuyến (< offline - 0.15); probe_single_feature_dominance bắt refund_issued_proxy (1D AUC > 0.90) và C2ST > 0.55. |
| 2 | test_class2_temporal_lookahead_and_label_maturity_truncation_bias |
Khẳng định tách ngẫu nhiên rò rỉ chuỗi chồng lấn 10 bước (AUC > 0.65) trong khi tách cách ly rơi về ~0.50; nhãn 0d chưa trưởng thành vi phạm > 50% và đẩy thiên lệch dự báo < -15%. |
| 3 | test_class3_smote_before_cv_leakage_bayes_prior_offset_and_permutation_null |
Khẳng định SMOTE-trước-CV thổi PR-AUC (> +0.40 so với trong nếp), fit_bayes_prior_offset phục hồi chính xác tiên nghiệm (atol=1e-12), và run_permutation_null_canary bắt Full TE trên nhãn nhiễu (null_mean > 0.65) vs. sạch (~0.50). |
| 4 | test_class4_and_class5_group_overlap_duplicate_c2st_blindness_and_nndr |
Chứng minh GroupKFold giao thực thể == 0 (tụt > 0.15 AUC so với tách ngẫu nhiên); bản sao trùng lặp làm mù C2ST (0.50 +/- 0.08) trong khi SHA-256 & NNDR bắt chính xác > 10% trùng lặp (0% trên tập sạch). |
| 5 | test_class6_bitemporal_asof_backfill_and_quadratic_c2st_ec2st_canaries |
Kiểm chứng vi phạm ASOF = 100%, SCD-1 sụp trực tuyến, Quadratic C2ST > 0.70 (trong khi Linear C2ST < 0.56 bỏ lọt), và siêu martingale E-C2ST vượt ngưỡng bác bỏ >= 20.0. |
| 6 | test_proper_scoring_rules_murphy_brier_decomposition_and_f1_impropriety |
Khẳng định tiên tri \(q\) thắng mọi dự báo méo trên Log-Loss & Spherical, đẳng thức Murphy brier_binned == reliability - resolution + uncertainty (atol=1e-12), bất biến ROC-AUC, và phản chứng \(F_1\) thưởng nói dối (0.0 vs. > 0.45). |
| 7 | test_calibration_diagnostics_ece_vs_ace_debiased_l2_and_smoothece |
Chứng minh ACE > 2 * ECE khi Bin 0 triệt tiêu sai lệch cục bộ, kiểm chứng Monte Carlo debiased_l2_ce2 có kỳ vọng ~0 (< 5e-4) so với thiên lệch dương của ECE, và hồi quy smECE* lưới thích nghi ở băng thông mịn \(\sigma < 0.005\) không bị răng cưa Nyquist. |
| 8 | test_classical_calibrators_platt_temperature_beta_and_json_state_dict |
Kiểm chứng Temperature giữ nguyên ROC-AUC (atol=1e-12), Platt thắng Temperature khi có dịch chuyển nền (ACE < 0.035), Beta thắng Platt trên đuôi lệch Beta, và khứ hồi JSON State-Dict (atol=1e-12). |
| 9 | test_pava_isotonic_kkt_optimality_ties_and_small_n_overfit |
Khẳng định fit_pava_blocks thỏa đơn điệu, đồng nhất điểm trùng, điều kiện KKT đối ngẫu tiền tố (\(\lambda_k \ge 0\), atol=1e-11), khóa bộ đệm chỉ đọc, và PAVA thua Temperature tại \(n_{\text{cal}} = 150\). |
| 10 | test_inductive_venn_abers_fast_parity_with_bruteforce_pava_and_cvap |
Đối chiếu chéo 40 lần ngẫu nhiên giữa IVAP \(O(m\log m)\) và PAVA vét cạn từng điểm khớp tới atol=1e-12, \(0 \le p_0 < p_1 \le 1\), \(p_{\text{VA}} \in (0, 1)\), khứ hồi JSON, và CVAP khớp trên K lát OOF rời nhau hoàn toàn cải thiện Log-Loss. |
| 11 | test_multiclass_dirichlet_odir_and_temperature_scaling |
Khẳng định Temperature đa lớp bất biến 100% Top-1 argmax, Dirichlet + ODIR cải thiện Log-Loss vượt cả Temperature trên 3 lớp lệch nền, và khứ hồi JSON chính xác (atol=1e-12). |
| 12 | test_bayes_cost_threshold_instance_dependent_and_miscalibration_profit_collapse |
Kiểm chứng tương đương Cost/Utility (\(35/530\)), ngưỡng phụ thuộc mẫu \(t^*(\mathbf{x}_i)\), và cùng ROC-AUC (atol=1e-12) nhưng lệch hiệu chuẩn mất hàng chục nghìn USD + DCA NB < 0. |
| 13 | test_capacity_constrained_knapsack_shadow_price_and_decision_curve |
Khẳng định nghịch đảo xếp hạng khi số tiền biến thiên ($100 vs. $200), giá bóng \(\mu^* > 0\) nâng ngưỡng \(t^*_{\mu^*}\), và Calibrated Top-K thắng cả t=0.50 lẫn Uncalibrated Top-K về lợi nhuận ròng & Dollar Recall. |
| 14 | test_cli_demo_script_workbench_json_and_zero_forbidden_imports |
Thực thi run_lab_demo.py (returncode == 0), kiểm tra cấu trúc JSON workbench_panels (6 KPI, 4 bar, 4 bảng) và quét AST bảo mật deserialization toàn bộ tệp .py 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#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Kaufman, S., Rosset, S., Perlich, C., & Stitelman, O. (2012); Kapoor, S., & Narayanan, A. (2023). Leakage in Data Mining: Formulation, Detection, and Avoidance (ACM TKDD) & Leakage and the Reproducibility Crisis in Machine-Learning-Based Science (Patterns 2023).
Vì sao quan trọng: Đặt nền tảng lọc nhân quả \(\mathcal{F}_{t_{\text{obs}}}\) và kiểm toán hơn 329 bài báo khoa học để hệ thống hóa 6–8 lớp rò rỉ xuyên ngành. - Ojala, M., & Garriga, G. C. (2010); Lopez-Paz, D., & Oquab, M. (
C2ST, ICLR 2017); Pandeva, T., et al. (E-C2ST, TMLR 2024); Vandewiele, G., et al. (2021).
Vì sao quan trọng: Cung cấp lý thuyết thống kê cho kiểm định hoán vị toàn pipeline,C2ST& siêu martingaleE-C2SThợp lệ mọi thời điểm, và chứng minh rò rỉSMOTE-trước-CV. - Gneiting, T., & Raftery, A. E. (JASA 2007); Murphy, A. H. (1973); Lipton, Z. C., Elkan, C., & Naryanaswamy, B. (ECML 2014).
Vì sao quan trọng: Thiết lập biểu diễn Bregman cho quy tắc chuẩn nghiêm ngặt (Log-Loss,BrierMurphy,Spherical) và chứng minh \(F_1\) thưởng sự thổi phồng xác suất. - Platt, J. (1999) & Lin et al. (2007); Barlow et al. (1972) & Zadrozny–Elkan (KDD 2002); Guo et al. (ICML 2017); Kull et al. (
BetaAISTATS 2017;Dirichlet ODIRNeurIPS 2019).
Vì sao quan trọng: Hệ thống hóa bộ công cụ hiệu chuẩn hậu nghiệm chuẩn mực theo cỡ mẫu \(n_{\text{cal}}\), hình thái đuôi, và đa lớp có chính quy hóaODIR. - Nixon, J., et al. (
ACE, CVPRW 2019); Kumar, A., Liang, P., & Ma, T. (Debiased CE & Scaling-Binning, NeurIPS 2019); Błasiok, J., Gopalan, P., Hu, L., & Nakkiran, P. (STOC 2023&SmoothECEICLR 2024).
Vì sao quan trọng: Giải quyết triệt để bẫy thiên lệch dương hữu hạn mẫu củaECE, đưa raACE,Debiased L2-CE, và thước đo không siêu tham sốsmECE^*. - Vovk, V., & Petej, I. (
UAI 2014); Vovk, V., Petej, I., & Fedorova, V. (NeurIPS 2015); Angelopoulos, A. N., et al. (Conformal Risk Control, ICLR 2024); Hollmann, N., et al. (TabPFN v2, Nature 2025); Giovannotti, P., & Gammerman, A. (COPA 2024); Bahnsen, A. C., et al. (2015); Vickers, A. J., & Elkin, E. B. (2006).
Vì sao quan trọng: Mang lại bảo chứng phân phối tự doInductive / Cross Venn-Aberstruy vấn \(O(\log m)\), cầu nốiCRCvới độ bất định LLM/Bảng dữ liệu, và lý thuyết quyết định nhạy chi phí / hàng đợi năng lực /DCA.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Phân biệt rò rỉ Điều kiện A (vi phạm lọc \(\mathcal{F}_{t_{\text{obs}}}\)) và Điều kiện B (vi phạm cô lập tách tập); chứng minh vì sao ngay cả khi
SMOTEđược đặt vào bên trong nếpCVnhưng không bù log-odds tiên nghiệm, mô hình vẫn hỏng quyết định Bayes? - Q2: Chứng minh công thức xác suất nhiễm chéo cha–con \(1 - 1/K^2 = 96\%\) khi
SMOTEchạy trước5-Fold CV, và giải thích vì saoOOF C2STlại mù hoàn toàn (AUC_adv = 0.500) trước35%bản sao trùng lặp chia ngẫu nhiên xuyên hai tập? - Q3: Giải thích cơ chế của thiên lệch cắt cụt nhãn trễ \(c_i < \Delta t_{\text{horizon}}\) khiến tỷ lệ dự báo tụt
-30.8%, và vì saoQuadratic C2STbắt đượcSCD-1backfill (0.961) khiLinear C2STbị đánh lừa (0.523)? - Q4: Chứng minh Phân rã Murphy chính xác của
Brier Score(\(\text{BS}_{\text{binned}} = \text{REL} - \text{RES} + \text{UNC}\)) và xây dựng phản ví dụ chứng minh \(F_1\) tại ngưỡng0.5là quy tắc không chuẩn (improper). - Q5: Vì sao
ECEđều chiều rộng lại mang thiên lệch dương \(O(\sqrt{B/n})\) ngay trên tiên tri hoàn hảo và có thể bỏ sót sai lệch cục bộ ở Bin 0? Trình bày cáchACE,Debiased L2-CE, vàSmoothECE(smECE*) khắc phục từng khuyết tật này. - Q6: Chứng minh thuật toán ngăn xếp
PAVAchạy trong \(O(n\log n)\) và thỏa điều kiện đối ngẫuKKT(\(\lambda_k \ge 0\)); sau đó so sánh điều kiện thắng/thua giữaTemperature Scaling,Platt Scaling,Beta Calibration, vàPAVAkhi \(n_{\text{cal}} = 200\) hoặc có dịch chuyển tỷ lệ nền. - Q7: Chứng minh \(0 \le p_0(s^*) < p_1(s^*) \le 1\) trong
Inductive Venn-Abersvà dẫn xuất công thức thu gọn điểm minimax Log-Loss \(p_{\text{VA}} = \frac{p_1}{1 - p_0 + p_1}\), chỉ ra vì sao nó tự khôi phục Laplace smoothing tại biên. - Q8: Giải thích bằng Định lý Tích phân Sụp đổ Lợi nhuận và Ba-lô Lagrangian giá bóng \(\mu^*\) lý do hai mô hình có
ROC-AUC = 0.860y hệt nhau lại chênh nhau tới $35,000 lợi nhuận ròng và gây đảo lộn thứ tự ưu tiên hàng đợiK = 120.
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%): Thiết lập định nghĩa lọc \(\mathcal{F}_{t_{\text{obs}}}\) và kiểm định toàn bộ 6 Lớp Rò rỉ trongleakage_auditor.py; kiểm chứngaudit_class1..class6_*và giải thích cơ chế bổ trợ giữa1D Dominance,Permutation Null,Quadratic C2ST/E-C2ST, vàSHA-256 + NNDR. - Bài tập 2 (
20%): Chứng minh xác suất nhiễm chéoSMOTE-trước-CV(\(1 - 1/K^2\)) và độ lệch log-odds \(+\ln(M+1)\); thực nghiệmaudit_class3_smote_and_preproc_before_cvcùngfit_bayes_prior_offsetđể đo bước nhảyPR-AUC(0.952 -> 0.189) và hiệu chỉnh tỷ lệ nền (0.230 -> 0.072). - Bài tập 3 (
15%): Chứng minh tính chuẩn nghiêm ngặt củaLog-Loss,Brier(Murphy),Sphericalvà phản chứng \(F_1\)/ROC-AUC; chạycompute_brier_and_murphyvàcompute_calibration_diagnosticsđể đối chiếuECE,ACE,Debiased L2-CE, vàsmECE*. - Bài tập 4 (
15%): Chứng minh thuật toán ngăn xếpPAVA(\(O(n\log n)\),KKT\(\lambda_k \ge 0\)) và độ lồi chặt củaTemperature Scalingtheo \(1/T\); đối chứngTemperature,Platt,Beta,PAVA, vàDirichlet + ODIRtrên ba chế độ (\(n_{\text{cal}}=200\), dịch tỷ lệ nền, và đuôi lệch Beta). - Bài tập 5 (
20%): Chứng minh định lý hiệu chuẩn hữu hạn mẫu và công thức thu gọn \(p_{\text{VA}} = \frac{p_1}{1 - p_0 + p_1}\) củaInductive Venn-Abers; đối chiếu bao lồi \(O(m \log m)\) vớiPAVAvét cạn (atol=1e-12) và thiết kế luật phân luồng người duyệt từ \((p_0, p_1)\). - Bài tập 6 (
15%): Dẫn xuất ngưỡng \(t^*(\mathbf{x}_i)\), giá bóng Lagrangian \(\mu^*\) vàDCA Net Benefit; chạysolve_capacity_constrained_triagetrên hàng đợiK = 120để tái lập mức tăng+188.3%($13,739 -> $39,611) cùng sụp đổ -$35,000 khiROC-AUC = 0.860giữ nguyên, qua đủ14/14pytest.
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 (6 Lớp Rò rỉ, \(1 - 1/K^2\), Murphy 1973, \(F_1\) bất chuẩn, PAVA KKT, IVAP minimax \(\frac{p_1}{1-p_0+p_1}\), Ba-lô \(\mu^*\)); gói eval_calibration_lab vượt 14/14 pytest (uv.lock) với 0 import deserialization không an toàn (Test 14) và sai số IVAP bao lồi < 1e-12; đồng bộ chuẩn xác các cổng canary, smECE*, JSON State-Dict, và tối ưu hàng đợi theo \(\Delta u_i / w_i\). |
| Senior Standard | 75–89% | Triển khai thông suốt 14/14 pytest, thực hiện đúng các bộ hiệu chuẩn và ngưỡng chi phí, nhưng còn thiếu chiều sâu khi phân tích điểm mù C2ST trước trùng lặp, chứng minh KKT của PAVA/IVAP, hoặc bẫy thiên lệch dương \(O(\sqrt{B/n})\) của ECE. |
| Needs Remediation | < 75% | Chạy SMOTE/TargetEncoder trước khi tách CV; khớp bộ hiệu chuẩn trên \(\mathcal{D}_{\text{tr}}\); dùng ROC-AUC hoặc Accuracy/t=0.5 để chọn ngưỡng chi phí; gộp hàng đợi bằng \(\hat{p}_i\) thô hay FIFO; dùng pickle/joblib (CWE-502) gây rò rỉ bảo mật trong lab. |
Leakage Illusion (Apparent CV/Offline) vs Clean OOT/Live Reality
Automated Leakage Canary Detection Signals Across Vectors
Post-Hoc Calibrator Out-of-Time Log-Loss & Adaptive Calibration Error (ACE-15)
Fraud Queue (K=120) Daily Net Dollar Savings vs Approve-All Baseline
6-Class Evaluation Leakage Audit & Canary Gate Signals
| Leakage Class | Apparent Metric | Clean OOT / Live Metric | Primary Canary Detector Signal | Gate Action |
|---|---|---|---|---|
| Class 1: Target Proxy | ROC 0.989 | Live ROC 0.802 | 1D AUC=0.946 (refund_issued_proxy) | BLOCK (Drop post-outcome feature) |
| Class 2: Temporal & Maturity | Rand AUC 0.879 | 0d -30.8% | Purged AUC 0.532 | 60d -5.7% | Immature rate ratio=0.62 | BLOCK (Purged OOT + >=60d maturity) |
| Class 3: SMOTE & TE Before CV | PR 0.952 (AUC 0.975) | Clean PR 0.189 (AUC 0.770) | Perm-Null TE=0.880; Prox=0.52 | BLOCK (Move inside fold + prior offset) |
| Class 4: Group Overlap | Rand AUC 0.664 | Group AUC 0.486 | GroupKFold intersection=0 | BLOCK (Enforce GroupKFold) |
| Class 5: Exact/Near Duplicates | Dup 1NN AUC 0.754 | Dedup AUC 0.593 | C2ST blind 0.500 vs Hash 35.0% | BLOCK (Pre-split SHA-256 + NNDR) |
| Class 6: Feature Store ASOF | Off AUC 1.000 | Live AUC 0.603 (Clean 0.721) | Quad C2ST=0.961; E-C2ST=1.0e+12 | BLOCK (SCD-2 PIT ASOF join) |
Proper Scoring & Calibration Comparison (n_cal=2000, n_test=3000)
| Calibrator | Log-Loss | Brier Score | Murphy REL / RES | ECE-15 / ACE-15 | SmoothECE* | ROC-AUC |
|---|---|---|---|---|---|---|
| Uncalibrated Raw | 0.1716 | 0.04760 | 0.00262 / 0.00769 | 0.0203 / 0.0212 | 0.0211 | 0.8645 |
| Temperature Scaling (1p) | 0.1688 | 0.04762 | 0.00306 / 0.00813 | 0.0213 / 0.0229 | 0.0213 | 0.8645 |
| Platt Scaling (2p) | 0.1646 | 0.04531 | 0.00024 / 0.00760 | 0.0094 / 0.0095 | 0.0111 | 0.8645 |
| Beta Calibration (3p) | 0.1646 | 0.04532 | 0.00040 / 0.00778 | 0.0108 / 0.0096 | 0.0113 | 0.8645 |
| PAVA Isotonic | 0.1708 | 0.04668 | 0.00184 / 0.00810 | 0.0155 / 0.0117 | 0.0154 | 0.8574 |
| Inductive Venn-Abers (IVAP) | 0.1688 | 0.04647 | 0.00138 / 0.00783 | 0.0176 / 0.0137 | 0.0179 | 0.8601 |
| Cross Venn-Abers (CVAP-5) | 0.1705 | 0.04615 | 0.00124 / 0.00810 | 0.0241 / 0.0192 | 0.0224 | 0.8645 |
Regime Ablations: Small n_cal=200 Overfit, Beta Skew & 3-Class Dirichlet ODIR
| Experimental Regime | Comparator A | Comparator B | Comparator C | Engineering Takeaway |
|---|---|---|---|---|
| Small Holdout (n_cal=200, Overconfident) | Temp NLL=0.6294 | Platt NLL=0.6332 | PAVA NLL=0.7313 (IVAP=0.6336) | PAVA overfits severely at n=200; Temp & IVAP dominate |
| Prior + Slope Shift (Main Cohort) | Temp ACE=0.0229 | Platt ACE=0.0095 | IVAP ACE=0.0137 | 1-param Temp blind to intercept shift; Platt/IVAP fix both |
| Skewed Beta Score Tails | Platt ACE=0.0506 | Beta ACE=0.0323 | Beta NLL=0.3521 vs Platt 0.3599 | Beta Calibration captures asymmetric tail densities |
| 3-Class Logit Shift (Dirichlet ODIR) | Raw NLL=1.0234 | Temp NLL=0.9270 | Dirichlet+ODIR NLL=0.9188 | Dirichlet+ODIR fixes per-class bias without O(K^2) overfit |
Cost-Sensitive & Capacity-Constrained Fraud Triage (Cap K=120, Exposure=$69,952)
| Decision Policy | Executed Alerts | Fraud Caught (TP) | Count Recall | Dollar Recall | Net Savings vs Approve-All |
|---|---|---|---|---|---|
| 1. Naive Cutoff t=0.50 (Raw Prob Sort) | 75 | 30 | 17.8% | 20.0% | $13,739.17 |
| 2. Uncal Global t*=0.045 (Cand=716) | 120 | 43 | 25.4% | 26.8% | $18,258.54 |
| 3. Cal Global t*=0.045 (Cand=1001) | 120 | 44 | 26.0% | 27.2% | $18,544.34 |
| 4. Cal Instance t*(x) FIFO Saturated (Cand=879) | 120 | 16 | 9.5% | 8.7% | $4,799.12 |
| 5. Uncal Capacity Top-K (Miscalibrated Rank) | 120 | 38 | 22.5% | 53.6% | $36,853.71 |
| 6. Cal IVAP Capacity Top-K (mu*=$131.00) | 120 | 33 | 19.5% | 57.8% | $39,610.56 |
| 7. Cal Instance t*(x) Uncapped Upper Bound | 879 | 120 | 71.0% | 92.8% | $55,351.44 |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/ch07-leakage-and-calibration-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "eval-calibration-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for Leakage-Proof Evaluation (6-Class Taxonomy & Canaries), Proper Scoring Rules, Post-Hoc & Venn-Abers Calibration, and Bayes Cost-Sensitive Capacity Triage (T1-P2-U02)."
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"
"""Public API for eval_calibration_lab (Unit T1-P2-U02): Leakage-Proof Evaluation, Calibration & Bayes Cost Triage."""
from eval_calibration_lab.calibrators import (
BetaCalibrator,
CalibratorConfig,
CrossVennAbersCalibrator,
DirichletODIRCalibrator,
InductiveVennAbersCalibrator,
IsotonicPavaCalibrator,
PavaSolution,
PlattScalingCalibrator,
TemperatureScalingCalibrator,
compute_brier_and_murphy,
compute_calibration_diagnostics,
compute_log_loss,
compute_spherical_score,
fit_bayes_prior_offset,
fit_pava_blocks,
ivap_bruteforce_p0_p1,
)
from eval_calibration_lab.cost_decision_engine import (
CostMatrixConfig,
compute_bayes_threshold,
compute_decision_curve_analysis,
compute_instance_thresholds,
compute_marginal_net_benefits,
compute_miscalibration_profit_collapse,
evaluate_decision_policy,
run_full_ch07_benchmarks,
solve_capacity_constrained_triage,
)
from eval_calibration_lab.leakage_auditor import (
LeakageAuditConfig,
RidgeLogisticModel,
apply_naive_target_encoding,
apply_oof_target_encoding,
apply_smote_oversampling,
audit_class1_target_proxy_leakage,
audit_class2_temporal_and_maturity_leakage,
audit_class3_smote_and_preproc_before_cv,
audit_class4_group_overlap_leakage,
audit_class5_duplicate_leakage,
audit_class6_feature_store_asof_skew,
compute_ec2st_supermartingale,
compute_pr_auc,
compute_roc_auc,
fit_predict_knn_proba,
fit_ridge_logistic_classifier,
group_kfold_indices,
logit_from_proba,
make_leakage_audit_dataframe,
probe_single_feature_dominance,
run_duplicate_nndr_and_asof_canaries,
run_oof_c2st_canary,
run_permutation_null_canary,
stable_sigmoid,
stratified_kfold_indices,
)
__all__ = [
"BetaCalibrator",
"CalibratorConfig",
"CostMatrixConfig",
"CrossVennAbersCalibrator",
"DirichletODIRCalibrator",
"InductiveVennAbersCalibrator",
"IsotonicPavaCalibrator",
"LeakageAuditConfig",
"PavaSolution",
"PlattScalingCalibrator",
"RidgeLogisticModel",
"TemperatureScalingCalibrator",
"apply_naive_target_encoding",
"apply_oof_target_encoding",
"apply_smote_oversampling",
"audit_class1_target_proxy_leakage",
"audit_class2_temporal_and_maturity_leakage",
"audit_class3_smote_and_preproc_before_cv",
"audit_class4_group_overlap_leakage",
"audit_class5_duplicate_leakage",
"audit_class6_feature_store_asof_skew",
"compute_bayes_threshold",
"compute_brier_and_murphy",
"compute_calibration_diagnostics",
"compute_decision_curve_analysis",
"compute_ec2st_supermartingale",
"compute_instance_thresholds",
"compute_log_loss",
"compute_marginal_net_benefits",
"compute_miscalibration_profit_collapse",
"compute_pr_auc",
"compute_roc_auc",
"compute_spherical_score",
"evaluate_decision_policy",
"fit_bayes_prior_offset",
"fit_pava_blocks",
"fit_predict_knn_proba",
"fit_ridge_logistic_classifier",
"group_kfold_indices",
"ivap_bruteforce_p0_p1",
"logit_from_proba",
"make_leakage_audit_dataframe",
"probe_single_feature_dominance",
"run_duplicate_nndr_and_asof_canaries",
"run_full_ch07_benchmarks",
"run_oof_c2st_canary",
"run_permutation_null_canary",
"solve_capacity_constrained_triage",
"stable_sigmoid",
"stratified_kfold_indices",
]
"""Leakage-proof evaluation taxonomy, automated canary probes, and pure-NumPy linear/kNN baselines."""
from __future__ import annotations
import hashlib
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
class LeakageAuditConfig(BaseModel):
"""Strict immutable configuration for automated leakage canary audits."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_folds: int = Field(default=5, ge=2, le=20)
smote_k_neighbors: int = Field(default=5, ge=1, le=25)
dominance_auc_threshold: float = Field(default=0.85, gt=0.5, le=1.0)
c2st_auc_threshold: float = Field(default=0.55, gt=0.5, le=1.0)
n_permutations: int = Field(default=40, ge=10, le=500)
duplicate_nndr_threshold: float = Field(default=0.20, gt=0.0, le=1.0)
near_dup_cos_threshold: float = Field(default=0.995, gt=0.5, le=1.0)
seed: int = Field(default=42, ge=0)
@dataclass(frozen=True, slots=True)
class RidgeLogisticModel:
"""Immutable L2-regularized binary logistic classifier fitted via damped IRLS."""
intercept: float
coef: np.ndarray
feature_mean: np.ndarray
feature_std: np.ndarray
def predict_logits(self, X: np.ndarray) -> np.ndarray:
"""Compute raw log-odds scores on standardized inputs."""
X_arr = np.asarray(X, dtype=np.float64)
X_std = (X_arr - self.feature_mean) / self.feature_std
return X_std @ self.coef + self.intercept
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Return calibrated-style raw model probabilities in (0, 1)."""
return np.asarray(stable_sigmoid(self.predict_logits(X)), dtype=np.float64)
def stable_sigmoid(z: np.ndarray | float) -> np.ndarray | float:
"""Overflow-safe sigmoid mapping real logits into [0, 1]."""
arr = np.asarray(z, dtype=np.float64)
out = np.empty_like(arr, dtype=np.float64)
pos = arr >= 0.0
out[pos] = 1.0 / (1.0 + np.exp(-arr[pos]))
exp_neg = np.exp(arr[~pos])
out[~pos] = exp_neg / (1.0 + exp_neg)
if np.ndim(z) == 0:
return float(out.item())
return out
def logit_from_proba(p: np.ndarray, eps: float = 1e-12) -> np.ndarray:
"""Safely map probabilities into finite log-odds."""
p_clip = np.clip(np.asarray(p, dtype=np.float64), eps, 1.0 - eps)
return np.log(p_clip / (1.0 - p_clip))
def compute_roc_auc(y_true: np.ndarray, y_score: np.ndarray) -> float:
"""Exact Mann-Whitney ROC-AUC with average-rank tie handling."""
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_sorted), dtype=np.float64)
i = 0
n = len(s_sorted)
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)) / (float(n_pos) * float(n_neg))
return float(np.clip(auc, 0.0, 1.0))
def compute_pr_auc(y_true: np.ndarray, y_score: np.ndarray) -> float:
"""Stepwise Average Precision (PR-AUC) matching sklearn tie-grouped precision drops."""
y = np.asarray(y_true, dtype=np.int64)
s = np.asarray(y_score, dtype=np.float64)
n_pos = int(np.sum(y == 1))
if n_pos == 0:
return 0.0
order = np.argsort(-s, kind="mergesort")
y_sorted = y[order]
s_sorted = s[order]
# Collapse exact score ties so threshold steps are exact
distinct_mask = np.r_[np.diff(s_sorted) != 0.0, True]
tps = np.cumsum(y_sorted)[distinct_mask].astype(np.float64)
fps = np.cumsum(1 - y_sorted)[distinct_mask].astype(np.float64)
recalls = tps / float(n_pos)
precisions = tps / np.maximum(tps + fps, 1.0)
prev_recalls = np.r_[0.0, recalls[:-1]]
return float(np.sum((recalls - prev_recalls) * precisions))
def fit_ridge_logistic_classifier(
X: np.ndarray,
y: np.ndarray,
l2_alpha: float = 1.0,
max_iter: int = 45,
tol: float = 1e-7,
) -> RidgeLogisticModel:
"""Fit binary L2-regularized logistic regression via Armijo-damped IRLS with unpenalized intercept."""
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = X_arr.shape
mean = np.mean(X_arr, axis=0)
std = np.std(X_arr, axis=0)
std = np.where(std > 1e-12, std, 1.0)
X_std = (X_arr - mean) / std
X_aug = np.column_stack([np.ones(n, dtype=np.float64), X_std])
p_base = float(np.clip(np.mean(y_arr), 1e-4, 1.0 - 1e-4))
beta = np.zeros(d + 1, dtype=np.float64)
beta[0] = math.log(p_base / (1.0 - p_base))
reg_diag = np.full(d + 1, l2_alpha, dtype=np.float64)
reg_diag[0] = 0.0
reg_mat = np.diag(reg_diag)
def _objective(b_vec: np.ndarray) -> float:
eta_v = X_aug @ b_vec
nll = float(np.sum((1.0 - y_arr) * eta_v + np.maximum(-eta_v, 0.0) + np.log1p(np.exp(-np.abs(eta_v)))))
return nll + 0.5 * float(np.sum(reg_diag * (b_vec * b_vec)))
cur_obj = _objective(beta)
for _ in range(max_iter):
eta = X_aug @ beta
p = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(p * (1.0 - p), 1e-12)
grad = X_aug.T @ (p - y_arr) + reg_diag * beta
hess = (X_aug * w[:, None]).T @ X_aug + reg_mat + 1e-8 * np.eye(d + 1)
direction = np.linalg.solve(hess, grad)
step = 1.0
accepted = False
while step >= 1e-6:
cand = beta - step * direction
cand_obj = _objective(cand)
if cand_obj <= cur_obj + 1e-12:
beta = cand
cur_obj = cand_obj
accepted = True
break
step *= 0.5
if not accepted or float(np.linalg.norm(step * direction, ord=np.inf)) < tol:
break
coef = beta[1:].copy()
coef.setflags(write=False)
mean_ro = mean.copy()
mean_ro.setflags(write=False)
std_ro = std.copy()
std_ro.setflags(write=False)
return RidgeLogisticModel(
intercept=float(beta[0]),
coef=coef,
feature_mean=mean_ro,
feature_std=std_ro,
)
def fit_predict_knn_proba(
X_train: np.ndarray,
y_train: np.ndarray,
X_eval: np.ndarray,
k: int = 7,
) -> np.ndarray:
"""Pure-NumPy standardized Euclidean k-nearest-neighbor probability estimator."""
X_tr = np.asarray(X_train, dtype=np.float64)
y_tr = np.asarray(y_train, dtype=np.float64)
X_ev = np.asarray(X_eval, dtype=np.float64)
mean = np.mean(X_tr, axis=0)
std = np.std(X_tr, axis=0)
std = np.where(std > 1e-12, std, 1.0)
Z_tr = (X_tr - mean) / std
Z_ev = (X_ev - mean) / std
k_eff = min(max(1, k), len(Z_tr))
tr_norm2 = np.sum(Z_tr * Z_tr, axis=1)
preds = np.empty(len(Z_ev), dtype=np.float64)
batch_size = 512
for start in range(0, len(Z_ev), batch_size):
block = Z_ev[start : start + batch_size]
b_norm2 = np.sum(block * block, axis=1)[:, None]
d2 = np.maximum(b_norm2 + tr_norm2[None, :] - 2.0 * (block @ Z_tr.T), 0.0)
nn_idx = np.argpartition(d2, kth=k_eff - 1, axis=1)[:, :k_eff]
preds[start : start + batch_size] = np.mean(y_tr[nn_idx], axis=1)
return preds
def apply_smote_oversampling(
X: np.ndarray,
y: np.ndarray,
target_ratio: float = 1.0,
k_neighbors: int = 5,
seed: int = 42,
) -> tuple[np.ndarray, np.ndarray]:
"""Pure-NumPy SMOTE minority oversampling returning augmented (X_aug, y_aug)."""
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
pos_idx = np.flatnonzero(y_arr == 1)
neg_count = int(np.sum(y_arr == 0))
pos_count = len(pos_idx)
if pos_count < 2 or neg_count == 0:
return X_arr.copy(), y_arr.copy()
desired_pos = round(neg_count * target_ratio)
n_syn = max(0, desired_pos - pos_count)
if n_syn == 0:
return X_arr.copy(), y_arr.copy()
X_pos = X_arr[pos_idx]
mean = np.mean(X_arr, axis=0)
std = np.std(X_arr, axis=0)
std = np.where(std > 1e-12, std, 1.0)
Z_pos = (X_pos - mean) / std
z_norm2 = np.sum(Z_pos * Z_pos, axis=1)
d2 = np.maximum(z_norm2[:, None] + z_norm2[None, :] - 2.0 * (Z_pos @ Z_pos.T), 0.0)
np.fill_diagonal(d2, np.inf)
k_eff = min(k_neighbors, pos_count - 1)
knn = np.argpartition(d2, kth=k_eff - 1, axis=1)[:, :k_eff]
rng = np.random.default_rng(np.random.SeedSequence(seed))
base_choices = rng.integers(0, pos_count, size=n_syn)
nbr_slots = rng.integers(0, k_eff, size=n_syn)
nbr_choices = knn[base_choices, nbr_slots]
u = rng.uniform(0.0, 1.0, size=(n_syn, 1))
X_syn = X_pos[base_choices] + u * (X_pos[nbr_choices] - X_pos[base_choices])
y_syn = np.ones(n_syn, dtype=np.int64)
return np.vstack([X_arr, X_syn]), np.concatenate([y_arr, y_syn])
def apply_naive_target_encoding(
cat_ids: np.ndarray,
y: np.ndarray,
smoothing_m: float = 10.0,
) -> np.ndarray:
"""Leaky in-sample target encoding fit directly on full labels (demonstrates Class 3 leak)."""
cats = np.asarray(cat_ids, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
prior = float(np.mean(y_arr))
max_cat = int(np.max(cats)) + 1
counts = np.bincount(cats, minlength=max_cat).astype(np.float64)
sums = np.bincount(cats, weights=y_arr, minlength=max_cat).astype(np.float64)
enc_map = (sums + smoothing_m * prior) / (counts + smoothing_m)
return enc_map[cats]
def apply_oof_target_encoding(
cat_train: np.ndarray,
y_train: np.ndarray,
cat_eval: np.ndarray | None = None,
n_folds: int = 5,
smoothing_m: float = 10.0,
seed: int = 42,
) -> tuple[np.ndarray, np.ndarray | None]:
"""Leakage-free out-of-fold empirical Bayes target encoding."""
cats_tr = np.asarray(cat_train, dtype=np.int64)
y_tr = np.asarray(y_train, dtype=np.float64)
n = len(cats_tr)
max_cat = int(max(int(np.max(cats_tr)), int(np.max(cat_eval)) if cat_eval is not None else 0)) + 1
rng = np.random.default_rng(np.random.SeedSequence(seed))
folds = rng.permutation(n) % n_folds
oof = np.empty(n, dtype=np.float64)
for k in range(n_folds):
val_mask = folds == k
tr_mask = ~val_mask
prior = float(np.mean(y_tr[tr_mask]))
counts = np.bincount(cats_tr[tr_mask], minlength=max_cat).astype(np.float64)
sums = np.bincount(cats_tr[tr_mask], weights=y_tr[tr_mask], minlength=max_cat).astype(np.float64)
enc_map = (sums + smoothing_m * prior) / (counts + smoothing_m)
oof[val_mask] = enc_map[cats_tr[val_mask]]
eval_enc = None
if cat_eval is not None:
prior_full = float(np.mean(y_tr))
counts_full = np.bincount(cats_tr, minlength=max_cat).astype(np.float64)
sums_full = np.bincount(cats_tr, weights=y_tr, minlength=max_cat).astype(np.float64)
full_map = (sums_full + smoothing_m * prior_full) / (counts_full + smoothing_m)
eval_enc = full_map[np.asarray(cat_eval, dtype=np.int64)]
return oof, eval_enc
def stratified_kfold_indices(
y: np.ndarray,
n_folds: int = 5,
seed: int = 42,
) -> list[tuple[np.ndarray, np.ndarray]]:
"""Deterministic stratified K-Fold split indices."""
y_arr = np.asarray(y, dtype=np.int64)
rng = np.random.default_rng(np.random.SeedSequence(seed))
fold_ids = np.empty(len(y_arr), dtype=np.int64)
for cls_val in (0, 1):
cls_idx = np.flatnonzero(y_arr == cls_val)
rng.shuffle(cls_idx)
for pos, idx in enumerate(cls_idx):
fold_ids[idx] = pos % n_folds
return [
(np.flatnonzero(fold_ids != k), np.flatnonzero(fold_ids == k))
for k in range(n_folds)
]
def group_kfold_indices(
groups: np.ndarray,
n_folds: int = 5,
seed: int = 42,
) -> list[tuple[np.ndarray, np.ndarray]]:
"""Deterministic GroupKFold ensuring zero entity overlap between train and val."""
grp = np.asarray(groups)
uniq = np.unique(grp)
rng = np.random.default_rng(np.random.SeedSequence(seed))
rng.shuffle(uniq)
group_to_fold = {g: idx % n_folds for idx, g in enumerate(uniq)}
row_folds = np.array([group_to_fold[g] for g in grp], dtype=np.int64)
return [
(np.flatnonzero(row_folds != k), np.flatnonzero(row_folds == k))
for k in range(n_folds)
]
# ---------------------------------------------------------------------------
# 4 Automated Leakage Canary Detectors
# ---------------------------------------------------------------------------
def _discrete_nmi(x: np.ndarray, y: np.ndarray, n_bins: int = 10) -> float:
"""Compute quantile-binned Normalized Mutual Information I(X; Y) / H(Y)."""
y_arr = np.asarray(y, dtype=np.int64)
p1 = float(np.mean(y_arr))
if p1 <= 0.0 or p1 >= 1.0:
return 0.0
h_y = -(p1 * math.log(p1) + (1.0 - p1) * math.log(1.0 - p1))
edges = np.unique(np.quantile(x, np.linspace(0.0, 1.0, n_bins + 1)))
if len(edges) <= 2:
bins = (x > np.median(x)).astype(np.int64)
else:
bins = np.clip(np.digitize(x, edges[1:-1], right=True), 0, len(edges) - 2)
n = float(len(y_arr))
n_b = int(np.max(bins)) + 1
mi = 0.0
for b in range(n_b):
mask = bins == b
nb = int(np.sum(mask))
if nb == 0:
continue
p_b = nb / n
n_b1 = int(np.sum(y_arr[mask] == 1))
n_b0 = nb - n_b1
if n_b1 > 0:
p_b1 = n_b1 / n
mi += p_b1 * math.log(p_b1 / (p_b * p1))
if n_b0 > 0:
p_b0 = n_b0 / n
mi += p_b0 * math.log(p_b0 / (p_b * (1.0 - p1)))
return float(max(0.0, min(1.0, mi / max(h_y, 1e-12))))
def probe_single_feature_dominance(
X: np.ndarray,
y: np.ndarray,
feature_names: list[str] | None = None,
dominance_threshold: float = 0.85,
) -> dict[str, Any]:
"""Canary 2A: Scan every raw column for target-proxy dominance (symmetric AUC & NMI)."""
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
d = X_arr.shape[1]
names = feature_names or [f"f_{j}" for j in range(d)]
records: list[dict[str, Any]] = []
flagged: list[str] = []
for j in range(d):
raw_auc = compute_roc_auc(y_arr, X_arr[:, j])
sym_auc = max(raw_auc, 1.0 - raw_auc)
nmi = _discrete_nmi(X_arr[:, j], y_arr)
is_flag = sym_auc >= dominance_threshold
if is_flag:
flagged.append(names[j])
records.append({"feature": names[j], "sym_auc_1d": sym_auc, "nmi": nmi, "flagged": is_flag})
records.sort(key=lambda r: r["sym_auc_1d"], reverse=True)
return {
"max_sym_auc_1d": records[0]["sym_auc_1d"] if records else 0.5,
"top_feature": records[0]["feature"] if records else "",
"flagged_features": flagged,
"dominance_threshold": dominance_threshold,
"feature_profiles": records,
}
def run_permutation_null_canary(
pipeline_eval_fn: Callable[[np.ndarray, np.ndarray], float],
X: np.ndarray,
y: np.ndarray,
n_permutations: int = 30,
seed: int = 42,
null_leak_threshold: float = 0.55,
) -> dict[str, Any]:
"""Canary 1: Re-run full pipeline on permuted targets to catch pipeline/TE/SMOTE leaks."""
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
obs_score = float(pipeline_eval_fn(X_arr, y_arr))
rng = np.random.default_rng(np.random.SeedSequence(seed))
null_scores = np.empty(n_permutations, dtype=np.float64)
for b in range(n_permutations):
y_perm = rng.permutation(y_arr)
null_scores[b] = float(pipeline_eval_fn(X_arr, y_perm))
null_mean = float(np.mean(null_scores))
null_std = float(np.std(null_scores))
p_value = float((1 + np.sum(null_scores >= obs_score)) / (n_permutations + 1))
n_pos = int(np.sum(y_arr == 1))
n_neg = int(np.sum(y_arr == 0))
mw_std = math.sqrt((n_pos + n_neg + 1.0) / max(12.0 * n_pos * n_neg, 1.0))
null_z_above_chance = (null_mean - 0.5) / max(mw_std / math.sqrt(n_permutations), 1e-6)
return {
"obs_score": obs_score,
"null_mean": null_mean,
"null_std": null_std,
"null_max": float(np.max(null_scores)),
"p_value": p_value,
"null_z_above_chance": float(null_z_above_chance),
"pipeline_leakage_detected": bool(null_mean > null_leak_threshold),
}
def run_oof_c2st_canary(
X_ref: np.ndarray,
X_cur: np.ndarray,
feature_names: list[str] | None = None,
n_folds: int = 5,
quadratic: bool = True,
c2st_threshold: float = 0.55,
seed: int = 42,
) -> dict[str, Any]:
"""Canary 3A: Out-of-Fold Classifier Two-Sample Test (linear or quadratic features)."""
Xr = np.asarray(X_ref, dtype=np.float64)
Xc = np.asarray(X_cur, dtype=np.float64)
d = Xr.shape[1]
names = feature_names or [f"f_{j}" for j in range(d)]
X_all = np.vstack([Xr, Xc])
z_all = np.concatenate([np.zeros(len(Xr), dtype=np.int64), np.ones(len(Xc), dtype=np.int64)])
folds = stratified_kfold_indices(z_all, n_folds=n_folds, seed=seed)
oof_probs = np.empty(len(z_all), dtype=np.float64)
coef_accum = np.zeros(d * (2 if quadratic else 1), dtype=np.float64)
for tr_idx, va_idx in folds:
mean_tr = np.mean(X_all[tr_idx], axis=0)
std_tr = np.where(np.std(X_all[tr_idx], axis=0) > 1e-12, np.std(X_all[tr_idx], axis=0), 1.0)
Z_tr = (X_all[tr_idx] - mean_tr) / std_tr
Z_va = (X_all[va_idx] - mean_tr) / std_tr
if quadratic:
F_tr = np.hstack([Z_tr, Z_tr * Z_tr])
F_va = np.hstack([Z_va, Z_va * Z_va])
else:
F_tr, F_va = Z_tr, Z_va
clf = fit_ridge_logistic_classifier(F_tr, z_all[tr_idx], l2_alpha=5.0)
oof_probs[va_idx] = clf.predict_proba(F_va)
coef_accum += np.abs(clf.coef) / float(n_folds)
auc_adv = compute_roc_auc(z_all, oof_probs)
n_r = float(len(Xr))
n_c = float(len(Xc))
null_std = math.sqrt((n_r + n_c + 1.0) / max(12.0 * n_r * n_c, 1.0))
z_stat = (auc_adv - 0.5) / null_std
# Normal two-sided tail via erfc
p_val = float(math.erfc(abs(z_stat) / math.sqrt(2.0)))
if quadratic:
col_scores = coef_accum[:d] + coef_accum[d:]
else:
col_scores = coef_accum
culprits = [
{"feature": names[j], "importance": float(col_scores[j])}
for j in np.argsort(-col_scores)
]
return {
"auc_adv": auc_adv,
"z_stat": float(z_stat),
"p_value": p_val,
"quadratic": quadratic,
"shift_or_leak_detected": bool(auc_adv >= c2st_threshold),
"top_culprits": culprits[: min(5, len(culprits))],
}
def compute_ec2st_supermartingale(
X_ref: np.ndarray,
X_cur: np.ndarray,
batch_size: int = 120,
quadratic: bool = True,
alpha: float = 0.05,
seed: int = 42,
) -> dict[str, Any]:
"""Canary 3B: Sequential anytime-valid E-C2ST betting martingale (Pandeva et al., 2024)."""
Xr = np.asarray(X_ref, dtype=np.float64)
Xc = np.asarray(X_cur, dtype=np.float64)
rng = np.random.default_rng(np.random.SeedSequence(seed))
idx_r = rng.permutation(len(Xr))
idx_c = rng.permutation(len(Xc))
n_pairs = min(len(Xr), len(Xc))
half = batch_size // 2
n_batches = n_pairs // half
if n_batches < 3:
half = max(20, n_pairs // 4)
n_batches = n_pairs // half
wealth = 1.0
wealth_path = [1.0]
hist_X: list[np.ndarray] = []
hist_z: list[np.ndarray] = []
rejected_at_step: int | None = None
rejection_thresh = 1.0 / alpha
for t in range(n_batches):
sl = slice(t * half, (t + 1) * half)
Xb_r = Xr[idx_r[sl]]
Xb_c = Xc[idx_c[sl]]
Xb = np.vstack([Xb_r, Xb_c])
zb = np.concatenate([np.zeros(half, dtype=np.int64), np.ones(half, dtype=np.int64)])
if t >= 1:
X_past = np.vstack(hist_X)
z_past = np.concatenate(hist_z)
mean_p = np.mean(X_past, axis=0)
std_p = np.where(np.std(X_past, axis=0) > 1e-12, np.std(X_past, axis=0), 1.0)
Zp = (X_past - mean_p) / std_p
Zb = (Xb - mean_p) / std_p
Fp = np.hstack([Zp, Zp * Zp]) if quadratic else Zp
Fb = np.hstack([Zb, Zb * Zb]) if quadratic else Zb
clf = fit_ridge_logistic_classifier(Fp, z_past, l2_alpha=5.0)
preds = (clf.predict_proba(Fb) >= 0.5).astype(np.int64)
# Predictable conservative betting fraction from historical OOF confidence
past_probs = clf.predict_proba(Fp)
past_acc = float(np.mean((past_probs >= 0.5).astype(np.int64) == z_past))
bet = float(np.clip(2.0 * (past_acc - 0.5), 0.0, 0.45))
# Each pair/sample contributes (1 + bet * (+1 or -1)); mean zero under H0 (E[E_t]=1)
gains = np.where(preds == zb, 1.0 + bet, 1.0 - bet)
e_t = float(np.prod(gains))
wealth = min(wealth * e_t, 1e12)
wealth_path.append(wealth)
if rejected_at_step is None and wealth >= rejection_thresh:
rejected_at_step = t
hist_X.append(Xb)
hist_z.append(zb)
return {
"final_wealth": float(wealth),
"rejection_threshold": float(rejection_thresh),
"rejected": bool(wealth >= rejection_thresh or rejected_at_step is not None),
"rejected_at_batch": rejected_at_step,
"n_batches": int(n_batches),
"wealth_path": wealth_path,
}
def _row_sha256_hashes(X: np.ndarray, decimals: int = 8) -> list[str]:
"""Compute canonical SHA-256 hex digest for each numeric feature row."""
X_round = np.round(np.asarray(X, dtype=np.float64), decimals=decimals)
# Normalize -0.0 -> +0.0 before byte hashing
X_round = np.where(X_round == 0.0, 0.0, X_round)
hashes: list[str] = []
for row in X_round:
payload = ",".join("NAN" if math.isnan(float(v)) else f"{float(v):.{decimals}f}" for v in row)
hashes.append(hashlib.sha256(payload.encode("utf-8")).hexdigest())
return hashes
def run_duplicate_nndr_and_asof_canaries(
X_tr: np.ndarray,
X_te: np.ndarray,
obs_ts: np.ndarray | None = None,
feat_ts_matrix: np.ndarray | None = None,
label_horizon: float | None = None,
eval_cutoff: float | None = None,
y_obs: np.ndarray | None = None,
sla_lag: float = 0.0,
nndr_threshold: float = 0.20,
near_cos_threshold: float = 0.995,
) -> dict[str, Any]:
"""Canary 4: Exact SHA-256 duplicates, cross-split NNDR/proximity, PIT ASOF, and maturity check."""
Xtr = np.asarray(X_tr, dtype=np.float64)
Xte = np.asarray(X_te, dtype=np.float64)
tr_hashes = set(_row_sha256_hashes(Xtr))
te_hashes = _row_sha256_hashes(Xte)
exact_hits = sum(1 for h in te_hashes if h in tr_hashes)
exact_dup_rate = float(exact_hits / max(len(Xte), 1))
# Standardized cross-split distances
mean = np.mean(Xtr, axis=0)
std = np.where(np.std(Xtr, axis=0) > 1e-12, np.std(Xtr, axis=0), 1.0)
Ztr = (Xtr - mean) / std
Zte = (Xte - mean) / std
# Intra-train baseline 1-NN spacing (subsample up to 800 rows for speed)
sub_n = min(800, len(Ztr))
Zsub = Ztr[:sub_n]
sub_n2 = np.sum(Zsub * Zsub, axis=1)
d2_intra = np.maximum(sub_n2[:, None] + sub_n2[None, :] - 2.0 * (Zsub @ Zsub.T), 0.0)
np.fill_diagonal(d2_intra, np.inf)
d1_intra = np.sqrt(np.min(d2_intra, axis=1))
median_d1_intra = float(max(np.median(d1_intra), 1e-8))
# Cross-split distances (chunked)
tr_n2 = np.sum(Ztr * Ztr, axis=1)
tr_unit = Ztr / np.maximum(np.linalg.norm(Ztr, axis=1, keepdims=True), 1e-12)
te_unit = Zte / np.maximum(np.linalg.norm(Zte, axis=1, keepdims=True), 1e-12)
d1_cross = np.empty(len(Zte), dtype=np.float64)
d2_cross = np.empty(len(Zte), dtype=np.float64)
max_cos = np.empty(len(Zte), dtype=np.float64)
bs = 256
for s in range(0, len(Zte), bs):
blk = Zte[s : s + bs]
b_n2 = np.sum(blk * blk, axis=1)[:, None]
d2 = np.maximum(b_n2 + tr_n2[None, :] - 2.0 * (blk @ Ztr.T), 0.0)
part = np.partition(d2, kth=min(1, len(Ztr) - 1), axis=1)
d1_cross[s : s + bs] = np.sqrt(part[:, 0])
d2_cross[s : s + bs] = np.sqrt(part[:, min(1, len(Ztr) - 1)])
cos_blk = te_unit[s : s + bs] @ tr_unit.T
max_cos[s : s + bs] = np.max(cos_blk, axis=1)
prox_ratios = d1_cross / median_d1_intra
nndr = d1_cross / np.maximum(d2_cross, 1e-12)
near_dup_mask = (prox_ratios <= nndr_threshold) | (max_cos >= near_cos_threshold)
asof_violation_rate = 0.0
if obs_ts is not None and feat_ts_matrix is not None:
obs_arr = np.asarray(obs_ts, dtype=np.float64)[:, None]
ft_arr = np.asarray(feat_ts_matrix, dtype=np.float64)
violations = np.any(ft_arr > (obs_arr - sla_lag + 1e-9), axis=1)
asof_violation_rate = float(np.mean(violations))
maturity_violation_rate = 0.0
immature_vs_mature_ratio = 1.0
if obs_ts is not None and label_horizon is not None and eval_cutoff is not None:
obs_arr = np.asarray(obs_ts, dtype=np.float64)
immature_mask = (obs_arr + label_horizon) > eval_cutoff
maturity_violation_rate = float(np.mean(immature_mask))
if y_obs is not None and np.any(immature_mask) and np.any(~immature_mask):
y_arr = np.asarray(y_obs, dtype=np.float64)
imm_rate = float(np.mean(y_arr[immature_mask]))
mat_rate = float(np.mean(y_arr[~immature_mask]))
if mat_rate > 1e-9:
immature_vs_mature_ratio = imm_rate / mat_rate
return {
"exact_dup_count": int(exact_hits),
"exact_dup_rate": exact_dup_rate,
"near_dup_rate": float(np.mean(near_dup_mask)),
"median_prox_ratio": float(np.median(prox_ratios)),
"p05_prox_ratio": float(np.quantile(prox_ratios, 0.05)),
"min_nndr": float(np.min(nndr)),
"p05_nndr": float(np.quantile(nndr, 0.05)),
"max_cos_p95": float(np.quantile(max_cos, 0.95)),
"asof_violation_rate": asof_violation_rate,
"maturity_violation_rate": maturity_violation_rate,
"immature_vs_mature_prev_ratio": float(immature_vs_mature_ratio),
}
# ---------------------------------------------------------------------------
# 6-Class Leakage Benchmark Scenarios (Articles #1 & #2 Integration)
# ---------------------------------------------------------------------------
def audit_class1_target_proxy_leakage(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 1: Post-outcome refund/chargeback proxy inflates offline AUC then collapses live."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n_tr = 1800 if quick else 4000
n_te = 1000 if quick else 2000
n_tot = n_tr + n_te
X_pre = rng.normal(0.0, 1.0, size=(n_tot, 6))
logits_true = -2.3 + 0.9 * X_pre[:, 0] - 0.7 * X_pre[:, 1] + 0.5 * X_pre[:, 2]
y = (rng.uniform(size=n_tot) < np.asarray(stable_sigmoid(logits_true))).astype(np.int64)
# Post-outcome proxy: refund_issued_flag (only populated offline after dispute settles!)
proxy_offline = np.where(
y == 1,
(rng.uniform(size=n_tot) < 0.92).astype(np.float64),
(rng.uniform(size=n_tot) < 0.02).astype(np.float64),
) + rng.normal(0.0, 0.05, size=n_tot)
X_tr_clean, X_te_clean = X_pre[:n_tr], X_pre[n_tr:]
X_tr_leak = np.column_stack([X_tr_clean, proxy_offline[:n_tr]])
X_te_leak_offline = np.column_stack([X_te_clean, proxy_offline[n_tr:]])
# Live inference at t_obs: post-outcome column is identically 0.0 (unobserved!)
X_te_leak_live = np.column_stack([X_te_clean, np.zeros(n_te, dtype=np.float64)])
y_tr, y_te = y[:n_tr], y[n_tr:]
clean_clf = fit_ridge_logistic_classifier(X_tr_clean, y_tr, l2_alpha=1.0)
leaky_clf = fit_ridge_logistic_classifier(X_tr_leak, y_tr, l2_alpha=1.0)
clean_auc = compute_roc_auc(y_te, clean_clf.predict_proba(X_te_clean))
clean_pr = compute_pr_auc(y_te, clean_clf.predict_proba(X_te_clean))
leak_offline_auc = compute_roc_auc(y_te, leaky_clf.predict_proba(X_te_leak_offline))
leak_offline_pr = compute_pr_auc(y_te, leaky_clf.predict_proba(X_te_leak_offline))
leak_live_probs = leaky_clf.predict_proba(X_te_leak_live)
leak_live_auc = compute_roc_auc(y_te, leak_live_probs)
leak_live_pr = compute_pr_auc(y_te, leak_live_probs)
names = [f"pre_feat_{j}" for j in range(6)] + ["refund_issued_proxy"]
dom_canary = probe_single_feature_dominance(X_tr_leak, y_tr, feature_names=names, dominance_threshold=0.85)
c2st_live = run_oof_c2st_canary(X_tr_leak, X_te_leak_live, feature_names=names, quadratic=True, seed=seed)
return {
"clean_oot_roc_auc": clean_auc,
"clean_oot_pr_auc": clean_pr,
"leaky_offline_roc_auc": leak_offline_auc,
"leaky_offline_pr_auc": leak_offline_pr,
"leaky_live_roc_auc": leak_live_auc,
"leaky_live_pr_auc": leak_live_pr,
"leaky_live_mean_prob": float(np.mean(leak_live_probs)),
"true_test_prevalence": float(np.mean(y_te)),
"dominance_canary": dom_canary,
"c2st_offline_vs_live_auc": c2st_live["auc_adv"],
}
def audit_class2_temporal_and_maturity_leakage(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 2: Overlapping horizon random split leak + right-censored label-maturity truncation."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
# Part A: Overlapping H=10 white-noise return target (true OOT predictability = 0.0 / AUC = 0.50)
n_ts = 1000 if quick else 2000
horizon = 10
innov = rng.normal(0.0, 1.0, size=n_ts + horizon)
cum_ret = np.array([float(np.sum(innov[t : t + horizon])) for t in range(n_ts)])
y_ts = (cum_ret > 0.0).astype(np.int64)
# Time index + smooth cumulative state proxies (zero future causality; local in time!)
t_idx = np.arange(n_ts, dtype=np.float64) / float(n_ts)
price_level = np.cumsum(innov[:n_ts])
X_ts = np.column_stack(
[
t_idx,
price_level,
np.sin(2.0 * math.pi * t_idx * 4.0) + rng.normal(0.0, 0.02, size=n_ts),
]
)
# Random K-Fold leaks adjacent overlapping t +/- 1 rows into kNN
rng_perm = rng.permutation(n_ts)
split_cut = int(0.8 * n_ts)
tr_r, te_r = rng_perm[:split_cut], rng_perm[split_cut:]
rand_probs = fit_predict_knn_proba(X_ts[tr_r], y_ts[tr_r], X_ts[te_r], k=3)
random_split_auc = compute_roc_auc(y_ts[te_r], rand_probs)
# Purged chronological split (gap >= horizon)
purge_end = split_cut - horizon
purged_probs = fit_predict_knn_proba(X_ts[:purge_end], y_ts[:purge_end], X_ts[split_cut:], k=3)
purged_oot_auc = compute_roc_auc(y_ts[split_cut:], purged_probs)
# Part B: Delayed chargeback label-maturity truncation (horizon = 60 days, snapshot = day 90)
n_hist = 6000 if quick else 12000
n_mature_test = 2500 if quick else 5000
X_tr = rng.normal(0.0, 1.0, size=(n_hist, 5))
obs_day = rng.uniform(0.0, 90.0, size=n_hist)
eval_cutoff = 90.0
mat_horizon = 60.0
logits_h = -3.15 + 1.15 * X_tr[:, 0] - 0.85 * X_tr[:, 1] + 0.55 * X_tr[:, 2]
y_true_hist = (rng.uniform(size=n_hist) < np.asarray(stable_sigmoid(logits_h))).astype(np.int64)
# Gamma-like dispute arrival times (shape=3, scale=10 -> mean ~30d, ~94% by 60d)
arrival_delay = rng.gamma(shape=3.0, scale=10.0, size=n_hist)
cens_age = eval_cutoff - obs_day
y_obs_trunc = np.where((y_true_hist == 1) & (arrival_delay <= np.minimum(mat_horizon, cens_age)), 1, 0)
# Mature out-of-time test set (all observed >= 60d before snapshot)
X_mtest = rng.normal(0.0, 1.0, size=(n_mature_test, 5))
logits_mt = -3.15 + 1.15 * X_mtest[:, 0] - 0.85 * X_mtest[:, 1] + 0.55 * X_mtest[:, 2]
y_mtest = (rng.uniform(size=n_mature_test) < np.asarray(stable_sigmoid(logits_mt))).astype(np.int64)
naive_clf = fit_ridge_logistic_classifier(X_tr, y_obs_trunc, l2_alpha=1.0)
naive_pred = naive_clf.predict_proba(X_mtest)
mature_mask = cens_age >= mat_horizon
purged_clf = fit_ridge_logistic_classifier(X_tr[mature_mask], y_obs_trunc[mature_mask], l2_alpha=1.0)
purged_pred = purged_clf.predict_proba(X_mtest)
true_prev = float(np.mean(y_mtest))
naive_mean_pred = float(np.mean(naive_pred))
purged_mean_pred = float(np.mean(purged_pred))
maturity_canary = run_duplicate_nndr_and_asof_canaries(
X_tr[:500],
X_mtest[:500],
obs_ts=obs_day,
label_horizon=mat_horizon,
eval_cutoff=eval_cutoff,
y_obs=y_obs_trunc,
)
return {
"overlap_random_split_auc": random_split_auc,
"overlap_purged_oot_auc": purged_oot_auc,
"naive_0d_obs_train_prev": float(np.mean(y_obs_trunc)),
"purged_60d_obs_train_prev": float(np.mean(y_obs_trunc[mature_mask])),
"mature_test_true_prev": true_prev,
"naive_0d_mean_pred": naive_mean_pred,
"purged_60d_mean_pred": purged_mean_pred,
"naive_relative_bias": float((naive_mean_pred - true_prev) / max(true_prev, 1e-9)),
"purged_relative_bias": float((purged_mean_pred - true_prev) / max(true_prev, 1e-9)),
"maturity_violation_rate": maturity_canary["maturity_violation_rate"],
"immature_vs_mature_prev_ratio": maturity_canary["immature_vs_mature_prev_ratio"],
}
def audit_class3_smote_and_preproc_before_cv(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 3: SMOTE-before-CV cross-fold contamination + Full-TE caught by Permutation Null Canary."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n = 1800 if quick else 3500
d = 10
X = rng.normal(0.0, 1.0, size=(n, d))
logits = -3.65 + 0.95 * X[:, 0] - 0.70 * X[:, 1] + 0.45 * X[:, 2]
y = (rng.uniform(size=n) < np.asarray(stable_sigmoid(logits))).astype(np.int64)
pi_true = float(np.mean(y))
# 1. Leaky SMOTE BEFORE 5-fold CV (7-NN)
X_sm_all, y_sm_all = apply_smote_oversampling(X, y, target_ratio=1.0, k_neighbors=5, seed=seed)
folds_sm = stratified_kfold_indices(y_sm_all, n_folds=5, seed=seed)
oof_sm_before = np.empty(len(y_sm_all), dtype=np.float64)
for tr_i, va_i in folds_sm:
oof_sm_before[va_i] = fit_predict_knn_proba(X_sm_all[tr_i], y_sm_all[tr_i], X_sm_all[va_i], k=7)
smote_before_cv_auc = compute_roc_auc(y_sm_all, oof_sm_before)
smote_before_cv_pr = compute_pr_auc(y_sm_all, oof_sm_before)
# 2. Fold-Internal SMOTE (clean val untouched, uncalibrated vs Bayes prior offset)
folds_clean = stratified_kfold_indices(y, n_folds=5, seed=seed)
oof_sm_inside = np.empty(n, dtype=np.float64)
oof_sm_offset = np.empty(n, dtype=np.float64)
oof_clean_logreg = np.empty(n, dtype=np.float64)
for fold_idx, (tr_i, va_i) in enumerate(folds_clean):
X_tr_sm, y_tr_sm = apply_smote_oversampling(X[tr_i], y[tr_i], target_ratio=1.0, k_neighbors=5, seed=seed + fold_idx + 1)
p_raw_sm = fit_predict_knn_proba(X_tr_sm, y_tr_sm, X[va_i], k=7)
oof_sm_inside[va_i] = p_raw_sm
pi_tr_sm = float(np.mean(y_tr_sm))
log_offset = math.log((pi_true * (1.0 - pi_tr_sm)) / max((1.0 - pi_true) * pi_tr_sm, 1e-12))
oof_sm_offset[va_i] = np.asarray(stable_sigmoid(logit_from_proba(p_raw_sm) + log_offset), dtype=np.float64)
clf_clean = fit_ridge_logistic_classifier(X[tr_i], y[tr_i], l2_alpha=2.0)
oof_clean_logreg[va_i] = clf_clean.predict_proba(X[va_i])
smote_inside_auc = compute_roc_auc(y, oof_sm_inside)
smote_inside_pr = compute_pr_auc(y, oof_sm_inside)
clean_logreg_auc = compute_roc_auc(y, oof_clean_logreg)
clean_logreg_pr = compute_pr_auc(y, oof_clean_logreg)
# Check NNDR on fold 0 SMOTE-before-CV vs clean fold 0
tr0_sm, va0_sm = folds_sm[0]
nndr_smote_before = run_duplicate_nndr_and_asof_canaries(X_sm_all[tr0_sm], X_sm_all[va0_sm])
tr0_cl, va0_cl = folds_clean[0]
nndr_clean = run_duplicate_nndr_and_asof_canaries(X[tr0_cl], X[va0_cl])
# 3. High-cardinality Target Encoding under Permutation Null Canary
n_te_demo = 1200 if quick else 2400
n_cats = 400 if quick else 500
X_cat_num = rng.normal(0.0, 1.0, size=(n_te_demo, 3))
cat_ids = rng.integers(0, n_cats, size=n_te_demo)
y_te_demo = (rng.uniform(size=n_te_demo) < np.asarray(stable_sigmoid(-1.8 + 0.7 * X_cat_num[:, 0]))).astype(np.int64)
def _leaky_te_pipeline(X_mat: np.ndarray, y_vec: np.ndarray) -> float:
te_col = apply_naive_target_encoding(cat_ids, y_vec, smoothing_m=2.0)
X_full = np.column_stack([X_mat, te_col])
f_list = stratified_kfold_indices(y_vec, n_folds=5, seed=seed)
oof_p = np.empty(len(y_vec), dtype=np.float64)
for tr_k, va_k in f_list:
m = fit_ridge_logistic_classifier(X_full[tr_k], y_vec[tr_k], l2_alpha=2.0)
oof_p[va_k] = m.predict_proba(X_full[va_k])
return compute_roc_auc(y_vec, oof_p)
def _clean_te_pipeline(X_mat: np.ndarray, y_vec: np.ndarray) -> float:
f_list = stratified_kfold_indices(y_vec, n_folds=5, seed=seed)
oof_p = np.empty(len(y_vec), dtype=np.float64)
for fold_k, (tr_k, va_k) in enumerate(f_list):
_, te_va = apply_oof_target_encoding(cat_ids[tr_k], y_vec[tr_k], cat_ids[va_k], n_folds=4, smoothing_m=5.0, seed=seed + fold_k)
te_tr, _ = apply_oof_target_encoding(cat_ids[tr_k], y_vec[tr_k], None, n_folds=4, smoothing_m=5.0, seed=seed + fold_k)
X_tr_f = np.column_stack([X_mat[tr_k], te_tr])
X_va_f = np.column_stack([X_mat[va_k], te_va])
m = fit_ridge_logistic_classifier(X_tr_f, y_vec[tr_k], l2_alpha=2.0)
oof_p[va_k] = m.predict_proba(X_va_f)
return compute_roc_auc(y_vec, oof_p)
n_perm = 12 if quick else 30
perm_leaky_te = run_permutation_null_canary(_leaky_te_pipeline, X_cat_num, y_te_demo, n_permutations=n_perm, seed=seed)
perm_clean_te = run_permutation_null_canary(_clean_te_pipeline, X_cat_num, y_te_demo, n_permutations=n_perm, seed=seed)
return {
"true_prevalence": pi_true,
"smote_before_cv_roc_auc": smote_before_cv_auc,
"smote_before_cv_pr_auc": smote_before_cv_pr,
"smote_inside_cv_roc_auc": smote_inside_auc,
"smote_inside_cv_pr_auc": smote_inside_pr,
"smote_inside_mean_pred_unadjusted": float(np.mean(oof_sm_inside)),
"smote_inside_mean_pred_bayes_offset": float(np.mean(oof_sm_offset)),
"clean_logreg_roc_auc": clean_logreg_auc,
"clean_logreg_pr_auc": clean_logreg_pr,
"smote_before_cv_near_dup_rate": nndr_smote_before["near_dup_rate"],
"smote_before_cv_median_prox": nndr_smote_before["median_prox_ratio"],
"clean_cv_median_prox": nndr_clean["median_prox_ratio"],
"perm_leaky_te_null_mean_auc": perm_leaky_te["null_mean"],
"perm_leaky_te_detected": perm_leaky_te["pipeline_leakage_detected"],
"perm_clean_te_null_mean_auc": perm_clean_te["null_mean"],
"perm_clean_te_detected": perm_clean_te["pipeline_leakage_detected"],
}
def audit_class4_group_overlap_leakage(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 4: Repeated entity/borrower snapshots split randomly vs GroupKFold."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n_groups = 180 if quick else 360
obs_per_group = 8
n = n_groups * obs_per_group
groups = np.repeat(np.arange(n_groups), obs_per_group)
# Static entity fingerprint + strong random effect u_g
static_sig = rng.normal(0.0, 1.0, size=(n_groups, 4))
u_g = rng.normal(0.0, 3.0, size=n_groups)
X_static = np.repeat(static_sig, obs_per_group, axis=0) + rng.normal(0.0, 0.04, size=(n, 4))
X_dyn = rng.normal(0.0, 1.0, size=(n, 2))
X = np.hstack([X_static, 0.15 * X_dyn])
logits = -1.6 + np.repeat(u_g, obs_per_group) + 0.55 * X_dyn[:, 0]
y = (rng.uniform(size=n) < np.asarray(stable_sigmoid(logits))).astype(np.int64)
# Leaky Random/Stratified K-Fold (entity overlaps train/val)
folds_rand = stratified_kfold_indices(y, n_folds=5, seed=seed)
oof_rand = np.empty(n, dtype=np.float64)
for tr_i, va_i in folds_rand:
oof_rand[va_i] = fit_predict_knn_proba(X[tr_i], y[tr_i], X[va_i], k=1)
# Clean GroupKFold (zero borrower overlap)
folds_grp = group_kfold_indices(groups, n_folds=5, seed=seed)
oof_grp = np.empty(n, dtype=np.float64)
group_overlap_counts = []
for tr_i, va_i in folds_grp:
oof_grp[va_i] = fit_predict_knn_proba(X[tr_i], y[tr_i], X[va_i], k=1)
group_overlap_counts.append(len(set(groups[tr_i].tolist()) & set(groups[va_i].tolist())))
return {
"random_kfold_roc_auc": compute_roc_auc(y, oof_rand),
"random_kfold_pr_auc": compute_pr_auc(y, oof_rand),
"group_kfold_roc_auc": compute_roc_auc(y, oof_grp),
"group_kfold_pr_auc": compute_pr_auc(y, oof_grp),
"group_kfold_overlap_count": int(max(group_overlap_counts)),
}
def audit_class5_duplicate_leakage(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 5: Exact/near-duplicate records defeat C2ST (AUC ~ 0.50) while SHA-256 & NNDR catch 100%."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n_base = 800 if quick else 1600
d = 6
X_base = rng.normal(0.0, 1.0, size=(n_base, d))
y_base = (rng.uniform(size=n_base) < np.asarray(stable_sigmoid(-0.5 + 0.8 * X_base[:, 0] - 0.6 * X_base[:, 1]))).astype(
np.int64
)
# Clone 35% of base rows as exact + 10% as tiny-jitter near duplicates, then random split
n_exact = int(0.35 * n_base)
n_near = int(0.15 * n_base)
idx_ex = rng.choice(n_base, size=n_exact, replace=False)
idx_nr = rng.choice(n_base, size=n_near, replace=False)
X_all = np.vstack([X_base, X_base[idx_ex], X_base[idx_nr] + rng.normal(0.0, 0.01, size=(n_near, d))])
y_all = np.concatenate([y_base, y_base[idx_ex], y_base[idx_nr]])
perm = rng.permutation(len(X_all))
cut = int(0.7 * len(X_all))
tr_idx, te_idx = perm[:cut], perm[cut:]
X_tr, y_tr = X_all[tr_idx], y_all[tr_idx]
X_te, y_te = X_all[te_idx], y_all[te_idx]
# 1-NN / 3-NN memorizes leaked duplicates across splits
p_dup = fit_predict_knn_proba(X_tr, y_tr, X_te, k=1)
dup_test_auc = compute_roc_auc(y_te, p_dup)
# Clean deduplicated split (strictly disjoint base rows)
clean_cut = int(0.7 * n_base)
p_clean = fit_predict_knn_proba(X_base[:clean_cut], y_base[:clean_cut], X_base[clean_cut:], k=1)
clean_test_auc = compute_roc_auc(y_base[clean_cut:], p_clean)
# Run C2ST (blind!) vs SHA-256 + NNDR (catches exact & near duplicates!)
c2st_dup = run_oof_c2st_canary(X_tr, X_te, quadratic=True, seed=seed)
nndr_dup = run_duplicate_nndr_and_asof_canaries(X_tr, X_te, nndr_threshold=0.20, near_cos_threshold=0.995)
nndr_clean = run_duplicate_nndr_and_asof_canaries(
X_base[:clean_cut], X_base[clean_cut:], nndr_threshold=0.20, near_cos_threshold=0.995
)
return {
"dup_split_1nn_roc_auc": dup_test_auc,
"clean_dedup_1nn_roc_auc": clean_test_auc,
"c2st_dup_auc_blind": c2st_dup["auc_adv"],
"dup_exact_hash_rate": nndr_dup["exact_dup_rate"],
"dup_near_dup_rate": nndr_dup["near_dup_rate"],
"dup_p05_prox_ratio": nndr_dup["p05_prox_ratio"],
"clean_exact_hash_rate": nndr_clean["exact_dup_rate"],
"clean_p05_prox_ratio": nndr_clean["p05_prox_ratio"],
}
def audit_class6_feature_store_asof_skew(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Class 6: Bitemporal ASOF violation & SCD-1 variance backfill caught by quadratic C2ST/E-C2ST."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n_tr = 1400 if quick else 2800
n_te = 1000 if quick else 2000
# Clean features observed strictly before decision obs_ts
X_tr_clean = rng.normal(0.0, 1.0, size=(n_tr, 4))
X_te_live = rng.normal(0.0, 1.0, size=(n_te, 4))
y_tr = (rng.uniform(size=n_tr) < np.asarray(stable_sigmoid(-1.5 + 0.8 * X_tr_clean[:, 0] - 0.6 * X_tr_clean[:, 1]))).astype(
np.int64
)
y_te = (rng.uniform(size=n_te) < np.asarray(stable_sigmoid(-1.5 + 0.8 * X_te_live[:, 0] - 0.6 * X_te_live[:, 1]))).astype(
np.int64
)
# SCD-1 backfill in offline feature store: column 3 gets zero-mean, high-variance post-event signal
# (Matched mean = 0 tricks linear C2ST, while quadratic C2ST & ASOF timestamps catch it immediately!)
backfill_tr = np.where(y_tr == 1, 2.4, -2.4 * (np.mean(y_tr) / max(1.0 - np.mean(y_tr), 1e-6))) + rng.normal(
0.0, 0.35, size=n_tr
)
backfill_tr = (backfill_tr - np.mean(backfill_tr)) * 2.2 # zero-mean variance inflation + target leak
X_tr_backfill = np.column_stack([X_tr_clean, backfill_tr])
# Live serving at t_obs only sees stationary zero-mean unit-variance pre-event tier
X_te_backfill_live = np.column_stack([X_te_live, rng.normal(0.0, 0.4, size=n_te)])
# Offline val if backfilled looks artificially great
backfill_te_offline = np.where(y_te == 1, 2.4, -2.4 * (np.mean(y_te) / max(1.0 - np.mean(y_te), 1e-6))) + rng.normal(
0.0, 0.35, size=n_te
)
backfill_te_offline = (backfill_te_offline - np.mean(backfill_te_offline)) * 2.2
X_te_backfill_offline = np.column_stack([X_te_live, backfill_te_offline])
obs_ts = np.arange(n_tr, dtype=np.float64) * 60.0
feat_ts_mat = np.repeat(obs_ts[:, None], 5, axis=1) - 10.0
# Backfilled column 4 materialized AFTER obs_ts (+3600s late!)
feat_ts_mat[:, 4] = obs_ts + 3600.0
clf_backfill = fit_ridge_logistic_classifier(X_tr_backfill, y_tr, l2_alpha=1.0)
clf_clean = fit_ridge_logistic_classifier(X_tr_clean, y_tr, l2_alpha=1.0)
names = ["tx_vel", "amt_z", "acct_age", "device_rep", "risk_tier_backfilled"]
c2st_linear = run_oof_c2st_canary(X_tr_backfill, X_te_backfill_live, feature_names=names, quadratic=False, seed=seed)
c2st_quad = run_oof_c2st_canary(X_tr_backfill, X_te_backfill_live, feature_names=names, quadratic=True, seed=seed)
ec2st = compute_ec2st_supermartingale(X_tr_backfill, X_te_backfill_live, batch_size=100, quadratic=True, seed=seed)
asof_audit = run_duplicate_nndr_and_asof_canaries(
X_tr_backfill[:400], X_te_backfill_live[:400], obs_ts=obs_ts[:400], feat_ts_matrix=feat_ts_mat[:400], sla_lag=0.0
)
return {
"backfill_offline_roc_auc": compute_roc_auc(y_te, clf_backfill.predict_proba(X_te_backfill_offline)),
"backfill_live_roc_auc": compute_roc_auc(y_te, clf_backfill.predict_proba(X_te_backfill_live)),
"clean_pit_roc_auc": compute_roc_auc(y_te, clf_clean.predict_proba(X_te_live)),
"linear_c2st_auc": c2st_linear["auc_adv"],
"quadratic_c2st_auc": c2st_quad["auc_adv"],
"ec2st_final_wealth": ec2st["final_wealth"],
"ec2st_rejected": ec2st["rejected"],
"asof_violation_rate": asof_audit["asof_violation_rate"],
}
def make_leakage_audit_dataframe(results: dict[str, Any]) -> pd.DataFrame:
"""Summarize the 6-class leakage audit metrics cleanly into a Pandas DataFrame."""
rows = [
{
"leakage_class": "Class 1: Target Proxy",
"apparent_auc": results["class1"]["leaky_offline_roc_auc"],
"clean_or_live_auc": results["class1"]["leaky_live_roc_auc"],
"canary_signal": f"1D AUC={results['class1']['dominance_canary']['max_sym_auc_1d']:.3f}",
},
{
"leakage_class": "Class 2: Temporal + Maturity",
"apparent_auc": results["class2"]["overlap_random_split_auc"],
"clean_or_live_auc": results["class2"]["overlap_purged_oot_auc"],
"canary_signal": f"MatBias={results['class2']['naive_relative_bias']*100:.1f}%",
},
{
"leakage_class": "Class 3: SMOTE-before-CV",
"apparent_auc": results["class3"]["smote_before_cv_pr_auc"],
"clean_or_live_auc": results["class3"]["clean_logreg_pr_auc"],
"canary_signal": f"NullTE={results['class3']['perm_leaky_te_null_mean_auc']:.3f}",
},
{
"leakage_class": "Class 4: Group Overlap",
"apparent_auc": results["class4"]["random_kfold_roc_auc"],
"clean_or_live_auc": results["class4"]["group_kfold_roc_auc"],
"canary_signal": "GroupOverlap=0 (clean)",
},
{
"leakage_class": "Class 5: Exact/Near Dup",
"apparent_auc": results["class5"]["dup_split_1nn_roc_auc"],
"clean_or_live_auc": results["class5"]["clean_dedup_1nn_roc_auc"],
"canary_signal": f"Hash={results['class5']['dup_exact_hash_rate']*100:.1f}% (C2ST={results['class5']['c2st_dup_auc_blind']:.2f})",
},
{
"leakage_class": "Class 6: ASOF Backfill",
"apparent_auc": results["class6"]["backfill_offline_roc_auc"],
"clean_or_live_auc": results["class6"]["backfill_live_roc_auc"],
"canary_signal": f"QuadC2ST={results['class6']['quadratic_c2st_auc']:.3f}",
},
]
return pd.DataFrame(rows)
"""Proper scoring rules, calibration diagnostics (ECE/ACE/Debiased/smECE*), classical calibrators, and O(m log m) Inductive/Cross Venn-Abers predictors."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from eval_calibration_lab.leakage_auditor import (
compute_roc_auc,
logit_from_proba,
stable_sigmoid,
stratified_kfold_indices,
)
class CalibratorConfig(BaseModel):
"""Strict configuration for post-hoc probability calibration."""
model_config = ConfigDict(frozen=True, extra="forbid")
eps: float = Field(default=1e-7, gt=0.0, lt=0.1)
max_iter: int = Field(default=60, ge=5, le=500)
tol: float = Field(default=1e-10, gt=0.0, lt=1e-2)
n_bins: int = Field(default=15, ge=2, le=100)
# ---------------------------------------------------------------------------
# Strictly Proper Scoring Rules & Calibration Diagnostics
# ---------------------------------------------------------------------------
def compute_log_loss(
y_true: np.ndarray,
y_prob: np.ndarray,
eps: float = 1e-12,
) -> float:
"""Binary or multiclass negative log-likelihood (strictly proper)."""
p = np.asarray(y_prob, dtype=np.float64)
if p.ndim == 1:
y = np.asarray(y_true, dtype=np.float64)
pc = np.clip(p, eps, 1.0 - eps)
return float(-np.mean(y * np.log(pc) + (1.0 - y) * np.log(1.0 - pc)))
y_idx = np.asarray(y_true, dtype=np.int64)
pc = np.clip(p, eps, 1.0)
pc = pc / np.sum(pc, axis=1, keepdims=True)
chosen = pc[np.arange(len(y_idx)), y_idx]
return float(-np.mean(np.log(np.clip(chosen, eps, 1.0))))
def compute_spherical_score(
y_true: np.ndarray,
y_prob: np.ndarray,
eps: float = 1e-12,
) -> float:
"""Positive-oriented strictly proper Spherical Score p_y / ||p||_2."""
p = np.asarray(y_prob, dtype=np.float64)
if p.ndim == 1:
y = np.asarray(y_true, dtype=np.int64)
pc = np.clip(p, eps, 1.0 - eps)
p_mat = np.column_stack([1.0 - pc, pc])
else:
y = np.asarray(y_true, dtype=np.int64)
p_mat = np.clip(p, eps, 1.0)
p_mat = p_mat / np.sum(p_mat, axis=1, keepdims=True)
norms = np.linalg.norm(p_mat, axis=1)
p_y = p_mat[np.arange(len(y)), y]
return float(np.mean(p_y / np.maximum(norms, eps)))
def compute_brier_and_murphy(
y_true: np.ndarray,
y_prob: np.ndarray,
n_bins: int = 15,
) -> dict[str, float]:
"""Binary Brier score plus exact Murphy (1973) REL - RES + UNC decomposition."""
y = np.asarray(y_true, dtype=np.float64)
p = np.clip(np.asarray(y_prob, dtype=np.float64), 0.0, 1.0)
n = float(len(y))
brier_exact = float(np.mean((p - y) ** 2))
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.clip(np.digitize(p, edges[1:-1], right=True), 0, n_bins - 1)
y_bar = float(np.mean(y))
uncertainty = y_bar * (1.0 - y_bar)
p_binned = np.empty_like(p)
rel = 0.0
res = 0.0
for b in range(n_bins):
mask = bin_ids == b
nb = int(np.sum(mask))
if nb == 0:
continue
pb_bar = float(np.mean(p[mask]))
yb_bar = float(np.mean(y[mask]))
p_binned[mask] = pb_bar
w_b = float(nb) / n
rel += w_b * ((pb_bar - yb_bar) ** 2)
res += w_b * ((yb_bar - y_bar) ** 2)
brier_binned = float(np.mean((p_binned - y) ** 2))
within_bin_residual = brier_exact - brier_binned
return {
"brier_score": brier_exact,
"brier_binned": brier_binned,
"reliability": float(rel),
"resolution": float(res),
"uncertainty": float(uncertainty),
"within_bin_residual": float(within_bin_residual),
}
def _compute_smooth_ece_fixed_point(
y: np.ndarray,
p: np.ndarray,
grid_size: int = 201,
n_bisect: int = 24,
) -> float:
"""Hyperparameter-free SmoothECE (smECE*) fixed point via reflected Gaussian kernel."""
p_row = p[None, :]
res_row = (y - p)[None, :]
def _smece_at_sigma(sigma: float) -> float:
# Adaptive quadrature grid prevents Nyquist aliasing when sigma < 0.005 (dt <= sigma / 4)
eff_grid_size = max(grid_size, min(4001, math.ceil(4.0 / max(sigma, 1e-4)) + 1))
t_grid = np.linspace(0.0, 1.0, eff_grid_size, dtype=np.float64)
inv_2s2 = 0.5 / (sigma * sigma)
norm_const = 1.0 / (math.sqrt(2.0 * math.pi) * sigma)
smooth_res = np.empty(eff_grid_size, dtype=np.float64)
chunk_sz = 256
for start in range(0, eff_grid_size, chunk_sz):
t_blk = t_grid[start : start + chunk_sz, None]
d0 = t_blk - p_row
d1 = t_blk + p_row
d2 = 2.0 - t_blk - p_row
k_refl = norm_const * (
np.exp(-(d0 * d0) * inv_2s2)
+ np.exp(-(d1 * d1) * inv_2s2)
+ np.exp(-(d2 * d2) * inv_2s2)
)
smooth_res[start : start + chunk_sz] = np.abs(np.mean(res_row * k_refl, axis=1))
dt = 1.0 / float(eff_grid_size - 1)
return float(np.sum(0.5 * (smooth_res[:-1] + smooth_res[1:]) * dt))
lo = 1e-4
hi = 1.0
for _ in range(n_bisect):
mid = 0.5 * (lo + hi)
if _smece_at_sigma(mid) > mid:
lo = mid
else:
hi = mid
return float(0.5 * (lo + hi))
def _fit_logistic_2d_unsmoothed(scores: np.ndarray, y: np.ndarray, max_iter: int = 40) -> tuple[float, float]:
"""Fit Cox logistic recalibration logit(P(Y=1)) = alpha + slope * score."""
s = np.asarray(scores, dtype=np.float64)
yf = np.asarray(y, dtype=np.float64)
a, b = 1.0, 0.0
for _ in range(max_iter):
eta = np.clip(a * s + b, -30.0, 30.0)
q = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(q * (1.0 - q), 1e-10)
diff = q - yf
g0 = float(np.sum(diff * s)) + 1e-8 * (a - 1.0)
g1 = float(np.sum(diff)) + 1e-8 * b
h00 = float(np.sum(w * s * s)) + 1e-6
h01 = float(np.sum(w * s))
h11 = float(np.sum(w)) + 1e-6
det = h00 * h11 - h01 * h01
if abs(det) < 1e-15:
break
da = (h11 * g0 - h01 * g1) / det
db = (-h01 * g0 + h00 * g1) / det
a -= da
b -= db
if max(abs(da), abs(db)) < 1e-10:
break
return float(a), float(b)
def _fit_citl_intercept(logits: np.ndarray, y: np.ndarray, max_iter: int = 35) -> float:
"""Solve sum(sigma(z_i + alpha)) = sum(y_i) for Calibration-in-the-Large intercept."""
z = np.asarray(logits, dtype=np.float64)
y_sum = float(np.sum(y))
alpha = 0.0
for _ in range(max_iter):
q = np.asarray(stable_sigmoid(np.clip(z + alpha, -30.0, 30.0)), dtype=np.float64)
grad = float(np.sum(q)) - y_sum
hess = float(np.sum(np.maximum(q * (1.0 - q), 1e-10))) + 1e-9
step = grad / hess
alpha -= step
if abs(step) < 1e-10:
break
return float(alpha)
def compute_calibration_diagnostics(
y_true: np.ndarray,
y_prob: np.ndarray,
n_bins: int = 15,
include_smoothece: bool = True,
) -> dict[str, Any]:
"""Comprehensive calibration diagnostics: ECE, ACE, MCE, Debiased L2-CE, smECE*, CITL, Slope."""
y = np.asarray(y_true, dtype=np.float64)
p = np.clip(np.asarray(y_prob, dtype=np.float64), 1e-7, 1.0 - 1e-7)
n = float(len(y))
# 1. Equal-width ECE & reliability diagram arrays
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.clip(np.digitize(p, edges[1:-1], right=True), 0, n_bins - 1)
ece = 0.0
mce_ece = 0.0
ew_bins: list[dict[str, float | int]] = []
for b in range(n_bins):
mask = bin_ids == b
nb = int(np.sum(mask))
if nb == 0:
continue
pb = float(np.mean(p[mask]))
yb = float(np.mean(y[mask]))
err = abs(yb - pb)
ece += (float(nb) / n) * err
mce_ece = max(mce_ece, err)
ew_bins.append({"bin": b, "count": nb, "mean_pred": pb, "mean_true": yb})
# 2. Equal-mass Adaptive Calibration Error (ACE) & Kumar et al. Debiased L2-CE
order = np.argsort(p, kind="mergesort")
chunks = np.array_split(order, min(n_bins, len(order)))
ace_errs: list[float] = []
debiased_ce2 = 0.0
for idx_chunk in chunks:
nb = len(idx_chunk)
if nb == 0:
continue
pb = float(np.mean(p[idx_chunk]))
yb = float(np.mean(y[idx_chunk]))
ace_errs.append(abs(yb - pb))
sq_term = (yb - pb) ** 2
if nb >= 2:
sq_term -= (yb * (1.0 - yb)) / float(nb - 1)
debiased_ce2 += (float(nb) / n) * sq_term
ace = float(np.mean(ace_errs)) if ace_errs else 0.0
mce_ace = float(np.max(ace_errs)) if ace_errs else 0.0
debiased_ce = math.sqrt(max(0.0, debiased_ce2))
logits = logit_from_proba(p, eps=1e-7)
cal_slope, cal_intercept = _fit_logistic_2d_unsmoothed(logits, y)
citl_alpha = _fit_citl_intercept(logits, y)
murphy = compute_brier_and_murphy(y, p, n_bins=n_bins)
sm_ece = _compute_smooth_ece_fixed_point(y, p) if include_smoothece else float("nan")
return {
"log_loss": compute_log_loss(y, p),
"brier_score": murphy["brier_score"],
"reliability": murphy["reliability"],
"resolution": murphy["resolution"],
"uncertainty": murphy["uncertainty"],
"spherical_score": compute_spherical_score(y, p),
"ece": float(ece),
"ace": ace,
"mce_ece": float(mce_ece),
"mce_ace": mce_ace,
"debiased_l2_ce2": float(debiased_ce2),
"debiased_l2_ce": float(debiased_ce),
"smooth_ece": float(sm_ece),
"citl_alpha": citl_alpha,
"calibration_slope": cal_slope,
"calibration_intercept": cal_intercept,
"mean_pred": float(np.mean(p)),
"prevalence": float(np.mean(y)),
"roc_auc": compute_roc_auc(y, p),
"reliability_bins": ew_bins,
}
# ---------------------------------------------------------------------------
# Pure-NumPy Post-Hoc Calibrators (JSON State-Dict Serializable, Zero Pickle)
# ---------------------------------------------------------------------------
class TemperatureScalingCalibrator:
"""Single-parameter Temperature Scaling sigma(z/T) or softmax(Z/T) preserving rank & Top-1."""
def __init__(self, eps: float = 1e-7, max_iter: int = 40, tol: float = 1e-10) -> None:
self.eps = eps
self.max_iter = max_iter
self.tol = tol
self.temperature_: float = 1.0
self.multiclass_: bool = False
def _to_logits(self, scores: np.ndarray, scores_are_logits: bool) -> np.ndarray:
arr = np.asarray(scores, dtype=np.float64)
if arr.ndim == 2:
if scores_are_logits:
return arr
pc = np.clip(arr, self.eps, 1.0)
return np.log(pc)
if scores_are_logits:
return arr
return logit_from_proba(arr, eps=self.eps)
def fit(self, scores: np.ndarray, y: np.ndarray, scores_are_logits: bool = False) -> TemperatureScalingCalibrator:
z = self._to_logits(scores, scores_are_logits)
self.multiclass_ = z.ndim == 2
beta = 1.0 # inverse temperature 1/T
if not self.multiclass_:
yf = np.asarray(y, dtype=np.float64)
for _ in range(self.max_iter):
eta = np.clip(beta * z, -30.0, 30.0)
q = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(q * (1.0 - q), 1e-12)
grad = float(np.mean((q - yf) * z))
hess = float(np.mean(w * z * z)) + 1e-9
step = grad / hess
beta_new = float(np.clip(beta - step, 0.02, 20.0))
if abs(beta_new - beta) < self.tol:
beta = beta_new
break
beta = beta_new
else:
y_idx = np.asarray(y, dtype=np.int64)
n = len(y_idx)
for _ in range(self.max_iter):
scaled = beta * z
scaled -= np.max(scaled, axis=1, keepdims=True)
exp_s = np.exp(scaled)
probs = exp_s / np.sum(exp_s, axis=1, keepdims=True)
ez = np.sum(probs * z, axis=1)
ez2 = np.sum(probs * (z * z), axis=1)
var_z = np.maximum(ez2 - ez * ez, 0.0)
z_true = z[np.arange(n), y_idx]
grad = float(np.mean(ez - z_true))
hess = float(np.mean(var_z)) + 1e-9
step = grad / hess
beta_new = float(np.clip(beta - step, 0.02, 20.0))
if abs(beta_new - beta) < self.tol:
beta = beta_new
break
beta = beta_new
self.temperature_ = float(1.0 / beta)
return self
def predict_proba(self, scores: np.ndarray, scores_are_logits: bool = False) -> np.ndarray:
z = self._to_logits(scores, scores_are_logits) / self.temperature_
if z.ndim == 2:
z_shift = z - np.max(z, axis=1, keepdims=True)
exp_z = np.exp(z_shift)
return exp_z / np.sum(exp_z, axis=1, keepdims=True)
return np.asarray(stable_sigmoid(z), dtype=np.float64)
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "temperature",
"temperature": float(self.temperature_),
"multiclass": bool(self.multiclass_),
"eps": float(self.eps),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> TemperatureScalingCalibrator:
obj = cls(eps=float(state["eps"]))
obj.temperature_ = float(state["temperature"])
obj.multiclass_ = bool(state["multiclass"])
return obj
class PlattScalingCalibrator:
"""Lin, Lin & Weng (2007) 2-parameter Platt Scaling with Laplace target smoothing."""
def __init__(self, eps: float = 1e-7, max_iter: int = 50, tol: float = 1e-10) -> None:
self.eps = eps
self.max_iter = max_iter
self.tol = tol
self.slope_a_: float = 1.0
self.intercept_b_: float = 0.0
def fit(self, scores: np.ndarray, y: np.ndarray, scores_are_logits: bool = False) -> PlattScalingCalibrator:
z = np.asarray(scores, dtype=np.float64) if scores_are_logits else logit_from_proba(scores, eps=self.eps)
y_arr = np.asarray(y, dtype=np.int64)
n_pos = float(np.sum(y_arr == 1))
n_neg = float(np.sum(y_arr == 0))
t_pos = (n_pos + 1.0) / (n_pos + 2.0)
t_neg = 1.0 / (n_neg + 2.0)
targets = np.where(y_arr == 1, t_pos, t_neg)
a, b = 1.0, 0.0
def _nll(ca: float, cb: float) -> float:
eta = ca * z + cb
# Safe log(1 + exp(-eta)): max(-eta, 0) + log(1 + exp(-|eta|))
return float(np.sum((1.0 - targets) * eta + np.maximum(-eta, 0.0) + np.log1p(np.exp(-np.abs(eta)))))
cur_loss = _nll(a, b)
for _ in range(self.max_iter):
eta = np.clip(a * z + b, -30.0, 30.0)
q = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(q * (1.0 - q), 1e-12)
diff = q - targets
g0 = float(np.sum(diff * z))
g1 = float(np.sum(diff))
h00 = float(np.sum(w * z * z)) + 1e-8
h01 = float(np.sum(w * z))
h11 = float(np.sum(w)) + 1e-8
det = h00 * h11 - h01 * h01
if abs(det) < 1e-16:
break
da = (h11 * g0 - h01 * g1) / det
db = (-h01 * g0 + h00 * g1) / det
step = 1.0
accepted = False
while step >= 1e-6:
na, nb = a - step * da, b - step * db
if _nll(na, nb) <= cur_loss + 1e-12:
a, b = na, nb
cur_loss = _nll(a, b)
accepted = True
break
step *= 0.5
if not accepted or max(abs(step * da), abs(step * db)) < self.tol:
break
self.slope_a_ = float(a)
self.intercept_b_ = float(b)
return self
def predict_proba(self, scores: np.ndarray, scores_are_logits: bool = False) -> np.ndarray:
z = np.asarray(scores, dtype=np.float64) if scores_are_logits else logit_from_proba(scores, eps=self.eps)
return np.asarray(stable_sigmoid(self.slope_a_ * z + self.intercept_b_), dtype=np.float64)
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "platt",
"slope_a": float(self.slope_a_),
"intercept_b": float(self.intercept_b_),
"eps": float(self.eps),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> PlattScalingCalibrator:
obj = cls(eps=float(state["eps"]))
obj.slope_a_ = float(state["slope_a"])
obj.intercept_b_ = float(state["intercept_b"])
return obj
class BetaCalibrator:
"""Kull, Silva Filho & Flach (2017) 3-parameter Beta Calibration: sigma(a ln s - b ln(1-s) + c)."""
def __init__(self, eps: float = 1e-6, max_iter: int = 50) -> None:
self.eps = eps
self.max_iter = max_iter
self.a_: float = 1.0
self.b_: float = 1.0
self.c_: float = 0.0
def _fit_unconstrained(self, X: np.ndarray, y: np.ndarray) -> np.ndarray:
n, k = X.shape
X_aug = np.column_stack([X, np.ones(n, dtype=np.float64)])
beta = np.zeros(k + 1, dtype=np.float64)
for _ in range(self.max_iter):
eta = np.clip(X_aug @ beta, -30.0, 30.0)
q = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(q * (1.0 - q), 1e-12)
grad = X_aug.T @ (q - y) + 1e-8 * beta
hess = (X_aug * w[:, None]).T @ X_aug + 1e-7 * np.eye(k + 1)
step = np.linalg.solve(hess, grad)
beta -= step
if float(np.linalg.norm(step, ord=np.inf)) < 1e-10:
break
return beta
def fit(self, probs: np.ndarray, y: np.ndarray) -> BetaCalibrator:
s = np.clip(np.asarray(probs, dtype=np.float64), self.eps, 1.0 - self.eps)
yf = np.asarray(y, dtype=np.float64)
x1 = np.log(s)
x2 = -np.log(1.0 - s)
beta_full = self._fit_unconstrained(np.column_stack([x1, x2]), yf)
a, b, c = float(beta_full[0]), float(beta_full[1]), float(beta_full[2])
if a < 0.0 or b < 0.0:
# Constrained boundary projection (Kull et al., 2017): evaluate active sets
candidates: list[tuple[float, float, float, float]] = []
b_only = self._fit_unconstrained(x2[:, None], yf)
if b_only[0] >= 0.0:
p_c = np.asarray(stable_sigmoid(b_only[0] * x2 + b_only[1]), dtype=np.float64)
candidates.append((compute_log_loss(yf, p_c), 0.0, float(b_only[0]), float(b_only[1])))
a_only = self._fit_unconstrained(x1[:, None], yf)
if a_only[0] >= 0.0:
p_c = np.asarray(stable_sigmoid(a_only[0] * x1 + a_only[1]), dtype=np.float64)
candidates.append((compute_log_loss(yf, p_c), float(a_only[0]), 0.0, float(a_only[1])))
p_base = float(np.clip(np.mean(yf), 1e-6, 1.0 - 1e-6))
c_const = math.log(p_base / (1.0 - p_base))
candidates.append((compute_log_loss(yf, np.full_like(yf, p_base)), 0.0, 0.0, c_const))
_, a, b, c = min(candidates, key=lambda item: item[0])
self.a_ = float(a)
self.b_ = float(b)
self.c_ = float(c)
return self
def predict_proba(self, probs: np.ndarray) -> np.ndarray:
s = np.clip(np.asarray(probs, dtype=np.float64), self.eps, 1.0 - self.eps)
eta = self.a_ * np.log(s) - self.b_ * np.log(1.0 - s) + self.c_
return np.asarray(stable_sigmoid(eta), dtype=np.float64)
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "beta",
"a": float(self.a_),
"b": float(self.b_),
"c": float(self.c_),
"eps": float(self.eps),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> BetaCalibrator:
obj = cls(eps=float(state["eps"]))
obj.a_ = float(state["a"])
obj.b_ = float(state["b"])
obj.c_ = float(state["c"])
return obj
@dataclass(frozen=True, slots=True)
class PavaSolution:
"""Read-only pooled PAVA blocks preserving exact tie invariance and KKT optimality."""
unique_scores: np.ndarray
unique_weights: np.ndarray
unique_pos_sums: np.ndarray
unique_fitted: np.ndarray
block_min_scores: np.ndarray
block_max_scores: np.ndarray
block_values: np.ndarray
block_weights: np.ndarray
block_pos_sums: np.ndarray
def fit_pava_blocks(
scores: np.ndarray,
y: np.ndarray,
weights: np.ndarray | None = None,
) -> PavaSolution:
"""Exact O(n log n) tie-merged stack Pool Adjacent Violators Algorithm (PAVA)."""
s_arr = np.asarray(scores, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.ones_like(y_arr) if weights is None else np.asarray(weights, dtype=np.float64)
order = np.argsort(s_arr, kind="mergesort")
s_sorted = s_arr[order]
y_sorted = y_arr[order]
w_sorted = w_arr[order]
# Step 1: Collapse exact score ties into strictly increasing unique score levels
uniq_scores, inv = np.unique(s_sorted, return_inverse=True)
m_uniq = len(uniq_scores)
u_weights = np.bincount(inv, weights=w_sorted, minlength=m_uniq).astype(np.float64)
u_sums = np.bincount(inv, weights=w_sorted * y_sorted, minlength=m_uniq).astype(np.float64)
# Step 2: O(m_uniq) stack PAVA pooling adjacent violators
# Stack stores [sum_wy, sum_w, start_u_idx, end_u_idx]
stack: list[list[float | int]] = []
for r in range(m_uniq):
stack.append([float(u_sums[r]), float(u_weights[r]), r, r])
while len(stack) >= 2:
prev_val = float(stack[-2][0]) / float(stack[-2][1])
curr_val = float(stack[-1][0]) / float(stack[-1][1])
if prev_val > curr_val:
top = stack.pop()
stack[-1][0] = float(stack[-1][0]) + float(top[0])
stack[-1][1] = float(stack[-1][1]) + float(top[1])
stack[-1][3] = int(top[3])
else:
break
u_fit = np.empty(m_uniq, dtype=np.float64)
b_min = np.empty(len(stack), dtype=np.float64)
b_max = np.empty(len(stack), dtype=np.float64)
b_val = np.empty(len(stack), dtype=np.float64)
b_w = np.empty(len(stack), dtype=np.float64)
b_s = np.empty(len(stack), dtype=np.float64)
for b_idx, blk in enumerate(stack):
s_sum = float(blk[0])
w_sum = float(blk[1])
i0 = int(blk[2])
i1 = int(blk[3])
val = s_sum / w_sum
u_fit[i0 : i1 + 1] = val
b_min[b_idx] = uniq_scores[i0]
b_max[b_idx] = uniq_scores[i1]
b_val[b_idx] = val
b_w[b_idx] = w_sum
b_s[b_idx] = s_sum
for arr in (uniq_scores, u_weights, u_sums, u_fit, b_min, b_max, b_val, b_w, b_s):
arr.setflags(write=False)
return PavaSolution(
unique_scores=uniq_scores,
unique_weights=u_weights,
unique_pos_sums=u_sums,
unique_fitted=u_fit,
block_min_scores=b_min,
block_max_scores=b_max,
block_values=b_val,
block_weights=b_w,
block_pos_sums=b_s,
)
class IsotonicPavaCalibrator:
"""Non-parametric monotonic calibration via exact stack PAVA + JSON serialization."""
def __init__(self, interpolation: str = "linear") -> None:
if interpolation not in ("linear", "step"):
raise ValueError("interpolation must be 'linear' or 'step'")
self.interpolation = interpolation
self.x_knots_: np.ndarray = np.array([], dtype=np.float64)
self.y_knots_: np.ndarray = np.array([], dtype=np.float64)
self.solution_: PavaSolution | None = None
def fit(self, scores: np.ndarray, y: np.ndarray) -> IsotonicPavaCalibrator:
sol = fit_pava_blocks(scores, y)
self.solution_ = sol
if self.interpolation == "linear":
# Piecewise linear over unique score knots (exact sklearn isotonic knot convention)
x_k = sol.unique_scores.copy()
y_k = sol.unique_fitted.copy()
else:
x_k = sol.block_max_scores.copy()
y_k = sol.block_values.copy()
x_k.setflags(write=False)
y_k.setflags(write=False)
self.x_knots_ = x_k
self.y_knots_ = y_k
return self
def predict_proba(self, scores: np.ndarray) -> np.ndarray:
s = np.asarray(scores, dtype=np.float64)
if self.interpolation == "linear":
return np.interp(s, self.x_knots_, self.y_knots_)
idx = np.clip(np.searchsorted(self.x_knots_, s, side="left"), 0, len(self.y_knots_) - 1)
return self.y_knots_[idx]
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "pava_isotonic",
"interpolation": self.interpolation,
"x_knots": self.x_knots_.tolist(),
"y_knots": self.y_knots_.tolist(),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> IsotonicPavaCalibrator:
obj = cls(interpolation=str(state["interpolation"]))
xk = np.array(state["x_knots"], dtype=np.float64)
yk = np.array(state["y_knots"], dtype=np.float64)
xk.setflags(write=False)
yk.setflags(write=False)
obj.x_knots_ = xk
obj.y_knots_ = yk
return obj
class DirichletODIRCalibrator:
"""Multiclass Dirichlet Calibration on log-probabilities with ODIR regularization (Kull et al., 2019)."""
def __init__(
self,
lambda_diag: float = 1.0,
lambda_off: float = 10.0,
mu_bias: float = 1.0,
eps: float = 1e-7,
max_iter: int = 80,
) -> None:
self.lambda_diag = lambda_diag
self.lambda_off = lambda_off
self.mu_bias = mu_bias
self.eps = eps
self.max_iter = max_iter
self.W_: np.ndarray = np.array([], dtype=np.float64)
self.b_: np.ndarray = np.array([], dtype=np.float64)
@staticmethod
def _softmax(logits: np.ndarray) -> np.ndarray:
z = logits - np.max(logits, axis=1, keepdims=True)
e = np.exp(z)
return e / np.sum(e, axis=1, keepdims=True)
def fit(self, probs: np.ndarray, y: np.ndarray) -> DirichletODIRCalibrator:
P = np.clip(np.asarray(probs, dtype=np.float64), self.eps, 1.0)
U = np.log(P)
y_idx = np.asarray(y, dtype=np.int64)
n, k = U.shape
Y_oh = np.eye(k, dtype=np.float64)[y_idx]
W = np.eye(k, dtype=np.float64)
b = np.zeros(k, dtype=np.float64)
eye_k = np.eye(k, dtype=np.float64)
off_mask = 1.0 - eye_k
# Pure-NumPy Adam + L2-ODIR warm-started from Identity W=I, b=0 (fast & globally convex!)
mW = np.zeros_like(W)
vW = np.zeros_like(W)
mb = np.zeros_like(b)
vb = np.zeros_like(b)
lr = 0.08
for t in range(1, self.max_iter + 1):
Q = self._softmax(U @ W.T + b[None, :])
diff = (Q - Y_oh) / float(n)
gW = diff.T @ U + (2.0 * self.lambda_diag / float(n)) * ((W - eye_k) * eye_k) + (2.0 * self.lambda_off / float(n)) * (W * off_mask)
gb = np.sum(diff, axis=0) + (2.0 * self.mu_bias / float(n)) * b
mW = 0.9 * mW + 0.1 * gW
vW = 0.999 * vW + 0.001 * (gW * gW)
mb = 0.9 * mb + 0.1 * gb
vb = 0.999 * vb + 0.001 * (gb * gb)
mW_hat = mW / (1.0 - 0.9**t)
vW_hat = vW / (1.0 - 0.999**t)
mb_hat = mb / (1.0 - 0.9**t)
vb_hat = vb / (1.0 - 0.999**t)
stepW = lr * mW_hat / (np.sqrt(vW_hat) + 1e-8)
stepb = lr * mb_hat / (np.sqrt(vb_hat) + 1e-8)
W -= stepW
b -= stepb
if max(float(np.max(np.abs(stepW))), float(np.max(np.abs(stepb)))) < 1e-7:
break
W.setflags(write=False)
b.setflags(write=False)
self.W_ = W
self.b_ = b
return self
def predict_proba(self, probs: np.ndarray) -> np.ndarray:
P = np.clip(np.asarray(probs, dtype=np.float64), self.eps, 1.0)
U = np.log(P)
return self._softmax(U @ self.W_.T + self.b_[None, :])
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "dirichlet_odir",
"W": self.W_.tolist(),
"b": self.b_.tolist(),
"eps": float(self.eps),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> DirichletODIRCalibrator:
obj = cls(eps=float(state["eps"]))
W = np.array(state["W"], dtype=np.float64)
b = np.array(state["b"], dtype=np.float64)
W.setflags(write=False)
b.setflags(write=False)
obj.W_ = W
obj.b_ = b
return obj
# ---------------------------------------------------------------------------
# SOTA Inductive & Cross Venn-Abers Predictors (O(m log m) Fit, O(log m) Query)
# ---------------------------------------------------------------------------
def _hull_cross(ox: float, oy: float, ax: float, ay: float, bx: float, by: float) -> float:
"""2D cross product (a - o) x (b - o); <= 0 implies non-strict clockwise / non-convex."""
return (ax - ox) * (by - oy) - (ay - oy) * (bx - ox)
def _compute_f1_hull_values(u_weights: np.ndarray, u_sums: np.ndarray) -> np.ndarray:
"""Compute exact F1[0..k-1] over unique score blocks via two-hull lower common tangent (O(k log^2 k))."""
k = len(u_weights)
px = np.concatenate(([0.0], np.cumsum(u_weights)))
py = np.concatenate(([0.0], np.cumsum(u_sums)))
qx = px[:-1] - 1.0
qy = py[:-1] - 1.0
# Build suffix right lower hulls R_k .. R_1 via reverse monotone stack + undo log
r_hull: list[int] = [k]
undo_pops: list[list[int]] = [[] for _ in range(k + 1)]
for i in range(k - 1, 0, -1):
popped: list[int] = []
xi, yi = float(px[i]), float(py[i])
while len(r_hull) >= 2:
j1 = r_hull[-1]
j2 = r_hull[-2]
if _hull_cross(xi, yi, float(px[j1]), float(py[j1]), float(px[j2]), float(py[j2])) <= 0.0:
popped.append(r_hull.pop())
else:
break
r_hull.append(i)
undo_pops[i] = popped
# Maintain prefix left lower hull L_{i-1} forward while popping/undoing R_i
l_hull: list[int] = []
f1 = np.empty(k, dtype=np.float64)
def _max_slope_from_left(rx: float, ry: float) -> float:
lo_l = 0
hi_l = len(l_hull) - 1
while lo_l < hi_l:
mid_l = (lo_l + hi_l) // 2
a0 = l_hull[mid_l]
a1 = l_hull[mid_l + 1]
slope_to_r = (ry - float(qy[a0])) / (rx - float(qx[a0]))
edge_l = (float(qy[a1]) - float(qy[a0])) / (float(qx[a1]) - float(qx[a0]))
if slope_to_r > edge_l:
lo_l = mid_l + 1
else:
hi_l = mid_l
a_best = l_hull[lo_l]
return (ry - float(qy[a_best])) / (rx - float(qx[a_best]))
# Note: r_hull stores indices in DESCENDING order (top of stack is smallest index i)!
for i in range(1, k + 1):
# Push Q_{i-1} onto L_{i-1}
q_idx = i - 1
xi, yi = float(qx[q_idx]), float(qy[q_idx])
while len(l_hull) >= 2:
a1 = l_hull[-2]
a2 = l_hull[-1]
if _hull_cross(float(qx[a1]), float(qy[a1]), float(qx[a2]), float(qy[a2]), xi, yi) <= 0.0:
l_hull.pop()
else:
break
l_hull.append(q_idx)
# Binary search along R_i (reverse order inside r_hull: idx m -> right neighbor m - 1!)
# Increasing x order corresponds to going from len-1 down to 0
n_r = len(r_hull)
lo_p = 0
hi_p = n_r - 1
while lo_p < hi_p:
mid_p = (lo_p + hi_p) // 2
b0 = r_hull[n_r - 1 - mid_p]
b1 = r_hull[n_r - 2 - mid_p]
s_mid = _max_slope_from_left(float(px[b0]), float(py[b0]))
edge_r = (float(py[b1]) - float(py[b0])) / (float(px[b1]) - float(px[b0]))
if edge_r < s_mid:
lo_p = mid_p + 1
else:
hi_p = mid_p
b_best = r_hull[n_r - 1 - lo_p]
f1[i - 1] = float(np.clip(_max_slope_from_left(float(px[b_best]), float(py[b_best])), 0.0, 1.0))
# Advance R_i -> R_{i+1} by undoing step i
if i < k:
popped_i = r_hull.pop()
assert popped_i == i
r_hull.extend(reversed(undo_pops[i]))
return f1
class InductiveVennAbersCalibrator:
"""Fast O(m log m) Inductive Venn-Abers Predictor with O(log m) vectorized (p0, p1) & minimax p_va."""
def __init__(self) -> None:
self.unique_scores_: np.ndarray = np.array([], dtype=np.float64)
self.f0_table_: np.ndarray = np.array([], dtype=np.float64) # length k + 1: [0.0, F0[0..k-1]]
self.f1_table_: np.ndarray = np.array([], dtype=np.float64) # length k + 1: [F1[0..k-1], 1.0]
self.n_cal_: int = 0
def fit(self, scores: np.ndarray, y: np.ndarray) -> InductiveVennAbersCalibrator:
s_arr = np.asarray(scores, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
order = np.argsort(s_arr, kind="mergesort")
s_sorted = s_arr[order]
y_sorted = y_arr[order]
uniq_scores, inv = np.unique(s_sorted, return_inverse=True)
m_uniq = len(uniq_scores)
u_weights = np.bincount(inv, minlength=m_uniq).astype(np.float64)
u_sums = np.bincount(inv, weights=y_sorted, minlength=m_uniq).astype(np.float64)
f1_vals = _compute_f1_hull_values(u_weights, u_sums)
# Exact Label-Reversal Duality: F0[i] = 1 - F1_rev[k - 1 - i]
rev_weights = u_weights[::-1]
rev_sums = rev_weights - u_sums[::-1]
f1_rev = _compute_f1_hull_values(rev_weights, rev_sums)
f0_vals = 1.0 - f1_rev[::-1]
f0_table = np.concatenate(([0.0], np.clip(f0_vals, 0.0, 1.0)))
f1_table = np.concatenate((np.clip(f1_vals, 0.0, 1.0), [1.0]))
uniq_ro = uniq_scores.copy()
uniq_ro.setflags(write=False)
f0_table.setflags(write=False)
f1_table.setflags(write=False)
self.unique_scores_ = uniq_ro
self.f0_table_ = f0_table
self.f1_table_ = f1_table
self.n_cal_ = len(s_arr)
return self
def predict_p0_p1(self, scores: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Vectorized O(N_test log m) query returning exact Venn-Abers interval (p0, p1)."""
s = np.asarray(scores, dtype=np.float64)
idx0 = np.searchsorted(self.unique_scores_, s, side="right")
idx1 = np.searchsorted(self.unique_scores_, s, side="left")
p0 = self.f0_table_[idx0]
p1 = self.f1_table_[idx1]
return p0, p1
def predict_proba(self, scores: np.ndarray, return_bounds: bool = False) -> np.ndarray | tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return minimax log-loss regularized point prediction p_va = p1 / (1 - p0 + p1)."""
p0, p1 = self.predict_p0_p1(scores)
p_va = p1 / (1.0 - p0 + p1)
if return_bounds:
return p_va, p0, p1
return p_va
def to_state_dict(self) -> dict[str, Any]:
return {
"method": "inductive_venn_abers",
"n_cal": int(self.n_cal_),
"unique_scores": self.unique_scores_.tolist(),
"f0_table": self.f0_table_.tolist(),
"f1_table": self.f1_table_.tolist(),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> InductiveVennAbersCalibrator:
obj = cls()
obj.n_cal_ = int(state["n_cal"])
u = np.array(state["unique_scores"], dtype=np.float64)
f0 = np.array(state["f0_table"], dtype=np.float64)
f1 = np.array(state["f1_table"], dtype=np.float64)
for arr in (u, f0, f1):
arr.setflags(write=False)
obj.unique_scores_ = u
obj.f0_table_ = f0
obj.f1_table_ = f1
return obj
def ivap_bruteforce_p0_p1(
cal_scores: np.ndarray,
cal_y: np.ndarray,
test_scores: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Reference brute-force O(N_test * m log m) PAVA verifier for testing exact parity."""
c_s = np.asarray(cal_scores, dtype=np.float64)
c_y = np.asarray(cal_y, dtype=np.float64)
t_s = np.asarray(test_scores, dtype=np.float64)
p0 = np.empty(len(t_s), dtype=np.float64)
p1 = np.empty(len(t_s), dtype=np.float64)
for idx, s_star in enumerate(t_s):
aug_s = np.append(c_s, s_star)
sol0 = fit_pava_blocks(aug_s, np.append(c_y, 0.0))
sol1 = fit_pava_blocks(aug_s, np.append(c_y, 1.0))
i0 = int(np.searchsorted(sol0.unique_scores, s_star))
i1 = int(np.searchsorted(sol1.unique_scores, s_star))
p0[idx] = float(sol0.unique_fitted[i0])
p1[idx] = float(sol1.unique_fitted[i1])
return p0, p1
class CrossVennAbersCalibrator:
"""K-fold Cross Venn-Abers Predictor aggregating (p0, p1) across disjoint OOF folds (Vovk et al. 2015)."""
def __init__(self, n_folds: int = 5, seed: int = 42) -> None:
self.n_folds = n_folds
self.seed = seed
self.fold_calibrators_: list[InductiveVennAbersCalibrator] = []
self.fold_indices_: list[np.ndarray] = []
def fit(self, scores: np.ndarray, y: np.ndarray) -> CrossVennAbersCalibrator:
s_arr = np.asarray(scores, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
folds = stratified_kfold_indices(y_arr, n_folds=self.n_folds, seed=self.seed)
self.fold_calibrators_ = []
self.fold_indices_ = []
for _, cal_idx in folds:
cal = InductiveVennAbersCalibrator().fit(s_arr[cal_idx], y_arr[cal_idx])
self.fold_calibrators_.append(cal)
idx_ro = np.asarray(cal_idx, dtype=np.int64).copy()
idx_ro.setflags(write=False)
self.fold_indices_.append(idx_ro)
return self
def predict_proba(self, scores: np.ndarray) -> np.ndarray:
s_arr = np.asarray(scores, dtype=np.float64)
log_odds_sum = np.zeros(len(s_arr), dtype=np.float64)
for cal in self.fold_calibrators_:
p0, p1 = cal.predict_p0_p1(s_arr)
# p1 >= 1/(m+1) > 0 and 1 - p0 >= 1/(m+1) > 0 guaranteed by Theorem 1.1!
log_odds_sum += np.log(np.maximum(p1, 1e-15)) - np.log(np.maximum(1.0 - p0, 1e-15))
mean_log_odds = log_odds_sum / float(len(self.fold_calibrators_))
return np.asarray(stable_sigmoid(mean_log_odds), dtype=np.float64)
def fit_bayes_prior_offset(
y_prob: np.ndarray,
pi_train: float,
pi_true: float,
eps: float = 1e-12,
) -> np.ndarray:
"""Exact Elkan (2001) / Saerens (2002) log-odds prior correction for resampled classifiers."""
offset = math.log((pi_true * (1.0 - pi_train)) / max((1.0 - pi_true) * pi_train, eps))
return np.asarray(stable_sigmoid(logit_from_proba(y_prob, eps=eps) + offset), dtype=np.float64)
"""Bayes-optimal asymmetric & instance-dependent cost matrices, Lagrangian capacity triage, DCA, and full Ch 07 benchmark runner."""
from __future__ import annotations
from typing import Any
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from eval_calibration_lab.calibrators import (
BetaCalibrator,
CrossVennAbersCalibrator,
DirichletODIRCalibrator,
InductiveVennAbersCalibrator,
IsotonicPavaCalibrator,
PlattScalingCalibrator,
TemperatureScalingCalibrator,
compute_calibration_diagnostics,
compute_log_loss,
)
from eval_calibration_lab.leakage_auditor import (
audit_class1_target_proxy_leakage,
audit_class2_temporal_and_maturity_leakage,
audit_class3_smote_and_preproc_before_cv,
audit_class4_group_overlap_leakage,
audit_class5_duplicate_leakage,
audit_class6_feature_store_asof_skew,
compute_roc_auc,
stable_sigmoid,
)
class CostMatrixConfig(BaseModel):
"""Strict 2x2 asymmetric decision cost/benefit configuration."""
model_config = ConfigDict(frozen=True, extra="forbid")
cost_fp: float = Field(default=15.0, gt=0.0)
cost_fn: float = Field(default=250.0, gt=0.0)
benefit_tp: float = Field(default=0.0)
benefit_tn: float = Field(default=0.0)
capacity_k: int = Field(default=150, ge=1)
def compute_bayes_threshold(
cost_fp: float,
cost_fn: float,
benefit_tp: float = 0.0,
benefit_tn: float = 0.0,
) -> float:
"""Exact Bayes-optimal threshold t* = (C_FP + B_TN) / ((C_FP + B_TN) + (C_FN + B_TP))."""
num = float(cost_fp + benefit_tn)
den = num + float(cost_fn + benefit_tp)
if num <= 0.0 or den <= 0.0:
raise ValueError("Decision cost/benefit spreads must yield strictly positive numerator and denominator.")
return float(num / den)
def compute_instance_thresholds(
cost_fp: np.ndarray | float,
cost_fn: np.ndarray | float,
benefit_tp: np.ndarray | float = 0.0,
benefit_tn: np.ndarray | float = 0.0,
) -> np.ndarray:
"""Vectorized instance-dependent Bayes threshold t*(x_i)."""
num = np.asarray(cost_fp, dtype=np.float64) + np.asarray(benefit_tn, dtype=np.float64)
den = num + np.asarray(cost_fn, dtype=np.float64) + np.asarray(benefit_tp, dtype=np.float64)
return np.clip(num / np.maximum(den, 1e-12), 0.0, 1.0)
def compute_marginal_net_benefits(
y_prob: np.ndarray,
cost_fp: np.ndarray | float,
cost_fn: np.ndarray | float,
benefit_tp: np.ndarray | float = 0.0,
benefit_tn: np.ndarray | float = 0.0,
) -> np.ndarray:
"""Expected net utility gain Delta_u_i = E[U(1, Y) - U(0, Y) | x_i] of flagging item i."""
p = np.asarray(y_prob, dtype=np.float64)
pos_gain = np.asarray(benefit_tp, dtype=np.float64) + np.asarray(cost_fn, dtype=np.float64)
neg_loss = np.asarray(cost_fp, dtype=np.float64) + np.asarray(benefit_tn, dtype=np.float64)
return p * pos_gain - (1.0 - p) * neg_loss
def evaluate_decision_policy(
y_true: np.ndarray,
actions: np.ndarray,
cost_fp: np.ndarray | float,
cost_fn: np.ndarray | float,
benefit_tp: np.ndarray | float = 0.0,
benefit_tn: np.ndarray | float = 0.0,
exposure_amounts: np.ndarray | None = None,
) -> dict[str, float | int]:
"""Evaluate realized net dollar savings vs approve-all baseline plus precision/recall/dollar-recall."""
y = np.asarray(y_true, dtype=np.int64)
a = np.asarray(actions, dtype=np.int64)
c_fp = np.broadcast_to(np.asarray(cost_fp, dtype=np.float64), y.shape)
c_fn = np.broadcast_to(np.asarray(cost_fn, dtype=np.float64), y.shape)
b_tp = np.broadcast_to(np.asarray(benefit_tp, dtype=np.float64), y.shape)
b_tn = np.broadcast_to(np.asarray(benefit_tn, dtype=np.float64), y.shape)
tp_mask = (a == 1) & (y == 1)
fp_mask = (a == 1) & (y == 0)
fn_mask = (a == 0) & (y == 1)
tn_mask = (a == 0) & (y == 0)
tp = int(np.sum(tp_mask))
fp = int(np.sum(fp_mask))
fn = int(np.sum(fn_mask))
alerts = int(np.sum(a == 1))
# Savings relative to baseline a == 0 (all approved): catching y=1 saves (b_tp + c_fn), false alarm costs (c_fp + b_tn)
net_savings_vs_approve_all = float(
np.sum(b_tp[tp_mask] + c_fn[tp_mask]) - np.sum(c_fp[fp_mask] + b_tn[fp_mask])
)
total_realized_utility = float(
np.sum(b_tp[tp_mask]) + np.sum(b_tn[tn_mask]) - np.sum(c_fp[fp_mask]) - np.sum(c_fn[fn_mask])
)
precision = float(tp / alerts) if alerts > 0 else 0.0
n_pos = int(np.sum(y == 1))
recall = float(tp / n_pos) if n_pos > 0 else 0.0
f1 = (2.0 * precision * recall / (precision + recall)) if (precision + recall) > 0.0 else 0.0
if exposure_amounts is not None:
exp_arr = np.asarray(exposure_amounts, dtype=np.float64)
total_fraud_dollars = float(np.sum(exp_arr[y == 1]))
caught_fraud_dollars = float(np.sum(exp_arr[tp_mask]))
dollar_recall = (caught_fraud_dollars / total_fraud_dollars) if total_fraud_dollars > 0.0 else 0.0
else:
dollar_recall = recall
return {
"alerts": alerts,
"tp": tp,
"fp": fp,
"fn": fn,
"precision": precision,
"recall": recall,
"f1": f1,
"dollar_recall": float(dollar_recall),
"net_savings_vs_baseline": net_savings_vs_approve_all,
"total_realized_utility": total_realized_utility,
}
def solve_capacity_constrained_triage(
y_prob: np.ndarray,
cost_fp: np.ndarray | float,
cost_fn: np.ndarray | float,
capacity_k: float,
benefit_tp: np.ndarray | float = 0.0,
benefit_tn: np.ndarray | float = 0.0,
review_weights: np.ndarray | None = None,
) -> dict[str, Any]:
"""Lagrangian greedy KKT solver maximizing sum(a_i * Delta_u_i) subject to sum(w_i * a_i) <= K."""
p = np.asarray(y_prob, dtype=np.float64)
n = len(p)
c_fp = np.broadcast_to(np.asarray(cost_fp, dtype=np.float64), (n,))
c_fn = np.broadcast_to(np.asarray(cost_fn, dtype=np.float64), (n,))
b_tp = np.broadcast_to(np.asarray(benefit_tp, dtype=np.float64), (n,))
b_tn = np.broadcast_to(np.asarray(benefit_tn, dtype=np.float64), (n,))
w = np.ones(n, dtype=np.float64) if review_weights is None else np.asarray(review_weights, dtype=np.float64)
delta_u = compute_marginal_net_benefits(p, c_fp, c_fn, b_tp, b_tn)
pos_indices = np.flatnonzero(delta_u > 0.0)
ratios = delta_u[pos_indices] / np.maximum(w[pos_indices], 1e-12)
order_desc = pos_indices[np.argsort(-ratios, kind="mergesort")]
actions = np.zeros(n, dtype=np.int64)
used_cap = 0.0
shadow_price_mu = 0.0
for rank_idx, item_idx in enumerate(order_desc):
wt = float(w[item_idx])
if used_cap + wt <= float(capacity_k) + 1e-12:
actions[item_idx] = 1
used_cap += wt
else:
# First excluded positive-EV item sets Lagrangian capacity shadow price mu*
shadow_price_mu = float(delta_u[item_idx] / max(wt, 1e-12))
break
pos_gain = b_tp + c_fn
neg_loss = c_fp + b_tn
effective_thresholds = np.clip((neg_loss + shadow_price_mu * w) / np.maximum(pos_gain + neg_loss, 1e-12), 0.0, 1.0)
return {
"actions": actions,
"marginal_utilities": delta_u,
"positive_ev_candidates": len(pos_indices),
"selected_count": int(np.sum(actions)),
"used_capacity": float(used_cap),
"shadow_price_mu": float(shadow_price_mu),
"effective_thresholds": effective_thresholds,
"expected_savings": float(np.sum(delta_u[actions == 1])),
}
def compute_decision_curve_analysis(
y_true: np.ndarray,
y_prob: np.ndarray,
thresholds: np.ndarray | list[float],
) -> dict[str, list[float]]:
"""Vickers & Elkin (2006) Net Benefit NB(t) vs Treat-All and Treat-None."""
y = np.asarray(y_true, dtype=np.int64)
p = np.asarray(y_prob, dtype=np.float64)
n = float(len(y))
prev = float(np.mean(y))
nb_model: list[float] = []
nb_all: list[float] = []
nb_none: list[float] = []
for t in thresholds:
tf = float(t)
odds_w = tf / max(1.0 - tf, 1e-9)
pred = p >= tf
tp = float(np.sum(pred & (y == 1)))
fp = float(np.sum(pred & (y == 0)))
nb_model.append((tp / n) - (fp / n) * odds_w)
nb_all.append(prev - (1.0 - prev) * odds_w)
nb_none.append(0.0)
return {
"thresholds": [float(t) for t in thresholds],
"net_benefit_model": nb_model,
"net_benefit_all": nb_all,
"net_benefit_none": nb_none,
}
def compute_miscalibration_profit_collapse(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Prove Theorem 7.3: identical ROC-AUC under monotone logit distortion causes massive Bayes loss & DCA harm."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
n = 3000 if quick else 6000
x = rng.normal(0.0, 1.0, size=(n, 4))
# True base rate ~2.0% < t* = 4.76% so massive over-prediction causes Net Benefit < 0 (strict net harm!)
z_true = -4.50 + 1.25 * x[:, 0] - 0.9 * x[:, 1] + 0.65 * x[:, 2]
q_true = np.asarray(stable_sigmoid(z_true), dtype=np.float64)
y = (rng.uniform(size=n) < q_true).astype(np.int64)
c_fp = 25.0
c_fn = 500.0
t_star = compute_bayes_threshold(c_fp, c_fn) # 25 / 525 = 0.047619
p_overconf = np.asarray(stable_sigmoid(2.8 * z_true), dtype=np.float64)
p_underconf = np.asarray(stable_sigmoid(0.35 * z_true), dtype=np.float64)
p_prior_shift = np.asarray(stable_sigmoid(z_true + 3.2), dtype=np.float64)
auc_oracle = compute_roc_auc(y, q_true)
auc_over = compute_roc_auc(y, p_overconf)
auc_under = compute_roc_auc(y, p_underconf)
auc_shift = compute_roc_auc(y, p_prior_shift)
pol_cal = evaluate_decision_policy(y, (q_true >= t_star).astype(np.int64), c_fp, c_fn)
pol_over = evaluate_decision_policy(y, (p_overconf >= t_star).astype(np.int64), c_fp, c_fn)
pol_under = evaluate_decision_policy(y, (p_underconf >= t_star).astype(np.int64), c_fp, c_fn)
pol_shift = evaluate_decision_policy(y, (p_prior_shift >= t_star).astype(np.int64), c_fp, c_fn)
dca_shift = compute_decision_curve_analysis(y, p_prior_shift, [t_star])
dca_cal = compute_decision_curve_analysis(y, q_true, [t_star])
return {
"bayes_threshold": t_star,
"roc_auc_oracle": auc_oracle,
"roc_auc_overconfident": auc_over,
"roc_auc_underconfident": auc_under,
"roc_auc_prior_shifted": auc_shift,
"calibrated_net_savings": pol_cal["net_savings_vs_baseline"],
"overconfident_net_savings": pol_over["net_savings_vs_baseline"],
"underconfident_net_savings": pol_under["net_savings_vs_baseline"],
"prior_shifted_net_savings": pol_shift["net_savings_vs_baseline"],
"calibrated_nb_at_tstar": dca_cal["net_benefit_model"][0],
"prior_shifted_nb_at_tstar": dca_shift["net_benefit_model"][0],
}
def run_full_ch07_benchmarks(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Execute complete reproducible Ch 07 benchmark suite across Leakage, Calibration, and Cost Triage."""
# -----------------------------------------------------------------------
# 1. Six-Class Leakage & Canary Benchmarks (Article #1)
# -----------------------------------------------------------------------
leak_c1 = audit_class1_target_proxy_leakage(seed=seed + 1, quick=quick)
leak_c2 = audit_class2_temporal_and_maturity_leakage(seed=seed + 2, quick=quick)
leak_c3 = audit_class3_smote_and_preproc_before_cv(seed=seed + 3, quick=quick)
leak_c4 = audit_class4_group_overlap_leakage(seed=seed + 4, quick=quick)
leak_c5 = audit_class5_duplicate_leakage(seed=seed + 5, quick=quick)
leak_c6 = audit_class6_feature_store_asof_skew(seed=seed + 6, quick=quick)
# -----------------------------------------------------------------------
# 2. Calibration & SOTA Venn-Abers Benchmarks (Article #2)
# -----------------------------------------------------------------------
rng = np.random.default_rng(np.random.SeedSequence(seed + 100))
n_cal = 2000 if quick else 4000
n_test = 3000 if quick else 5000
# Payment fraud + overconfident / shifted raw GBDT-like scores + log-normal transaction amounts
def _gen_fraud_cohort(n_rows: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
x = rng.normal(0.0, 1.0, size=(n_rows, 5))
tx_amt = np.clip(np.exp(rng.normal(4.8, 1.35, size=n_rows)), 15.0, 5000.0)
z_true = -3.85 + 1.15 * x[:, 0] - 0.90 * x[:, 1] + 0.65 * x[:, 2] + 0.30 * np.log(tx_amt / 120.0)
p_true = np.asarray(stable_sigmoid(z_true), dtype=np.float64)
y_obs = (rng.uniform(size=n_rows) < p_true).astype(np.int64)
# Simulated raw uncalibrated score: overconfident 1.55x slope + 1:4 negative-subsampling log-odds shift (+0.95)
z_raw = 1.55 * z_true + 0.95 + rng.normal(0.0, 0.25, size=n_rows)
p_raw = np.asarray(stable_sigmoid(z_raw), dtype=np.float64)
return p_raw, z_raw, y_obs, tx_amt
p_raw_cal, z_raw_cal, y_cal, _ = _gen_fraud_cohort(n_cal)
p_raw_te, z_raw_te, y_te, tx_amt_te = _gen_fraud_cohort(n_test)
cal_temp = TemperatureScalingCalibrator().fit(z_raw_cal, y_cal, scores_are_logits=True)
cal_platt = PlattScalingCalibrator().fit(z_raw_cal, y_cal, scores_are_logits=True)
cal_beta = BetaCalibrator().fit(p_raw_cal, y_cal)
cal_pava = IsotonicPavaCalibrator(interpolation="linear").fit(p_raw_cal, y_cal)
cal_ivap = InductiveVennAbersCalibrator().fit(p_raw_cal, y_cal)
cal_cvap = CrossVennAbersCalibrator(n_folds=5, seed=seed + 101).fit(p_raw_cal, y_cal)
p_temp_te = cal_temp.predict_proba(z_raw_te, scores_are_logits=True)
p_platt_te = cal_platt.predict_proba(z_raw_te, scores_are_logits=True)
p_beta_te = cal_beta.predict_proba(p_raw_te)
p_pava_te = cal_pava.predict_proba(p_raw_te)
p_ivap_te, ivap_p0, ivap_p1 = cal_ivap.predict_proba(p_raw_te, return_bounds=True)
p_cvap_te = cal_cvap.predict_proba(p_raw_te)
diag_raw = compute_calibration_diagnostics(y_te, p_raw_te, n_bins=15, include_smoothece=True)
diag_temp = compute_calibration_diagnostics(y_te, p_temp_te, n_bins=15, include_smoothece=True)
diag_platt = compute_calibration_diagnostics(y_te, p_platt_te, n_bins=15, include_smoothece=True)
diag_beta = compute_calibration_diagnostics(y_te, p_beta_te, n_bins=15, include_smoothece=True)
diag_pava = compute_calibration_diagnostics(y_te, p_pava_te, n_bins=15, include_smoothece=True)
diag_ivap = compute_calibration_diagnostics(y_te, p_ivap_te, n_bins=15, include_smoothece=True)
diag_cvap = compute_calibration_diagnostics(y_te, p_cvap_te, n_bins=15, include_smoothece=True)
# IVAP epistemic interval diagnostics at underwriting cutoff t*=0.08
ivap_widths = ivap_p1 - ivap_p0
t_underwrite = 0.08
ivap_boundary_ambiguous_rate = float(np.mean((ivap_p0 <= t_underwrite) & (t_underwrite <= ivap_p1)))
ivap_wide_uncertainty_rate = float(np.mean(ivap_widths >= 0.03))
# Small-n_cal (n=200) vs Shifted-Acuity vs Skewed-Beta Regimes
n_small = 200
z_sm_cal = rng.normal(-1.0, 1.4, size=n_small)
# Zero prevalence shift, pure 1.9x logit overconfidence
y_sm_cal = (rng.uniform(size=n_small) < np.asarray(stable_sigmoid(z_sm_cal / 1.9))).astype(np.int64)
z_sm_te = rng.normal(-1.0, 1.4, size=2000)
y_sm_te = (rng.uniform(size=2000) < np.asarray(stable_sigmoid(z_sm_te / 1.9))).astype(np.int64)
sm_temp = TemperatureScalingCalibrator().fit(z_sm_cal, y_sm_cal, scores_are_logits=True).predict_proba(z_sm_te, scores_are_logits=True)
sm_platt = PlattScalingCalibrator().fit(z_sm_cal, y_sm_cal, scores_are_logits=True).predict_proba(z_sm_te, scores_are_logits=True)
sm_pava = IsotonicPavaCalibrator().fit(np.asarray(stable_sigmoid(z_sm_cal)), y_sm_cal).predict_proba(np.asarray(stable_sigmoid(z_sm_te)))
sm_ivap = InductiveVennAbersCalibrator().fit(np.asarray(stable_sigmoid(z_sm_cal)), y_sm_cal).predict_proba(np.asarray(stable_sigmoid(z_sm_te)))
# Asymmetric Skewed Beta scores (a >> b asymmetry where Beta outperforms symmetric Platt)
y_skew_cal = rng.integers(0, 2, size=1200)
s_skew_cal = np.where(y_skew_cal == 1, rng.beta(4.5, 1.0, size=1200), rng.beta(1.0, 1.6, size=1200))
y_skew_te = rng.integers(0, 2, size=2000)
s_skew_te = np.where(y_skew_te == 1, rng.beta(4.5, 1.0, size=2000), rng.beta(1.0, 1.6, size=2000))
sk_platt = PlattScalingCalibrator().fit(s_skew_cal, y_skew_cal).predict_proba(s_skew_te)
sk_beta = BetaCalibrator().fit(s_skew_cal, y_skew_cal).predict_proba(s_skew_te)
diag_sk_platt = compute_calibration_diagnostics(y_skew_te, sk_platt, n_bins=15, include_smoothece=False)
diag_sk_beta = compute_calibration_diagnostics(y_skew_te, sk_beta, n_bins=15, include_smoothece=False)
# 3-Class Dirichlet + ODIR vs Temperature Scaling
n_mc_cal, n_mc_te, k_cls = 800, 1500, 3
logits_mc_cal = rng.normal(0.0, 1.5, size=(n_mc_cal, k_cls)) + np.array([[0.8, -0.4, -0.4]])
true_mc_probs_cal = DirichletODIRCalibrator._softmax(logits_mc_cal * 0.55 + np.array([[-0.3, 0.2, 0.1]]))
y_mc_cal = np.array([rng.choice(k_cls, p=row) for row in true_mc_probs_cal], dtype=np.int64)
logits_mc_te = rng.normal(0.0, 1.5, size=(n_mc_te, k_cls)) + np.array([[0.8, -0.4, -0.4]])
true_mc_probs_te = DirichletODIRCalibrator._softmax(logits_mc_te * 0.55 + np.array([[-0.3, 0.2, 0.1]]))
y_mc_te = np.array([rng.choice(k_cls, p=row) for row in true_mc_probs_te], dtype=np.int64)
p_mc_raw = DirichletODIRCalibrator._softmax(logits_mc_te)
mc_temp = TemperatureScalingCalibrator().fit(logits_mc_cal, y_mc_cal, scores_are_logits=True).predict_proba(logits_mc_te, scores_are_logits=True)
mc_dir = DirichletODIRCalibrator(lambda_diag=1.0, lambda_off=8.0).fit(DirichletODIRCalibrator._softmax(logits_mc_cal), y_mc_cal).predict_proba(p_mc_raw)
# -----------------------------------------------------------------------
# 3. Cost-Sensitive & Capacity-Constrained Fraud Triage (Article #2)
# -----------------------------------------------------------------------
c_rev = 15.0
c_fee = 15.0
c_fp_vec = np.full(n_test, c_rev, dtype=np.float64)
c_fn_vec = tx_amt_te + c_fee
capacity_k = 120 if quick else 150
global_t_star = compute_bayes_threshold(c_rev, float(np.mean(c_fn_vec)))
inst_t_vec = compute_instance_thresholds(c_fp_vec, c_fn_vec)
# Policy 1: Naive t=0.50 (capped at K by prob descending)
naive_cand = np.flatnonzero(p_raw_te >= 0.50)
naive_act = np.zeros(n_test, dtype=np.int64)
if len(naive_cand) > 0:
top_n = naive_cand[np.argsort(-p_raw_te[naive_cand])[:capacity_k]]
naive_act[top_n] = 1
pol_naive_050 = evaluate_decision_policy(y_te, naive_act, c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
# Policy 2: Uncalibrated Global t* (ranked by prob, capped at K)
ug_cand = np.flatnonzero(p_raw_te >= global_t_star)
ug_act = np.zeros(n_test, dtype=np.int64)
if len(ug_cand) > 0:
ug_act[ug_cand[np.argsort(-p_raw_te[ug_cand])[:capacity_k]]] = 1
pol_uncal_global = evaluate_decision_policy(y_te, ug_act, c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
pol_uncal_global["uncapped_candidates"] = len(ug_cand)
# Policy 3: Calibrated (IVAP) Global t* (ranked by prob, capped at K)
cg_cand = np.flatnonzero(p_ivap_te >= global_t_star)
cg_act = np.zeros(n_test, dtype=np.int64)
if len(cg_cand) > 0:
cg_act[cg_cand[np.argsort(-p_ivap_te[cg_cand])[:capacity_k]]] = 1
pol_cal_global = evaluate_decision_policy(y_te, cg_act, c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
pol_cal_global["uncapped_candidates"] = len(cg_cand)
# Policy 4: Calibrated Instance t*(x) FIFO Saturated Queue (first K chronological positive EV arrivals)
fifo_cand = np.flatnonzero(p_ivap_te >= inst_t_vec)
fifo_act = np.zeros(n_test, dtype=np.int64)
fifo_act[fifo_cand[:capacity_k]] = 1
pol_fifo_saturated = evaluate_decision_policy(y_te, fifo_act, c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
pol_fifo_saturated["uncapped_candidates"] = len(fifo_cand)
# Policy 5: Uncalibrated Capacity-Optimal Top-K (ranked by Delta_u using raw miscalibrated scores!)
triage_uncal = solve_capacity_constrained_triage(p_raw_te, c_fp_vec, c_fn_vec, capacity_k=capacity_k)
pol_uncal_topk = evaluate_decision_policy(y_te, triage_uncal["actions"], c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
# Policy 6: Calibrated (IVAP) Capacity-Optimal Top-K (ranked by calibrated Delta_u, Lagrangian shadow price mu*)
triage_cal = solve_capacity_constrained_triage(p_ivap_te, c_fp_vec, c_fn_vec, capacity_k=capacity_k)
pol_cal_topk = evaluate_decision_policy(y_te, triage_cal["actions"], c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te)
# Policy 7: Calibrated Instance t*(x) Uncapped Reference
pol_cal_uncapped = evaluate_decision_policy(
y_te, (p_ivap_te >= inst_t_vec).astype(np.int64), c_fp_vec, c_fn_vec, exposure_amounts=tx_amt_te
)
profit_collapse = compute_miscalibration_profit_collapse(seed=seed + 200, quick=quick)
return {
"leakage_audits": {
"class1": leak_c1,
"class2": leak_c2,
"class3": leak_c3,
"class4": leak_c4,
"class5": leak_c5,
"class6": leak_c6,
},
"calibration": {
"n_cal": n_cal,
"n_test": n_test,
"raw": diag_raw,
"temperature": diag_temp,
"platt": diag_platt,
"beta": diag_beta,
"pava": diag_pava,
"ivap": diag_ivap,
"cvap": diag_cvap,
"ivap_uncertainty": {
"mean_width": float(np.mean(ivap_widths)),
"max_width": float(np.max(ivap_widths)),
"boundary_ambiguous_rate_at_008": ivap_boundary_ambiguous_rate,
"wide_uncertainty_rate_ge_003": ivap_wide_uncertainty_rate,
},
"small_n_200_overfit_ablation": {
"temp_logloss": compute_log_loss(y_sm_te, sm_temp),
"platt_logloss": compute_log_loss(y_sm_te, sm_platt),
"pava_logloss": compute_log_loss(y_sm_te, sm_pava),
"ivap_logloss": compute_log_loss(y_sm_te, sm_ivap),
},
"skewed_beta_ablation": {
"platt_ace": diag_sk_platt["ace"],
"beta_ace": diag_sk_beta["ace"],
"platt_logloss": diag_sk_platt["log_loss"],
"beta_logloss": diag_sk_beta["log_loss"],
},
"multiclass_dirichlet_odir": {
"raw_logloss": compute_log_loss(y_mc_te, p_mc_raw),
"temp_logloss": compute_log_loss(y_mc_te, mc_temp),
"dirichlet_odir_logloss": compute_log_loss(y_mc_te, mc_dir),
"raw_top1_acc": float(np.mean(np.argmax(p_mc_raw, axis=1) == y_mc_te)),
"temp_top1_acc": float(np.mean(np.argmax(mc_temp, axis=1) == y_mc_te)),
},
},
"cost_decisions": {
"capacity_k": capacity_k,
"global_t_star": global_t_star,
"total_fraud_exposure_usd": float(np.sum(tx_amt_te[y_te == 1])),
"naive_t050": pol_naive_050,
"uncal_global_tstar": pol_uncal_global,
"cal_global_tstar": pol_cal_global,
"cal_fifo_saturated": pol_fifo_saturated,
"uncal_capacity_topk": pol_uncal_topk,
"cal_capacity_topk": {
**pol_cal_topk,
"shadow_price_mu": triage_cal["shadow_price_mu"],
"mean_effective_t": float(np.mean(triage_cal["effective_thresholds"])),
},
"cal_instance_uncapped": pol_cal_uncapped,
"profit_collapse_identical_auc": profit_collapse,
},
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 07 (eval_calibration_lab)."""
from __future__ import annotations
import argparse
import json
import math
import sys
from pathlib import Path
from typing import Any
import numpy as np
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import eval_calibration_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from eval_calibration_lab.cost_decision_engine import run_full_ch07_benchmarks
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy scalars/arrays and non-finite floats into strict JSON-safe primitives."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar(val: float, floor: float = 0.001) -> float:
"""Guarantee strictly positive finite bar values for dashboard width rendering."""
if not math.isfinite(val):
return floor
return float(max(floor, abs(val)))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Leakage-Proof Evaluation & Calibration Workbench."""
parser = argparse.ArgumentParser(
description="Run Lab 07: 6-Class Leakage Canaries, SOTA Calibration (Venn-Abers) & Bayes Cost Triage."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true", help="Run compact CI/demo sample budgets.")
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Output JSON path (e.g., artifacts/ch07_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
lk = bench["leakage_audits"]
c1, c2, c3, c4, c5, c6 = lk["class1"], lk["class2"], lk["class3"], lk["class4"], lk["class5"], lk["class6"]
cal = bench["calibration"]
d_raw = cal["raw"]
d_temp = cal["temperature"]
d_platt = cal["platt"]
d_beta = cal["beta"]
d_pava = cal["pava"]
d_ivap = cal["ivap"]
d_cvap = cal["cvap"]
ivap_u = cal["ivap_uncertainty"]
sm_n = cal["small_n_200_overfit_ablation"]
skew = cal["skewed_beta_ablation"]
mc = cal["multiclass_dirichlet_odir"]
cd = bench["cost_decisions"]
pol_050 = cd["naive_t050"]
pol_ug = cd["uncal_global_tstar"]
pol_cg = cd["cal_global_tstar"]
pol_fifo = cd["cal_fifo_saturated"]
pol_utop = cd["uncal_capacity_topk"]
pol_ctop = cd["cal_capacity_topk"]
pol_uncap = cd["cal_instance_uncapped"]
pcol = cd["profit_collapse_identical_auc"]
ace_over_ece = d_raw["ace"] / max(d_raw["ece"], 1e-6)
lift_pct = (
(pol_ctop["net_savings_vs_baseline"] - pol_050["net_savings_vs_baseline"])
/ max(abs(pol_050["net_savings_vs_baseline"]), 1.0)
* 100.0
)
kpis = [
{
"id": "kpi_smote_and_dup_leakage_gap",
"label": "SMOTE-before-CV PR-AUC & Dup NNDR",
"value": f"{c3['smote_before_cv_pr_auc']:.3f} -> {c3['clean_logreg_pr_auc']:.3f}",
"unit": "PR-AUC",
"status": "critical",
"detail": (
f"Perm-Null TE AUC={c3['perm_leaky_te_null_mean_auc']:.3f} vs clean {c3['perm_clean_te_null_mean_auc']:.3f}; "
f"Dup C2ST blind ({c5['c2st_dup_auc_blind']:.3f}) while Hash={c5['dup_exact_hash_rate']*100:.1f}%."
),
},
{
"id": "kpi_maturity_truncation_and_asof",
"label": "Label Maturity Bias & ASOF Backfill",
"value": f"{c2['naive_relative_bias']*100:+.1f}% | Live {c6['backfill_live_roc_auc']:.3f}",
"unit": "Bias / AUC",
"status": "warn",
"detail": (
f"60d purge cuts bias to {c2['purged_relative_bias']*100:+.1f}%; "
f"Quad C2ST={c6['quadratic_c2st_auc']:.3f} catches SCD-1 skew (ASOF viol={c6['asof_violation_rate']*100:.0f}%)."
),
},
{
"id": "kpi_ece_vs_ace_and_smoothece",
"label": "Raw Calibration (ECE / ACE / smECE*)",
"value": f"ACE {d_raw['ace']:.4f} | smECE {d_raw['smooth_ece']:.4f}",
"unit": f"ECE {d_raw['ece']:.4f}",
"status": "warn",
"detail": (
f"ACE/ECE ratio={ace_over_ece:.2f}x; IVAP cuts ACE to {d_ivap['ace']:.4f} "
f"& smECE* to {d_ivap['smooth_ece']:.4f} (Slope={d_raw['calibration_slope']:.2f} -> {d_ivap['calibration_slope']:.2f})."
),
},
{
"id": "kpi_ivap_calibration_and_brier",
"label": "IVAP Log-Loss & Murphy Reliability",
"value": f"NLL {d_raw['log_loss']:.3f} -> {d_ivap['log_loss']:.3f}",
"unit": f"REL {d_ivap['reliability']:.5f}",
"status": "ok",
"detail": (
f"Brier {d_raw['brier_score']:.4f} -> {d_ivap['brier_score']:.4f} (CVAP={d_cvap['log_loss']:.4f}); "
f"IVAP mean width={ivap_u['mean_width']:.4f}, boundary review={ivap_u['boundary_ambiguous_rate_at_008']*100:.1f}%."
),
},
{
"id": "kpi_miscalibration_profit_collapse",
"label": "Identical ROC-AUC Profit Collapse",
"value": f"AUC {pcol['roc_auc_oracle']:.3f} | -{pcol['calibrated_net_savings'] - pcol['prior_shifted_net_savings']:.0f} USD",
"unit": "Bayes Loss",
"status": "critical",
"detail": (
f"Oracle Net=${pcol['calibrated_net_savings']:.0f} vs Prior-Shifted Net=${pcol['prior_shifted_net_savings']:.0f} "
f"(Underconf Net=${pcol['underconfident_net_savings']:.0f}; DCA NB={pcol['prior_shifted_nb_at_tstar']:.4f})."
),
},
{
"id": "kpi_capacity_triage_dollar_lift",
"label": f"Top-{cd['capacity_k']} Fraud Queue Net Savings",
"value": f"${pol_050['net_savings_vs_baseline']:,.0f} -> ${pol_ctop['net_savings_vs_baseline']:,.0f}",
"unit": f"+{lift_pct:.1f}% Lift",
"status": "ok",
"detail": (
f"Dollar Recall {pol_050['dollar_recall']*100:.1f}% -> {pol_ctop['dollar_recall']*100:.1f}%; "
f"Shadow price mu*=${pol_ctop['shadow_price_mu']:.2f}/slot lifts effective threshold."
),
},
]
bars = [
{
"id": "bar_leakage_illusion_vs_clean_oot",
"title": "Leakage Illusion (Apparent CV/Offline) vs Clean OOT/Live Reality",
"metric_label": "Score",
"items": [
{"label": "c1_proxy_offline_vs_live", "value": _pos_bar(c1["leaky_offline_roc_auc"]), "display": f"{c1['leaky_offline_roc_auc']:.3f} -> {c1['leaky_live_roc_auc']:.3f}", "css_class": "is-slow"},
{"label": "c3_smote_before_vs_clean_pr", "value": _pos_bar(c3["smote_before_cv_pr_auc"]), "display": f"PR {c3['smote_before_cv_pr_auc']:.3f} -> {c3['clean_logreg_pr_auc']:.3f}", "css_class": "is-slow"},
{"label": "c4_random_vs_group_kfold", "value": _pos_bar(c4["random_kfold_roc_auc"]), "display": f"{c4['random_kfold_roc_auc']:.3f} -> {c4['group_kfold_roc_auc']:.3f}", "css_class": "is-mid"},
{"label": "c6_backfill_off_vs_live", "value": _pos_bar(c6["backfill_offline_roc_auc"]), "display": f"{c6['backfill_offline_roc_auc']:.3f} -> {c6['backfill_live_roc_auc']:.3f}", "css_class": "is-slow"},
],
},
{
"id": "bar_canary_detection_sensitivity",
"title": "Automated Leakage Canary Detection Signals Across Vectors",
"metric_label": "Canary AUC / Rate",
"items": [
{"label": "canary_1d_proxy_auc", "value": _pos_bar(c1["dominance_canary"]["max_sym_auc_1d"]), "display": f"1D AUC {c1['dominance_canary']['max_sym_auc_1d']:.3f}", "css_class": "is-fast"},
{"label": "canary_perm_null_te_auc", "value": _pos_bar(c3["perm_leaky_te_null_mean_auc"]), "display": f"Null {c3['perm_leaky_te_null_mean_auc']:.3f}", "css_class": "is-fast"},
{"label": "canary_quad_c2st_backfill", "value": _pos_bar(c6["quadratic_c2st_auc"]), "display": f"Quad {c6['quadratic_c2st_auc']:.3f} (Lin {c6['linear_c2st_auc']:.3f})", "css_class": "is-fast"},
{"label": "canary_dup_c2st_vs_hash", "value": _pos_bar(c5["dup_exact_hash_rate"] + c5["dup_near_dup_rate"]), "display": f"Hash {c5['dup_exact_hash_rate']*100:.1f}% (C2ST {c5['c2st_dup_auc_blind']:.2f})", "css_class": "is-mid"},
],
},
{
"id": "bar_calibrator_logloss_and_ace",
"title": "Post-Hoc Calibrator Out-of-Time Log-Loss & Adaptive Calibration Error (ACE-15)",
"metric_label": "Log-Loss",
"items": [
{"label": "raw_uncalibrated", "value": _pos_bar(d_raw["log_loss"]), "display": f"NLL {d_raw['log_loss']:.4f} | ACE {d_raw['ace']:.4f}", "css_class": "is-slow"},
{"label": "temperature_1p", "value": _pos_bar(d_temp["log_loss"]), "display": f"NLL {d_temp['log_loss']:.4f} | ACE {d_temp['ace']:.4f}", "css_class": "is-mid"},
{"label": "platt_2p_laplace", "value": _pos_bar(d_platt["log_loss"]), "display": f"NLL {d_platt['log_loss']:.4f} | ACE {d_platt['ace']:.4f}", "css_class": "is-fast"},
{"label": "ivap_venn_abers", "value": _pos_bar(d_ivap["log_loss"]), "display": f"NLL {d_ivap['log_loss']:.4f} | ACE {d_ivap['ace']:.4f}", "css_class": "is-fast"},
],
},
{
"id": "bar_decision_policy_net_savings",
"title": f"Fraud Queue (K={cd['capacity_k']}) Daily Net Dollar Savings vs Approve-All Baseline",
"metric_label": "Net Savings ($)",
"items": [
{"label": "fifo_saturated_queue", "value": _pos_bar(pol_fifo["net_savings_vs_baseline"]), "display": f"${pol_fifo['net_savings_vs_baseline']:,.0f} ({pol_fifo['dollar_recall']*100:.1f}% $Rec)", "css_class": "is-slow"},
{"label": "naive_t_050_prob_sort", "value": _pos_bar(pol_050["net_savings_vs_baseline"]), "display": f"${pol_050['net_savings_vs_baseline']:,.0f} ({pol_050['dollar_recall']*100:.1f}% $Rec)", "css_class": "is-mid"},
{"label": "uncal_capacity_topk", "value": _pos_bar(pol_utop["net_savings_vs_baseline"]), "display": f"${pol_utop['net_savings_vs_baseline']:,.0f} ({pol_utop['dollar_recall']*100:.1f}% $Rec)", "css_class": "is-mid"},
{"label": "cal_ivap_capacity_topk", "value": _pos_bar(pol_ctop["net_savings_vs_baseline"]), "display": f"${pol_ctop['net_savings_vs_baseline']:,.0f} ({pol_ctop['dollar_recall']*100:.1f}% $Rec)", "css_class": "is-fast"},
],
},
]
tables = [
{
"id": "table_six_class_leakage_canary_audit",
"title": "6-Class Evaluation Leakage Audit & Canary Gate Signals",
"columns": ["Leakage Class", "Apparent Metric", "Clean OOT / Live Metric", "Primary Canary Detector Signal", "Gate Action"],
"rows": [
["Class 1: Target Proxy", f"ROC {c1['leaky_offline_roc_auc']:.3f}", f"Live ROC {c1['leaky_live_roc_auc']:.3f}", f"1D AUC={c1['dominance_canary']['max_sym_auc_1d']:.3f} ({c1['dominance_canary']['top_feature']})", "BLOCK (Drop post-outcome feature)"],
["Class 2: Temporal & Maturity", f"Rand AUC {c2['overlap_random_split_auc']:.3f} | 0d {c2['naive_relative_bias']*100:+.1f}%", f"Purged AUC {c2['overlap_purged_oot_auc']:.3f} | 60d {c2['purged_relative_bias']*100:+.1f}%", f"Immature rate ratio={c2['immature_vs_mature_prev_ratio']:.2f}", "BLOCK (Purged OOT + >=60d maturity)"],
["Class 3: SMOTE & TE Before CV", f"PR {c3['smote_before_cv_pr_auc']:.3f} (AUC {c3['smote_before_cv_roc_auc']:.3f})", f"Clean PR {c3['clean_logreg_pr_auc']:.3f} (AUC {c3['clean_logreg_roc_auc']:.3f})", f"Perm-Null TE={c3['perm_leaky_te_null_mean_auc']:.3f}; Prox={c3['smote_before_cv_median_prox']:.2f}", "BLOCK (Move inside fold + prior offset)"],
["Class 4: Group Overlap", f"Rand AUC {c4['random_kfold_roc_auc']:.3f}", f"Group AUC {c4['group_kfold_roc_auc']:.3f}", f"GroupKFold intersection={c4['group_kfold_overlap_count']}", "BLOCK (Enforce GroupKFold)"],
["Class 5: Exact/Near Duplicates", f"Dup 1NN AUC {c5['dup_split_1nn_roc_auc']:.3f}", f"Dedup AUC {c5['clean_dedup_1nn_roc_auc']:.3f}", f"C2ST blind {c5['c2st_dup_auc_blind']:.3f} vs Hash {c5['dup_exact_hash_rate']*100:.1f}%", "BLOCK (Pre-split SHA-256 + NNDR)"],
["Class 6: Feature Store ASOF", f"Off AUC {c6['backfill_offline_roc_auc']:.3f}", f"Live AUC {c6['backfill_live_roc_auc']:.3f} (Clean {c6['clean_pit_roc_auc']:.3f})", f"Quad C2ST={c6['quadratic_c2st_auc']:.3f}; E-C2ST={c6['ec2st_final_wealth']:.1e}", "BLOCK (SCD-2 PIT ASOF join)"],
],
},
{
"id": "table_calibrator_benchmark_comparison",
"title": f"Proper Scoring & Calibration Comparison (n_cal={cal['n_cal']}, n_test={cal['n_test']})",
"columns": ["Calibrator", "Log-Loss", "Brier Score", "Murphy REL / RES", "ECE-15 / ACE-15", "SmoothECE*", "ROC-AUC"],
"rows": [
["Uncalibrated Raw", f"{d_raw['log_loss']:.4f}", f"{d_raw['brier_score']:.5f}", f"{d_raw['reliability']:.5f} / {d_raw['resolution']:.5f}", f"{d_raw['ece']:.4f} / {d_raw['ace']:.4f}", f"{d_raw['smooth_ece']:.4f}", f"{d_raw['roc_auc']:.4f}"],
["Temperature Scaling (1p)", f"{d_temp['log_loss']:.4f}", f"{d_temp['brier_score']:.5f}", f"{d_temp['reliability']:.5f} / {d_temp['resolution']:.5f}", f"{d_temp['ece']:.4f} / {d_temp['ace']:.4f}", f"{d_temp['smooth_ece']:.4f}", f"{d_temp['roc_auc']:.4f}"],
["Platt Scaling (2p)", f"{d_platt['log_loss']:.4f}", f"{d_platt['brier_score']:.5f}", f"{d_platt['reliability']:.5f} / {d_platt['resolution']:.5f}", f"{d_platt['ece']:.4f} / {d_platt['ace']:.4f}", f"{d_platt['smooth_ece']:.4f}", f"{d_platt['roc_auc']:.4f}"],
["Beta Calibration (3p)", f"{d_beta['log_loss']:.4f}", f"{d_beta['brier_score']:.5f}", f"{d_beta['reliability']:.5f} / {d_beta['resolution']:.5f}", f"{d_beta['ece']:.4f} / {d_beta['ace']:.4f}", f"{d_beta['smooth_ece']:.4f}", f"{d_beta['roc_auc']:.4f}"],
["PAVA Isotonic", f"{d_pava['log_loss']:.4f}", f"{d_pava['brier_score']:.5f}", f"{d_pava['reliability']:.5f} / {d_pava['resolution']:.5f}", f"{d_pava['ece']:.4f} / {d_pava['ace']:.4f}", f"{d_pava['smooth_ece']:.4f}", f"{d_pava['roc_auc']:.4f}"],
["Inductive Venn-Abers (IVAP)", f"{d_ivap['log_loss']:.4f}", f"{d_ivap['brier_score']:.5f}", f"{d_ivap['reliability']:.5f} / {d_ivap['resolution']:.5f}", f"{d_ivap['ece']:.4f} / {d_ivap['ace']:.4f}", f"{d_ivap['smooth_ece']:.4f}", f"{d_ivap['roc_auc']:.4f}"],
["Cross Venn-Abers (CVAP-5)", f"{d_cvap['log_loss']:.4f}", f"{d_cvap['brier_score']:.5f}", f"{d_cvap['reliability']:.5f} / {d_cvap['resolution']:.5f}", f"{d_cvap['ece']:.4f} / {d_cvap['ace']:.4f}", f"{d_cvap['smooth_ece']:.4f}", f"{d_cvap['roc_auc']:.4f}"],
],
},
{
"id": "table_small_n_and_shift_regimes",
"title": "Regime Ablations: Small n_cal=200 Overfit, Beta Skew & 3-Class Dirichlet ODIR",
"columns": ["Experimental Regime", "Comparator A", "Comparator B", "Comparator C", "Engineering Takeaway"],
"rows": [
["Small Holdout (n_cal=200, Overconfident)", f"Temp NLL={sm_n['temp_logloss']:.4f}", f"Platt NLL={sm_n['platt_logloss']:.4f}", f"PAVA NLL={sm_n['pava_logloss']:.4f} (IVAP={sm_n['ivap_logloss']:.4f})", "PAVA overfits severely at n=200; Temp & IVAP dominate"],
["Prior + Slope Shift (Main Cohort)", f"Temp ACE={d_temp['ace']:.4f}", f"Platt ACE={d_platt['ace']:.4f}", f"IVAP ACE={d_ivap['ace']:.4f}", "1-param Temp blind to intercept shift; Platt/IVAP fix both"],
["Skewed Beta Score Tails", f"Platt ACE={skew['platt_ace']:.4f}", f"Beta ACE={skew['beta_ace']:.4f}", f"Beta NLL={skew['beta_logloss']:.4f} vs Platt {skew['platt_logloss']:.4f}", "Beta Calibration captures asymmetric tail densities"],
["3-Class Logit Shift (Dirichlet ODIR)", f"Raw NLL={mc['raw_logloss']:.4f}", f"Temp NLL={mc['temp_logloss']:.4f}", f"Dirichlet+ODIR NLL={mc['dirichlet_odir_logloss']:.4f}", "Dirichlet+ODIR fixes per-class bias without O(K^2) overfit"],
],
},
{
"id": "table_cost_and_capacity_policy_shootout",
"title": f"Cost-Sensitive & Capacity-Constrained Fraud Triage (Cap K={cd['capacity_k']}, Exposure=${cd['total_fraud_exposure_usd']:,.0f})",
"columns": ["Decision Policy", "Executed Alerts", "Fraud Caught (TP)", "Count Recall", "Dollar Recall", "Net Savings vs Approve-All"],
"rows": [
["1. Naive Cutoff t=0.50 (Raw Prob Sort)", f"{pol_050['alerts']}", f"{pol_050['tp']}", f"{pol_050['recall']*100:.1f}%", f"{pol_050['dollar_recall']*100:.1f}%", f"${pol_050['net_savings_vs_baseline']:,.2f}"],
[f"2. Uncal Global t*={cd['global_t_star']:.3f} (Cand={pol_ug['uncapped_candidates']})", f"{pol_ug['alerts']}", f"{pol_ug['tp']}", f"{pol_ug['recall']*100:.1f}%", f"{pol_ug['dollar_recall']*100:.1f}%", f"${pol_ug['net_savings_vs_baseline']:,.2f}"],
[f"3. Cal Global t*={cd['global_t_star']:.3f} (Cand={pol_cg['uncapped_candidates']})", f"{pol_cg['alerts']}", f"{pol_cg['tp']}", f"{pol_cg['recall']*100:.1f}%", f"{pol_cg['dollar_recall']*100:.1f}%", f"${pol_cg['net_savings_vs_baseline']:,.2f}"],
[f"4. Cal Instance t*(x) FIFO Saturated (Cand={pol_fifo['uncapped_candidates']})", f"{pol_fifo['alerts']}", f"{pol_fifo['tp']}", f"{pol_fifo['recall']*100:.1f}%", f"{pol_fifo['dollar_recall']*100:.1f}%", f"${pol_fifo['net_savings_vs_baseline']:,.2f}"],
["5. Uncal Capacity Top-K (Miscalibrated Rank)", f"{pol_utop['alerts']}", f"{pol_utop['tp']}", f"{pol_utop['recall']*100:.1f}%", f"{pol_utop['dollar_recall']*100:.1f}%", f"${pol_utop['net_savings_vs_baseline']:,.2f}"],
[f"6. Cal IVAP Capacity Top-K (mu*=${pol_ctop['shadow_price_mu']:.2f})", f"{pol_ctop['alerts']}", f"{pol_ctop['tp']}", f"{pol_ctop['recall']*100:.1f}%", f"{pol_ctop['dollar_recall']*100:.1f}%", f"${pol_ctop['net_savings_vs_baseline']:,.2f}"],
["7. Cal Instance t*(x) Uncapped Upper Bound", f"{pol_uncap['alerts']}", f"{pol_uncap['tp']}", f"{pol_uncap['recall']*100:.1f}%", f"{pol_uncap['dollar_recall']*100:.1f}%", f"${pol_uncap['net_savings_vs_baseline']:,.2f}"],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
bench = run_full_ch07_benchmarks(seed=args.seed, quick=args.quick)
panels = _build_workbench_panels(bench)
payload = _sanitize_json_value(
{
"config": {"seed": args.seed, "quick": bool(args.quick), "output": args.output},
"workbench_panels": panels,
"benchmarks": bench,
}
)
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")
print("=== Lab 07: Leakage-Proof Evaluation, Calibration & Bayes Cost Workbench ===")
for kpi in panels["kpis"]:
print(f"[{kpi['status'].upper():8s}] {kpi['label']}: {kpi['value']} ({kpi['unit']})")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Automated 14-test contract verification suite for Lab 07 (`eval_calibration_lab`)."""
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
from eval_calibration_lab import (
BetaCalibrator,
CalibratorConfig,
CostMatrixConfig,
CrossVennAbersCalibrator,
DirichletODIRCalibrator,
InductiveVennAbersCalibrator,
IsotonicPavaCalibrator,
LeakageAuditConfig,
PlattScalingCalibrator,
TemperatureScalingCalibrator,
audit_class1_target_proxy_leakage,
audit_class2_temporal_and_maturity_leakage,
audit_class3_smote_and_preproc_before_cv,
audit_class4_group_overlap_leakage,
audit_class5_duplicate_leakage,
audit_class6_feature_store_asof_skew,
compute_bayes_threshold,
compute_brier_and_murphy,
compute_calibration_diagnostics,
compute_instance_thresholds,
compute_log_loss,
compute_miscalibration_profit_collapse,
compute_roc_auc,
compute_spherical_score,
evaluate_decision_policy,
fit_bayes_prior_offset,
fit_pava_blocks,
ivap_bruteforce_p0_p1,
logit_from_proba,
make_leakage_audit_dataframe,
solve_capacity_constrained_triage,
stable_sigmoid,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
# ---------------------------------------------------------------------------
# Test 1: Strict Pydantic Configs & Class 1 Target-Proxy Dominance Canary
# ---------------------------------------------------------------------------
def test_pydantic_strict_configs_and_class1_target_proxy_dominance_canary() -> None:
with pytest.raises(ValidationError):
LeakageAuditConfig(unknown_flag=True) # extra="forbid"
with pytest.raises(ValidationError):
CalibratorConfig(eps=-0.1)
with pytest.raises(ValidationError):
CostMatrixConfig(unknown_cost=99.0)
c1 = audit_class1_target_proxy_leakage(seed=42, quick=True)
assert c1["leaky_offline_roc_auc"] > c1["clean_oot_roc_auc"] + 0.12
assert c1["leaky_live_roc_auc"] < c1["leaky_offline_roc_auc"] - 0.15
assert "refund_issued_proxy" in c1["dominance_canary"]["flagged_features"]
assert c1["dominance_canary"]["max_sym_auc_1d"] > 0.90
assert c1["c2st_offline_vs_live_auc"] > 0.55
# ---------------------------------------------------------------------------
# Test 2: Class 2 Temporal Look-Ahead & Label-Maturity Truncation Bias
# ---------------------------------------------------------------------------
def test_class2_temporal_lookahead_and_label_maturity_truncation_bias() -> None:
c2 = audit_class2_temporal_and_maturity_leakage(seed=42, quick=True)
# Random split leaks overlapping 10-step horizon above pure white noise chance (0.50)
assert c2["overlap_random_split_auc"] > 0.65
assert c2["overlap_purged_oot_auc"] < c2["overlap_random_split_auc"] - 0.10
# Right-censored 0d naive window severely underpredicts mature base rate
assert c2["maturity_violation_rate"] > 0.50
assert c2["immature_vs_mature_prev_ratio"] < 0.75
assert c2["naive_relative_bias"] < -0.15
assert abs(c2["purged_relative_bias"]) < abs(c2["naive_relative_bias"])
# ---------------------------------------------------------------------------
# Test 3: Class 3 SMOTE-before-CV, Bayes Prior Offset & Permutation Null Canary
# ---------------------------------------------------------------------------
def test_class3_smote_before_cv_leakage_bayes_prior_offset_and_permutation_null() -> None:
c3 = audit_class3_smote_and_preproc_before_cv(seed=42, quick=True)
assert c3["smote_before_cv_pr_auc"] > c3["smote_inside_cv_pr_auc"] + 0.40
assert c3["smote_before_cv_roc_auc"] > 0.90
assert c3["smote_before_cv_median_prox"] < c3["clean_cv_median_prox"]
# Fold-internal SMOTE inflates mean pred far above true prevalence until Bayes offset corrects it
assert c3["smote_inside_mean_pred_unadjusted"] > c3["true_prevalence"] * 2.5
assert abs(c3["smote_inside_mean_pred_bayes_offset"] - c3["true_prevalence"]) < abs(
c3["smote_inside_mean_pred_unadjusted"] - c3["true_prevalence"]
)
# Exact Bayes prior offset check on constant predictions
p_shifted = fit_bayes_prior_offset(np.array([0.5, 0.5]), pi_train=0.5, pi_true=0.04)
assert np.allclose(p_shifted, 0.04, atol=1e-12)
# Permutation Null Canary catches leaky full-dataset TE even on completely random targets!
assert c3["perm_leaky_te_detected"] is True
assert c3["perm_leaky_te_null_mean_auc"] > 0.65
assert c3["perm_clean_te_detected"] is False
assert abs(c3["perm_clean_te_null_mean_auc"] - 0.50) < 0.05
# ---------------------------------------------------------------------------
# Test 4: Class 4 Group Overlap & Class 5 Duplicate C2ST Blindness vs NNDR
# ---------------------------------------------------------------------------
def test_class4_and_class5_group_overlap_duplicate_c2st_blindness_and_nndr() -> None:
c4 = audit_class4_group_overlap_leakage(seed=42, quick=True)
assert c4["group_kfold_overlap_count"] == 0
assert c4["random_kfold_roc_auc"] > c4["group_kfold_roc_auc"] + 0.15
c5 = audit_class5_duplicate_leakage(seed=42, quick=True)
assert c5["dup_split_1nn_roc_auc"] > c5["clean_dedup_1nn_roc_auc"] + 0.05
# C2ST stays blind (~0.50) on randomly split duplicates while SHA-256 & NNDR catch them!
assert abs(c5["c2st_dup_auc_blind"] - 0.50) < 0.08
assert c5["dup_exact_hash_rate"] > 0.10
assert c5["dup_near_dup_rate"] > c5["dup_exact_hash_rate"]
assert c5["clean_exact_hash_rate"] == 0.0
# ---------------------------------------------------------------------------
# Test 5: Class 6 Bitemporal ASOF Backfill, Quadratic C2ST & E-C2ST Martingale
# ---------------------------------------------------------------------------
def test_class6_bitemporal_asof_backfill_and_quadratic_c2st_ec2st_canaries() -> None:
c6 = audit_class6_feature_store_asof_skew(seed=42, quick=True)
assert c6["asof_violation_rate"] == 1.0
assert c6["backfill_offline_roc_auc"] > 0.90
assert c6["backfill_live_roc_auc"] < c6["clean_pit_roc_auc"]
# Quadratic C2ST catches zero-mean variance backfill skew where linear C2ST fails
assert c6["linear_c2st_auc"] < 0.56
assert c6["quadratic_c2st_auc"] > 0.70
assert c6["ec2st_rejected"] is True
assert c6["ec2st_final_wealth"] >= 20.0
df_summary = make_leakage_audit_dataframe(
{
"class1": audit_class1_target_proxy_leakage(seed=42, quick=True),
"class2": audit_class2_temporal_and_maturity_leakage(seed=42, quick=True),
"class3": audit_class3_smote_and_preproc_before_cv(seed=42, quick=True),
"class4": audit_class4_group_overlap_leakage(seed=42, quick=True),
"class5": audit_class5_duplicate_leakage(seed=42, quick=True),
"class6": c6,
}
)
assert len(df_summary) == 6
# ---------------------------------------------------------------------------
# Test 6: Strictly Proper Scoring Rules, Murphy Brier Identity & F1 Impropriety
# ---------------------------------------------------------------------------
def test_proper_scoring_rules_murphy_brier_decomposition_and_f1_impropriety() -> None:
rng = np.random.default_rng(42)
q = rng.uniform(0.05, 0.95, size=2000)
y = (rng.uniform(size=2000) < q).astype(np.int64)
# Strict propriety: oracle q beats distorted forecasts in Log-Loss, Brier, and Spherical
p_bad = np.asarray(stable_sigmoid(logit_from_proba(q) * 2.2 + 0.6))
assert compute_log_loss(y, q) < compute_log_loss(y, p_bad)
assert compute_spherical_score(y, q) > compute_spherical_score(y, p_bad)
murphy = compute_brier_and_murphy(y, p_bad, n_bins=15)
assert math.isclose(
murphy["brier_binned"],
murphy["reliability"] - murphy["resolution"] + murphy["uncertainty"],
abs_tol=1e-12,
)
assert murphy["brier_score"] > compute_brier_and_murphy(y, q, n_bins=15)["brier_score"]
# ROC-AUC invariance under strictly monotone transform
assert math.isclose(compute_roc_auc(y, q), compute_roc_auc(y, p_bad), abs_tol=1e-12)
# F1 impropriety: at true q=0.35, honest prediction at t=0.5 gives F1=0, lying upward gives F1 > 0.45!
y_const = (rng.uniform(size=3000) < 0.35).astype(np.int64)
p_honest = np.full(3000, 0.35)
p_lie = np.full(3000, 0.60)
f1_honest = evaluate_decision_policy(y_const, (p_honest >= 0.5).astype(int), 1.0, 1.0)["f1"]
f1_lie = evaluate_decision_policy(y_const, (p_lie >= 0.5).astype(int), 1.0, 1.0)["f1"]
assert f1_honest == 0.0 and f1_lie > 0.45
# ---------------------------------------------------------------------------
# Test 7: Calibration Diagnostics (ECE vs ACE, Debiased L2-CE, SmoothECE*)
# ---------------------------------------------------------------------------
def test_calibration_diagnostics_ece_vs_ace_debiased_l2_and_smoothece() -> None:
rng = np.random.default_rng(123)
# 90% crowd inside [0.005, 0.065] with opposing local bias cancelling in Bin 0 of ECE-15
n = 4000
p = np.where(
np.arange(n) < int(0.45 * n),
rng.uniform(0.005, 0.030, size=n),
np.where(np.arange(n) < int(0.90 * n), rng.uniform(0.035, 0.065, size=n), rng.uniform(0.08, 0.45, size=n)),
)
q_true = np.where(p < 0.032, p * 2.4, np.where(p < 0.067, p * 0.42, p))
y = (rng.uniform(size=n) < q_true).astype(np.int64)
diag = compute_calibration_diagnostics(y, p, n_bins=15, include_smoothece=True)
assert diag["ace"] > diag["ece"] * 2.0
assert diag["smooth_ece"] > 0.01
# Verify Kumar et al. (2019) Debiased L2-CE^2 has near-zero mean on perfectly calibrated draws
deb_vals = []
ece_vals = []
for s_idx in range(25):
r_mc = np.random.default_rng(1000 + s_idx)
p_mc = r_mc.uniform(0.05, 0.95, size=1000)
y_mc = (r_mc.uniform(size=1000) < p_mc).astype(np.int64)
d_mc = compute_calibration_diagnostics(y_mc, p_mc, n_bins=15, include_smoothece=False)
deb_vals.append(d_mc["debiased_l2_ce2"])
ece_vals.append(d_mc["ece"])
assert abs(float(np.mean(deb_vals))) < 5e-4
assert float(np.mean(ece_vals)) > 0.012 # Plug-in ECE always has positive O(sqrt(B/n)) bias
# Regression check: fine-bandwidth SmoothECE aliasing (sigma < 0.005 between coarse 1/100 grid ticks)
# 1998 alternating samples at p=0.505 cancel out; 2 positive residuals at p=0.255 yield integral mass ~0.000745
n_fine = 2000
p_fine = np.full(n_fine, 0.505, dtype=np.float64)
y_fine = np.zeros(n_fine, dtype=np.float64)
y_fine[:999] = 1.0 # symmetric half 0, half 1 at 0.505 (tiny -0.005 net mean residual there)
p_fine[-2:] = 0.255
y_fine[-2:] = 1.0
from eval_calibration_lab.calibrators import _compute_smooth_ece_fixed_point
smece_fine = _compute_smooth_ece_fixed_point(y_fine, p_fine)
assert smece_fine > 0.003, f"SmoothECE fine-bandwidth aliasing regression: got {smece_fine}"
# ---------------------------------------------------------------------------
# Test 8: Temperature, Platt, Beta Calibrators & Zero-Pickle JSON State-Dict
# ---------------------------------------------------------------------------
def test_classical_calibrators_platt_temperature_beta_and_json_state_dict() -> None:
rng = np.random.default_rng(42)
z_cal = rng.normal(-1.4, 1.3, size=1500)
z_te = rng.normal(-1.4, 1.3, size=1500)
# Both overconfidence (slope < 1) and prevalence shift (intercept != 0)
y_cal = (rng.uniform(size=1500) < np.asarray(stable_sigmoid(0.55 * z_cal - 0.9))).astype(np.int64)
y_te = (rng.uniform(size=1500) < np.asarray(stable_sigmoid(0.55 * z_te - 0.9))).astype(np.int64)
p_raw_te = np.asarray(stable_sigmoid(z_te))
temp = TemperatureScalingCalibrator().fit(z_cal, y_cal, scores_are_logits=True)
platt = PlattScalingCalibrator().fit(z_cal, y_cal, scores_are_logits=True)
p_temp = temp.predict_proba(z_te, scores_are_logits=True)
p_platt = platt.predict_proba(z_te, scores_are_logits=True)
assert math.isclose(compute_roc_auc(y_te, p_temp), compute_roc_auc(y_te, p_raw_te), abs_tol=1e-12)
assert compute_log_loss(y_te, p_platt) < compute_log_loss(y_te, p_temp)
diag_platt = compute_calibration_diagnostics(y_te, p_platt, include_smoothece=False)
diag_temp = compute_calibration_diagnostics(y_te, p_temp, include_smoothece=False)
assert diag_platt["ace"] < 0.035
assert diag_platt["ace"] < diag_temp["ace"] * 0.5
# Beta calibrator beats Platt on strongly asymmetric Beta-skewed scores
y_sk_c = rng.integers(0, 2, size=1200)
s_sk_c = np.where(y_sk_c == 1, rng.beta(4.5, 1.0, size=1200), rng.beta(1.0, 1.6, size=1200))
y_sk_t = rng.integers(0, 2, size=1500)
s_sk_t = np.where(y_sk_t == 1, rng.beta(4.5, 1.0, size=1500), rng.beta(1.0, 1.6, size=1500))
beta_c = BetaCalibrator().fit(s_sk_c, y_sk_c)
platt_sk = PlattScalingCalibrator().fit(s_sk_c, y_sk_c)
assert beta_c.a_ >= 0.0 and beta_c.b_ >= 0.0
assert compute_log_loss(y_sk_t, beta_c.predict_proba(s_sk_t)) < compute_log_loss(
y_sk_t, platt_sk.predict_proba(s_sk_t)
)
# JSON State-Dict round-trip exactness
platt_rt = PlattScalingCalibrator.from_state_dict(json.loads(json.dumps(platt.to_state_dict())))
temp_rt = TemperatureScalingCalibrator.from_state_dict(json.loads(json.dumps(temp.to_state_dict())))
beta_rt = BetaCalibrator.from_state_dict(json.loads(json.dumps(beta_c.to_state_dict())))
assert np.allclose(platt.predict_proba(z_te, scores_are_logits=True), platt_rt.predict_proba(z_te, scores_are_logits=True), atol=1e-12)
assert np.allclose(temp.predict_proba(z_te, scores_are_logits=True), temp_rt.predict_proba(z_te, scores_are_logits=True), atol=1e-12)
assert np.allclose(beta_c.predict_proba(s_sk_t), beta_rt.predict_proba(s_sk_t), atol=1e-12)
# ---------------------------------------------------------------------------
# Test 9: PAVA Isotonic KKT Optimality, Tie Invariance & Small-n Overfit
# ---------------------------------------------------------------------------
def test_pava_isotonic_kkt_optimality_ties_and_small_n_overfit() -> None:
rng = np.random.default_rng(7)
s = rng.choice([0.1, 0.2, 0.35, 0.5, 0.7, 0.85, 0.9], size=80)
y = rng.integers(0, 2, size=80).astype(np.float64)
sol = fit_pava_blocks(s, y)
# Monotonicity & exact KKT verification: every prefix inside every merged block has mean >= block mean (lambda_k >= 0)
assert np.all(np.diff(sol.block_values) >= -1e-12)
assert np.all(np.diff(sol.unique_fitted) >= -1e-12)
pos = 0
for b_idx in range(len(sol.block_values)):
b_val = sol.block_values[b_idx]
b_w = sol.block_weights[b_idx]
cum_w = 0.0
cum_s = 0.0
while pos < len(sol.unique_scores) and cum_w < b_w - 1e-12:
cum_w += sol.unique_weights[pos]
cum_s += sol.unique_pos_sums[pos]
if cum_w < b_w - 1e-12:
assert (cum_s - cum_w * b_val) >= -1e-11 # Dual multiplier lambda_k >= 0!
pos += 1
assert math.isclose(cum_s / cum_w, b_val, abs_tol=1e-11)
with pytest.raises(ValueError):
sol.unique_fitted[0] = 0.5 # Read-only buffer
# Small-ncal=150 PAVA overfits badly compared to Temperature Scaling
z_sm = rng.normal(0.0, 1.5, size=150)
y_sm = (rng.uniform(size=150) < np.asarray(stable_sigmoid(z_sm / 2.0))).astype(np.int64)
z_te = rng.normal(0.0, 1.5, size=1500)
y_te = (rng.uniform(size=1500) < np.asarray(stable_sigmoid(z_te / 2.0))).astype(np.int64)
pava_sm = IsotonicPavaCalibrator().fit(np.asarray(stable_sigmoid(z_sm)), y_sm)
temp_sm = TemperatureScalingCalibrator().fit(z_sm, y_sm, scores_are_logits=True)
assert compute_log_loss(y_te, temp_sm.predict_proba(z_te, scores_are_logits=True)) < compute_log_loss(
y_te, pava_sm.predict_proba(np.asarray(stable_sigmoid(z_te)))
)
# ---------------------------------------------------------------------------
# Test 10: Fast O(m log m) IVAP Parity vs Brute-Force PAVA & CVAP
# ---------------------------------------------------------------------------
def test_inductive_venn_abers_fast_parity_with_bruteforce_pava_and_cvap() -> None:
rng = np.random.default_rng(42)
for trial in range(40):
m = int(rng.integers(3, 60))
if trial % 2 == 0:
s_cal = rng.choice([0.05, 0.2, 0.4, 0.6, 0.8, 0.95], size=m).astype(np.float64)
else:
s_cal = rng.normal(0.0, 1.0, size=m)
y_cal = rng.integers(0, 2, size=m).astype(np.float64)
s_test = np.concatenate([s_cal[: min(4, m)], rng.normal(0.0, 1.5, size=20), [np.min(s_cal) - 0.5, np.max(s_cal) + 0.5]])
ivap = InductiveVennAbersCalibrator().fit(s_cal, y_cal)
fp0, fp1 = ivap.predict_p0_p1(s_test)
bp0, bp1 = ivap_bruteforce_p0_p1(s_cal, y_cal, s_test)
assert np.allclose(fp0, bp0, atol=1e-12)
assert np.allclose(fp1, bp1, atol=1e-12)
assert np.all(fp0 < fp1)
assert np.all(fp1 >= (1.0 / (m + 1)) - 1e-12)
assert np.all(fp0 <= (m / (m + 1)) + 1e-12)
p_va = ivap.predict_proba(s_test)
assert np.all((p_va >= fp0 - 1e-12) & (p_va <= fp1 + 1e-12))
assert np.all((p_va > 0.0) & (p_va < 1.0)) # Never infinite Log-Loss boundary 0/1!
# JSON round-trip & CVAP calibration check
s_c = rng.normal(0.0, 1.4, size=800)
y_c = (rng.uniform(size=800) < np.asarray(stable_sigmoid(0.6 * s_c - 0.8))).astype(np.int64)
s_t = rng.normal(0.0, 1.4, size=1000)
y_t = (rng.uniform(size=1000) < np.asarray(stable_sigmoid(0.6 * s_t - 0.8))).astype(np.int64)
ivap_f = InductiveVennAbersCalibrator().fit(s_c, y_c)
ivap_rt = InductiveVennAbersCalibrator.from_state_dict(json.loads(json.dumps(ivap_f.to_state_dict())))
assert np.allclose(ivap_f.predict_proba(s_t), ivap_rt.predict_proba(s_t), atol=1e-12)
cvap = CrossVennAbersCalibrator(n_folds=5, seed=42).fit(s_c, y_c)
p_cvap = cvap.predict_proba(s_t)
assert compute_log_loss(y_t, p_cvap) < compute_log_loss(y_t, np.asarray(stable_sigmoid(s_t)))
# Regression check: CVAP fits strictly on disjoint K-fold out-of-fold splits (Vovk et al. 2015)
assert sum(cal.n_cal_ for cal in cvap.fold_calibrators_) == len(y_c)
all_cvap_idx = np.concatenate(cvap.fold_indices_)
assert len(all_cvap_idx) == len(y_c) and len(np.unique(all_cvap_idx)) == len(y_c)
# ---------------------------------------------------------------------------
# Test 11: Multiclass Dirichlet + ODIR & Temperature Scaling
# ---------------------------------------------------------------------------
def test_multiclass_dirichlet_odir_and_temperature_scaling() -> None:
rng = np.random.default_rng(42)
n_c, n_t, k = 800, 1200, 3
z_c = rng.normal(0.0, 1.5, size=(n_c, k)) + np.array([[0.9, -0.5, -0.4]])
z_t = rng.normal(0.0, 1.5, size=(n_t, k)) + np.array([[0.9, -0.5, -0.4]])
true_c = DirichletODIRCalibrator._softmax(z_c * 0.5 + np.array([[-0.4, 0.25, 0.15]]))
true_t = DirichletODIRCalibrator._softmax(z_t * 0.5 + np.array([[-0.4, 0.25, 0.15]]))
y_c = np.array([rng.choice(k, p=r) for r in true_c], dtype=np.int64)
y_t = np.array([rng.choice(k, p=r) for r in true_t], dtype=np.int64)
p_raw = DirichletODIRCalibrator._softmax(z_t)
temp_mc = TemperatureScalingCalibrator().fit(z_c, y_c, scores_are_logits=True)
p_temp = temp_mc.predict_proba(z_t, scores_are_logits=True)
assert np.array_equal(np.argmax(p_raw, axis=1), np.argmax(p_temp, axis=1)) # Exact Top-1 invariance!
dir_cal = DirichletODIRCalibrator(lambda_diag=1.0, lambda_off=8.0).fit(DirichletODIRCalibrator._softmax(z_c), y_c)
p_dir = dir_cal.predict_proba(p_raw)
assert compute_log_loss(y_t, p_dir) < compute_log_loss(y_t, p_temp) < compute_log_loss(y_t, p_raw)
assert np.allclose(np.sum(p_dir, axis=1), 1.0, atol=1e-12)
dir_rt = DirichletODIRCalibrator.from_state_dict(json.loads(json.dumps(dir_cal.to_state_dict())))
assert np.allclose(p_dir, dir_rt.predict_proba(p_raw), atol=1e-12)
# ---------------------------------------------------------------------------
# Test 12: Bayes Cost Threshold, Instance t*(x) & Identical-AUC Profit Collapse
# ---------------------------------------------------------------------------
def test_bayes_cost_threshold_instance_dependent_and_miscalibration_profit_collapse() -> None:
# Cost formulation vs Utility (benefit) formulation match identically:
# C_FP - C_TN = 25 - (-10) = 35; C_FN - C_TP = 500 - (+5) = 495 (since benefit_tp=-5 => C_TP=+5) -> 35 / 530
t_cost = compute_bayes_threshold(cost_fp=25.0, cost_fn=500.0, benefit_tp=-5.0, benefit_tn=10.0)
assert math.isclose(t_cost, 35.0 / 530.0, abs_tol=1e-12)
inst_t = compute_instance_thresholds(cost_fp=np.array([15.0, 15.0]), cost_fn=np.array([30.0, 5015.0]))
assert math.isclose(inst_t[0], 15.0 / 45.0, abs_tol=1e-12)
assert math.isclose(inst_t[1], 15.0 / 5030.0, abs_tol=1e-12)
pcol = compute_miscalibration_profit_collapse(seed=42, quick=True)
# Identical ROC-AUC across all 4 monotone transforms!
assert math.isclose(pcol["roc_auc_oracle"], pcol["roc_auc_overconfident"], abs_tol=1e-12)
assert math.isclose(pcol["roc_auc_oracle"], pcol["roc_auc_underconfident"], abs_tol=1e-12)
assert math.isclose(pcol["roc_auc_oracle"], pcol["roc_auc_prior_shifted"], abs_tol=1e-12)
# Yet profit collapses severely (and prior-shifted causes Net Benefit < 0 net harm!)
assert pcol["calibrated_net_savings"] > pcol["overconfident_net_savings"] + 500.0
assert pcol["calibrated_net_savings"] > pcol["underconfident_net_savings"] + 5000.0
assert pcol["calibrated_net_savings"] > pcol["prior_shifted_net_savings"] + 15000.0
assert pcol["prior_shifted_nb_at_tstar"] < 0.0
# ---------------------------------------------------------------------------
# Test 13: Capacity-Constrained Knapsack Shadow Price mu* & DCA Harm
# ---------------------------------------------------------------------------
def test_capacity_constrained_knapsack_shadow_price_and_decision_curve() -> None:
# Heterogeneous ranking inversion example (exact analytical check)
# Item A: amt=100, true p=0.20 -> u=10; uncal p_hat=0.85 -> u_hat=75
# Item B: amt=200, true p=0.35 -> u=60; uncal p_hat=0.40 -> u_hat=70
c_fp = np.array([10.0, 10.0, 10.0])
c_fn = np.array([100.0, 200.0, 50.0])
p_cal = np.array([0.20, 0.35, 0.50])
p_uncal = np.array([0.85, 0.40, 0.15])
sol_cal = solve_capacity_constrained_triage(p_cal, c_fp, c_fn, capacity_k=1)
sol_uncal = solve_capacity_constrained_triage(p_uncal, c_fp, c_fn, capacity_k=1)
assert sol_cal["actions"][1] == 1 and sol_cal["actions"][0] == 0 # Picks B ($60 EV vs $10)
assert sol_uncal["actions"][0] == 1 and sol_uncal["actions"][1] == 0 # Miscalibration picks A!
assert sol_cal["shadow_price_mu"] > 0.0
assert np.all(sol_cal["effective_thresholds"] > compute_instance_thresholds(c_fp, c_fn))
# Full benchmark check: Calibrated Capacity Top-K outperforms Naive t=0.50 & Uncalibrated Top-K
from eval_calibration_lab.cost_decision_engine import run_full_ch07_benchmarks
bench = run_full_ch07_benchmarks(seed=42, quick=True)
cd = bench["cost_decisions"]
assert cd["cal_capacity_topk"]["net_savings_vs_baseline"] > cd["naive_t050"]["net_savings_vs_baseline"]
assert cd["cal_capacity_topk"]["net_savings_vs_baseline"] > cd["uncal_capacity_topk"]["net_savings_vs_baseline"]
assert cd["cal_capacity_topk"]["dollar_recall"] > cd["naive_t050"]["dollar_recall"]
# ---------------------------------------------------------------------------
# Test 14: CLI Demo Execution, Workbench JSON Contract & Zero Forbidden Imports
# ---------------------------------------------------------------------------
def test_cli_demo_script_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch07_demo.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
],
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed: {proc.stderr}"
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert kpi["value"] and kpi["label"]
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
# Security-Only AST deserialization scan across src/, scripts/, and tests/
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) >= 6
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}"
ASOF)
refund_issued_proxy (Lớp 1) hay cột kho dữ liệu SCD Type-1 ghi đè không giữ dấu ASOF (Lớp 6) lại đưa ROC-AUC ngoại tuyến lên 0.989–1.000 nhưng sụp xuống 0.603–0.802 khi phục vụ thật?refund_issued_proxy bị cổng 1D Dominance bắt tại AUC = 0.946, còn Lớp 6 vi phạm ASOF 100%.
SMOTE-trước-CV (1 - 1/K^2) & Canary Hoán vị Nhãn
SMOTE trước 5-Fold CV trên dữ liệu mất cân bằng 3.9% (Lab 07), điều gì xảy ra với nhiễm chéo cha–con, PR-AUC, và xác suất dự báo nếu đưa SMOTE vào trong nếp mà quên bù log-odds?96% điểm SMOTE ở tập val có cha mẹ ở tập train. Đồng thời Full-TE trước tách bị Canary Hoán vị Nhãn tóm sống với Null AUC = 0.880 trên nhãn xáo ngẫu nhiên (vs. 0.496 sạch).
Label-Maturity) & Điểm mù C2ST Trước Bản sao
0d vs. 60d purge) và sự bổ trợ giữa C2ST bậc hai với băm SHA-256 / NNDR?C2ST không vượt nổi 0.500. Do đó SHA-256 + NNDR và Quad C2ST / E-C2ST (supermartingale Ville \(M_t \ge 1/\alpha\)) phải đi cùng nhau.
Log-Loss, Murphy Brier, Spherical) vs. \(F_1\)
Log-Loss, Brier Score và Spherical Score là các quy tắc tính điểm chuẩn nghiêm ngặt (strictly proper), trong khi ROC-AUC và \(F_1\) (ngưỡng 0.50) lại thất bại?0.50 ép mô hình trung thực dự đoán toàn 0 (F1 = 0) trong khi nói dối tăng lên 0.60 thu được F1 > 0.45, chứng minh \(F_1\) khuyến khích thổi phồng xác suất.
ECE vs. ACE, Debiased L2-CE & SmoothECE
[0, 0.07], những khuyết tật nào của ECE đều chiều rộng đã được ACE, Debiased L2-CE (Kumar 2019) và SmoothECE (Błasiok 2024) khắc phục?[0.005, 0.065], ACE cao hơn 2x–4.4x ECE vì không bị triệt tiêu trong Bin 0, còn kiểm định Monte Carlo chứng minh debiased_l2_ce2 đạt kỳ vọng < 5e-4 trong khi plug-in ECE dương rõ rệt (> 0.012).
Temperature, Platt, Beta, PAVA, Dirichlet+ODIR)
Lab 07 khi chọn bộ hiệu chuẩn hậu nghiệm trên tập \(\mathcal{D}_{\text{cal}}\) tách rời, kết luận nào ĐÚNG?n_cal = 200, PAVA tạo bậc thang nhiễu làm nổ Log-Loss (0.7313 vs. Temperature 0.6294). Ngược lại khi có dịch chuyển tỷ lệ nền (Case 1/3), 1 tham số \(T\) thiếu hệ số chặn nên phải dùng Platt, Beta (khi hai đuôi bất đối xứng), Dirichlet+ODIR (đa lớp), hoặc IVAP.
Inductive & Cross Venn-Abers (IVAP/CVAP)
Inductive Venn-Abers (IVAP) vừa đạt bảo chứng hiệu chuẩn hữu hạn mẫu không tham số, vừa chạy được ở phục vụ trực tuyến < 0.2 ms?InductiveVennAbersCalibrator tiền tính hai bao lồi + đối ngẫu đảo nhãn khớp chính xác ivap_bruteforce_p0_p1 tới 1.11e-16, tự động cho ra cận bất định (p0, p1) để định tuyến 3.4% ca chạm ngưỡng sang duyệt tay.
$69,952 bị chặn công suất thẩm định K = 120 ca/ngày (Lab 07), vì sao giữ nguyên ROC-AUC = 0.860 vẫn gây mất $35,000 khi lệch hiệu chuẩn, và chính sách nào tối đa hóa lợi nhuận hàng đợi?$15 đến $5,000, so sánh \(\Delta u_1 > \Delta u_2\) cần hiệu chuẩn định lượng tuyệt đối (cardinal calibration) chính xác. FIFO bão hòa chỉ thu $4,799 (8.7% Dollar Recall), trong khi Ba-lô Lagrangian IVAP thu $39,611 (57.8% Dollar Recall) nhờ giá bóng \(\mu^* = 131.00\) USD/slot.
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 — Hình thức hóa Lọc \(\mathcal{F}_{t_{\text{obs}}}\) & Kiểm toán 6 Lớp Rò rỉ trong leakage_auditor.py
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết rõ hai điều kiện gây rò rỉ (Điều kiện A: \(\sigma(\tilde{\mathbf{X}}) \not\subseteq \mathcal{F}_{t_{\text{obs}}}\); Điều kiện B: \(\mathcal{D}_{\text{tr}} \not\perp \mathcal{D}_{\text{te}}\)) và điều kiện lưỡng thời điểm ASOF: \(\tau_{\text{event}} \le t_{\text{obs}} - \Delta_{\text{sla}} \land \tau_{\text{avail}} \le t_{\text{obs}}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi các hàm audit_class1..class6_* và make_leakage_audit_dataframe trong eval_calibration_lab.leakage_auditor, đối chiếu ngưỡng bắt của 1D Dominance, Quadratic C2ST / E-C2ST, và SHA-256 / NNDR.
Tiêu chí Đáp án & Số đối chứng
Lớp 1 refund_issued_proxy nhảy lên 0.989 -> 0.802 (1D AUC = 0.946); Lớp 2 0d nhãn trễ thiên lệch -30.8% (sửa bằng 60d purge còn -5.7%); Lớp 4 GroupKFold tụt 0.664 -> 0.486; Lớp 6 SCD-1 sụp 1.000 -> 0.603 và bị Quad C2ST = 0.961 (Lin = 0.523, E-C2ST = 1.0e+12) bắt sống.
Bài tập 2 — Chứng minh Nhiễm chéo SMOTE-trước-CV (\(1 - 1/K^2\)) & Canary Hoán vị Nhãn
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính xác suất để cả hai điểm cha mẹ \(\mathbf{x}_i, \mathbf{x}_j\) của điểm nội suy \(\mathbf{x}_{\text{syn}}\) đều rơi vào cùng nếp kiểm định (1/K^2), rồi suy ra phần bù; tiếp tục dẫn xuất độ lệch log-odds \(\ln(M+1)\) theo định lý Bayes.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy audit_class3_smote_and_preproc_before_cv, fit_bayes_prior_offset, và run_permutation_null_canary trên cả apply_naive_target_encoding lẫn apply_oof_target_encoding.
Tiêu chí Đáp án & Số đối chứng
Với K = 5, nhiễm chéo cha–con đạt 96.0%, đẩy PR-AUC của 7-NN lên 0.952 so với 0.189 của Clean LogReg (smote_inside PR = 0.060). Bù tiên nghiệm hạ dự báo nền 0.230 -> 0.072, và Perm-Null Canary bắt sống Full-TE ở 0.880 trên nhãn xáo ngẫu nhiên (OOF-TE = 0.496).
Bài tập 3 — Quy tắc Chuẩn Nghiêm ngặt (Murphy Brier, Phản chứng \(F_1\)) & Chẩn đoán ACE / smECE*
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khai triển \(\hat{p}_i - y_i = (\hat{p}_i - \bar{p}_b) + (\bar{p}_b - \bar{y}_b) + (\bar{y}_b - y_i)\) kết hợp đồng nhất thức ANOVA nhị phân để rút ra REL - RES + UNC; đồng thời giải phương trình \(\mathbb{E}[\widehat{\text{CE}}_{\text{deb}}^2] = (\bar{p}_b - \mu_b)^2\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi compute_brier_and_murphy, compute_spherical_score, và compute_calibration_diagnostics(..., include_smoothece=True) trên dữ liệu dồn vào [0.005, 0.065] và mô phỏng Monte Carlo 25 hạt.
Tiêu chí Đáp án & Số đối chứng
brier_binned khớp reliability - resolution + uncertainty tới 1e-12; tại \(q = 0.35\), báo thật cho F1 = 0.0 còn 0.60 cho F1 > 0.45; ACE phát hiện lỗi Bin 0 cao gấp >2x ECE; debiased_l2_ce2 đạt trung bình < 5e-4 (không thiên lệch) còn ECE dương > 0.012.
Bài tập 4 — Ngăn xếp PAVA KKT, Lồi Temperature & Đối chứng Chéo 3 Chế độ Hiệu chuẩn
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết hàm Lagrange của tối ưu bình phương đơn điệu để chứng minh mọi tiền tố trong khối gộp có \(\lambda_k \ge 0\); tính \(\mathcal{L}''(\beta_{\text{inv}}) = \frac{1}{m}\sum \operatorname{Var}(z_{ic})\) để chứng minh Temperature Scaling lồi toàn cục theo \(1/T\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
So sánh TemperatureScalingCalibrator, PlattScalingCalibrator, BetaCalibrator, IsotonicPavaCalibrator và DirichletODIRCalibrator ở ba chế độ trong calibrators.py và kiểm tra khứ hồi JSON.
Tiêu chí Đáp án & Số đối chứng
Ở n_cal = 200, Temperature thắng tuyệt đối (NLL = 0.6294 vs. PAVA = 0.7313); khi có dịch chuyển nền (Main Cohort), Platt hạ ACE 0.0212 -> 0.0095 (Murphy REL 0.00262 -> 0.00024); trên đuôi Beta lệch, Beta hạ ACE 0.0506 -> 0.0323; trên 3 lớp lệch nền, Dirichlet+ODIR đạt NLL = 0.9188 vs. Temp 0.9270.
Bài tập 5 — Chứng minh Inductive Venn-Abers (p_0 < p_1, Minimax p_VA) & Thuật toán Bao lồi \(O(m \log m)\)
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng đồng nhất thức max-min Barlow để chứng minh \(p_1 - p_0 \ge \frac{1}{m+1}\), rồi đặt hai nhánh hối tiếc Log-Loss \(\ln\frac{1-p_0}{1-p} = \ln\frac{p_1}{p}\) bằng nhau để suy ra \(p_{\text{VA}} = \frac{p_1}{1 - p_0 + p_1}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu InductiveVennAbersCalibrator với ivap_bruteforce_p0_p1 trên 40 bài thử ngẫu nhiên có trùng điểm số và kiểm thử CrossVennAbersCalibrator (CVAP).
Tiêu chí Đáp án & Số đối chứng
Hai bao lồi tiền tính O(m log m) + np.searchsorted O(log m) khớp PAVA vét cạn từng điểm tới 1.11e-16; IVAP đạt NLL = 0.1688 (CVAP-5 = 0.1705), ACE = 0.0137, độ rộng trung bình 0.0105, tự động chuyển 3.4% ca biên (\(t^*=0.08 \in [p_0, p_1]\)) sang duyệt tay.
Bài tập 6 — Ngưỡng Phụ thuộc Mẫu \(t^*(\mathbf{x}_i)\), Ba-lô Giá bóng \(\mu^*\) & Sụp đổ Lợi nhuận Khi ROC-AUC Không Đổi
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thiết lập bài toán Ba-lô Lagrangian \(\max \sum a_i \Delta u_i\) với \(\sum w_i a_i \le K_{\text{cap}}\) để suy ra ngưỡng hiệu dụng \(t^*_{\mu^*}(\mathbf{x}_i) = t^*(\mathbf{x}_i) + \frac{\mu^* w_i}{\Delta B_i}\), và viết tích phân tổn thất vùng bất đồng \([\min(t^*, g^{-1}(t^*)), \max(t^*, g^{-1}(t^*))]\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy compute_miscalibration_profit_collapse, solve_capacity_constrained_triage và scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch07_workbench_results.json, đồng thời đảm bảo 14/14 pytest đều PASS (0 import cấm).
Tiêu chí Đáp án & Số đối chứng
Cùng ROC-AUC = 0.860, dịch chuyển tiên nghiệm làm mất -$35,000 ($28,725 -> -$6,275, DCA NB = -0.0042). Trên hàng đợi K = 120, IVAP + Ba-lô Lagrangian (\(\mu^* = 131.00\) USD/slot) thu $39,611 (+188.3% so với t=0.50: $13,739 và gấp 8.25x FIFO: $4,799), cứu 57.8% tiền gian lận.