Chương 04 — Vòng đời Machine Learning Lặp, OOP Khoa học Dữ liệu Tái lập & Phân tích Dữ liệu Khám phá Chống Rò rỉ
Từ Vòng đời Lặp 7 Giai đoạn, Bố cục src/, Pydantic v2 & Protocol fit/transform, SeedSequence, Chứng minh Rò rỉ Tiền Tách tập, Rubin MCAR/MAR/MNAR, MAD 50%, OOF m-Estimate & Nghịch lý Simpson đến Toán học Dịch chuyển Phân phối (PSI, JSD, W_1, KS Jacobi, OOF C2ST/MMD), uv/Marimo/Pandera/Narwhals & Phả hệ SHA-256 Không-pickle.
Unit ID:
T1-P1-U04
Track & Part: Track 1 (DSAI) — Part 1: Mathematical Foundations, Statistical Inference & Causal Decision Science (part-01-math-stats-and-causal)
Truy xuất Giáo trình Gốc (R28): Lesson 3 (The ML Lifecycle: From Exploratory Data Analysis to Causal Reasoning — phủ trọn vẹn 100% 5 nội dung:OOP for Data Science,Structure a data science project,ML lifecycle,Experiment tracking, vàMethodology for efficient EDA) (Ranh giới không chồng lấn: mục 6Causal analysiscùng Bài viết Chuyên sâu#3chuyển giao trực tiếp sangch-05-causal-inference-and-uplift-modeling.md(T1-P1-U05); Bài viết#1chuyển sangch-07-leakage-proof-evaluation-and-calibration.md(T1-P2); và Feature Store thời gian thực, CI/CD thăng hạng mô hình & giám sát trôi nhãn trễ#15–#17tham chiếu sang Track 2EDAI)
Bài thực hành Song hành (Lab 04):labs/ch04-lifecycle-oop-and-eda-workbench/(lifecycle_eda_lab)
Tình huống Mở đầu: Bốn Sai lầm Kiến trúc Phá vỡ Hệ thống ML Trước Khi Huấn luyện Một Mô hình Nào#
Trong thực tiễn kỹ thuật học máy sản xuất (production DSAI), phần lớn các sự cố nghiêm trọng không xuất phát từ việc chọn nhầm kiến trúc mạng nơ-ron hay hàm mất mát, mà nảy sinh ngay trong giai đoạn chuẩn bị dữ liệu, tổ chức mã nguồn và phân tích khám phá (EDA) trước khi mô hình kịp nhìn thấy dữ liệu thật:
- Thảm họa $3,600,000 từ Sai lệch Đơn vị & Sentinel Thầm lặng (
Unit Mismatch & Silent Sentinel): Một microservice thanh toán âm thầm đổi đơn vị trườngmonthly_spendtừ USD sang xu (\(\times 100\)), hoặc bản phát hànhiOS v4.2(18%lưu lượng giao hàng) đổieta_secondstừ giây sang mili-giây (\(\times 1{,}000\)) đồng thời thay giá trị thiếuNULLbằng hằng số-1.0trên25%gói tin. Vì kiểu dữ liệu trên đường truyền vẫn làfloat64hợp lệ, dịch vụ suy luận tiếp tục trả vềHTTP 200 OKsuốt30ngày chờ nhãn trưởng thành — gây thiệt hại quyết định trực tiếp $3,600,000 trong khiPSItoàn cục chỉ báo0.135 < 0.25. Ngược lại, một Hợp đồng Dữ liệu (Data Contract) tại Giai đoạn 2 chặn đứng lô dữ liệu lỗi trong dưới5giây với thiệt hại $0. - Ảo ảnh Lọc nhiễu Trắng
+0.62& Bẫy Nhìn trước Thời gian (Pre-Split Screening & PIT Look-Ahead): TínhStandardScaler, điền thiếu, hoặc chọn top-kđặc trưng tương quan cao nhất trước khi tách tập biến100%nhiễu Gaussian trắng độc lập hoàn toàn (\(N=100, d=2{,}000\)) thành kết quả tập kiểm tra ảo \(\operatorname{Corr}_{\text{te}} \approx +0.62\) (\(R^2_{\text{te}} \approx +0.31\)). Song song đó, trong phê duyệt tín dụng, việc kết nối (join) ảnh chụp bảng biến đổi sau quyết định (etl_run_tsthay vì Point-in-TimeASOFjoin) thổi phồngROC-AUCngoại tuyến lên0.93–1.000rồi rơi thẳng xuống0.527–0.69ngay khi phục vụ khách hàng thật. - Sụp đổ Ghi nhớ
merchant_idZipf & Phá hủy Tín hiệuMNARBệnh viện: Mã hóa trung bình mục tiêu trong mẫu cho50,000cửa hàng tuân theo luật Zipf (40%+có dưới5giao dịch) đẩyAUChuấn luyện lên0.78–0.99nhưng tụt xuống0.647ở tập kiểm tra. Trong hồi sức tích cực (ICU), điền trung bình mù (blind mean imputation) cho xét nghiệmlactate_mmol(p_miss = 0.583) nén phương sai còn đúng \(1 - 0.583 = 0.417\) và đánh tụtAUCtrên bệnh nhân mới từ0.827xuống0.525vì vứt bỏ tín hiệu lâm sàng nằm trong chính cờ báo thiếuis_missing. - Mồ chôn
.ipynb, Nổ ABIpickle(CWE-502) & Nghịch lý Simpson47 pp: Một sổ tay.ipynbcó thứ tự thực thi nhảy cóc ([14, 3, 29, 8]) kết hợp với tệp.pklgãynumpy._corekhi nâng cấpNumPy 1.26 -> 2.2làm mất hoàn toàn khả năng tái lập và mở lỗ hổng thực thi mã từ xa (RCE), trong khiEDAcộng gộp không phân tầng biến hỗn tạp đảo ngược hoàn toàn kết luận sản phẩm từ+5.0 ppthành-47.0 pp.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn học phần T1-P1-U04 (Chương 04 và lifecycle_eda_lab), học viên có đủ năng lực để:
- Thiết kế Vòng đời ML Khép kín & Cổng Rủi ro Định lượng (Systems Rigor): Đối chiếu mô hình thác nước
CRISP-DMvới vòng đời lặp 7 giai đoạn ràng buộc hợp đồng; tính toán mô hình chi phí sai lỗi (Cost-of-Error) giữa Giai đoạn 2 ($0) và Giai đoạn 6 ($3,600,000); và áp dụng đúng nhân quả Point-in-Time (ASOF) cùng cấu trúc tách tập (Temporal+ \(\Delta_{\text{gap}}\),GroupKFold,Stratified). - Xây dựng Pipeline OOP Bất biến Sâu, Chuẩn
Protocol& Không-pickle(OOP & Security Rigor): Giải thích 5 khuyết tật của.ipynbvà cơ chếsrc/chống bóng mờsys.path[0]; kết hợpPydantic v2ở biên ngoài với@dataclass(frozen=True, slots=True)và bộ đệmNumPychỉ đọcsetflags(write=False); thiết kế bộ biến đổityping.Protocolthỏa tính bất biến theo lô (row-wise batch invariance); cô lập luồng ngẫu nhiên bằngSeedSequence+PCG64; và tuần tự hóa quaJSON State-Dictkiểm bămSHA-256miễn nhiễmCWE-502/skopsCVE-2025-54886. - Chứng minh Đại số Rò rỉ Tiền Tách tập, Co rút Thiếu dữ liệu, Đổ vỡ
MAD& Nghịch lý Simpson (Mathematical EDA Rigor): Chứng minh chuẩn hóa tiền tách tập tạo phản tương quan \(\rho = -1\) giữa phần dư hai tập và lọc nhiễu \(N=100, d=2{,}000\) tạo ảo giác \(+0.62\); chứng minh Định lý co rút phương sai \((1 - p_{\text{miss}})\sigma_X^2\) dướiMCARvà ranh giới bất khả nhận dạngMAR/MNAR; suy diễn \(c_{\text{MAD}} \approx 1.4826\), điểm đổ vỡ \(50\%\) củaMADvà thang dự phòngMeanADkhiMAD == 0; thiết lập mã hóa mục tiêu Bayes thực nghiệmOOFm-estimate; và giải tích phân rã Simpson \(2 \times 2\) cùng chuẩn hóa trực tiếp nối sang Chương 05. - Chẩn đoán Dịch chuyển Phân phối Đơn biến & Đa biến SOTA 2024–2026 (Distribution Shift Rigor): Phân biệt 4 lớp dịch chuyển (
Covariate,Label/Prior,Concept,Schema); chứng minhPSIlà KL đối xứng Jeffreys với thiên lệch vô hiệu dương chính xác \((B-1)(1/n_{\text{ref}} + 1/n_{\text{cur}})\) (hệ số1, không phải1/2); chứng minh \(\operatorname{JSD}_{\text{nat}} \in [0, \ln 2]\) và không gian metric \(\sqrt{\operatorname{JSD}}\); suy diễn 1D \(W_1\) qua bắt cặp đồng biến xử lý dịch chuyển đơn vị khiPSI/JSD/KSmù; đánh giáKSbằng chuỗi song đối Jacobi theta (\(\lambda < 0.27\)); và phát hiện xoay tương quan đa biến bằngC2STOOF bậc hai và \(\widehat{\operatorname{MMD}}_u^2\) (E-C2ST,MMDEW). - Kiểm chứng Đầu–Cuối bằng Workbench Pure-Python + NumPy/Pandas/Pydantic (
lifecycle_eda_lab): Điều phối phả hệ thí nghiệm định danh nội dungSHA-256(MLflow 2.x/3.0,DVC,W&B), hệ công cụuv/Marimo/Pandera/Narwhals, và đáp ứng đủ14ca kiểm thử hợp đồngpytest(lõi tham chiếu thuần Python/NumPy/Pandas/Pydantic kết hợp Test 14 chạy Rào chắn AST Chỉ Bảo mật cấm tuyệt đốipickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshal).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P1-U04, Dòng R28)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R28) |
Nâng cấp Chuẩn SOTA 2026 (ch-04) |
Mục trong Chương 04 | Mô-đun & Hợp đồng Kiểm thử (lifecycle_eda_lab) |
|---|---|---|---|
| 1. OOP for Data Science | Tách cấu hình định kiểu (Pydantic v2 ConfigDict(frozen=True, extra="forbid")) khỏi trạng thái bất biến sâu (@dataclass(frozen=True, slots=True) + setflags(write=False)); typing.Protocol (PEP 544, @runtime_checkable) vs. ABC/BaseEstimator; Bảng chuyển trạng thái .fit()/.transform() & bất biến theo lô; StatefulPipeline & ColumnRouter; SeedSequence + PCG64; tuần tự hóa JSON State-Dict không-pickle (CWE-502, skops >= 0.13.0 CVE-2025-54886, safetensors) |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.1, §2.3) + Trụ cột 3 (§3.1 Case 5, §3.4) + Widget missingness-imputation-explorer |
contracts_and_lineage.py (ReproducibleRngTree), pipelines_and_encoders.py (StatefulTransformer, StatefulStandardizer, RobustMADImputer, StatefulPipeline, ColumnRouter), Tests 2, 3, 4 |
| 2. Structure a data science project | 5 khuyết tật cấu trúc của .ipynb đơn khối & Nguyên tắc Thấu kính Mỏng; bố cục PEP 621 src/ vô hiệu hóa bóng mờ sys.path[0]; quản lý tất định uv + uv.lock + PEP 723; Sổ tay DAG Phản ứng (Marimo) + cảnh báo đột biến tại chỗ; Tường lửa Hợp đồng 2–3 Lớp (Pydantic v2 + Pandera) & Narwhals / set_output |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.3) + Trụ cột 3 (§3.1 Cases 2, 5; §3.2 FM1) | pyproject.toml, src/lifecycle_eda_lab/, contracts_and_lineage.py (SplitContract, DataContractSchema), Tests 1, 2, 14 |
| 3. ML lifecycle | Phê phán thác nước CRISP-DM; Vòng đời ML Lặp 7 Giai đoạn Khép kín; mô hình phân tích Chi phí Sai lỗi Giai đoạn 2 ($0, 1x) vs. Giai đoạn 6 ($3,600,000, >10,000x); ma trận chọn cấu trúc tách tập (Temporal + \(\Delta_{\text{gap}}\), GroupKFold, Stratified) & nhân quả ASOF PIT |
Trụ cột 1 (§1.1) + Mermaid 1, 3 + Trụ cột 3 (§3.1 Cases 1, 2; §3.3 Cẩm nang 2 & Checklist) | contracts_and_lineage.py (SplitContract, .verify_splits, split_dataframe), eda_and_drift.py (run_full_lifecycle_benchmarks), Tests 1, 2, 13, 14 |
| 4. Experiment tracking | Bốn Trụ cột Tái lập (Git SHA + git_is_dirty, raw_data_sha256 + split_sha256, uv_lock_sha256 + BLAS/SIMD, Pydantic JSON chuẩn tắc + SeedSequence spawn_keys); mã băm chạy định danh nội dung manifest_sha256; cô lập chỉ số theo nhãn tập; đối chiếu MLflow 2.x/3.0, DVC, W&B Artifacts & sổ cái JSONL nội bộ |
Trụ cột 2 (§2.3) + Trụ cột 3 (§3.1 Case 5; §3.2 FM6) | contracts_and_lineage.py (sha256_bytes, hash_dataframe_sha256, build_experiment_manifest), scripts/run_lab_demo.py, Tests 3, 4, 14 |
| 5. Methodology for efficient EDA | Lý thuyết EDA Tách tập Trước: chứng minh chuẩn hóa tiền tách tập (\(\rho = -1\)) & lọc nhiễu trắng \(N=100, d=2{,}000\) (+0.62 vs 0); Rubin MCAR/MAR/MNAR + định lý \((1-p_{\text{miss}})\sigma_X^2\) + cờ is_missing; MAD (\(c_{\text{MAD}} \approx 1.4826\), \(50\%\) đổ vỡ, nhánh dự phòng MeanAD); OOF \(m\)-estimate + gộp __RARE__; đại số Simpson 26.5% vs 73.5% & chuẩn hóa trực tiếp; Dịch chuyển Phân phối SOTA (PSI thiên lệch \((B-1)(n_{\text{ref}}^{-1}+n_{\text{cur}}^{-1})\), JSD \([0,\ln 2]\) & \(\sqrt{\text{JSD}}\), 1D \(W_1\), KS Jacobi theta, C2ST OOF & \(\widehat{\operatorname{MMD}}_u^2\)) |
Trụ cột 1 (§1.3–§1.4) + Trụ cột 2 (§2.1–§2.2) + Trụ cột 3 (§3.1 Cases 1–4; §3.2 FM2–FM5; §3.3 Cẩm nang 1–2) + Mermaid 2 + Widgets leakage-audit-simulator, drift-psi-wasserstein-explorer |
pipelines_and_encoders.py (RobustMADImputer, OutOfFoldTargetEncoder), eda_and_drift.py (compute_mad_zscore, diagnose_missingness_mechanisms, simpson_paradox_audit, simulate_presplit_leakage_audit, compute_psi, compute_jsd, compute_wasserstein_1d, compute_ks_statistic, adversarial_validation_oof_auc, compute_rbf_mmd_u2), Tests 5–13 |
(6. Causal analysis — Chuyển giao sang ch-05 & Bài viết #3) |
(SCM DAGs, Backdoor Criterion, Potential Outcomes, IPW/AIPW, Double ML & Uplift Modeling) | Chuyển giao tường minh từ §1.4 Đại số Simpson & §1.1 Giai đoạn 1 \(\to\) ch-05 (T1-P1-U05) |
Triển khai tại labs/lab-02-eda-to-causal-uplift-pipeline/ |
Bảng Ký hiệu Toán học & Quy ước Phân giải Trùng lặp (Unified Disambiguated Notation)#
Chính sách Khử trùng lặp Ký hiệu Xuyên suốt Chương 04 &
lifecycle_eda_lab:
- Phân biệt
m_smooth,n_ref / n_cur,m_errvàm_batch: Dànhm_smooth(smoothing_mtrong mã nguồn) cho trọng số giả đếm Bayes thực nghiệm \(m\)-estimate; loại bỏ ký hiệu \(m\) trơn làm cỡ mẫu trongKS, \(W_1\) vàMMD, luôn viết tường minh \(n_{\text{ref}}, n_{\text{cur}}\) (và \(n_{\text{eff}} := (n_{\text{ref}}^{-1} + n_{\text{cur}}^{-1})^{-1}\)); dành \(m_{\text{err}}\) cho số mẫu bị nhiễm bẩn đối nghịch trong điểm đổ vỡ Donoho–Huber (\(\varepsilon_n^* = m_{\text{err}}/n\)); và dành \(m_{\text{batch}}\) cho kích thước lô suy luận (\(\mathbf{B} \in \mathbb{R}^{m_{\text{batch}} \times d}\)) để chữ hoa \(B\) chỉ dùng cho số lượng bin biểu đồ.- Khóa Hệ số Thiên lệch Vô hiệu
PSI(1, KHÔNG phải1/2) & Đơn vịJSD(bitsvs.nats): Vì \(\operatorname{PSI}(P_{\text{ref}}, P_{\text{cur}}) = D_{\text{KL}}(P_{\text{ref}} \| P_{\text{cur}}) + D_{\text{KL}}(P_{\text{cur}} \| P_{\text{ref}})\) là tổng của hai phân kỳ KL đối xứng (\(\frac{1}{2} + \frac{1}{2} = \mathbf{1}\)), thiên lệch kỳ vọng tiệm cận dưới \(H_0\) là(B - 1)(1/n_ref + 1/n_cur)(chính xác từng hệ số, tuyệt đối không chia đôi!). Đối vớiJSD, phân biệt rạch ròi \(\operatorname{JSD}_{\text{nat}} \in [0, \ln 2]\) (log tự nhiên \(\ln\), khớp hệ thức \(\operatorname{JSD}_{\text{nat}} \approx \frac{1}{8}\operatorname{PSI}\)) với \(\operatorname{JSD}_{\text{bit}} := \frac{1}{\ln 2}\operatorname{JSD}_{\text{nat}} \in [0, 1]\) (log cơ số 2 mặc định trongcompute_jsd(..., base="bits"), khớp giá trị0.623 bitstrong Case 2).- Phân biệt \(p_{\text{miss}}\) vs. \(p_b, q_b\) và \(\mathbf{M}\) vs. \(M_{\text{mix}}\): Dành \(p_{\text{miss}}\) (\(p_{\text{miss}, j}\)) cho xác suất thiếu biên \(P(M_j = 1)\) và \(\mathbf{M} \in \{0, 1\}^{n \times d}\) cho ma trận chỉ báo thiếu; dành
p_b, q_b(\(\hat{p}_b, \hat{q}_b\)) cho xác suất bin \(b \in \{1, \dots, B\}\) của phân phối tham chiếu và hiện tại; và viết \(M_{\text{mix}} := \frac{1}{2}(P_{\text{ref}} + P_{\text{cur}})\) cho phân phối hỗn hợp củaJSD.- Phân biệt các đại lượng \(\Delta\) & \(\varepsilon\): \(\Delta_{\text{gap}}\) (
embargo_seconds) là khoảng đệm cấm rò rỉ thời gian (\(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\)); \(\Delta t_{\text{horizon}}\) là chân trời trưởng thành nhãn; \(\Delta t_{\text{obs}}\) là khoảng cách giữa hai lần đo lâm sàng; \(\Delta\mu := \mu_{\text{cur}} - \mu_{\text{ref}}\) là độ dịch kỳ vọng; \(\Delta T_{\text{detect}}\) là độ trễ phát hiện sự cố ngoài sản xuất; \(\varepsilon_n^*\) là điểm đổ vỡ hữu hạn; \(\varepsilon_{\text{floor}}\) (eps) là ngưỡng làm mịn chống chia \(0\); và \(\varepsilon_j\) là sai số ngẫu nhiên trực giao trong Chứng minh 2.
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa Xuyên suốt Chương 04 | Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (lifecycle_eda_lab) |
|---|---|---|---|---|
| \(N, n_{\text{tr}}, n_{\text{val}}, n_{\text{te}}\) | \(\mathbb{N}_+\) | Tổng số mẫu \(N = n_{\text{tr}} + n_{\text{val}} + n_{\text{te}}\); tỷ lệ \(\alpha_{\text{tr}}, \alpha_{\text{val}}, \alpha_{\text{te}}\) | Tách biệt khỏi \(n_{\text{ref}}, n_{\text{cur}}\) khi giám sát trôi | train_ratio, val_ratio, test_ratio |
| \(\mathcal{D}_{\text{tr}}, \mathcal{D}_{\text{val}}, \mathcal{D}_{\text{te}}\) | Tập dữ liệu | Các phân vùng cách ly (\(\mathcal{D}_{\text{tr}}^{(-k)}\) loại bỏ nếp OOF thứ \(k\)) | Tách biệt khỏi phân phối \(P_{\text{ref}}, P_{\text{cur}}\) | train_df, val_df, test_df |
| \(P_{\text{ref}}, P_{\text{cur}}\) | Phân phối | Phân phối tham chiếu (huấn luyện) và hiện tại (kiểm tra/phục vụ) | Thay cho cặp \(P, Q\) dễ gây nhầm | expected, actual / u_values, v_values |
| \(n_{\text{ref}}, n_{\text{cur}}, n_{\text{eff}}\) | \(\mathbb{N}_+, \mathbb{R}_{>0}\) | Cỡ mẫu tham chiếu/hiện tại; cỡ mẫu điều hòa \((n_{\text{ref}}^{-1} + n_{\text{cur}}^{-1})^{-1}\) | Không dùng \(m\) trơn trong KS, \(W_1\), MMD |
n_ref, n_cur, n_eff |
| \(\Delta_{\text{gap}}, \Delta t_{\text{horizon}}\) | \(\mathbb{R}_{\ge 0}\) | Đệm cấm thời gian (\(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\)); chân trời nhãn | Thống nhất thay \(\Delta_{\text{embargo}}\), \(H\) | embargo_seconds |
| \(\Delta\mu, \Delta T_{\text{detect}}\) | \(\mathbb{R}, \mathbb{R}_{>0}\) | Độ dịch kỳ vọng \(\mu_{\text{cur}} - \mu_{\text{ref}}\); độ trễ phát hiện (ngày) | Tách biệt khỏi \(\Delta_{\text{gap}}\) | — |
| \(\mathcal{F}, T_{\hat{\boldsymbol{\theta}}}, \hat{\boldsymbol{\theta}}\) | Toán tử / Trạng thái | Bộ ước lượng .fit() trên tập train; ánh xạ bất biến theo lô .transform() |
Báo lỗi NotFittedError nếu chưa khớp |
StatefulTransformer, _state |
| \(\mathbf{M} \in \{0, 1\}^{n \times d}, p_{\text{miss}}\) | Ma trận, \([0, 1]\) | Ma trận chỉ báo thiếu (\(M_{ij}=1\) nếu thiếu); tỷ lệ thiếu biên \(P(M_j=1)\) | Tách khỏi \(M_{\text{mix}}\) (JSD) & \(p_b\) (PSI) |
missing_rate, is_missing |
| \(c_{\text{MAD}}, c_{\text{MeanAD}}\) | \(\mathbb{R}_{>0}\) | \(1/\Phi^{-1}(0.75) \approx 1.4826022\); \(\sqrt{\pi/2} \approx 1.2533141\) (khi MAD==0) |
— | consistency_constant, 1.2533141373155003 |
| \(m_{\text{err}}, \varepsilon_n^*\) | \(\mathbb{N}_{\ge 0}, (0, 0.5]\) | Số điểm ngoại lai bị thay thế; điểm đổ vỡ hữu hạn \(m_{\text{err}}/n\) | Tách khỏi \(m_{\text{smooth}}\) và \(\varepsilon_{\text{floor}}\) | — |
| \(m_{\text{smooth}}, \mu_0, n_c\) | \(\mathbb{R}_{>0}, \mathbb{R}, \mathbb{N}_{\ge 0}\) | Trọng số giả đếm Bayes thực nghiệm; tiên nghiệm toàn cục \(\bar{y}_{\text{tr}}\); số mẫu lớp \(c\) | Không dùng \(m\) trơn trong mã hóa mục tiêu | smoothing_m, global_prior_, min_samples |
| \(w_A, w_B, r_{G, s}\) | \([0, 1]\) | Tỷ trọng tầng 1 và tỷ lệ chuyển đổi nhóm \(G\) trong tầng \(s\) (Simpson) | Tách khỏi trọng số hạt nhân/logistic | within_stratum_effect, mix_shift_confounding |
| \(B, p_b, q_b, M_{\text{mix}}\) | \(\mathbb{N}_{\ge 2}, (0, 1], \text{Dist}\) | Số bin biểu đồ; xác suất bin ref/cur; hỗn hợp \(\frac{1}{2}(P_{\text{ref}}+P_{\text{cur}})\) | Không dùng \(M\) trơn cho hỗn hợp JSD |
bins, effective_bins |
| \(\operatorname{PSI}, \operatorname{JSD}_{\text{bit}}, \operatorname{JSD}_{\text{nat}}\) | \(\mathbb{R}_{\ge 0}, [0, 1], [0, \ln 2]\) | KL Jeffreys (\(\mathbb{E}_{H_0}[\widehat{\operatorname{PSI}}] \approx (B-1)(n_{\text{ref}}^{-1}+n_{\text{cur}}^{-1})\)); JSD cơ số 2 & cơ số \(e\) | Khóa hệ số 1 và bits vs. nats |
compute_psi, compute_jsd(..., base=...) |
| \(W_1, \widetilde{W}_1, D_{n_{\text{ref}}, n_{\text{cur}}}\) | \(\mathbb{R}_{\ge 0}, [0, 1]\) | Wasserstein-1 1D; chuẩn hóa \(W_1/\max(\text{IQR}_{\text{ref}}, \sigma_{\text{ref}}, \varepsilon)\); thống kê KS | Thay cho \(D_{n,m}\) cũ | compute_wasserstein_1d, compute_ks_statistic |
| \(\operatorname{AUC}_{\text{adv}}, \widehat{\operatorname{MMD}}_u^2\) | \([0, 1], \mathbb{R}\) | ROC-AUC ngoài nếp của Kiểm định Đối nghịch (C2ST); U-thống kê RBF MMD |
Phân biệt C2ST tuyến tính vs. bậc hai |
adversarial_validation_oof_auc, compute_rbf_mmd_u2 |
Trụ cột 1 — Vòng đời ML Lặp, Kiến trúc OOP Sản xuất & Chứng minh Toán học EDA Chống Rò rỉ (First-Principles ML Lifecycle, Production OOP & Leakage-Free EDA Proofs)#
1.1 Vòng đời ML Lặp 7 Giai đoạn & Kinh tế học Chi phí Sai lỗi (7-Stage Closed-Loop ML Lifecycle vs. CRISP-DM)#
Bốn Lỗi Cấu trúc của Mô hình Thác nước CRISP-DM (1996–2000)#
Ra đời trong giai đoạn tư vấn khai phá dữ liệu ngoại tuyến một lần, CRISP-DM (Cross-Industry Standard Process for Data Mining) tổ chức công việc theo chuỗi tuần tự gần như tuyến tính: Business Understanding \(\to\) Data Understanding \(\to\) Data Preparation \(\to\) Modeling \(\to\) Evaluation \(\to\) Deployment. Dù trên sơ đồ có vài mũi tên quay lui cục bộ, áp dụng CRISP-DM lên hệ thống ML sản xuất hiện đại tạo ra bốn lỗi mang tính hệ thống:
- Rò rỉ Tiền Tách tập tại Bước Data Understanding (
Pre-Split Leakage):CRISP-DMtruyền thống khuyến khích tính thống kê mô tả, khớp phân phối, điền giá trị thiếu, cắt ngưỡng ngoại lai (winsorization) và lọc tương quan trên toàn bộ bảng dữ liệu trước khi chia tập huấn luyện/kiểm tra. Mọi tham số tính trên tập gộp đều làm rò rỉ hình học của tập kiểm tra vào tập huấn luyện (xem chứng minh đại số ở §1.3). - Giả định Thế giới Tĩnh (
Static-World Stationarity):CRISP-DMxem Deployment như điểm kết thúc trên phân phối dừng \(P(X, Y)\). Trong thực tế, hệ thống đối mặt liên tục với dịch chuyển hiệp phương sai (\(P_{\text{cur}}(X) \neq P_{\text{ref}}(X)\)), dịch chuyển nhãn tiên nghiệm (\(P_{\text{cur}}(Y) \neq P_{\text{ref}}(Y)\)), trôi khái niệm (\(P_{\text{cur}}(Y \mid X) \neq P_{\text{ref}}(Y \mid X)\)) và vòng lặp phản hồi chính sách (chính quyết định của mô hình thay đổi tập khách hàng được cấp vốn/can thiệp, làm kiểm duyệt nhãn phản thực tương lai). - Vực thẳm Bàn giao Sổ tay–Kỹ thuật (
Training–Serving Skew): Nhà khoa học dữ liệu viết tiền xử lý mệnh lệnh trong sổ tay.ipynb, còn kỹ sư hậu cần viết lại bằng SQL, Java hoặc Rust. Sai lệch nhỏ ở làm tròn múi giờ, phép chia nguyên, xử lýNaNvs.0, hoặc biên phân vị âm thầm phá hỏng vector đặc trưng trực tuyến mà không hề ném ngoại lệ. - Đánh giá Tách rời Chi phí Quyết định & Hiệu chuẩn: Chỉ nhìn vào chỉ số xếp hạng (
ROC-AUC,PR-AUC,RMSE) bỏ qua việc xác suất \(\hat{p}(x)\) có được hiệu chuẩn cho ngưỡng chi phí bất đối xứng \(\tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\) hay không (ch-07), cũng như bỏ qua ngân sách độ trễp99và bộ nhớ khi phục vụ.
Vòng đời ML Lặp 7 Giai đoạn Khép kín Ràng buộc Hợp đồng (7-Stage Closed-Loop Lifecycle)#
Hệ thống ML chuẩn 2026 thay CRISP-DM bằng vòng đời lặp 7 giai đoạn khép kín, trong đó mỗi giai đoạn chỉ được chuyển tiếp khi vượt qua một Cổng Bất biến Định lượng (Mandatory Gate):
| Giai đoạn | Tạo tác Cốt lõi (Primary Artifacts) |
Bất biến / Cổng Bắt buộc (Mandatory Gate) |
Phản mẫu Ngăn chặn (Anti-Pattern Prevented) |
|---|---|---|---|
| 1. Đóng khung Bài toán & Chi phí Quyết định | Đặc tả mục tiêu, ma trận chi phí \((C_{\text{FP}}, C_{\text{FN}})\), thời điểm quan sát \(t_{\text{obs}}\), chân trời nhãn \(\Delta t_{\text{horizon}}\), baseline đơn giản, SLO |
Phân tách dự báo \(\mathbb{E}[Y \mid X]\) khỏi tác động nhân quả \(\tau(X) = \mathbb{E}[Y(1)-Y(0) \mid X]\) (ch-05); chốt ngân sách độ trễ & chi phí |
Tối ưu ROC-AUC dự đoán rời bỏ khi chiến dịch giữ chân cần uplift gia tăng (ch-05) |
2. Hợp đồng Dữ liệu Tại Thời điểm Quyết định (PIT) |
Schema định kiểu (Pydantic v2/Pandera), hợp đồng ASOF timestamp, danh sách sentinel cấm, mã băm SHA-256 ảnh gốc |
Nhân quả thời gian: \(t_{\text{feature}} \le t_{\text{obs}}\) cho mọi đặc trưng; chặn tức thì khi đổi đơn vị, xuất hiện -1/-999 hoặc vỡ nullability |
Rò rỉ hậu quả sau biến cố (post-outcome backfill) & lỗi chuyển đơn vị thầm lặng |
3. Cổng Cô lập Tách tập Trước (Split-First Isolation Gate) |
Hồ sơ chỉ số train / val / test bất biến + split_sha256 |
Cách ly tuyệt đối \(\mathcal{D}_{\text{te}}\): Chọn cấu trúc tách khớp DGP (Thời gian + \(\Delta_{\text{gap}}\), Nhóm thực thể, hay Phân tầng i.i.d.) trước MỌI thống kê EDA, đồ thị, điền thiếu hay lọc biến |
Rò rỉ chuẩn hóa tiền tách tập & ảo ảnh lọc nhiễu trắng nhiều chiều (§1.3) |
| 4. Kỹ thuật Pipeline Có trạng thái | StatefulPipeline / ColumnRouter với bộ tham số đóng băng sau .fit() |
.fit(\(\mathcal{D}_{\text{tr}}\)) chỉ đọc tập huấn luyện; .transform(\(\mathbf{X}\)) thuần khiết, bất biến theo lô và ném NotFittedError nếu chưa khớp |
Lệch huấn luyện–phục vụ, chuẩn hóa theo lô kiểm tra, ghi nhớ nhãn OOF |
| 5. Theo dõi Thí nghiệm & Phả hệ Định danh Nội dung | RunLineageManifest gắn chặt 4 trụ cột tái lập, chỉ số OOF gắn nhãn tập, gói JSON State-Dict không-pickle |
Mọi thí nghiệm so sánh phải chia sẻ cùng split_sha256; cây Git bẩn (git_is_dirty=True) bị chặn thăng hạng |
Kết quả "tốt nhất" từ bộ nhớ sổ tay cũ; tinh chỉnh siêu tham số lén nhìn \(\mathcal{D}_{\text{te}}\) |
| 6. Triển khai Bóng / Kiểm thử Canary & Hiệu chuẩn | Nhật ký đối chiếu song song (Shadow Parity), kiểm tra ECE/Brier (ch-07), biểu đồ độ trễ p95/p99, nút hoàn tác |
Sai khác bằng \(0\) giữa vector trực tuyến \(\mathbf{x}_{\text{online}}\) và tái dựng PIT ngoại tuyến \(\mathbf{x}_{\text{offline}}\); khóa ngưỡng quyết định theo tỷ lệ nền thực tế |
Phục vụ HTTP 200 OK ra điểm số rác sau khi lệch mã hóa hoặc lệch đơn vị |
| 7. Giám sát Dịch chuyển Tự động & Vòng lặp Tái huấn luyện | Cảnh báo dịch chuyển (PSI, JSD, \(W_1\), KS, C2ST/MMD), theo dõi nhãn trễ, chính sách kích hoạt tái huấn luyện |
Tách bạch dịch chuyển hiệp phương sai lành tính khỏi trôi khái niệm (\(P(Y \mid X)\) đổi); quay về Giai đoạn 1/2 với cửa sổ PIT sạch |
Vòng lặp tự đầu độc nhật ký & suy thoái âm thầm theo mùa vụ/vĩ mô |
Quy tắc Chọn Cấu trúc Phân tách Tại Giai đoạn 3 (Split Topology Decision Rules)#
Áp dụng tách ngẫu nhiên phân tầng lên dữ liệu không thỏa tính độc lập đồng nhất (i.i.d.) phá hủy ngay tính hợp lệ của Giai đoạn 3:
- Phân tách Thời gian / Gốc Cuộn (
Temporal / Rolling-Origin Split): Bất cứ khi nào quan sát đến theo trình tự thời gian (\(t_1 \le t_2 \le \dots \le t_N\)), bắt buộc thỏa mãn điều kiện cách ly thời gian kèm đệm cấm (embargo / purge gap) \(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\):\[\max_{i \in \mathcal{D}_{\text{tr}}} t_i + \Delta_{\text{gap}} \le \min_{j \in \mathcal{D}_{\text{te}}} t_j.\]Khoảng đệm \(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\) đảm bảo mọi cửa sổ trưởng thành nhãn của tập huấn luyện (ví dụ vỡ nợ 90 ngày, gian lận bồi hoàn 30 ngày) kết thúc hoàn toàn trước khi bắt đầu quan sát đầu tiên của tập kiểm định/kiểm tra (tham chiếuch-07vàch-13). - Phân tách Theo Thực thể / Nhóm (
Entity / Group-Aware Split—GroupKFold/StratifiedGroupKFold): Khi nhiều dòng dữ liệu chia sẻ cùng một thực thể nền (patient_id,user_id,merchant_id,device_id,session_id), bắt buộc tập thực thể giao bằng rỗng:\[\mathcal{G}(\mathcal{D}_{\text{tr}}) \cap \mathcal{G}(\mathcal{D}_{\text{val}}) = \emptyset, \qquad \mathcal{G}(\mathcal{D}_{\text{tr}}) \cap \mathcal{G}(\mathcal{D}_{\text{te}}) = \emptyset, \qquad \mathcal{G}(\mathcal{D}_{\text{val}}) \cap \mathcal{G}(\mathcal{D}_{\text{te}}) = \emptyset,\]ngăn mô hình ghi nhớ dấu vân tay riêng của từng bệnh nhân hay cửa hàng xuyên qua biên tách tập. - Phân tách Ngẫu nhiên Phân tầng (
Stratified Random Split): Chỉ hợp lệ khi các dòng dữ liệu là mẫu hoán vịi.i.d.thuần túy từ \(P(X, Y)\), không có tự tương quan thời gian và không lặp lại định danh thực thể.
Mô hình Phân tích Chi phí Sai lỗi (Cost-of-Error Analytical Model)#
Khác với phần mềm tất định truyền thống (vỡ hợp đồng API sẽ ném ngoại lệ 500 ngay lập tức), pipeline ML âm thầm nuốt trọn đầu vào sai đơn vị hay giá trị sentinel và vẫn xuất ra xác suất thực kèm mã HTTP 200 OK. Tổng chi phí kinh tế của một lỗi thoát qua các giai đoạn \(s \in \{1, \dots, 7\}\) được mô hình hóa bởi:
trong đó \(V_{\text{daily}}\) là lưu lượng quyết định hằng ngày, \(\Delta T_{\text{detect}}\) là độ trễ phát hiện tính bằng ngày (thường bị chặn dưới bởi độ trễ trưởng thành nhãn \(\Delta t_{\text{horizon}}\) nếu giám sát chỉ dựa vào nhãn thật), \(\Delta e\) là tỷ lệ sai sót quyết định tăng thêm do lỗi gây ra, và \(c_{\text{err}}\) là chi phí kinh tế trung bình cho mỗi quyết định sai.
Bài toán Đối chiếu FinTech (V_daily = 100,000, \(\Delta T_{\text{detect}} = 30\) ngày, \(\Delta e = 0.08\), c_err = 15 USD): Giả sử microservice thanh toán đổi monthly_spend từ USD sang xu (\(\times 100\)) và thay NULL ở debt_to_income thành -999.0:
| Giai đoạn Phát hiện Lỗi | Độ trễ Phát hiện | Tổn thất Quyết định Trực tiếp | Chi phí Kỹ thuật & Tính toán | Tác động Dữ liệu & Khắc phục | Hệ số Nhân Chi phí Tổng |
|---|---|---|---|---|---|
| Giai đoạn 2: Cổng Hợp đồng Dữ liệu | < 5 giây (chặn trước khi tách tập) |
$0 (0 yêu cầu thật bị chạm) |
\(\sim 0.5\text{–}1\) giờ kỹ sư xử lý (\(\approx\) $100–$200) | 0 nhiễm bẩn mô hình; 0 nhật ký huấn luyện bị đầu độc | \(1\times\) (Chuẩn gốc) |
| Giai đoạn 4/5: Pipeline / Kiểm định Bóng | Vài giờ đến vài ngày | $0 (chặn trước khi mở lưu lượng thật) | Lãng phí chu kỳ GPU/CPU & truy vết đa mô-đun (\(\approx\) $1,000–$3,000) | Cần trích xuất lại ảnh PIT sạch & huấn luyện lại |
\(\sim 10\times\text{–}20\times\) |
| Giai đoạn 6: Suy thoái Âm thầm Sau Triển khai | \(\Delta T_{\text{detect}} \approx 30\) ngày (trễ nhãn vỡ nợ) | \(100{,}000 \times 30 \times 0.08 \times 15\text{ USD} =\) 3,600,000 USD | Ứng cứu sự cố, hoàn tác khẩn cấp, kiểm toán pháp lý (\(\approx\) $50,000+) | Nghiêm trọng: 30 ngày định giá sai đầu độc toàn bộ nhật ký tương lai, buộc cách ly nhóm và gán nhãn lại |
\(> 10{,}000\times\) (Thảm họa) |
1.2 Kiến trúc Dự án src/, OOP Cho Khoa học Dữ liệu & Cô lập SeedSequence (Production DS Project Layout, Typed OOP & Deterministic RNG)#
Năm Khuyết tật Cấu trúc của .ipynb Đơn khối & Nguyên tắc Thấu kính Mỏng#
Sổ tay tương tác (.ipynb) phù hợp để vẽ biểu đồ khám phá và trình bày báo cáo, nhưng sụp đổ hoàn toàn khi dùng làm mã nguồn chính cho hệ thống ML sản xuất bởi 5 khiếm khuyết cấu trúc:
| Chế độ Hỏng | Cơ chế Thời gian chạy / Định dạng | Hậu quả Sản xuất Cụ thể |
|---|---|---|
1. Thực thi Lệch Thứ tự (Out-of-Order Execution) |
Trạng thái hạt nhân \(S_t\) là hàm phụ thuộc đường đi của chuỗi ô đã chạy \((c_{i_1}, \dots, c_{i_k})\) thay vì thứ tự từ trên xuống \((c_1, \dots, c_m)\). Xóa hoặc chạy lại một ô cũ vẫn giữ biến biến đổi trong RAM. | Chạy Restart & Run All chết NameError hoặc âm thầm cho ra chỉ số khác hoàn toàn con số đã báo cáo trong Git. |
2. Đột biến Trạng thái Toàn cục Ẩn (Hidden Mutable Globals) |
Mọi ô dùng chung một không gian globals() khả biến. Các phép gán tại chỗ (df["col"] = ..., scaler.fit_transform(df)) ghi đè đối tượng thượng nguồn không có biên phạm vi. |
Chạy đúp ô tiền xử lý làm phép chuẩn hóa hoặc biến đổi \(\ln\) chồng lớp hai lần; không thể truy vết trạng thái nào tạo ra mô hình nào. |
| 3. Nhiễu JSON AST Khó So sánh Git | .ipynb tuần tự hóa từng dòng code thành mảng JSON kẹp chung với execution_count, siêu dữ liệu widget, luồng stdout và ảnh PNG mã hóa base64. |
Sửa 3 dòng công thức tạo ra một tệp diff dài 4,000 dòng JSON, phá hỏng quy trình Code Review và liên tục xung đột hợp nhất nhánh. |
4. Rò rỉ Bộ nhớ Biến Treo (Dangling IPython Refs) |
IPython lưu tham chiếu ẩn tới mọi đầu ra (_, __, ___, _oh, Out[k]) và bộ nhớ đệm lịch sử (_ih), giữ chặt các DataFrame nhiều GB trong RAM ngay cả sau khi người dùng gọi del df. |
Phiên EDA dài đột ngột tràn bộ nhớ OOM dù bề ngoài biến đã được giải phóng. |
| 5. Không Thể Import & Không Thể Kiểm thử | Hàm viết trong .ipynb không thể được import sạch bởi pytest, mypy, FastAPI hay worker điều phối nếu không bọc qua lớp vỏ nbconvert/papermill mong manh. |
Không có unit test, không kiểm tra bất biến rò rỉ tự động, buộc phải viết lại toàn bộ trước khi triển khai. |
Nguyên tắc Thấu kính Mỏng (
The Thin-Lens Principle): Tuyệt đối không đặt hợp đồng dữ liệu, bộ tách tập, bộ biến đổi có trạng thái hay thuật toán đánh giá bên trong tệp.ipynb.100%logic phải nằm trong các mô-đun định kiểu và có kiểm thử dướisrc/<pkg>/; sổ tay chỉ đóng vai trò thấu kính quan sát mỏng (thin inspection lens, gọifrom mypkg.eda import ...) và được xóa sạch đầu ra (nbstripout) trước khi commit.
Cấu trúc Dự án Chuẩn PEP 621 src/ & Cơ chế Chặn Bóng mờ sys.path[0]#
Cấu trúc dự án khoa học dữ liệu chuẩn công nghiệp tuân theo PEP 621 / PEP 517 với thư mục src/:
ml-lifecycle-project/
├── pyproject.toml # Metadata PEP 621, phụ thuộc, build-system, cấu hình ruff/mypy/pytest
├── uv.lock # Tệp khóa băm mật mã tất định đa nền tảng (Trụ cột 2)
├── README.md
├── .gitignore # Bỏ qua data/, artifacts/, .venv/, __pycache__/
├── configs/ # Đặc tả thử nghiệm & pipeline bất biến (JSON/TOML)
├── data/
│ ├── raw/ # Ảnh nguồn CHỈ ĐỌC bất biến (+ bản kê SHA-256)
│ ├── interim/ # Các lát train/val/test đã qua kiểm tra schema & tách tập
│ └── processed/ # Bảng đặc trưng đã vật chất hóa (sinh thuần túy từ src/)
├── src/
│ └── lifecycle_eda_lab/ # Gói cài đặt được (bắt buộc cài qua `uv sync` / `pip install -e .`)
│ ├── __init__.py
│ ├── contracts_and_lineage.py
│ ├── pipelines_and_encoders.py
│ └── eda_and_drift.py
├── tests/ # Unit tests, leakage invariants & AST guards
├── scripts/ # Điểm vào CLI mỏng (train.py, run_lab_demo.py)
├── artifacts/ # Gói JSON state-dict không-pickle, manifest SHA-256
└── notebooks/ # Sổ tay quan sát mỏng (chỉ gọi API từ src/)
Vì sao bố cục src/ triệt tiêu bẫy bóng mờ sys.path[0]? Khi chạy python scripts/train.py hoặc python -m pytest tại thư mục gốc <repo_root>, Python luôn chèn thư mục làm việc hiện tại vào đầu danh sách tìm kiếm sys.path[0]. Trong bố cục phẳng (<repo_root>/<pkg>/__init__.py), Python tìm thấy <repo_root>/<pkg> trực tiếp qua sys.path[0] và bỏ qua hoàn toàn gói đã đóng gói trong site-packages—khiến mọi kiểm thử chạy trơn tru trên máy lập trình viên dù pyproject.toml thiếu gói con, thiếu tệp py.typed, hoặc thiếu khai báo phụ thuộc runtime, và chỉ phát nổ khi đóng container Docker! Ngược lại, trong bố cục src/ (<repo_root>/src/<pkg>/), thư mục gốc không chứa <pkg>, nên import <pkg> sẽ báo lỗi ngay lập tức (ModuleNotFoundError) nếu chưa cài đặt gói đúng chuẩn bánh xe (wheel metadata), bảo đảm môi trường kiểm thử cục bộ khớp 100% với môi trường đóng gói sản xuất.
Tách Cấu hình Biên (Pydantic v2) khỏi Trạng thái Nội bộ Bất biến Sâu (@dataclass(frozen=True, slots=True) + setflags(write=False))#
Truyền từ điển dict[str, Any] không định kiểu qua các lớp pipeline dễ lọt lỗi gõ nhầm thầm lặng (vd. cfg.get("smothing_m", 10.0) âm thầm dùng mặc định 10.0 mà không báo lỗi sai chính tả smothing_m). Kỹ thuật OOP khoa học dữ liệu hiện đại phân rã rạch ròi hai tầng:
| Tiêu chí | Pydantic v2 (BaseModel + ConfigDict) |
@dataclass(frozen=True, slots=True) (Python Stdlib) |
|---|---|---|
| Vai trò Kiến trúc | Hợp đồng biên ngoài: cấu hình CLI/JSON/YAML, hợp đồng bảng & kiểm tra tải trọng API | Đối tượng giá trị nội bộ nhẹ: bó tham số đã khớp (FittedStandardizerState), cây RNG, kết quả chẩn đoán |
| Kiểm định Kiểu Runtime | Toàn diện bằng nhân Rust (pydantic-core), ép kiểu hoặc nghiêm ngặt (strict=True), báo đường dẫn trường ValidationError |
Không kiểm tra tự động lúc chạy nếu không viết thủ công trong __post_init__ |
| Chống Khóa Lạ / Gõ nhầm | ConfigDict(extra="forbid") chặn ngay lập tức mọi khóa JSON/YAML lạ |
slots=True loại bỏ __dict__ từng thực thể (tiết kiệm ~40–50% RAM) và cấm gán thuộc tính mới |
| Bất biến & Ràng buộc Chéo | ConfigDict(frozen=True), Field(gt=0, lt=1) & @model_validator(mode="after") kiểm tra tổng tỷ lệ, đệm embargo |
frozen=True chặn gán lại thuộc tính; dùng object.__setattr__ nếu cần khóa suy dẫn trong __post_init__ |
| Tuần tự hóa Chuẩn tắc | Có sẵn .model_dump(), .model_dump_json() và .model_json_schema() |
Cần chuyển tay hoặc qua bộ mã hóa JSON tường minh |
Cảnh báo Tinh vi — Bất biến Nông vs. Đột biến Bộ đệm (
Shallow Immutability vs. Buffer Mutability): Trong Python, cả@dataclass(frozen=True)lẫnConfigDict(frozen=True)của Pydantic chỉ đảm bảo bất biến nông: chúng cấm gán lại tham chiếustate.mean = new_arr, nhưng không ngăn hành vi sửa phần tử bên trong vùng nhớ khả biến (state.mean[0] = 999.0haystate.mapping["x"] = 0.0)! Để đạt bất biến sâu thực sự cho trạng thái đã huấn luyện, mọi danh sách/từ điển phải chuyển sangtuple/types.MappingProxyType, và mọi mảngNumPyphải bị khóa bộ đệm C chỉ đọc bằngarr.setflags(write=False)ngay trong.fit()/__post_init__—buộc mọi nỗ lực ghi đè tại chỗ phải némValueError: assignment destination is read-only.
Định kiểu Cấu trúc (typing.Protocol, PEP 544) vs. Kế thừa Danh nghĩa (ABC / BaseEstimator)#
- Kế thừa Danh nghĩa (
abc.ABCvàsklearn.base.BaseEstimator+TransformerMixin): Một lớp chỉ hợp lệ khi kế thừa tường minh từ lớp cha (class CustomScaler(BaseEstimator, TransformerMixin): ...). Hợp đồngBaseEstimatoryêu cầu mọi tham số__init__phải được lưu nguyên văn dưới cùng tên thuộc tính (cấm*args, cấm**kwargs, cấm biến đổi tham số trong__init__) đểget_params()/set_params()vàsklearn.base.clone()dựng lại được bản sao sạch chưa khớp bên trong kiểm định chéo (CV). Nhược điểm là sự trói buộc chặt vào thư viện bên thứ ba và xung đột MRO đa kế thừa. - Định kiểu Cấu trúc (
typing.Protocol, PEP 544 +@runtime_checkable): Hoạt động như "static duck typing": bất kỳ lớp nào cài đặt đúng chữ ký.fit(X, y=None)và.transform(X)đều tự động thỏa giao thứcStatefulTransformermà không cần kế thừa bất kỳ lớp cha nào! Lưu ý quan trọng: trình trang trí@runtime_checkablecủa Python khi chạyisinstance(obj, StatefulTransformer)chỉ kiểm tra sự tồn tại của tên phương thức (hasattr), chứ không kiểm tra kiểu tham số và kiểu trả về lúc runtime—do đó bắt buộc phải chạymypyhoặcpyrighttrongCIđể bảo đảm an toàn chữ ký đầy đủ.
Máy Trạng thái .fit() / .transform() & Bốn Bất biến Toán học#
Thay vì vẽ thêm sơ đồ thứ tư, toàn bộ máy trạng thái của bất kỳ toán tử tiền xử lý có trạng thái nào đều được khóa chặt bởi Bảng Chuyển trạng thái và 4 bất biến dưới đây:
| Trạng thái Hiện tại | Thao tác Gọi | Điều kiện Đầu vào | Trạng thái Kế tiếp / Ngoại lệ | Bất biến Bảo toàn |
|---|---|---|---|---|
Unfitted (\(\hat{\boldsymbol{\theta}} = \text{None}\)) |
.transform(\(\mathbf{B}\)) hoặc .to_state_dict() |
Bất kỳ \(\mathbf{B}\) | Ném NotFittedError (thất bại ồn ào) |
Cấm tự ý khớp trên dữ liệu kiểm tra hoặc cho đi qua nguyên trạng |
Unfitted (\(\hat{\boldsymbol{\theta}} = \text{None}\)) |
.fit(\(\mathbf{X}_{\text{tr}}, \mathbf{y}_{\text{tr}}\)) |
Khớp hợp đồng schema trên \(\mathcal{D}_{\text{tr}}\) (hoặc \(\mathcal{D}_{\text{tr}}^{(-k)}\)) | Fitted (tạo \(\hat{\boldsymbol{\theta}}\) bất biến sâu, khóa write=False) |
\(\hat{\boldsymbol{\theta}} = \mathcal{F}(\mathbf{X}_{\text{tr}}, \mathbf{y}_{\text{tr}}; c)\) — 0 byte từ \(\mathcal{D}_{\text{val}}/\mathcal{D}_{\text{te}}\) chạm vào \(\hat{\boldsymbol{\theta}}\) |
Fitted (\(\hat{\boldsymbol{\theta}}\) đóng băng) |
.transform(\(\mathbf{B}\)) |
\(\mathbf{B} \in \mathbb{R}^{m_{\text{batch}} \times d}\), đúng tên/thứ tự cột | Fitted (\(\hat{\boldsymbol{\theta}}\) bất biến nguyên vẹn) |
Bất biến theo lô từng dòng: \([T_{\hat{\boldsymbol{\theta}}}(\mathbf{B})]_{i,:} \equiv T_{\hat{\boldsymbol{\theta}}}(\mathbf{x}_i^\top)\;\forall m_{\text{batch}} \ge 1\) |
Fitted (\(\hat{\boldsymbol{\theta}}\) đóng băng) |
.fit(\(\mathbf{X}_{\text{tr}}^{(-k)}, \mathbf{y}_{\text{tr}}^{(-k)}\)) |
Chỉ cho phép bên trong bản sao CV độc lập |
Fitted (trạng thái mới của riêng nếp \(k\)) |
Cô lập hoàn toàn tham số giữa các nếp kiểm định chéo |
Khái quát hóa 4 bất biến từ bảng trên:
- Chốt Chặn Chưa Khớp (
Pre-Fit Guard): Chạm.transform()hoặc.to_state_dict()khi \(\hat{\boldsymbol{\theta}} = \text{None}\) lập tức némNotFittedError. - Ước lượng Chỉ trên Tập Huấn luyện: \(\hat{\boldsymbol{\theta}} = \mathcal{F}(\mathbf{X}_{\text{tr}}, \mathbf{y}_{\text{tr}}; c)\) đóng băng ngay khi
.fit()kết thúc. - Tính Trong suốt Tham chiếu & Bất biến Lô Từng dòng (
Row-Wise Batch Invariance): Với mọi ma trận lô \(\mathbf{B} = [\mathbf{x}_1, \dots, \mathbf{x}_{m_{\text{batch}}}]^\top \in \mathbb{R}^{m_{\text{batch}} \times d}\) (dù phục vụ trực tuyến \(m_{\text{batch}} = 1\) hay đánh giá ngoại tuyến \(m_{\text{batch}} = 10^5\)), hàng thứ \(i\) sau biến đổi chỉ phụ thuộc vào chính \(\mathbf{x}_i\) và trạng thái đóng băng \(\hat{\boldsymbol{\theta}}\):\[\big[T_{\hat{\boldsymbol{\theta}}}(\mathbf{B})\big]_{i,:} \equiv T_{\hat{\boldsymbol{\theta}}}(\mathbf{x}_i^\top) \qquad \text{và} \qquad \hat{\boldsymbol{\theta}}_{\text{after}} \equiv \hat{\boldsymbol{\theta}}_{\text{before}}.\](Ví dụ vi phạm kinh điển: gọidf.fillna(df.mean())lúc suy luận hay quên chuyển PyTorchBatchNormtừ.train()sang.eval(), khiến điểm dự báo API 1 dòng lệch hẳn so với chạy lô 200 dòng!) - Khóa Khớp Schema Cột & Chống Nuốt Cột (
Column Alignment Guard): Kiểm traX.shape[1]và khớp tên cột khi đầu vào làDataFrame; khi định tuyến quaColumnTransformer/ColumnRouter, chỉ cho phépremainder="drop"khi đã qua danh sách cột hợp đồng, tránh âm thầm vứt bỏ cột mới thêm từ thượng nguồn.
Cô lập Bộ sinh Số Ngẫu nhiên Tất định (SeedSequence + PCG64 vs. np.random.seed)#
Gọi hàm toàn cục cũ np.random.seed(42) làm thay đổi một thực thể RandomState (MT19937) dùng chung toàn tiến trình. Khi đó, thêm một phép lấy mẫu bootstrap trong mô-đun EDA sẽ tiêu thụ trước các số ngẫu nhiên và làm dịch chuyển ngầm danh sách ID tách tập train/test ở mô-đun kế tiếp, bên cạnh nhược điểm không an toàn đa luồng của MT19937. Kiến trúc tất định 2026 dùng np.random.SeedSequence(master_seed).spawn(4) để băm mật mã sinh 4 luồng con PCG64 (np.random.default_rng, chu kỳ \(2^{128}\)) độc lập hoàn toàn (split_rng, eda_rng, oof_rng, model_rng): rút 50,000 hay \(10^7\) mẫu từ eda_rng giữ nguyên từng bit của split_rng và model_rng.
1.3 Chứng minh Toán học Rò rỉ Tiền Tách tập (Mathematical Proofs of Pre-Split EDA & Preprocessing Leakage)#
Phân tích dữ liệu khám phá (EDA) không phải là vẽ đồ thị tùy hứng—nó là suy luận thống kê trên phân phối huấn luyện \(\mathcal{D}_{\text{tr}}\) dưới điều kiện cách ly tuyệt đối \(\mathcal{D}_{\text{te}}\). Hai chứng minh dưới đây bóc trần cái giá toán học phải trả nếu thực hiện tiền xử lý hay chọn đặc trưng trước khi tách tập.
Chứng minh 1 — Rò rỉ Chuẩn hóa & Điền Phân vị Tiền Tách tập#
Xét \(N = n_{\text{tr}} + n_{\text{te}}\) quan sát vô hướng \(\{X_1, \dots, X_N\}\) chia vào chỉ số huấn luyện \(\mathcal{I}_{\text{tr}}\) (\(|\mathcal{I}_{\text{tr}}| = n_{\text{tr}}\)) và kiểm tra \(\mathcal{I}_{\text{te}}\) (\(|\mathcal{I}_{\text{te}}| = n_{\text{te}}\)), với tỷ lệ \(\alpha_{\text{tr}} := n_{\text{tr}}/N\) và \(\alpha_{\text{te}} := n_{\text{te}}/N = 1 - \alpha_{\text{tr}}\).
- Bước 1 (Phân rã Mô-men ANOVA Chính xác): Gọi \(\bar{X}_{\text{tr}}, \hat{\sigma}_{\text{tr}}^2\) và \(\bar{X}_{\text{te}}, \hat{\sigma}_{\text{te}}^2\) là trung bình và phương sai MLE riêng từng tập. Khi chuẩn hóa trên toàn bộ dữ liệu gộp, tham số rò rỉ tuân theo phân rã ANOVA chính xác:
\[\bar{X}_{\text{all}} = \alpha_{\text{tr}}\bar{X}_{\text{tr}} + \alpha_{\text{te}}\bar{X}_{\text{te}}, \qquad \hat{\sigma}_{\text{all}}^2 = \alpha_{\text{tr}}\hat{\sigma}_{\text{tr}}^2 + \alpha_{\text{te}}\hat{\sigma}_{\text{te}}^2 + \alpha_{\text{tr}}\alpha_{\text{te}}\big(\bar{X}_{\text{tr}} - \bar{X}_{\text{te}}\big)^2,\]vì \(\bar{X}_{\text{tr}} - \bar{X}_{\text{all}} = \alpha_{\text{te}}(\bar{X}_{\text{tr}} - \bar{X}_{\text{te}})\) và \(\bar{X}_{\text{te}} - \bar{X}_{\text{all}} = -\alpha_{\text{tr}}(\bar{X}_{\text{tr}} - \bar{X}_{\text{te}})\).
- Bước 2 (Phụ thuộc Liên tập Ngay cả Dưới Dữ liệu
i.i.d.Thuần túy): Giả sử \(X_1, \dots, X_N \stackrel{\text{i.i.d.}}{\sim} (\mu, \sigma^2)\) không có dịch chuyển phân phối. Xét đặc trưng quy tâm tiền tách tập trên tập huấn luyện \(\tilde{X}_i^{(c)} := X_i - \bar{X}_{\text{all}}\) (\(i \in \mathcal{I}_{\text{tr}}\)) và bất kỳ mẫu kiểm tra nào \(X_k\) (\(k \in \mathcal{I}_{\text{te}}\)):\[\tilde{X}_i^{(c)} = \left(1 - \frac{1}{N}\right)X_i - \frac{1}{N}\sum_{m \ne i} X_m \implies \operatorname{Cov}\!\left(\tilde{X}_i^{(c)},\, X_k\right) = -\frac{1}{N}\operatorname{Var}(X_k) = -\frac{\sigma^2}{N} \ne 0.\]Do \(\operatorname{Var}(\tilde{X}_i^{(c)}) = \sigma^2(1 - \frac{1}{N})\), tương quan từng điểm là \(-\frac{1}{\sqrt{N(N-1)}}\) và \(\operatorname{Corr}(\tilde{X}_i^{(c)}, \tilde{X}_k^{(c)}) = -\frac{1}{N-1}\). Đáng kinh ngạc hơn, vì đẳng thức đồng nhất \(\alpha_{\text{tr}}\bar{\tilde{X}}_{\text{tr}}^{(c)} + \alpha_{\text{te}}\bar{\tilde{X}}_{\text{te}}^{(c)} \equiv 0\), trung bình phần dư hai tập bị khóa chặt bởi:\[\bar{\tilde{X}}_{\text{te}}^{(c)} = -\frac{\alpha_{\text{tr}}}{\alpha_{\text{te}}}\bar{\tilde{X}}_{\text{tr}}^{(c)} \implies \operatorname{Corr}\!\left(\bar{\tilde{X}}_{\text{tr}}^{(c)},\; \bar{\tilde{X}}_{\text{te}}^{(c)}\right) = -1.\]Nghĩa là phần dư trung bình huấn luyện sau chuẩn hóa toàn cục phản tương quan tất định tuyệt đối (\(\rho = -1\)) với phần dư trung bình kiểm tra! - Bước 3 (Thiên lệch Dưới Dịch chuyển Phân phối & Rò rỉ Cực trị): Khi tập kiểm tra dịch chuyển sang \((\mu_{\text{te}}, \sigma_{\text{te}}^2)\) với \(\Delta\mu := \mu_{\text{te}} - \mu_{\text{tr}} \ne 0\):
- Bơm thiên lệch vào tập huấn luyện & che mờ dịch chuyển: Kỳ vọng trung bình huấn luyện sau quy tâm rò rỉ trở thành \(\mathbb{E}[\bar{X}_{\text{tr}} - \bar{X}_{\text{all}}] = -\alpha_{\text{te}}\Delta\mu \ne 0\), cấy trực tiếp vị trí tương lai \(\mu_{\text{te}}\) vào hệ số chệch mô hình trong khi bóp dẹt độ dịch biểu kiến trên tập kiểm tra từ \(\Delta\mu\) xuống còn \(\alpha_{\text{tr}}\Delta\mu\).
- Nén phương sai & hỏng chuẩn hóa \(L_2\): Nếu tập kiểm tra có biến động đuôi nặng (\(\sigma_{\text{te}}^2 \gg \sigma_{\text{tr}}^2\)), \(\hat{\sigma}_{\text{all}}^2 \ge \alpha_{\text{te}}\hat{\sigma}_{\text{te}}^2 + \alpha_{\text{tr}}\alpha_{\text{te}}\Delta\mu^2\) ép toàn bộ thang đặc trưng huấn luyện về \(0\), làm sai lệch hoàn toàn mức phạt \(L_2\)/
weight decayhiệu dụng. - Rò rỉ phân vị & Min–Max: Tương tự, điền thiếu theo phân vị toàn cục \(\hat{Q}_p^{\text{all}}\) ước lượng phân vị hỗn hợp \(\alpha_{\text{tr}} F_{\text{tr}} + \alpha_{\text{te}} F_{\text{te}}\), còn chuẩn hóa Min–Max toàn cục đưa biên cực trị \(\max \mathcal{D}_{\text{te}}\) vào giới hạn tập huấn luyện (xảy ra gần như chắc chắn khi biến đếm tăng theo thời gian). \(\blacksquare\)
Chứng minh 2 — Ảo ảnh Lọc Đặc trưng Nhiều chiều Trên Nhiễu Trắng (ESL §7.10.2 Exact Orthogonal Decomposition)#
Thiết lập: Xét ma trận đặc trưng \(\mathbf{X} \in \mathbb{R}^{N \times d}\) gồm \(N = 100\) quan sát và \(d = 2{,}000\) đặc trưng, chia \(50/50\) thành \(n_{\text{tr}} = 50\), \(n_{\text{te}} = 50\), cùng biến mục tiêu \(\mathbf{y} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_N)\). Toàn bộ biến đầu vào và đầu ra là nhiễu Gaussian trắng độc lập \(100\%\):
- Bước 1 (Phân phối Vô hiệu & Giá trị Cực trị Trên \(d = 2{,}000\)): Trên mẫu cỡ \(n\), bình phương tương quan Pearson mẫu của đặc trưng bất kỳ \(j\) tuân theo \(r_j^2 \sim \operatorname{Beta}\!\left(\frac{1}{2}, \frac{n-2}{2}\right)\) với \(\mathbb{E}[r_j] = 0\), \(\mathbb{E}[r_j^2] = \frac{1}{n-1}\). Qua phép biến đổi Fisher \(Z_j = \operatorname{artanh}(r_j) \approx \mathcal{N}(0, \frac{1}{n-3})\), lấy cực trị trên \(d = 2{,}000\) cột độc lập đẩy ngưỡng cực đại lên \(\max_{1\le j\le d} |Z_j| \approx \Phi^{-1}(1 - \frac{\ln 2}{2d}) \approx 3.6\text{–}3.7\), kéo theo \(\mathbb{E}[\max |r_j^{\text{all}}|] \approx \tanh(3.71/\sqrt{97}) \approx 0.360\) (giá trị Monte Carlo chính xác tại \(N=100\) là
0.354). - Bước 2 (Phép Quay Trực giao \(45^\circ\) Xuyên qua Biên Tách Tập): Đặt điểm tương quan chuẩn hóa trên từng nửa là \(u_j^{\text{tr}} := \sqrt{n_{\text{tr}}}\,r_j^{\text{tr}}\) và \(u_j^{\text{te}} := \sqrt{n_{\text{te}}}\,r_j^{\text{te}}\). Dưới \(H_0\) với \(n_{\text{tr}} = n_{\text{te}} = N/2 = 50\), \((u_j^{\text{tr}}, u_j^{\text{te}}) \approx \mathcal{N}(0, 1)^{\otimes 2}\) độc lập. Thực hiện phép quay trực giao \(45^\circ\):
\[S_j := \frac{u_j^{\text{tr}} + u_j^{\text{te}}}{\sqrt{2}} \approx u_j^{\text{all}}, \qquad D_j := \frac{u_j^{\text{tr}} - u_j^{\text{te}}}{\sqrt{2}}.\]Do phép quay trực giao bảo toàn phân phối Chuẩn độc lập, ta có \(S_j \perp\!\!\!\perp D_j\) với \(S_j, D_j \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(0, 1)\). Giải ngược lại và chia cho \(\sqrt{50}\) cho phép phân tích chính xác:\[r_j^{\text{tr}} = r_j^{\text{all}} + \varepsilon_j, \qquad r_j^{\text{te}} = r_j^{\text{all}} - \varepsilon_j, \qquad \varepsilon_j := \frac{D_j}{\sqrt{N}} \sim \mathcal{N}\!\left(0,\, \frac{1}{N}\right) \perp\!\!\!\perp r_j^{\text{all}}.\]
- Bước 3 (Đối chiếu Tách tập Trước vs. Lọc Tiền Tách tập):
- Trường hợp A — Tách tập Trước Sạch (
Split-First): Việc chọn top-\(k\) chỉ nhìn vào \(\mathcal{D}_{\text{tr}}\), hoàn toàn độc lập với \(\mathcal{D}_{\text{te}}\), nên \(\mathbb{E}[r(X_{\text{te}, j^*}, Y_{\text{te}}) \mid \mathcal{D}_{\text{tr}}] = 0\) và \(\mathbb{E}[\operatorname{Corr}(Y_{\text{te}}, \hat{Y}_{\text{te}})] = 0\). Dù \(R^2_{\text{in}}\) trong mẫu tăng vọt vì quá khớp (0.2412ở \(k=1\) tới0.8626ở \(k=20\)), phương sai ước lượng \(\|\hat{\boldsymbol{\beta}}\|_2^2 > 0\) cộng thêm sai số bình phương thuần túy trên tập kiểm tra, làm \(R^2_{\text{te}} < 0\) nghiêm ngặt—vạch trần ngay dữ liệu chỉ là nhiễu trắng. - Trường hợp B — Lọc Tiền Tách tập (
Pre-Split Leaked): Khi chọn \(j^*\) theo cực trị của \(|r_j^{\text{all}}|\) trên toàn bộ \(N\) mẫu, hệ thức trực giao cho kỳ vọng có điều kiện trên cả hai tập:\[\mathbb{E}\!\left[r_{j^*}^{\text{tr}} \,\middle|\, r_{j^*}^{\text{all}}\right] = r_{j^*}^{\text{all}}, \qquad \mathbb{E}\!\left[r_{j^*}^{\text{te}} \,\middle|\, r_{j^*}^{\text{all}}\right] = r_{j^*}^{\text{all}}.\]Cả hai nửa chia sẻ cùng một thiên lệch dương \(r_{j^*}^{\text{all}}\)! Hệ số OLS \(\hat{\beta}_{j^*} \approx r_{j^*}^{\text{tr}}\) cùng dấu với \(r_{j^*}^{\text{te}}\), cộng hưởng qua top-\(k\) biến thành ảo ảnh dự báo mạnh trên tập kiểm tra:
- Trường hợp A — Tách tập Trước Sạch (
| Số biến Top-\(k\) | Rò rỉ \(R^2_{\text{in}}\) | Rò rỉ \(R^2_{\text{te}}\) | Rò rỉ \(\operatorname{Corr}_{\text{te}}\) | Sạch \(R^2_{\text{in}}\) | Sạch \(R^2_{\text{te}}\) | Sạch \(\operatorname{Corr}_{\text{te}}\) |
|---|---|---|---|---|---|---|
| \(k = 1\) | 0.1352 |
+0.0552 |
+0.3507 |
0.2412 |
-0.3153 |
-0.0062 |
| \(k = 5\) | 0.4152 |
+0.2144 |
+0.5365 |
0.5766 |
-0.4447 |
+0.0009 |
| \(k = 10\) | 0.5788 |
+0.3081 |
+0.6155 |
0.7288 |
-0.4262 |
+0.0114 |
| \(k = 20\) | 0.7745 |
+0.2745 |
+0.6482 |
0.8626 |
-0.4532 |
+0.0132 |
(Kết quả: Lọc trước khi tách tập biến 100% nhiễu trắng thành mô hình có \(\operatorname{Corr}_{\text{te}} \approx +0.62\) tại \(k=10\) và \(R^2_{\text{te}} \approx +0.31\); chi tiết phân loại đầy đủ rò rỉ hậu cần và kiểm thử canary xem tiếp tại ch-07.) \(\blacksquare\)
1.4 Nền tảng Toán học EDA Sạch: Dữ liệu Thiếu, Ngoại lai, Mã hóa Mục tiêu & Nghịch lý Simpson (Missingness, Robust Outliers, Target Encoding & Simpson Algebra)#
Phân loại Cơ chế Thiếu dữ liệu Rubin (MCAR, MAR, MNAR) & Định lý Co rút Phương sai#
Theo Rubin (1976), phân hoạch ma trận dữ liệu đầy đủ \(\mathbf{Y}_{\text{comp}} = (\mathbf{Y}_{\text{obs}}, \mathbf{Y}_{\text{mis}})\) và gọi \(\mathbf{M} \in \{0, 1\}^{n \times d}\) là ma trận chỉ báo thiếu (\(M_{ij} = 1\) nếu ô \((i, j)\) bị thiếu), chi phối bởi tham số \(\phi\):
- MCAR (Missing Completely at Random): \(P(\mathbf{M} \mid \mathbf{Y}_{\text{obs}}, \mathbf{Y}_{\text{mis}}, \phi) = P(\mathbf{M} \mid \phi)\) — sự mất mát độc lập với cả dữ liệu quan sát lẫn dữ liệu bị khuyết (vd. rớt gói tin ngẫu nhiên đồng đều).
- MAR (Missing at Random): \(P(\mathbf{M} \mid \mathbf{Y}_{\text{obs}}, \mathbf{Y}_{\text{mis}}, \phi) = P(\mathbf{M} \mid \mathbf{Y}_{\text{obs}}, \phi)\) — xác suất thiếu phụ thuộc vào các hiệp phương sai đã quan sát (vd. người dùng iOS cũ bỏ qua trường thu nhập tùy chọn), nhưng độc lập với giá trị khuyết khi điều kiện hóa trên \(\mathbf{Y}_{\text{obs}}\).
- MNAR (Missing Not at Random): \(P(\mathbf{M} \mid \mathbf{Y}_{\text{obs}}, \mathbf{Y}_{\text{mis}}, \phi)\) phụ thuộc thực sự vào giá trị chưa quan sát \(\mathbf{Y}_{\text{mis}}\) ngay cả khi đã biết \(\mathbf{Y}_{\text{obs}}\) (vd. bệnh nhân nặng mới được bác sĩ chỉ định đo
lactate, người thu nhập cực cao ẩn lương).
Định lý 1.1 (Co rút Phương sai & Suy giảm Tương quan Dưới Điền Trung bình MCAR):
Cho biến ngẫu nhiên \(X\) có kỳ vọng \(\mu = \mathbb{E}[X]\) và phương sai \(\sigma_X^2 = \operatorname{Var}(X) > 0\); cho \(Z\) là biến bất kỳ có kỳ vọng \(\mu_Z\), phương sai \(\sigma_Z^2 > 0\) và hiệp phương sai \(\operatorname{Cov}(X, Z)\); và cho \(M \sim \operatorname{Bernoulli}(p_{\text{miss}})\) (\(p_{\text{miss}} \in (0, 1)\)) thỏa MCAR (\(M \perp\!\!\!\perp (X, Z)\)). Xét biến đã điền trung bình:
Khi đó:
- \(\mathbb{E}[\tilde{X}] = \mu\) (trung bình không thiên lệch);
- \(\operatorname{Var}(\tilde{X}) = (1 - p_{\text{miss}})\,\sigma_X^2\) (phương sai bị nén tuyến tính theo tỷ lệ thiếu);
- \(\operatorname{Cov}(\tilde{X}, Z) = (1 - p_{\text{miss}})\,\operatorname{Cov}(X, Z)\) và \(\rho(\tilde{X}, Z) = \sqrt{1 - p_{\text{miss}}}\,\rho(X, Z)\).
Chứng minh từng bước:
- Do \(M \perp\!\!\!\perp X\), \(\mathbb{E}[\tilde{X}] = \mu + \mathbb{E}[1 - M]\mathbb{E}[X - \mu] = \mu + (1 - p_{\text{miss}})\cdot 0 = \mu\).
- Vì \(1 - M \in \{0, 1\}\) nên \((1 - M)^2 = 1 - M\). Áp dụng \(M \perp\!\!\!\perp X\):
\[\operatorname{Var}(\tilde{X}) = \mathbb{E}\!\left[(\tilde{X} - \mu)^2\right] = \mathbb{E}\!\left[(1 - M)^2(X - \mu)^2\right] = \mathbb{E}[1 - M]\,\mathbb{E}\!\left[(X - \mu)^2\right] = (1 - p_{\text{miss}})\,\sigma_X^2.\](Hoặc dùng
LoTVtừch-03: \(\operatorname{Var}(\tilde{X}) = \mathbb{E}[\operatorname{Var}(\tilde{X} \mid M)] + \operatorname{Var}(\mathbb{E}[\tilde{X} \mid M]) = (1 - p_{\text{miss}})\sigma_X^2 + 0\).) - Tương tự nhờ \(M \perp\!\!\!\perp (X, Z)\):
\[\operatorname{Cov}(\tilde{X}, Z) = \mathbb{E}\!\left[(1 - M)(X - \mu)(Z - \mu_Z)\right] = (1 - p_{\text{miss}})\,\operatorname{Cov}(X, Z).\]Chia cho \(\sqrt{\operatorname{Var}(\tilde{X})}\,\sigma_Z = \sqrt{1 - p_{\text{miss}}}\,\sigma_X \sigma_Z\) thu được \(\rho(\tilde{X}, Z) = \sqrt{1 - p_{\text{miss}}}\,\rho(X, Z)\). \(\blacksquare\)
- Vai trò Cờ Chỉ báo
is_missing& Chẩn đoán Trên \(\mathcal{D}_{\text{tr}}\): DướiMARvàMNAR, bản thân chỉ báo \(M_j\) mang thông tin dự báo trực tiếp (độ nặng lâm sàng, độ dày hồ sơ tín dụng). Do đó, trong \(\mathcal{D}_{\text{tr}}\), luôn kiểm định cân bằng giữa nhóm thiếu (\(M_j=1\)) và nhóm quan sát (\(M_j=0\)) qua các biến \(X_k\) (\(k \ne j\)) và \(Y_{\text{tr}}\) bằng Welch \(t\)-test / Mann–Whitney U / \(\chi^2\) + kiểm soátBH-FDR(ch-03); nếu phát hiện tương quan có ý nghĩa, bắt buộc giữ lại cột nhị phânis_missing(được khóa schema trong.fit()). - Ranh giới Bất khả Nhận dạng (
MARvs.MNAR): Vì \(\mathbf{Y}_{\text{mis}}\) không bao giờ được quan sát trong tập dữ liệu thô, không tồn tại bất kỳ kiểm định thống kê thuần túy nào chỉ trên \((\mathbf{Y}_{\text{obs}}, \mathbf{M})\) có thể phân biệt đượcMARvàMNAR; việc phân định ranh giới này đòi hỏi tri thức nhân quả miền, truy vết quy trình sinh dữ liệu hoặc phân tích độ nhạy.
Ước lượng Bền vững, Điểm Đổ vỡ (\(0\%\) vs. \(25\%\) vs. \(50\%\)) & Hệ thống Dự phòng MAD == 0#
Cho mẫu \(\mathbf{x} = (x_1, \dots, x_n) \in \mathbb{R}^n\), định nghĩa điểm đổ vỡ thay thế mẫu hữu hạn (Donoho & Huber, 1983) của bộ ước lượng \(T\) là tỷ lệ nhiễm bẩn nhỏ nhất \(\varepsilon_n^* := m_{\text{err}}/n\) đủ để kẻ đối nghịch thay thế \(m_{\text{err}}\) quan sát và đẩy \(|T(\mathbf{x}')|\) ra vô cực (hoặc đẩy thang đo về \(0/\infty\)):
- Trung bình \(\bar{x}\) & Độ lệch chuẩn \(s\) (\(\varepsilon_n^* = 1/n \to 0\%\)): Chỉ
1điểm cảm biến nhiễu \(x_1 \mapsto 10^9\) kéo văng toàn bộ \(z\)-score của mọi điểm sạch. - Hàng rào Tukey IQR (\(\varepsilon_n^* \approx 25\%\)): Khoảng \([Q_1 - 1.5\cdot\text{IQR}, Q_3 + 1.5\cdot\text{IQR}]\) chịu được tối đa \(25\%\) ngoại lai mỗi đuôi; tuy nhiên trên phân phối lệch phải
LogNormal, hàng rào đối xứng gắn cờ nhầm quá nhiều khách hàng hợp lệ ở đuôi phải nếu chưa biến đổi \(\ln(x + c)\). - Trung vị & Độ lệch Tuyệt đối Trung vị (
MAD, \(\varepsilon_n^* = \lfloor(n+1)/2\rfloor/n \to 50\%\)):\[\operatorname{MAD}(\mathbf{x}) := \operatorname{med}\!\big(\lvert \mathbf{x} - \operatorname{med}(\mathbf{x}) \rvert\big), \qquad \hat{\sigma}_{\text{MAD}} := c_{\text{MAD}}\cdot\operatorname{MAD}(\mathbf{x}), \qquad z_{\text{MAD}, i} = \frac{x_i - \operatorname{med}(\mathbf{x})}{c_{\text{MAD}}\,\operatorname{MAD}(\mathbf{x})}.\]
- Suy diễn Hằng số Nhất quán Chuẩn \(c_{\text{MAD}} \approx 1.4826022\): Nếu \(X \sim \mathcal{N}(\mu, \sigma^2)\), trung vị tổng thể là \(\mu\) và \(|X - \mu| = \sigma |Z|\) (\(Z \sim \mathcal{N}(0, 1)\)). Trung vị tổng thể \(m_0\) của \(|X - \mu|\) thỏa:
\[P(|X - \mu| \le m_0) = \frac{1}{2} \iff 2\Phi\!\left(\frac{m_0}{\sigma}\right) - 1 = \frac{1}{2} \iff \Phi\!\left(\frac{m_0}{\sigma}\right) = \frac{3}{4} \implies \frac{m_0}{\sigma} = \Phi^{-1}(0.75) \approx 0.67448975.\]Do đó \(c_{\text{MAD}} := \frac{1}{\Phi^{-1}(0.75)} \approx 1.4826022\) đảm bảo \(\hat{\sigma}_{\text{MAD}} \xrightarrow{p} \sigma\) nhất quán Fisher trên phân phối Chuẩn.
- Chứng minh Điểm Đổ vỡ Tiệm cận \(50\%\) của
MAD: Giả sử \(m_{\text{err}} \le \lfloor(n-1)/2\rfloor\) điểm bị thay tùy ý, giữ lại \(n - m_{\text{err}} \ge \lceil(n+1)/2\rceil > n/2\) điểm sạch nằm trong đoạn hữu hạn \([a, b] := [\min_{\text{clean}} x_i, \max_{\text{clean}} x_i]\) có đường kính \(R_{\text{clean}} = b - a < \infty\). Vì nghiêm ngặt hơn một nửa tập dữ liệu nằm trong \([a, b]\), thống kê thứ tự trung vị \(\operatorname{med}(\mathbf{x}')\) bắt buộc bị kẹp trong \([a, b]\). Khi đó mọi điểm sạch (hơn \(n/2\) phần tử) đều có sai lệch \(|x_i - \operatorname{med}(\mathbf{x}')| \le R_{\text{clean}}\), kéo \(\operatorname{MAD}(\mathbf{x}') \le R_{\text{clean}} < \infty\). Chỉ khi \(m_{\text{err}} = \lceil n/2 \rceil\) (tỉ lệ \(\ge \lfloor(n+1)/2\rfloor/n \to 50\%\)) kẻ đối nghịch mới phá được cận trên, hoàn tất chứng minh. \(\blacksquare\)
Hệ thống Phân cấp Xử lý MAD == 0 (Dữ liệu dư thừa giá trị \(0\) — zero-inflated / Rời rạc): Khi hơn \(50\%\) giá trị huấn luyện trùng nhau (vd. chi tiêu 0, 0, 0, 0, 10), ta có \(\operatorname{med}(\mathbf{x}) = v_{\text{mode}}\) và \(\operatorname{MAD}(\mathbf{x}) = 0.0\), gây chia cho 0 (ZeroDivisionError / inf / NaN). Bắt buộc áp dụng thứ tự phân cấp 3 tầng:
- Tầng 1 — Tách mô hình Hurdle (ưu tiên cho chi tiêu/đếm): Tách chỉ báo \(\mathbb{I}[x > 0]\) và tính
MADriêng trên phân khúc dương \(X \mid X > 0\). - Tầng 2 — Dự phòng Độ lệch Tuyệt đối Trung bình (
MeanAD, Iglewicz & Hoaglin 1993): Khi \(\operatorname{MAD} == 0\), chuyển sang \(\hat{\sigma}_{\text{MeanAD}} = c_{\text{MeanAD}}\cdot\operatorname{MeanAD} = \sqrt{\frac{\pi}{2}}\cdot\frac{1}{n}\sum_{i=1}^n |x_i - \operatorname{med}(\mathbf{x})| \approx 1.2533141\cdot\operatorname{MeanAD}\) (vì \(\mathbb{E}[|Z|] = \sqrt{2/\pi}\) dưới \(\mathcal{N}(0, 1)\)), chấp nhận đánh đổi giảm điểm đổ vỡ để có mẫu số dương hợp lệ. - Tầng 3 — Chốt An toàn Hằng số (
Constant-Feature Guard): Nếu \(\operatorname{MeanAD} \le \varepsilon_{\text{floor}}\) (cột hoàn toàn hằng số trên tập train), ghi nhậnscale_mode = "constant"và ánh xạ mọi z-score về0.0.
Biến Phân loại Lực lượng cao (High-Cardinality) & Mã hóa Mục tiêu Empirical-Bayes OOF#
Với các cột tuân theo luật đuôi dài Zipf (merchant_id, zip_code, sku_id) có \(C \sim 10^3\text{–}10^6\) nhãn riêng biệt và đa số nhãn xuất hiện \(n_c \in \{1, 2, 3\}\) lần, One-Hot Encoding nổ số chiều \(O(C)\), còn lấy trung bình mục tiêu thô \(\bar{y}_c\) khiến mọi nhãn đơn lẻ (\(n_c = 1\)) sao chép y nguyên nhãn \(\bar{y}_c = y_i \in \{0, 1\}\) thành đặc trưng đầu vào!
Nối trực tiếp từ tiên nghiệm liên hợp Beta–Binomial (ch-03 §1.1), đặt tiên nghiệm \(\theta_c \sim \operatorname{Beta}(m_{\text{smooth}}\mu_0,\, m_{\text{smooth}}(1-\mu_0))\) quanh trung bình toàn cục \(\mu_0 := \bar{y}_{\text{tr}}\) với giả đếm làm trơn \(m_{\text{smooth}} > 0\). Kỳ vọng hậu nghiệm cho ra bộ ước lượng m-estimate Empirical-Bayes (Micci-Barreca, 2001):
- Hai giới hạn tiệm cận: Khi \(n_c \to 0\) (nhãn mới hoặc hiếm), \(\hat{e}_c \to \mu_0\) (co rút an toàn không bao giờ ra
NaN; với \(m_{\text{smooth}}=20, \mu_0=0.10\), một nhãn đơn lẻ dương \(n_c=1, \bar{y}_c=1\) được co từ1.000xuống0.143); khi \(n_c \to \infty\), \(\hat{e}_c \to \bar{y}_c\). - Cô lập Ngoài nếp (
Out-of-Fold — OOF): Ngay cả khi có \(m_{\text{smooth}}\), tính \(\hat{e}_{c(i)}\) bằng thống kê chứa chính \(y_i\) tạo rò rỉ trong hàng \(\partial \hat{e}_{c(i)}/\partial y_i = \frac{1}{n_c + m_{\text{smooth}}} > 0\). Vì vậy, trong.fit_transform(\(\mathbf{X}_{\text{tr}}, \mathbf{y}_{\text{tr}}\)), phải chia \(\mathcal{D}_{\text{tr}}\) thành \(K\) nếp (tôn trọnggroups), gộp trước các nhãn hiếm có \(n_c < n_{\min}\) vào thùng chung__RARE__, và mã hóa nếp \(k\) hoàn toàn từ bổ túc \(\mathcal{D}_{\text{tr}}^{(-k)}\); còn từ điển đầy đủ trên toàn bộ \(\mathcal{D}_{\text{tr}}\) chỉ đóng băng để phục vụ.transform(\(\mathbf{X}_{\text{val/te}}\)).
Đại số Nghịch lý Simpson & Cầu nối Nhân quả Sang ch-05#
Đánh giá chỉ số cộng gộp không phân tầng trong EDA dễ bị đảo dấu hoàn toàn bởi biến hỗn tạp. Xét hai biến thể \(A\) và \(B\) qua hai tầng \(s \in \{1, 2\}\) với tỷ lệ chuyển đổi tầng \(r_{A,s}, r_{B,s}\) và tỷ trọng lưu lượng rơi vào tầng 1 là \(w_A, w_B \in [0, 1]\). Vì \(r_G^{\text{agg}} = w_G r_{G,1} + (1 - w_G)r_{G,2}\), lấy hiệu hai tỷ lệ cộng gộp cho ra đẳng thức phân tách chính xác:
Minh họa bằng bảng \(2 \times 2\) chính xác với \(N = 2{,}000\) người dùng:
Phân khúc Tầng (Stratum) |
Biến thể A (\(n\), chuyển đổi, tỷ lệ) | Biến thể B (\(n\), chuyển đổi, tỷ lệ) | Thắng trong Tầng (\(A - B\)) |
|---|---|---|---|
Tầng 1: Di động Lạnh (Cold Mobile) (Nền thấp) |
900 người, 180 đơn \(\implies\) 20.0% |
100 người, 15 đơn \(\implies\) 15.0% |
Biến thể A (+5.0 pp) |
Tầng 2: Máy tính Cũ (Returning Desktop) (Nền cao) |
100 người, 85 đơn \(\implies\) 85.0% |
900 người, 720 đơn \(\implies\) 80.0% |
Biến thể A (+5.0 pp) |
| Tổng cộng gộp (Không phân tầng) | 1,000 người, 265 đơn \(\implies\) 26.5% (\(w_A = 0.90\)) |
1,000 người, 735 đơn \(\implies\) 73.5% (\(w_B = 0.10\)) |
Biến thể B?! (Ảo giác -47.0 pp!) |
Kiểm chứng trực tiếp qua đẳng thức phân tách:
Để khử nhiễu cơ cấu ngay trong EDA, áp dụng Chuẩn hóa Trực tiếp (Direct Standardization) theo tỷ trọng gộp chung \(w_s^{\text{pool}} = \frac{n_{A,s}+n_{B,s}}{N}\) (\(w_1^{\text{pool}} = w_2^{\text{pool}} = 0.50\)):
(Toàn bộ khung đồ thị nhân quả SCM/DAG, Tiêu chuẩn Cửa sau Backdoor Criterion, IPW/AIPW, Double ML và mô hình Uplift để giải quyết triệt để thiên lệch hỗn tạp được trình bày hoàn chỉnh tại ch-05-causal-inference-and-uplift-modeling.md.)
Trụ cột 2 — Kỹ thuật Pipeline Có trạng thái, Toán học Dịch chuyển Phân phối SOTA & Công cụ Tái lập 2024–2026 (Stateful OOP Pipelines, SOTA Distribution Shift & 2024–2026 Stack)#
2.1 Kỹ thuật Pipeline Có trạng thái, Xử lý Thiếu/Đuôi & Tuần tự hóa Không-pickle (Stateful Pipeline Engineering, OOF Encoding & Zero-Pickle Security)#
Ghép nối StatefulPipeline & ColumnRouter An toàn#
Một hệ thống sản xuất ghép chuỗi nhiều bước biến đổi liên tiếp \(M_{\hat{\phi}} \circ T_{K,\hat{\theta}_K} \circ \dots \circ T_{1,\hat{\theta}_1}\) qua StatefulPipeline và phân luồng song song theo kiểu cột số/phân loại qua ColumnRouter:
Hai nguyên tắc sống còn khi thiết kế hai lớp này:
- Cô lập Từng nếp Kiểm định Chéo: Mọi bước từ
RobustMADImputer,OutOfFoldTargetEncoderđếnStatefulStandardizerphải nằm bên trong đối tượng pipeline được nhân bản tươi mới cho từng nếp \(\mathcal{D}_{\text{tr}}^{(-k)}\); tuyệt đối không chạy biến đổi một phần bên ngoài trước vòng lặpCV. - Chống Nuốt Cột Ngầm (
Remainder Guard): Khi sử dụngColumnTransformer, mặc địnhremainder="drop"âm thầm vứt bỏ các cột mới vừa được kỹ sư dữ liệu thêm vào ở thượng nguồn mà không báo lỗi.ColumnRouterphải khóa mặc địnhremainder="error"trừ khi schema hợp đồng cho phép tường minh.
Kỹ thuật OutOfFoldTargetEncoder & Tự động Chẩn đoán Thiếu/Đuôi#
OutOfFoldTargetEncoderCấp Sản xuất:- Chuẩn hóa mọi
NaN/Nonethành token tường minh__MISSING__trước khi đếm tần suất. - Gộp mọi giá trị có số lần xuất hiện \(n_c < n_{\min}\) (
min_samples, vd.5) vào thùng__RARE__trước khi tính thống kê \(m\)-estimate trong từng nếp—ngăn các thực thể đơn lẻ nhiễu tạo khóa tra cứu riêng lẻ. - Hỗ trợ tham số
groupstrong.fit_transform(X_train, y_train, groups=...): nếu một bệnh nhân hoặc một cửa hàng có nhiều dòng, toàn bộ các dòng thuộc cùng mộtgroupphải rơi vào cùng một nếp OOF, nếu không thông tin mục tiêu của chính thực thể đó ở các dòng anh em sẽ rò rỉ xuyên nếp! Đối với luồng thời gian tuần tự thực sự, sử dụng biến thể Thống kê Mục tiêu Có thứ tự (CatBoost Ordered Target Statistics) chỉ tích lũy nhãn của các bản ghi có thời điểm \(t_j < t_i\).
- Chuẩn hóa mọi
- Tự động Chẩn đoán
MCAR/MAR/MNAR& Điền Thiếu Bền vững (RobustMADImputer): Hàmdiagnose_missingness_mechanisms(train_df, target_col=...)chạy duy nhất trêntrain_dfđể đo: (a) tỷ lệ thiếu \(p_{\text{miss}}\), (b) tỷ lệ bảo toàn phương sai lý thuyết \(1 - p_{\text{miss}}\) đối chiếu thực nghiệm, (c) tương quan điểm-nhị phân lớn nhất với các hiệp phương sai khác (max_covariate_corr), và (d) tương quan với mục tiêu huấn luyện (target_missingness_corr). Khi \(p_{\text{miss}} \ge 0.01\) và bất kỳ độ tương quan nào vượt ngưỡng (>= 0.12),RobustMADImputertự động khóa danh sách cột<col>_is_missingvàoindicator_cols_tại.fit()để suy luận luôn nhận đủ chiều và giá trị trung vị đóng băng từtrain_df.
Tuần tự hóa Không-pickle & An ninh Chuỗi cung ứng (CWE-502, skops CVE-2025-54886, safetensors)#
Dùng pickle, joblib hoặc cloudpickle để lưu pipeline và mô hình vi phạm cả tính an toàn lẫn tính tái lập:
- Thực thi Mã Từ xa Theo Thiết kế (
CWE-502): Định dạngpicklekhông phải dữ liệu thụ động—nó là một máy ảo ngăn xếp có các mã lệnhREDUCEvàGLOBALgọi trực tiếp hàm Python bất kỳ trong khipickle.load()chạy. Bất kỳ đối tượng nào định nghĩa__reduce__trả về(os.system, (...))đều kích hoạt thực thi mã độc trước khi hàm gọi kịp kiểm tra đối tượng trả về. - Các Lỗ hổng
CVEThực tế Năm 2025 Trong Lớp Vỏ Bảo vệ: Ngay cả các thư viện đóng gói thaypicklechoscikit-learncũng từng gặp lỗ hổng nghiêm trọng:skopsCVE-2025-54886(trênskops <= 0.12.0, hàmCard.get_model()âm thầm rơi ngược vềjoblib.load()nếu tệp không phải nén.skopshợp lệ, vượt mặt hoàn toàn danh sách kiểm duyệt kiểu!), cùng vớiCVE-2025-54412vàCVE-2025-54413trênOperatorFuncNode/MethodNode. Bản váskops >= 0.13.0đã gia cố kiểm tra nút và khóa chặt mặc địnhallow_pickle=False. - Đứt gãy Tương thích
ABIQua Bản nâng cấp (ModuleNotFoundError: numpy._core): Tệp.pkllưu cứng đường dẫn mô-đun nội bộ (sklearn.preprocessing._data,numpy.corevs.numpy._corekhi lênNumPy 2.x), khiến mô hình lưu từ 6 tháng trước chết ngay khi nâng cấp thư viện.
Giải pháp Chuẩn 2026 — Tách Mã Khỏi Trạng thái Bị động (Declarative JSON State-Dicts + SHA-256):
- Với mô hình học sâu (
PyTorch 2.x): dùngsafetensorscủa Hugging Face (nạp zero-copy quammap, tiêu đề thuần JSON, không bytecode). - Với mô hình cây phức tạp: dùng
skops >= 0.13.0(kiểm traget_untrusted_types+allow_pickle=False),ONNX, hoặc định dạng JSON thuần gốc củaLightGBM/XGBoost. - Với các bộ biến đổi và pipeline tùy biến trong
ch-04: tuần tự hóa thành JSON State-Dict chuẩn tắc chỉ chứa dữ liệu thuần{ "schema_version", "class_name", "feature_names", "config", "learned_params" }quajson.dumps(..., sort_keys=True, allow_nan=False), kèmpayload_sha256được kiểm tra toàn vẹn trước khi dựng lại đối tượng—miễn nhiễm100%vớiCWE-502và đọc được xuyên suốt mọi phiên bản Python,NumPy, Rust hay JavaScript.
2.2 Toán học Dịch chuyển Phân phối SOTA (Covariate / Label / Concept / Schema Shifts & PSI / JSD / \(W_1\) / KS / C2ST / MMD)#
Phân loại 4 Lớp Dịch chuyển Dữ liệu (Moreno-Torres et al., 2012 + Kỹ thuật Telemetry)#
Đặt phân phối tham chiếu là \(P_{\text{ref}}(X, Y)\) và phân phối hiện tại/phục vụ là \(P_{\text{cur}}(X, Y)\). Mọi biến động phân phối \(P_{\text{cur}}(X, Y) \neq P_{\text{ref}}(X, Y)\) quy về 4 chế độ sau:
| Lớp Dịch chuyển | Bất biến & Biến đổi Toán học | Cơ chế Phát sinh & Ví dụ | Vì sao ERM Thất bại / Chiến lược Phát hiện |
|---|---|---|---|
| 1. Covariate Shift (Dịch chuyển Hiệp phương sai) | \(P_{\text{cur}}(X) \neq P_{\text{ref}}(X)\), nhưng \(P_{\text{cur}}(Y \mid X) = P_{\text{ref}}(Y \mid X)\) | Nhân khẩu học chuyển vùng địa lý, mùa vụ làm thay đổi phân phối thu nhập trong bài toán nhân quả \(X \to Y\). | Bẫy ERM sai lớp mô hình: Ngay cả khi \(P(Y \mid X)\) giữ nguyên, bộ phân loại hữu hạn \(\hat{f}_{\text{ERM}} \in \mathcal{H}\) tập trung độ chính xác vào vùng \(P_{\text{ref}}(x)\) dày đặc và bỏ mặc sai số lớn ở vùng đuôi thưa—vùng bỗng trở thành tâm điểm của \(P_{\text{cur}}(X)\)! Phát hiện bằng PSI, JSD, \(W_1\), KS, C2ST, MMD. |
| 2. Label / Prior Shift (Dịch chuyển Nhãn Tiên nghiệm) | \(P_{\text{cur}}(Y) \neq P_{\text{ref}}(Y)\), nhưng \(P_{\text{cur}}(X \mid Y) = P_{\text{ref}}(X \mid Y)\) | Tỷ lệ gian lận hoặc dịch bệnh tăng vọt trong bài toán phản nhân quả \(Y \to X\) trong khi triệu chứng khi mắc bệnh không đổi. | Phát hiện qua BBSE (Black-Box Shift Estimation, Lipton et al. 2018) nghịch đảo ma trận nhầm lẫn; hiệu chỉnh trực tiếp qua dịch chuyển log-odds Bayes tại ch-07. |
| 3. Concept Drift (Trôi Khái niệm) | \(P_{\text{cur}}(Y \mid X) \neq P_{\text{ref}}(Y \mid X)\) (dù \(P_{\text{cur}}(X) = P_{\text{ref}}(X)\) hoàn toàn!) | Lạm phát làm thay đổi xác suất vỡ nợ ở cùng mức thu nhập; kẻ gian lận đổi chiến thuật lách luật. | Vô hình 100% trước mọi bộ giám sát chỉ nhìn \(X\) (PSI(X), KS(X), AUC_adv(X) đều \(\approx 0\))! Bắt buộc đợi nhãn trễ theo dõi ECE/loss hoặc vòng điều khiển ACI/DtACI (Track 2 Bài #17). |
| 4. Schema / Telemetry / Encoding Shift (Dịch chuyển Lược đồ) | Quan sát \(\tilde{X} = \phi_{\text{cur}}(X) \neq \phi_{\text{ref}}(X)\) dù \(X\) vật lý giữ nguyên | Đổi s \(\to\) ms (\(\times 1000\)), đổi NULL \(\to\) -1.0, cắt bớt float64 \(\to\) int8, lệch múi giờ UTC. |
Chặn đứng trước suy luận bằng Pydantic v2 + Pandera và bắt sớm qua \(W_1\) toàn cục + giám sát cắt lát theo phân khúc (D3). |
Thước đo 1 — PSI (Population Stability Index): Chứng minh Thiên lệch Vô hiệu Chính xác & Bẫy Đóng Bin#
Chia miền thực \(\mathbb{R}\) thành \(B \ge 2\) bin rời nhau \(\{I_1, \dots, I_B\}\) với xác suất dương \(p_b = P_{\text{ref}}(X \in I_b) > 0\) và \(q_b = P_{\text{cur}}(X \in I_b) > 0\). Định nghĩa:
Như vậy PSI chính là Phân kỳ KL Đối xứng Jeffreys: không âm, đối xứng, nhưng không phải metric (vi phạm bất đẳng thức tam giác và bùng nổ ra \(+\infty\) khi \(q_b \to 0\) mà \(p_b > 0\)).
Định lý 2.1 (Thiên lệch Vô hiệu Dương Chính xác & Luật Tiệm cận \(\chi^2_{B-1}\) — Yurdakul & Naranjo, 2020):
Giả sử \(H_0: P_{\text{ref}} = P_{\text{cur}}\) (trôi thực bằng 0) với \(p_b > 0\;\forall b\), và mẫu đếm độc lập \(\mathbf{C}^{\text{ref}} \sim \operatorname{Multinomial}(n_{\text{ref}}, \mathbf{p})\), \(\mathbf{C}^{\text{cur}} \sim \operatorname{Multinomial}(n_{\text{cur}}, \mathbf{p})\). Đặt \(\hat{p}_b = p_b + \delta_b\), \(\hat{q}_b = p_b + \eta_b\), và cỡ mẫu điều hòa \(n_{\text{eff}} := \big(n_{\text{ref}}^{-1} + n_{\text{cur}}^{-1}\big)^{-1}\). Khi \(n_{\text{ref}}, n_{\text{cur}} \to \infty\):
Chứng minh 4 bước (khẳng định hệ số 1, không phải 1/2):
- Mô-men lấy mẫu đa thức: Do hai mẫu độc lập, \(\mathbb{E}[\delta_b] = \mathbb{E}[\eta_b] = 0\), \(\operatorname{Var}(\delta_b) = \frac{p_b(1-p_b)}{n_{\text{ref}}}\), \(\operatorname{Var}(\eta_b) = \frac{p_b(1-p_b)}{n_{\text{cur}}}\) và \(\mathbb{E}[\delta_b\eta_b] = 0\). Đặt \(\Delta_b := \hat{p}_b - \hat{q}_b = \delta_b - \eta_b\), suy ra \(\mathbb{E}[\Delta_b^2] = p_b(1-p_b)\big(\frac{1}{n_{\text{ref}}} + \frac{1}{n_{\text{cur}}}\big) = \frac{p_b(1-p_b)}{n_{\text{eff}}}\).
- Khai triển Taylor bậc hai: Dùng \(\ln(p_b + u) = \ln p_b + \frac{u}{p_b} - \frac{u^2}{2p_b^2} + \mathcal{O}(|u|^3)\) cho cả \(\delta_b\) và \(\eta_b\):
\[\ln\frac{\hat{p}_b}{\hat{q}_b} = \frac{\delta_b - \eta_b}{p_b} - \frac{\delta_b^2 - \eta_b^2}{2p_b^2} + \mathcal{O}_p\!\left(n_{\min}^{-3/2}\right).\]
- Vì sao hệ số đứng trước là \(1\) (không có nhân tử \(1/2\)): Nhân hai vế với \(\hat{p}_b - \hat{q}_b = \delta_b - \eta_b\):
\[(\hat{p}_b - \hat{q}_b)\ln\frac{\hat{p}_b}{\hat{q}_b} = \frac{(\delta_b - \eta_b)^2}{p_b} - \frac{(\delta_b - \eta_b)(\delta_b^2 - \eta_b^2)}{2p_b^2} + \mathcal{O}_p\!\left(n_{\min}^{-2}\right).\]Khác với một phân kỳ KL đơn lẻ \(D_{\text{KL}}(\hat{P} \| P) \approx \frac{1}{2}\sum \frac{\delta_b^2}{p_b}\),
PSIcộng hai phân kỳ KL nên \(\frac{1}{2} + \frac{1}{2} = \mathbf{1}\). Hơn nữa phần dư bậc ba có kỳ vọng \(\mathcal{O}(n_{\min}^{-2})\) vì \(\mathbb{E}[\delta_b\eta_b^2] = 0\) và mô-men tâm bậc ba đa thức giảm cỡ \(n^{-2}\). - Cộng tổng qua \(B\) bin:
\[\mathbb{E}_{H_0}[\widehat{\operatorname{PSI}}] = \sum_{b=1}^B \frac{\mathbb{E}[\Delta_b^2]}{p_b} + \mathcal{O}\!\left(n_{\min}^{-2}\right) = \left(\frac{1}{n_{\text{ref}}} + \frac{1}{n_{\text{cur}}}\right)\sum_{b=1}^B (1 - p_b) + \mathcal{O}\!\left(n_{\min}^{-2}\right) = (B - 1)\left(\frac{1}{n_{\text{ref}}} + \frac{1}{n_{\text{cur}}}\right) + \mathcal{O}\!\left(n_{\min}^{-2}\right),\]do \(\sum_{b=1}^B p_b = 1\). Nhân hai vế với \(n_{\text{eff}}\) đưa \(\widehat{\operatorname{PSI}}\) về đúng thống kê Pearson \(X^2 = n_{\text{eff}}\sum \frac{(\hat{p}_b-\hat{q}_b)^2}{p_b} \xrightarrow{d} \chi^2_{B-1}\) có kỳ vọng \(B-1\) và phương sai \(2(B-1)\). \(\blacksquare\)
Thảm họa Mẫu nhỏ (\(B=20, n_{\text{cur}}=100, n_{\text{ref}}=5{,}000\)) & Quy tắc Đóng Bin An toàn:
Dưới trạng thái \(P_{\text{ref}} = P_{\text{cur}}\) sạch tuyệt đối, chỉ riêng thiên lệch Taylor đã đạt \((20-1)(\frac{1}{5000} + \frac{1}{100}) = \mathbf{0.1938}\); thêm việc xuất hiện bin rỗng (kỳ vọng 5 mẫu/bin làm xác suất có ít nhất 1 bin rỗng đạt \(\approx 12.6\%\)) nếu kẹp về \(\epsilon = 10^{-12}\) sẽ đẩy trung bình Monte Carlo lên ~0.354 > 0.25—kích hoạt báo động giả liên tục! Do đó, bắt buộc: (1) tính các cạnh phân vị duy nhất trên \(P_{\text{ref}}\), mở rộng hai đầu thành \((-\infty, \dots, +\infty)\) để giá trị ngoại khoảng rơi sạch vào bin đầu/cuối; (2) khử trùng cạnh bằng np.unique chống lỗi biến rời rạc/bơm 0; (3) thêm bin NaN tường minh; và (4) khóa ngưỡng tới hạn phụ thuộc cỡ mẫu \(\operatorname{PSI}_{\text{crit}}(\alpha) = \chi^2_{B-1,\, 1-\alpha}/n_{\text{eff}}\) (hoặc PRS của van Zyl & Potgieter 2023–2024 cho kiểm định tương đương).
Thước đo 2 — JSD (Jensen–Shannon Divergence): Cận Chặt \([0, \ln 2]\), Metric \(\sqrt{\operatorname{JSD}}\) & Đơn vị bits vs. nats#
Đặt phân phối hỗn hợp \(M_{\text{mix}} := \frac{1}{2}(P_{\text{ref}} + P_{\text{cur}})\). Ta định nghĩa JSD ở hai đơn vị quy đổi \(\operatorname{JSD}_{\text{bit}}(P_{\text{ref}} \| P_{\text{cur}}) := \frac{1}{\ln 2}\operatorname{JSD}_{\text{nat}}(P_{\text{ref}} \| P_{\text{cur}})\):
Chứng minh 3 dòng \(\operatorname{JSD}_{\text{nat}} \in [0, \ln 2]\): (1) Do \(D_{\text{KL}} \ge 0\), \(\operatorname{JSD}_{\text{nat}} \ge 0\) (bằng \(0\) iff \(P_{\text{ref}} = P_{\text{cur}}\) h.c.c.). (2) Với mọi điểm có \(p(x) > 0\), vì \(q(x) \ge 0\) nên \(m_{\text{mix}}(x) = \frac{1}{2}(p(x)+q(x)) \ge \frac{1}{2}p(x) > 0\), kéo theo \(\ln\frac{p(x)}{m_{\text{mix}}(x)} \le \ln\frac{p(x)}{\frac{1}{2}p(x)} = \ln 2\) (bằng \(\ln 2\) iff \(q(x) = 0\)); tương tự cho \(q(x) > 0\). (3) Tích phân/cộng tổng trên toàn miền cho \(\operatorname{JSD}_{\text{nat}} \le \frac{\ln 2}{2}(1 + 1) = \ln 2\) (1 bit), đạt cực đại khi và chỉ khi hai phân phối rời nhau hoàn toàn. \(\blacksquare\)
- Metric thực & Tương đương \(\operatorname{PSI}/8\): Endres & Schindelin (2003) chứng minh \(\sqrt{\operatorname{JSD}}\) thỏa mãn đầy đủ tính đối xứng, đồng nhất và bất đẳng thức tam giác (hợp lệ cho phân cụm cửa sổ dịch chuyển). Tại lân cận \(P_{\text{ref}} \approx P_{\text{cur}}\), khai triển bậc hai cho \(\operatorname{JSD}_{\text{nat}} \approx \frac{1}{8}\operatorname{PSI}\) và thiên lệch vô hiệu \(\approx \frac{B-1}{8}(n_{\text{ref}}^{-1} + n_{\text{cur}}^{-1})\). Khác với
PSIbùng nổ theo \(\ln(1/\epsilon)\) khi gặp bin không,JSDkhông bao giờ chia cho \(0\), nhưng lại bão hòa phẳng tại \(\ln 2\) (1bit) khi hai phân phối tách rời hoàn toàn—không phân biệt được dịch chuyển cách nhau0.1hay1,000.
Thước đo 3 — Khoảng cách Wasserstein-1 1D (\(W_1\) / Earth Mover's Distance)#
Từ đối ngẫu Kantorovich–Rubinstein trên \(\mathcal{P}_1(\mathbb{R})\):
Định lý 2.2 (Dạng Đóng Chính xác của \(W_1\) 1D Qua Bắt cặp Đồng biến):
Với hàm phân phối tích lũy \(F_{\text{ref}}, F_{\text{cur}}\) và hàm phân vị \(F^{-1}(u) := \inf\{x \in \mathbb{R} : F(x) \ge u\}\):
Chứng minh (Bắt cặp Fréchet–Hoeffding + Layer-Cake): Với mọi bắt cặp \(\gamma \in \Pi\), áp dụng đồng nhất thức \(|x - y| = \int_{-\infty}^\infty (\mathbb{I}[x \le t < y] + \mathbb{I}[y \le t < x])\,dt\) và đánh giá \(\mathbb{P}_\gamma(X \le t < Y) \ge (F_{\text{ref}}(t) - F_{\text{cur}}(t))_+\) cùng phần đối xứng suy ra \(W_1 \ge \int_{-\infty}^\infty |F_{\text{ref}}(t) - F_{\text{cur}}(t)|\,dt\). Đạt dấu bằng bằng cách lấy \(U \sim \operatorname{Uniform}(0, 1)\) và ghép cặp đồng biến \((X, Y) = (F_{\text{ref}}^{-1}(U), F_{\text{cur}}^{-1}(U))\), khi đó hai biến cố \(\{X \le t < Y\} \iff \{F_{\text{cur}}(t) < U \le F_{\text{ref}}(t)\}\) và \(\{Y \le t < X\}\) rời nhau hoàn toàn và có tổng xác suất đúng bằng \(|F_{\text{ref}}(t) - F_{\text{cur}}(t)|\). \(\blacksquare\)
- Thuật toán \(O((n_{\text{ref}}+n_{\text{cur}})\log(n_{\text{ref}}+n_{\text{cur}}))\) Chính xác Xử lý Đồng hạng: Sắp xếp mẫu tham chiếu \(\mathbf{u}\) và mẫu hiện tại \(\mathbf{v}\), hợp nhất thành mảng mốc tăng dần \(\mathbf{z} = (z_0 \le \dots \le z_{n_{\text{ref}}+n_{\text{cur}}-1})\). Trên mỗi dải \((z_k, z_{k+1})\), cả hai CDF thực nghiệm \(\hat{F}_{\text{ref}}\) và \(\hat{F}_{\text{cur}}\) đều hằng số từng khúc (
searchsorted(..., side="right")), nên tích phân quy về tổng hữu hạn chính xác tuyệt đối:\[\widehat{W}_1(\mathbf{u}, \mathbf{v}) = \sum_{k=0}^{n_{\text{ref}}+n_{\text{cur}}-2} \big\lvert \hat{F}_{\text{ref}}(z_k) - \hat{F}_{\text{cur}}(z_k) \big\rvert\,(z_{k+1} - z_k).\] - Vì sao \(W_1\) Bắt được Lỗi Đơn vị Mà
JSD/KSBỏ lọt: Giữa hai khối điểm \(\delta_0\) và \(\delta_\Delta\), cảJSD(bão hòa \(\ln 2\)) vàKS(bão hòa \(1.0\)) đều mù khoảng cách, trong khi \(W_1(\delta_0, \delta_\Delta) = |\Delta|\) tăng tuyến tính đúng theo đơn vị vật lý. Để so sánh giữa các cột khác đơn vị, dùng chuẩn hóa thang đo tham chiếu:\[\widetilde{W}_1 := \frac{W_1(P_{\text{ref}}, P_{\text{cur}})}{\max\big(\operatorname{IQR}_{\text{ref}},\, c_{\text{MAD}}\cdot\operatorname{MAD}_{\text{ref}},\, \varepsilon_{\text{floor}}\big)}.\]
Thước đo 4 — Kiểm định Hai mẫu KS & Chuỗi Song đối Jacobi Theta (\(\lambda < 0.27\))#
Thống kê hai mẫu KS là khoảng cách tối đa \(L_\infty\) trong không gian xác suất CDF:
(với hiệu chỉnh mẫu hữu hạn Stephens, 1970). Dưới \(H_0\), xác suất sống sót tiệm cận \(Q_{\text{KS}}(\lambda)\) có chuỗi đan dấu kinh điển \(2\sum_{k=1}^\infty (-1)^{k-1}e^{-2k^2\lambda^2}\), nhưng chuỗi này hội tụ rất chậm và mất độ chính xác do triệt tiêu số học khi \(\lambda < 0.27\)! Bằng phép lấy tổng Poisson qua hàm theta Jacobi (Marsaglia, Tsang & Wang, 2003), ta thu được chuỗi song đối hội tụ trong \(\le 5\) số hạng cho \(\lambda < 0.27\):
Phương pháp chuỗi kép này đạt sai số \(< 10^{-15}\) toàn miền không cần scipy. Tuy nhiên, cần nhớ 3 bẫy sản xuất của KS: (1) Mù phương sai & mù đuôi: độ nhạy tập trung tại trung vị \(F \approx 0.5\) nên \(5\%\) ngoại lai nhảy lên \(+10^6\) vẫn bị khóa trần cứng tại \(D \le 0.05\); (2) Bẫy dữ liệu lớn: tại \(n = m = 10^6\), ngưỡng \(D_{\text{crit}} \approx 0.00192\) nên một độ lệch \(0.005\sigma\) vô hại vẫn báo \(p < 10^{-10}\); (3) Bảo thủ trên dữ liệu rời rạc có nhiều đồng hạng.
Thước đo 5 — Dịch chuyển Đa biến (C2ST OOF AUC_adv & \(\widehat{\operatorname{MMD}}_u^2\)) & Biên 2024–2025#
| Thước đo | Miền & Không gian | Bị chặn? | Metric Tam giác? | Thiên lệch Vô hiệu (\(H_0\)) | Nhạy Khoảng cách Đột biến Tách rời? | Bắt Xoay Tương quan Đồng Biên 1D? | Độ phức tạp |
|---|---|---|---|---|---|---|---|
PSI (KL Jeffreys) |
1D chia bin / rời rạc | \([0, +\infty)\) | Không | \((B-1)(\frac{1}{n_{\text{ref}}}+\frac{1}{n_{\text{cur}}})\) | Không (nổ theo \(\ln(1/\epsilon)\)) | Không | \(O(n_{\text{ref}}+n_{\text{cur}}+B)\) |
JSD |
1D chia bin / rời rạc | \([0, \ln 2]\) ([0,1] bits) |
Có (\(\sqrt{\operatorname{JSD}}\)) | \(\approx \frac{B-1}{8}(\frac{1}{n_{\text{ref}}}+\frac{1}{n_{\text{cur}}})\) | Không (bão hòa tại \(\ln 2\)) | Không | \(O(n_{\text{ref}}+n_{\text{cur}}+B)\) |
| 1D \(W_1\) (Earth Mover) | 1D liên tục | \([0, +\infty)\) | Có | \(O(n_{\text{eff}}^{-1/2})\) | Có (\(= \lvert\Delta\rvert\) tuyến tính!) | Không | \(O((n_{\text{ref}}+n_{\text{cur}})\log)\) |
2-Sample KS |
1D liên tục | \([0, 1]\) | Có (trên CDF) | \(\mathbb{E}[D] \approx 0.87/\sqrt{n_{\text{eff}}}\) | Không (bão hòa ở \(1.0\)) | Không | \(O((n_{\text{ref}}+n_{\text{cur}})\log)\) |
OOF C2ST / \(\widehat{\operatorname{MMD}}_u^2\) |
Đa biến \(\mathbb{R}^d\) | AUC \(\in [0, 1]\) |
MMD Có |
AUC \(\approx 0.50\); MMD_u^2 \(= 0\) |
Có (AUC -> 1) |
Có (C2ST bậc hai / RBF MMD) |
C2ST \(O(K n d^2)\); MMD \(O(n^2 d)\) |
- Kiểm định Đối nghịch Ngoài nếp (
Adversarial Validation / C2ST— Lopez-Paz & Oquab, ICLR 2017): Gán nhãn miền \(Z=0\) cho \(\mathcal{D}_{\text{ref}}\) và \(Z=1\) cho \(\mathcal{D}_{\text{cur}}\) (bỏ hoàn toàn \(Y\)), chạy \(K\)-Fold CV phân tầng trong đó bộ điền trung vị, bộ chuẩn hóa và hồi quy logistic \(L_2\) (giải bằng Newton–Raphson tắt dần thuầnNumPy) chỉ được khớp bên trong từng nếp \(\mathcal{D}_{\text{tr}}^{(-k)}\), rồi đoAUC_advtrên điểm dự đoán ngoài nếp bằng công thức Mann–Whitney U đồng hạng từch-03:0.48–0.53: Hai tập bất khả phân biệt (dữ liệu dừng, chia tập sạch).0.55–0.70: Dịch chuyển đa biến mức trung bình.> 0.70(đặc biệt> 0.80): Báo động rò rỉ nghiêm trọng (cộtrow_id,timestamphay cột rò rỉ hậu quảPITbị lộ). Trích xuất ngay các trọng số \(|w_j|\) lớn nhất để quy trách nhiệm từng cột!
- Điểm Mù Hình học & Giải cứu Hạt nhân: Hai phân phối Chuẩn 2D có biên 1D giống hệt nhau \(\mathcal{N}(0, 1)\) nhưng xoay tương quan từ \(\rho = +0.85\) sang \(\rho = -0.85\) sẽ đánh lừa toàn bộ 4 thước đo 1D lẫn
C2STtuyến tính! Mở rộng đặc trưng bậc hai \(\phi(\mathbf{x}) = [\mathbf{x}, x_j^2, x_j x_k]\) (include_quadratic=True) hoặc tính thống kê \(U\) bất thiên vị củaMMDhạt nhân RBF (Gretton et al., JMLR 2012):\[\widehat{\operatorname{MMD}}_u^2 = \frac{1}{n_{\text{ref}}(n_{\text{ref}}-1)}\sum_{i\neq j} k(\mathbf{x}_i,\mathbf{x}_j) + \frac{1}{n_{\text{cur}}(n_{\text{cur}}-1)}\sum_{i\neq j} k(\mathbf{y}_i,\mathbf{y}_j) - \frac{2}{n_{\text{ref}} n_{\text{cur}}}\sum_{i=1}^{n_{\text{ref}}}\sum_{j=1}^{n_{\text{cur}}} k(\mathbf{x}_i,\mathbf{y}_j)\]với độ rộng \(k\) theo trung vị khoảng cách cặp đôi lập tức phát hiện xoay tương quan với lực kiểm định cao. - Mũi nhọn 2024–2025:
E-C2ST(Pandeva et al., TMLR 2024) thay \(p\)-value chân trời cố định bằnge-value nối thẳng vào Bất đẳng thức Ville (ch-03) để giám sát hợp lệ mọi thời điểm trên luồng;MMDEW(Kalinke et al., TMLR 2025) dùng cửa sổ mũ đạt độ phức tạp đa logarit thời gian/bộ nhớ thay cho \(O(n^2)\) củaMMDlô; vàMCD-DD(Wan et al., KDD 2024) kết hợp phân tách tương tác đặc trưng cho trôi khái niệm trực tuyến.
2.3 Công cụ SOTA 2024–2026 & Phả hệ Thí nghiệm Định danh Nội dung (SOTA 2024–2026 Tooling, Content-Addressed Lineage & Tracking Planes)#
1. Môi trường Tất định (uv, uv.lock, PEP 723)#
Các danh sách pip freeze > requirements.txt kiểu cũ thường xuyên sụp đổ vì lệch ABI nhị phân—điển hình là lỗi AttributeError: _ARRAY_API not found khi các gói biên dịch cho NumPy 1.x (scipy/sklearn) đụng phải NumPy 2.x. uv (viết bằng Rust, nhanh hơn pip 10–100x) khóa toàn bộ cây phụ thuộc bắc cầu cùng mã băm wheel/OS vào một tệp uv.lock đa nền tảng (uv sync --frozen trong CI), đồng thời hỗ trợ PEP 723 (inline script metadata + uv lock --script eda_audit.py) biến mọi kịch bản EDA đơn lẻ thành môi trường khép kín tái lập được.
2. Sổ tay DAG Phản ứng (Marimo, 2024–2026) & Cảnh báo Đột biến Tại chỗ (Mutation Blindness)#
Marimo giải quyết tận gốc thảm họa thực thi lệch thứ tự của .ipynb bằng cách phân tích cây cú pháp trừu tượng tĩnh (Static AST) để trích xuất tập biến định nghĩa (defs) và tham chiếu (refs) của từng ô thành một Đồ thị Có hướng Không chu trình (DAG):
- Sửa bất kỳ ô thượng nguồn nào sẽ tự động vô hiệu hóa và chạy lại mọi ô phụ thuộc theo đúng thứ tự tô-pô; hai ô không được định nghĩa trùng cùng một biến toàn cục; toàn bộ sổ tay được lưu thành tệp
.pythuần túy dễ dànggit diffvà chạy quaruff/mypy. - Cảnh báo Vận hành Quan trọng (
Mutation Blindness): Phân tích AST tĩnh củaMarimochỉ theo dõi phép gán lại tên biến (df = ...), không phát hiện được đột biến đối tượng tại chỗ (df["col"] = ...,list.append(...), hoặcscaler.fit(X_tr)thay đổi thuộc tính nội bộ của cùng một tham chiếu)! Vì vậy trongMarimobắt buộc phải tuân thủ phong cách bất biến hàm (trả về đối tượng mới) và dùngmo.stop(condition)để chặn các vòng huấn luyện nặng.
3. Tường lửa Kiểm định 3 Lớp & Bất khả tri DataFrame (Pydantic v2, Pandera, Narwhals, set_output)#
| Tầng Kiểm định | Công cụ SOTA 2024–2026 | Phạm vi Chặn Lỗi | Ranh giới Chạy |
|---|---|---|---|
| Lớp 1: Cấu hình & Tải trọng API | Pydantic v2 (pydantic-core Rust) |
Sai tỷ lệ chia tập, khóa cấu hình gõ nhầm (extra="forbid"), API JSON sai kiểu |
Micro-giây khi khởi động hoặc tại cổng API |
| Lớp 2: Hợp đồng Bảng Dữ liệu | Pandera (pa.DataFrameModel, pandera.polars) |
Thiếu/thừa cột, tụt kiểu (int64 -> float32), null bất hợp pháp, vượt biên vật lý, sentinel |
Vector hóa C/Rust trên lô hoặc kiểm tra kế hoạch LazyFrame |
| Lớp 3: Hợp đồng Phân phối Thống kê | Hồ sơ Trôi Đóng băng (PSI/JSD/\(W_1\)/C2ST) |
Lỗi chuyển đơn vị (1000x), lệch hiệp phương sai, xoay tương quan đa biến |
Trước suy luận theo lô và cổng thăng hạng mô hình |
Bên cạnh đó, Narwhals (không phụ thuộc ngoài) kết hợp với scikit-learn >= 1.4 .set_output(transform="polars") (SLEP018) cho phép viết các bộ biến đổi giữ nguyên tên cột và chạy trực tiếp trên Polars, Pandas, PyArrow, hay DuckDB mà không ép sao chép .to_pandas() tốn bộ nhớ.
4. Bốn Trụ cột Tái lập, Mã băm SHA-256 & Mặt phẳng Theo dõi (MLflow / DVC / W&B)#
Một thí nghiệm chỉ tái lập được chính xác từng bit khi khóa chặt đủ Bốn Trụ cột Tái lập (Four Pillars of Reproducibility):
| Trụ cột | Trường Mật mã / Phiên bản Bắt buộc Ghi | Lỗi Âm thầm Được Ngăn chặn |
|---|---|---|
| 1. Phả hệ Mã nguồn Bất biến | git_commit_sha, git_branch, git_is_dirty (git status --porcelain == "") |
Mất dấu mô hình "vô địch" do chạy trên sửa đổi cục bộ chưa commit |
| 2. Băm Nội dung Dữ liệu & Tách tập | dataset_sha256 (schema + băm từng hàng) + split_sha256 trên bộ chỉ số (train, val, test) |
So sánh nhầm hai lần chạy khi ETL âm thầm ghi đè hàng hoặc đổi ranh giới tập |
| 3. Môi trường Đóng băng | uv_lock_sha256, python, numpy, pandas, pydantic, platform_machine, BLAS/SIMD |
Trôi kết quả số học khi nâng cấp thư viện hoặc khác tập lệnh giảm tổng BLAS |
4. Cấu hình & Cây SeedSequence |
JSON chuẩn tắc từ Pydantic + master_seed & spawn_key từng luồng PCG64 |
Cờ CLI thất lạc và ghép nối ngẫu nhiên từ np.random.seed |
Từ 4 trụ cột này, tính toán một Mã băm Chạy Định danh Nội dung (manifest_sha256) duy nhất bằng SHA-256 trên chuỗi JSON sắp xếp khóa (sort_keys=True, allow_nan=False), gắn nhãn tách biệt metrics theo từng phân vùng (train, cv_oof, val, test), và chặn thăng hạng nếu git_is_dirty == True:
| Mặt phẳng Theo dõi | Kiến trúc Lưu trữ | Thế mạnh Nổi bật | Ràng buộc / Tiêu chuẩn Lựa chọn |
|---|---|---|---|
MLflow 2.x / 3.0 |
SQLite/PostgreSQL + Kho đối tượng S3/GCS | mlflow.data.from_pandas tính sẵn digest tập dữ liệu; bản 3.0 hợp nhất bảng dữ liệu, dấu vết đánh giá, prompt và model registry thành một đồ thị tài sản |
Cần vận hành máy chủ theo dõi & sao lưu DB cho nhóm lớn |
DVC (Data Version Control) |
Con trỏ .dvc nhẹ trong Git + DAG dvc.yaml + bộ đệm định danh nội dung |
Phiên bản hóa tập dữ liệu nhiều TB song hành chặt với Git commit; hỗ trợ dvc repro |
Tốt cho phả hệ tệp/DAG, thiếu bảng điều khiển đồ thị đường cong step phong phú |
Weights & Biases (W&B) |
SaaS quản lý / VPC riêng + DAG W&B Artifacts |
Đồ thị tương tác đa chiều, theo dõi HPO và phả hệ artifact trực quan |
Chi phí bản quyền và rào cản lưu trú dữ liệu trong ngân hàng/y tế |
Sổ cái JSONL + SHA-256 Nội bộ |
Tệp nhật ký nối đuôi JSONL + thư mục artifacts/ kiểm băm SHA-256 |
0 daemon ngoài, 0 kết nối mạng, tái lập 100% trong CI kín (air-gapped) & pytest |
Không có UI web sẵn; lý tưởng cho lab học thuật và hệ thống tài chính cách ly mạng |
(Quy tắc quản trị: mọi thí nghiệm dò tìm trong notebooks/ hoặc chạy khi git_is_dirty=True chỉ được ghi vào vùng dev/scratch; mọi mô hình ứng viên thăng hạng lên Stage 6 bắt buộc chạy từ CLI/CI sạch trên commit Git đã khóa cùng uv.lock.)
Trụ cột 3 — Nghiên cứu Tình huống Công nghiệp, Chẩn đoán Pháp y & Mã nguồn Phòng vệ (Industry Case Studies, Forensic Failure Modes, Playbooks & Defensive Code)#
3.1 Năm Nghiên cứu Tình huống Thực tế Từ Hệ thống Production (5 Named Industry Case Studies)#
Case 1 — Thẩm định Tín dụng & Chống Gian lận FinTech (Nubank fklearn / Stripe Radar)#
- Bối cảnh & Sự cố: Một mô hình dự đoán vỡ nợ 90 ngày (\(Y \in \{0, 1\}\)) huấn luyện trên
24tháng dữ liệu vay đạt0.93ROC-AUC (PR-AUC = 0.78) trong kiểm định chéo 5 nếp, nhưng ngay30ngày đầu triển khai thực tế (OOT),ROC-AUCrơi xuống0.69. - Giải phẫu Pháp y Rò rỉ Kép: (1) Bảng huấn luyện ghép bảng trạng thái tài khoản (
credit_limit_current,delinquency_count_latest) theo dấu thời gian chạy ETL hằng ngày (etl_run_ts) thay vì nốiASOFtại thời điểm ra quyết định (feature_available_ts <= decision_ts): các tài khoản vỡ nợ 60 ngày sau khi vay bị cắt giảm hạn mức và tăng bộ đếm nợ xấu trong ảnh chụp mới nhất—làm \(X_t\) phụ thuộc vào \(Y_{t+\Delta}\)! (2) Sổ tay khám phá chạyStandardScalertoàn cục trước khi tách tập. - Phát hiện & Benchmark Định lượng (\(N = 5{,}000\),
3,500lịch sử /1,500OOT): Mô hình rò rỉ đạt1.000CV AUC ngoại tuyến rồi sụp về0.527OOT AUC; sau khi gỡ cột hậu quảpost_default_limitvà tách tập trước mới chuẩn hóa,OOT AUCthực chất hồi phục về0.733. Kiểm định Đối nghịchOOFbáo độngAUC_adv = 1.000khi còn dấu thời gian ETL, và giữ ở0.789(tuyến tính) hoặc> 0.92(phi tuyến/bậc hai) khi cònpost_default_limit(do phân bố hai đỉnh cắt hạ/nâng hạn mức sau vay vắng mặt ở khách hàng mới!). - Khắc phục: Áp dụng triết lý Learn–Predict Separation của
Nubank fklearn, tách tập theo thời gian với đệm \(\Delta_{\text{gap}} \ge 90\) ngày, chỉ vật chất hóa đặc trưng qua nốiASOF PIT <= decision_ts - sla_bufferđồng bộ với độ trễ< 100 mscủaStripe Radar.
Case 2 — Dữ liệu Đo xa Di chuyển & Giao hàng (Uber Michelangelo Palette & D3 / DoorDash Sibyl)#
- Bối cảnh & Sự cố: Bản cập nhật ứng dụng di động
iOS v4.2(18%lưu lượng trực tuyến) âm thầm đổi đơn vị trườngeta_secondstừ giây (\(\sim 400\text{–}900\text{ s}\)) sang mili-giây (\(\times 1{,}000\)) và thay các gói tin mất GPS từNULL(NaN) sang-1.0trên25%ping của phiên bản này. - Điểm mù
PSIToàn cục vs.W_1& Cắt látD3(\(n_{\text{ref}} = n_{\text{cur}} = 5{,}000\)): Vìfloat64vẫn hợp lệ, API trả vềHTTP 200 OK. Các câyGBDTđẩy toàn bộ các chuyến-1.0xuống nhánh lá cực trái (eta < 120s) còn mô hình tuyến tính phát nổ trên giá trị \(\times 1{,}000\). Nghiêm trọng hơn,Global PSI = 0.135 < 0.25(dưới ngưỡng cảnh báo PagerDuty!),Global JSD = 0.024bits,Global KS = 0.134—vìPSItheo 10 phân vị gom tất cả giá trị vượt \(Q_{90}\) vào chung một bin \([Q_{90}, +\infty)\), đánh đồng900 svới900,000 ms! Trái lại, 1D Wasserstein toàn cục nhảy vọt lên \(W_1 = 59{,}554.3\text{ s}\) (gấp> 130xtrung bình nền~446 s), còn giám sát cắt lát theo chiềuapp_version == "iOS_4.2"(mẫu hìnhUber D3) bùng nổ tớiPSI = 10.625,JSD = 0.623bits, \(W_1 = 322{,}609.3\text{ s}\),KS = 0.725, và hợp đồngDataContractSchemachặn ngay tại cửa ngõ với3vi phạm tường minh (min = -1.0 < 0,max = 4.8e5 > 14400,sentinel -1.0).
Case 3 — Hồ sơ Bệnh án Điện tử Hồi sức Cấp cứu (Clinical ICU EHR, Lipton 2016 / GRU-D / Rubin MNAR)#
- Bối cảnh & Sự cố: Một hệ thống cảnh báo sớm nhiễm trùng huyết (
sepsis) dùngSimpleImputer(strategy="mean")không tạo cờis_missingvà chia nếp ngẫu nhiên theo dòng thay vì theopatient_id, đạt0.96ROC-AUC ảo nhưng thất bại thảm hại trên bệnh nhân mới. - Chứng thực Thực nghiệm (
400bệnh nhân,10giờ/người): Xét nghiệmlactate_mmolchỉ được bác sĩ chỉ định khi nghi ngờ sepsis (MNAR, \(p_{\text{miss}} = 0.583\)): tỷ lệ sepsis thực tế khilactate_mmolthiếu chỉ là17.9%so với78.7%khi được xét nghiệm! Việc điền trung bình mù làm tỷ lệ bảo toàn phương sai thực nghiệm rơi đúng về0.417 == 1 - 0.583như Định lý 1.1 dự báo. Khi chuyển sang tách nhóm sạchGroupSplit(patient_id): điền trung bình mù chỉ đạt0.525AUC trên bệnh nhân chưa từng thấy, còn thêm cờis_missingkhôi phục ngay0.827AUC (kết hợp khoảng thời gian \(\Delta t_{\text{obs}}\) theo kiến trúcGRU-D).
Case 4 — Sàn Thương mại Điện tử Nhiều chiều Zipf (Booking.com / Amazon / Micci-Barreca / CatBoost)#
- Bối cảnh & Sự cố: Mã hóa
merchant_idcho50,000người bán tuân theo phân phối đuôi dài Zipf (40%+có dưới5giao dịch) bằng trung bình mục tiêu thô trong mẫu biến các nhãn \(n_c \in \{1, 2, 3\}\) thành bản sao củay, khiếntrain AUC = 0.99và sụp xuống0.64trên tập kiểm tra. - Benchmark Định lượng (
120,000dòng,16,835merchant hoạt động,92.6%có< 5giao dịch): Mã hóa trung bình thô trong mẫu (\(m_{\text{smooth}} = 0, n_{\min} = 1\)) chotrain AUC = 0.780so vớitest AUC = 0.647(khoảng cách quá khớp0.133ngay cả với bộ phân loại tuyến tính điều chuẩn). Áp dụng 5-fold OOF Empirical-Bayes \(m\)-estimate (m_smooth = 15.0, min_samples = 5) + gộp__RARE__chotrain AUC = 0.677vàtest AUC = 0.681—xóa sạch khoảng hở quá khớp và tăng+3.4điểm AUC tổng quát hóa thực tế!
Case 5 — Nền tảng ML Truyền thông & Phát trực tuyến (Netflix Metaflow / Spotify ML Home)#
- Bối cảnh & Sự cố: Nhóm xếp hạng cá nhân hóa không thể tái dựng mô hình vô địch Q2 vì 3 đứt gãy hạ tầng:
.ipynbcó thứ tự chạy[14, 3, 29, 8], tệpdata_v2.csvbị ghi đè tại chỗ hai tuần sau, và tệpq2_ranker.pklvỡModuleNotFoundError: numpy._corekèm rủi ro bảo mậtCWE-502. - Khắc phục Kiến trúc: Chuyển toàn bộ logic sang các bước DAG định kiểu (
Metaflow/src/), gắn khóa cứngdataset_sha256,split_sha256,SeedSequencevà thay hoàn toàn.pklbằng JSON State-Dict không-picklecó kiểm tra bămSHA-256.
3.2 Sáu Chế độ Lỗi Vòng đời & EDA Kinh điển (Six Production Lifecycle & EDA Failure Modes)#
Chế độ Lỗi (FM) |
Triệu chứng Bề ngoài | Nguyên nhân Toán học / Hệ thống Gốc | Tín hiệu Phát hiện Chẩn đoán | Biện pháp Khắc phục Chuẩn mực |
|---|---|---|---|---|
| FM1: Thực thi Lệch Thứ tự & Trạng thái Toàn cục Ẩn | Sổ tay chạy đẹp lúc phân tích nhưng gãy hoặc ra số khác trong CI/Airflow | Không gian globals() khả biến phụ thuộc thứ tự chạy; np.random.seed toàn cục nối chuỗi chéo giữa EDA và chia tập |
execution_count không đơn điệu; Restart & Run All lỗi; manifest_sha256 đổi giữa các lần chạy |
Rút 100% logic về src/; sổ tay làm Thấu kính Mỏng (hoặc dùng Marimo AST DAG); SeedSequence.spawn() |
| FM2: Tiền xử lý & Lọc Đặc trưng Tiền Tách tập | CV báo 0.85–0.98 trên bảng rộng (\(d \gg N\)) rồi sụp về 0.50 ngoài thực tế |
Thiên lệch chung \(r_{j^*}^{\text{all}}\) làm N=100, d=5,000 nhiễu trắng đạt 0.868 pre-split vs. 0.378 in-fold (N=100, d=2,000: +0.62 vs. 0); quy tâm rò rỉ cho \(\rho = -1\) |
Sụt giảm mạnh giữa CV lồng/tách trước và CV sạch; Canary trộn ngẫu nhiên \(Y\) vẫn cho AUC >> 0.55 |
Cưỡng chế Cổng Split-First trước mọi thống kê/chuẩn hóa/lọc biến; chạy bài kiểm tra Canary nhãn ngẫu nhiên |
FM3: Nhìn trước Thời gian (PIT) & Trùng Thực thể |
AUC ngoại tuyến 0.90–0.96 nhưng tụt về 0.52–0.69 khi phục vụ khách hàng/bệnh viện mới |
Ghép bảng theo etl_run_ts thay vì ASOF <= t_obs; thiếu \(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\); chia dòng lặp lại patient_id/user_id |
Giao nhóm khác rỗng; max(train_ts) >= min(test_ts); AUC_adv > 0.80 chỉ đích danh cột hậu quả |
SplitContract.verify_splits() cưỡng chế đệm thời gian & tách thực thể; truy vấn ASOF PIT |
FM4: Điền Trung bình Mù MCAR & Xóa Tín hiệu MNAR |
Hết NaN nhưng độ nhạy cây/tuyến tính sụp đổ và khoảng tin cậy quá tự tin |
Co rút phương sai còn \((1 - p_{\text{miss}})\sigma_X^2\) (0.417 tại p_miss=0.583); mất cờ ẩn chứa lý do chỉ định/khuyết |
target_missingness_corr hoặc max_covariate_corr >= 0.12 (vd. 17.9% vs. 78.7% sepsis) |
Chạy diagnose_missingness_mechanisms(train_df); khóa schema cờ is_missing + điền trung vị khớp trên train |
FM5: Bão Báo động Giả PSI Mẫu nhỏ vs. Mù Đơn vị/Đuôi |
Báo động giả dày đặc ở lát nhỏ (93.8% FPR tại B=20, n_cur=50), nhưng bỏ sót lỗi 1000x (PSI=0.135 < 0.25) |
Thiên lệch dương \((B-1)(\frac{1}{n_{\text{ref}}}+\frac{1}{n_{\text{cur}}})\) + kẹp \(\epsilon\) bin rỗng đẩy H0 lên 93.8% FPR vs. KS 4.2%; bin phân vị chèn trần \(Q_{90}\) che mờ 1000x |
n_cur < 200 hoặc PSI < 2 * null_bias; hoặc \(W_1\) toàn cục nhảy \(> 100\times\) trong khi PSI < 0.25 |
Chặn trước bằng DataContractSchema; bật cờ small_sample_noise_risk, dùng KS cho mẫu nhỏ, \(W_1\) + cắt lát D3 cho biên độ |
FM6: Tuần tự hóa pickle/joblib Dễ vỡ & Mất An toàn |
Lỗi ModuleNotFoundError: numpy._core sau nâng cấp thư viện; cảnh báo RCE bảo mật |
pickle gọi __reduce__ thực thi mã tùy ý (CWE-502); skops <= 0.12.0 (CVE-2025-54886) rơi ngầm về joblib.load() |
Trình quét picklescan/bandit báo lỗi; gãy khi nâng NumPy 1.x -> 2.x |
Xóa bỏ pickle; xuất JSON State-Dict (allow_nan=False) + SHA-256, safetensors, hoặc skops >= 0.13.0 (allow_pickle=False) |
3.3 Hai Cẩm nang Quyết định & Kiến trúc Cổng Kiểm định Tự động (2 Decision Playbooks + Gatekeeper Diagram + 5-Point Checklist)#
Cẩm nang 1 — Ma trận Chọn Chiến lược Xử lý Dữ liệu Thiếu, Ngoại lai & Biến Phân loại#
| Chế độ Dữ liệu & Lực lượng | Tín hiệu Cơ chế | Tiền xử lý & Đặc trưng Khuyến nghị | Phản mẫu Bị cấm Tuyệt đối | Hàng rào & Tuần tự hóa |
|---|---|---|---|---|
Số — MCAR (\(p_{\text{miss}} < 0.05\), không tương quan \(X, Y\)) |
Mất gói tin đồng đều | Khớp bộ điền trung vị trên tập train; có thể bỏ cờ is_missing |
Điền trung bình trước tách tập; mã hóa thiếu thành -1.0/-999 |
Lưu train_median thuần JSON; chặn sentinel ở DataContractSchema |
Số — MAR (\(p_{\text{miss}}\) gắn với \(X_j\) đã quan sát) |
Thiết bị hoặc phiên bản app cũ bỏ trống trường | Bộ điền có điều kiện theo \(X_j\) trên train + thêm cờ is_missing nếu \(p_{\text{miss}} \ge 0.01\) |
Điền trung bình toàn cục phá hiệp phương sai có điều kiện | Giám sát max_null_fraction theo lát cắt; xuất từ điển tra cứu JSON |
Số — MNAR (Thiếu mang thông tin mục tiêu \(Y\)) |
Xét nghiệm lactate chỉ đo khi nghi sepsis; hồ sơ tín dụng mỏng |
Bắt buộc cờ nhị phân is_missing + \(\Delta t_{\text{obs}}\) (GRU-D) + điền trung vị train (hoặc định tuyến NaN gốc GBDT) |
Điền trung bình mù vứt bỏ mặt nạ thiếu (nén phương sai còn \(1-p_{\text{miss}}\)) | Khóa đồng bộ cột is_missing giữa dữ liệu huấn luyện và API trực tuyến |
Số — Đuôi Nặng / Nhiều Số \(0\) (\(\lvert\gamma_1\rvert > 2\) hoặc MAD == 0) |
Doanh thu GMV, độ trễ, số lần thử lại |
Z-score MAD khớp trên train + thang dự phòng Hurdle \(\to\) MeanAD \(\to\) Hằng số hoặc \(\ln(1+x)\) |
Z-score chuẩn hóa thường trực tiếp trên đuôi nặng hoặc chia trực tiếp cho MAD == 0 |
Kiểm tra scale_mode trong JSON state dict; chặn số âm trước log1p |
| Phân loại — Lực lượng Thấp/Trung bình (\(K \le 20\text{–}50\)) | Phương thức thanh toán, OS, khoa lâm sàng | One-Hot Encoding kèm nhóm tường minh __MISSING__ và __UNSEEN__ khớp trên train |
Bỏ qua nhãn mới hoặc văng lỗi khi gặp OS mới lúc phục vụ | Khóa danh sách known_categories trong JSON state dict |
| Phân loại — Lực lượng Cao Zipf (\(K \ge 1{,}000\)) | merchant_id, zip_code, user_agent |
OOF Empirical-Bayes \(m\)-estimate Target Encoding + gộp __RARE__ (\(n_c < n_{\min}\)) hoặc Ordered Stats |
Trung bình mục tiêu trong mẫu .fit(X,y).transform(X) ghi nhớ 0/1 |
Xuất mappings_ + fallback_values_ thuần số thực JSON; cô lập OOF theo groups |
Cẩm nang 2 — Ma trận Chọn Cấu trúc Phân tách & Thước đo Dịch chuyển Phân phối#
| Chế độ Bài toán / Giám sát | Ràng buộc Cấu trúc Chính | Phương pháp Tách tập / Dịch chuyển Khuyến nghị | Ngưỡng & Hàng rào Hành động | Chế độ Lỗi Ngăn chặn |
|---|---|---|---|---|
Bảng chuẩn Độc lập Chéo (Cross-Sectional i.i.d.) |
Các dòng độc lập đồng nhất (\(i \perp j\)) | StratifiedKFold / tách phân tầng qua SeedSequence |
Khớp mọi scaler, imputer, bộ lọc biến bên trong từng nếp train; chạy Canary nhãn ngẫu nhiên | Rò rỉ chuẩn hóa & lọc nhiễu FM2 |
| Thực thể Đa quan sát (Bệnh nhân, người dùng, cửa hàng) | Tương quan nội thực thể & vân tay cá nhân | GroupKFold / StratifiedGroupKFold (SplitContract(strategy="group")) |
Khẳng định giao tập nhóm bằng \(\emptyset\); truyền groups vào cả OutOfFoldTargetEncoder |
Ghi nhớ bệnh nhân/người dùng (0.96 -> 0.525) |
| Dự báo Chuỗi, Tín dụng, Gian lận | Không dừng, trễ nhãn trưởng thành \(\Delta t_{\text{horizon}}\) | Tách Thời gian + Đệm Cấm (\(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\)) | Khẳng định min_eval_ts >= max_train_ts + embargo_seconds; nối ASOF PIT |
Rò rỉ nhìn trước tương lai (Case 1) |
| Dịch chuyển Khối Lớn Qua Bin Cố định (\(n_{\text{cur}} \ge 500\)) | Thay đổi mật độ qua các dải phân vị tham chiếu | PSI (có bin NaN + cổng \(\chi^2_{B-1}\)) hoặc JSD ([0, 1] bits) |
PSI < 0.10 ổn định; 0.10–0.25 theo dõi; >= 0.25 cảnh báo chỉ khi small_sample_noise_risk == False |
Dịch chuyển hiệp phương sai & lỗi log(0) |
| Đổi Đơn vị & Đột biến Đuôi (\(\times 1000\) hay ngoại lai) | Giá trị vượt trần bị kẹp chung vào bin trên của PSI |
1D Wasserstein-1 (\(W_1\)) chuẩn hóa (\(\widetilde{W}_1 = W_1 / \max(\text{IQR}, 1.4826\cdot\text{MAD})\)) | Báo động khi \(\widetilde{W}_1 > 0.25\) (bắt ngay 59,554 s khi PSI toàn cục chỉ báo 0.135!) |
Mù đơn vị ms/s & đột biến đuôi (Case 2) |
| Lát Cắt Mẫu nhỏ (\(n_{\text{cur}} \in [30, 200]\) theo thành phố/OS) | Thiên lệch bin rỗng đẩy PSI báo động giả (93.8%) |
Hai mẫu KS (chuỗi kép Jacobi theta) + hiệu chỉnh Stephens |
Dựa vào p_value < 0.01 (kèm BH-FDR đa lát cắt) thay vì ngưỡng tĩnh PSI >= 0.25 |
Bão báo động giả mẫu nhỏ (FM5) |
| Dịch chuyển Đa biến & Kiểm toán Rò rỉ (\(d\) cột đồng thời) | Cột row_id, backfill hoặc xoay tương quan đồng biên |
OOF C2ST (AUC_adv) (kèm include_quadratic=True) & \(\widehat{\operatorname{MMD}}_u^2\) |
AUC_adv <= 0.55 sạch; 0.55–0.70 dịch vừa; > 0.80 rò rỉ nghiêm trọng -> kiểm tra top trọng số |
Lệch liên kết đa chiều & rò rỉ backfill |
Danh sách Kiểm tra Sẵn sàng Sản xuất 5 Điểm (5-Point Split-First Production Readiness Checklist):
- Dịch trái Hợp đồng Dữ liệu: Kiểm định mọi bản ghi đầu vào qua
DataContractSchema(allow_extra_columns=False, chặn+/-inf, chặnmin_value/max_valuevật lý vàforbidden_sentinels). - Xác minh Tách tập Trước (
Split-First): Thực thiSplitContract.verify_splits(train_df, test_df, val_df)xác nhận giao thực thể bằng rỗng và \(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\) trước mọi thao tác EDA. - Chẩn đoán Độc lập Tập Train & Canary Rò rỉ: Chạy
diagnose_missingness_mechanisms(train_df)để khóa cộtis_missing, chạysimpson_paradox_audit, và chạyadversarial_validation_oof_auc(cả tuyến tính vàinclude_quadratic=True) + Canary nhãn ngẫu nhiên. - Pipeline Bất biến Sâu & Không-
pickle: Khóa bộ đệmNumPybằngsetflags(write=False), chứng minh bất biến theo lô (1dòng vs.200dòng), và xuất duy nhất quato_signed_json()(allow_nan=False, kiểm chứngSHA-256). - Phả hệ Định danh Nội dung Đầy đủ: Đóng gói
build_experiment_manifest(...)chứadataset_sha256,split_sha256,config_sha256,state_dicts_sha256,SeedSequencespawn keys và khóauv.lock.
3.4 Mã nguồn Phòng vệ Chuẩn mực (Defensive Pure-Python + NumPy/Pandas/Pydantic Reference Snippets)#
Toàn bộ sáu thành phần phòng vệ dưới đây chạy thuần túy trên Python 3.10+ + numpy + pandas + pydantic v2 (0 phụ thuộc scipy, sklearn, polars hay pickle), đồng bộ 1-1 với gói lifecycle_eda_lab ở Trụ cột 4:
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
import math
import sys
from typing import Any, Literal, Protocol, runtime_checkable
import numpy as np
import pandas as pd
import pydantic
from pydantic import BaseModel, ConfigDict, Field, model_validator
# ==============================================================================
# 1. HỢP ĐỒNG TÁCH TẬP, HỢP ĐỒNG SCHEMA & CÂY SEEDSEQUENCE ĐỘC LẬP
# ==============================================================================
class SplitContract(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
strategy: Literal["temporal", "group", "stratified_iid"]
train_ratio: float = Field(..., gt=0.0, lt=1.0)
val_ratio: float = Field(default=0.0, ge=0.0, lt=1.0)
test_ratio: float = Field(..., gt=0.0, lt=1.0)
time_col: str | None = None
group_col: str | None = None
embargo_seconds: float = Field(default=0.0, ge=0.0)
@model_validator(mode="after")
def _validate_contract(self) -> "SplitContract":
if not math.isclose(self.train_ratio + self.val_ratio + self.test_ratio, 1.0, abs_tol=1e-6):
raise ValueError("Split ratios must sum to 1.0.")
if self.strategy == "temporal" and not (self.time_col and self.time_col.strip()):
raise ValueError("temporal split requires time_col.")
if self.strategy == "group" and not (self.group_col and self.group_col.strip()):
raise ValueError("group split requires group_col.")
return self
def verify_splits(
self, train_df: pd.DataFrame, test_df: pd.DataFrame, val_df: pd.DataFrame | None = None
) -> dict[str, Any]:
frames: list[tuple[str, pd.DataFrame]] = [("train", train_df)]
if val_df is not None and not val_df.empty:
frames.append(("val", val_df))
frames.append(("test", test_df))
if self.group_col is not None:
for i in range(len(frames)):
n1, d1 = frames[i]
g1 = set(d1[self.group_col].dropna().tolist())
for j in range(i + 1, len(frames)):
n2, d2 = frames[j]
overlap = g1 & set(d2[self.group_col].dropna().tolist())
if overlap:
raise ValueError(f"Group leakage ({n1} vs {n2}): {len(overlap)} shared entities.")
if self.strategy == "temporal":
assert self.time_col is not None
for (n1, d1), (n2, d2) in zip(frames[:-1], frames[1:]):
t1_max = float(pd.to_numeric(d1[self.time_col]).max())
t2_min = float(pd.to_numeric(d2[self.time_col]).min())
if t2_min < t1_max + self.embargo_seconds:
raise ValueError(f"Embargo violated ({n1}->{n2}): {t2_min} < {t1_max + self.embargo_seconds}")
return {"passed": True, "strategy": self.strategy}
class ColumnContract(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
name: str = Field(..., min_length=1)
dtype_family: Literal["float", "int", "bool", "str"]
nullable: bool = False
max_null_fraction: float = Field(default=0.0, ge=0.0, le=1.0)
min_value: float | None = None
max_value: float | None = None
forbidden_sentinels: tuple[float | int | str, ...] = ()
class DataContractSchema(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
schema_version: str = Field(..., min_length=1)
columns: tuple[ColumnContract, ...] = Field(..., min_length=1)
allow_extra_columns: bool = False
min_rows: int = Field(default=1, ge=1)
def validate_dataframe(self, df: pd.DataFrame, fail_fast: bool = True) -> dict[str, Any]:
errors: list[str] = []
if len(df) < self.min_rows:
errors.append(f"Row count {len(df)} < min_rows {self.min_rows}.")
exp, act = {c.name for c in self.columns}, set(df.columns)
if exp - act:
errors.append(f"Missing columns: {sorted(exp - act)}")
if not self.allow_extra_columns and (act - exp):
errors.append(f"Extra columns: {sorted(act - exp)}")
for col in self.columns:
if col.name not in df.columns:
continue
s = df[col.name]
null_frac = float(s.isna().mean()) if len(s) else 0.0
if (not col.nullable and null_frac > 0.0) or null_frac > col.max_null_fraction:
errors.append(f"{col.name}: null_frac={null_frac:.4f} violates contract.")
if col.dtype_family in ("float", "int") and len(s):
arr = s.to_numpy(dtype=np.float64, copy=False)
if np.any(np.isinf(arr)):
errors.append(f"{col.name}: contains +/-inf.")
fin = arr[np.isfinite(arr)]
if fin.size:
if col.min_value is not None and float(np.min(fin)) < col.min_value:
errors.append(f"{col.name}: min={float(np.min(fin)):.4g} < {col.min_value}")
if col.max_value is not None and float(np.max(fin)) > col.max_value:
errors.append(f"{col.name}: max={float(np.max(fin)):.4g} > {col.max_value}")
for sent in col.forbidden_sentinels:
if s.isin([sent]).any():
errors.append(f"{col.name}: forbidden sentinel {sent!r} detected.")
if errors and fail_fast:
raise ValueError("DataContractSchema failed:\n - " + "\n - ".join(errors))
return {"passed": not errors, "errors": errors}
@dataclass(frozen=True, slots=True)
class ReproducibleRngTree:
master_seed: int
split_rng: np.random.Generator
eda_rng: np.random.Generator
oof_rng: np.random.Generator
model_rng: np.random.Generator
@classmethod
def from_master_seed(cls, master_seed: int) -> "ReproducibleRngTree":
s_sp, s_ed, s_oo, s_mo = np.random.SeedSequence(master_seed).spawn(4)
return cls(
master_seed=master_seed,
split_rng=np.random.default_rng(s_sp),
eda_rng=np.random.default_rng(s_ed),
oof_rng=np.random.default_rng(s_oo),
model_rng=np.random.default_rng(s_mo),
)
# ==============================================================================
# 2. PIPELINE BẤT BIẾN SÂU (WRITE=FALSE), MAD ZERO-GUARD & OOF M-ESTIMATE
# ==============================================================================
class NotFittedError(RuntimeError):
"""Raised when transform/to_state_dict is invoked prior to fit()."""
@runtime_checkable
class StatefulTransformer(Protocol):
def fit(self, X: pd.DataFrame | np.ndarray, y: np.ndarray | pd.Series | None = None) -> Any: ...
def transform(self, X: pd.DataFrame | np.ndarray) -> Any: ...
@dataclass(frozen=True, slots=True)
class FittedStandardizerState:
mean: np.ndarray
scale: np.ndarray
constant_mask: tuple[bool, ...]
feature_names: tuple[str, ...]
n_samples_seen: int
def __post_init__(self) -> None:
self.mean.setflags(write=False)
self.scale.setflags(write=False)
class StatefulStandardizer:
"""Protocol-compliant standardizer with read-only NumPy state & signed JSON."""
def __init__(self, ignore_nan: bool = False, eps: float = 1e-12) -> None:
self.ignore_nan = bool(ignore_nan)
self.eps = float(eps)
self._state: FittedStandardizerState | None = None
def fit(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
columns: list[str] | None = None,
) -> "StatefulStandardizer":
if isinstance(X, pd.DataFrame):
cols = list(X.columns) if columns is None else list(columns)
arr = X[cols].to_numpy(dtype=np.float64)
else:
arr = np.asarray(X, dtype=np.float64)
cols = [f"f{i}" for i in range(arr.shape[1])] if columns is None else list(columns)
if arr.ndim != 2 or arr.shape[0] == 0:
raise ValueError("Input must be a non-empty 2D array.")
means, scales, const_mask = [], [], []
for j in range(arr.shape[1]):
col = arr[:, j]
if self.ignore_nan:
col = col[np.isfinite(col)]
elif np.any(np.isnan(col)):
raise ValueError(f"NaN encountered in '{cols[j]}' with ignore_nan=False.")
mu = float(np.mean(col))
sd = float(np.std(col, ddof=0))
is_c = sd <= self.eps
means.append(mu)
scales.append(1.0 if is_c else sd)
const_mask.append(is_c)
self._state = FittedStandardizerState(
mean=np.array(means, dtype=np.float64),
scale=np.array(scales, dtype=np.float64),
constant_mask=tuple(const_mask),
feature_names=tuple(cols),
n_samples_seen=int(arr.shape[0]),
)
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> pd.DataFrame | np.ndarray:
if self._state is None:
raise NotFittedError("StatefulStandardizer must be fitted before transform().")
st = self._state
is_df = isinstance(X, pd.DataFrame)
arr = X[list(st.feature_names)].to_numpy(dtype=np.float64) if is_df else np.asarray(X, dtype=np.float64)
if arr.ndim != 2 or arr.shape[1] != len(st.feature_names):
raise ValueError("Feature dimension mismatch during transform.")
scaled = (arr - st.mean) / st.scale
if is_df:
out = X.copy()
for idx, c in enumerate(st.feature_names):
out[c] = scaled[:, idx]
return out
return scaled
def to_state_dict(self) -> dict[str, Any]:
if self._state is None:
raise NotFittedError("Cannot serialize unfitted StatefulStandardizer.")
st = self._state
return {
"class": "StatefulStandardizer",
"format_version": "1.0",
"ignore_nan": self.ignore_nan,
"eps": self.eps,
"n_samples_seen": st.n_samples_seen,
"feature_names": list(st.feature_names),
"means": st.mean.tolist(),
"scales": st.scale.tolist(),
"constant_mask": list(st.constant_mask),
}
def to_signed_json(self) -> str:
body = self.to_state_dict()
canon = json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False)
body["payload_sha256"] = hashlib.sha256(canon.encode("utf-8")).hexdigest()
return json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False)
@classmethod
def from_signed_json(cls, payload: str) -> "StatefulStandardizer":
raw = json.loads(payload)
digest = raw.pop("payload_sha256", None)
canon = json.dumps(raw, sort_keys=True, separators=(",", ":"), allow_nan=False)
if digest != hashlib.sha256(canon.encode("utf-8")).hexdigest():
raise ValueError("Checksum mismatch: tampered or corrupted JSON state dict!")
obj = cls(ignore_nan=bool(raw["ignore_nan"]), eps=float(raw["eps"]))
obj._state = FittedStandardizerState(
mean=np.array(raw["means"], dtype=np.float64),
scale=np.array(raw["scales"], dtype=np.float64),
constant_mask=tuple(bool(v) for v in raw["constant_mask"]),
feature_names=tuple(str(c) for c in raw["feature_names"]),
n_samples_seen=int(raw["n_samples_seen"]),
)
return obj
def compute_mad_zscore(
values: np.ndarray | pd.Series | list[float],
consistency_constant: float = 1.4826022,
outlier_threshold: float = 3.5,
) -> dict[str, Any]:
arr = np.asarray(values, dtype=np.float64)
fin = np.isfinite(arr)
vals = arr[fin]
if vals.size == 0:
raise ValueError("Need >= 1 finite element.")
med = float(np.median(vals))
abs_dev = np.abs(vals - med)
mad = float(np.median(abs_dev))
if mad > 1e-12:
scale, mode = consistency_constant * mad, "mad"
else:
mean_ad = float(np.mean(abs_dev))
if mean_ad > 1e-12:
scale, mode = 1.2533141373155003 * mean_ad, "mean_ad_fallback"
else:
scale, mode = 1.0, "constant"
z = np.full(arr.shape, np.nan, dtype=np.float64)
z[fin] = 0.0 if mode == "constant" else (vals - med) / scale
mask = np.zeros(arr.shape, dtype=bool)
mask[fin] = np.abs(z[fin]) > outlier_threshold
return {"median": med, "mad": mad, "effective_scale": scale, "scale_mode": mode, "z_scores": z, "outlier_mask": mask}
class RobustMADImputer:
"""Train-only median + MAD/MeanAD imputer locking <col>_is_missing schema & JSON state."""
def __init__(
self,
numeric_cols: list[str] | tuple[str, ...],
add_missing_indicators: bool = True,
consistency_constant: float = 1.4826022,
eps: float = 1e-12,
) -> None:
self.numeric_cols = tuple(numeric_cols)
self.add_missing_indicators = bool(add_missing_indicators)
self.consistency_constant = float(consistency_constant)
self.eps = float(eps)
self._fitted = False
self.medians_: dict[str, float] = {}
self.scales_: dict[str, float] = {}
self.scale_modes_: dict[str, str] = {}
self.indicator_cols_: tuple[str, ...] = ()
def fit(self, X: pd.DataFrame, y: np.ndarray | pd.Series | None = None) -> "RobustMADImputer":
ind_cols: list[str] = []
self.medians_, self.scales_, self.scale_modes_ = {}, {}, {}
for col in self.numeric_cols:
arr = pd.to_numeric(X[col], errors="coerce").to_numpy(dtype=np.float64)
fin = np.isfinite(arr)
if not np.any(fin):
raise ValueError(f"Column '{col}' has zero finite values in training split.")
vals = arr[fin]
med = float(np.median(vals))
abs_dev = np.abs(vals - med)
mad = float(np.median(abs_dev))
if mad > self.eps:
sc, mode = self.consistency_constant * mad, "mad"
else:
mean_ad = float(np.mean(abs_dev))
sc, mode = (1.2533141373155003 * mean_ad, "mean_ad_fallback") if mean_ad > self.eps else (1.0, "constant")
self.medians_[col], self.scales_[col], self.scale_modes_[col] = med, sc, mode
if self.add_missing_indicators and np.any(np.isnan(arr)):
ind_cols.append(f"{col}_is_missing")
self.indicator_cols_ = tuple(ind_cols)
self._fitted = True
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
if not self._fitted:
raise NotFittedError("RobustMADImputer must be fitted before transform().")
out = X.copy()
ind_lookup = set(self.indicator_cols_)
for col in self.numeric_cols:
arr = pd.to_numeric(out[col], errors="coerce").to_numpy(dtype=np.float64)
miss = np.isnan(arr)
if f"{col}_is_missing" in ind_lookup:
out[f"{col}_is_missing"] = miss.astype(np.float64)
filled = np.where(miss, self.medians_[col], arr)
out[col] = 0.0 if self.scale_modes_[col] == "constant" else (filled - self.medians_[col]) / self.scales_[col]
return out
def to_state_dict(self) -> dict[str, Any]:
if not self._fitted:
raise NotFittedError("Cannot serialize unfitted RobustMADImputer.")
return {
"class": "RobustMADImputer",
"format_version": "1.0",
"numeric_cols": list(self.numeric_cols),
"add_missing_indicators": self.add_missing_indicators,
"consistency_constant": self.consistency_constant,
"eps": self.eps,
"medians": dict(self.medians_),
"scales": dict(self.scales_),
"scale_modes": dict(self.scale_modes_),
"indicator_cols": list(self.indicator_cols_),
}
class OutOfFoldTargetEncoder:
"""Groups-aware OOF Empirical-Bayes m-estimate target encoder with __RARE__ pooling."""
def __init__(
self,
cols: list[str] | tuple[str, ...],
smoothing_m: float = 10.0,
min_samples: int = 5,
n_folds: int = 5,
seed: int = 42,
missing_token: str = "__MISSING__",
rare_token: str = "__RARE__",
) -> None:
self.cols = tuple(cols)
self.smoothing_m = float(smoothing_m)
self.min_samples = int(min_samples)
self.n_folds = int(n_folds)
self.seed = int(seed)
self.missing_token = missing_token
self.rare_token = rare_token
self._fitted = False
self.global_prior_: float = 0.0
self.mappings_: dict[str, dict[str, float]] = {}
self.fallback_values_: dict[str, float] = {}
def _norm(self, s: pd.Series) -> pd.Series:
return s.astype("object").where(s.notna(), self.missing_token).astype(str)
def _fit_col(self, cats: pd.Series, y: np.ndarray) -> tuple[dict[str, float], float]:
mu0 = float(np.mean(y))
vc = cats.value_counts()
rare = set(vc[vc < self.min_samples].index)
pooled = cats.where(~cats.isin(rare), self.rare_token)
agg = pd.DataFrame({"c": pooled.to_numpy(), "y": y}).groupby("c", sort=True)["y"].agg(["count", "sum"])
m = self.smoothing_m
mp = {str(c): float((float(r["sum"]) + m * mu0) / (float(r["count"]) + m)) for c, r in agg.iterrows()}
return mp, float(mp.get(self.rare_token, mu0))
def fit(self, X: pd.DataFrame, y: np.ndarray | pd.Series) -> "OutOfFoldTargetEncoder":
y_arr = np.asarray(y, dtype=np.float64)
self.global_prior_ = float(np.mean(y_arr))
self.mappings_, self.fallback_values_ = {}, {}
for col in self.cols:
self.mappings_[col], self.fallback_values_[col] = self._fit_col(self._norm(X[col]), y_arr)
self._fitted = True
return self
def fit_transform(
self, X: pd.DataFrame, y: np.ndarray | pd.Series, groups: np.ndarray | pd.Series | None = None
) -> pd.DataFrame:
self.fit(X, y)
y_arr = np.asarray(y, dtype=np.float64)
n = len(X)
rng = np.random.default_rng(self.seed)
if groups is not None:
g = pd.Series(np.asarray(groups, dtype=object)).fillna(self.missing_token).astype(str).to_numpy()
ug = rng.permutation(np.unique(g))
k_eff = min(self.n_folds, len(ug))
g2f = {val: idx % k_eff for idx, val in enumerate(ug)}
fold_ids = np.array([g2f[val] for val in g], dtype=np.int64)
else:
k_eff = min(self.n_folds, n)
fold_ids = np.empty(n, dtype=np.int64)
for pos, i in enumerate(rng.permutation(n)):
fold_ids[i] = pos % k_eff
out = X.copy()
for col in self.cols:
cats = self._norm(X[col])
oof = np.empty(n, dtype=np.float64)
for f in range(k_eff):
vm = fold_ids == f
mp, fb = self._fit_col(cats.iloc[~vm], y_arr[~vm])
oof[vm] = cats.iloc[vm].map(mp).fillna(fb).to_numpy(dtype=np.float64)
out[col] = oof
return out
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
if not self._fitted:
raise NotFittedError("OutOfFoldTargetEncoder must be fitted before transform().")
out = X.copy()
for col in self.cols:
out[col] = self._norm(out[col]).map(self.mappings_[col]).fillna(self.fallback_values_[col]).to_numpy(dtype=np.float64)
return out
def to_state_dict(self) -> dict[str, Any]:
if not self._fitted:
raise NotFittedError("Cannot serialize unfitted OutOfFoldTargetEncoder.")
return {
"class": "OutOfFoldTargetEncoder",
"format_version": "1.0",
"cols": list(self.cols),
"smoothing_m": self.smoothing_m,
"min_samples": self.min_samples,
"global_prior": self.global_prior_,
"fallback_values": dict(self.fallback_values_),
"mappings": {c: dict(m) for c, m in self.mappings_.items()},
}
# ==============================================================================
# 3. DỊCH CHUYỂN PHÂN PHỐI: PSI, WASSERSTEIN-1, DUAL-SERIES KS & OOF C2ST/MMD
# ==============================================================================
def compute_psi(
expected: np.ndarray | list[float],
actual: np.ndarray | list[float],
bins: int = 10,
strategy: Literal["quantile", "uniform"] = "quantile",
eps: float = 1e-6,
include_nan_bin: bool = True,
) -> dict[str, Any]:
exp, act = np.asarray(expected, dtype=np.float64), np.asarray(actual, dtype=np.float64)
exp_nan, act_nan = int(np.sum(np.isnan(exp))), int(np.sum(np.isnan(act)))
ef, af = exp[np.isfinite(exp)], act[np.isfinite(act)]
if float(np.ptp(ef)) <= 1e-15:
c = float(ef[0])
m = int(np.sum(np.abs(af - c) <= 1e-12))
ec, ac = np.array([float(ef.size), 0.0]), np.array([float(m), float(af.size - m)])
else:
raw_edges = np.quantile(ef, np.linspace(0.0, 1.0, bins + 1)) if strategy == "quantile" else np.linspace(float(ef.min()), float(ef.max()), bins + 1)
u = np.unique(raw_edges)
edges = np.array([-np.inf, np.inf]) if u.size <= 2 else np.concatenate(([-np.inf], u[1:-1], [np.inf]))
ec, ac = np.histogram(ef, bins=edges)[0].astype(np.float64), np.histogram(af, bins=edges)[0].astype(np.float64)
if include_nan_bin and (exp_nan > 0 or act_nan > 0):
ec, ac = np.append(ec, float(exp_nan)), np.append(ac, float(act_nan))
p = np.clip(ec / float(np.sum(ec)), eps, None)
p /= float(np.sum(p))
q = np.clip(ac / float(np.sum(ac)), eps, None)
q /= float(np.sum(q))
psi = float(np.sum((q - p) * np.log(q / p)))
b_eff = int(p.size)
n_ref = int(exp.size if include_nan_bin else ef.size)
n_cur = int(act.size if include_nan_bin else af.size)
null_bias = float((b_eff - 1) * (1.0 / n_ref + 1.0 / n_cur))
return {"psi": psi, "effective_bins": b_eff, "expected_null_psi_bias": null_bias, "small_sample_noise_risk": bool(n_cur < 200 or psi < 2.0 * null_bias)}
def compute_wasserstein_1d(u_values: np.ndarray | list[float], v_values: np.ndarray | list[float]) -> float:
u_arr, v_arr = np.asarray(u_values, dtype=np.float64), np.asarray(v_values, dtype=np.float64)
u, v = np.sort(u_arr[np.isfinite(u_arr)]), np.sort(v_arr[np.isfinite(v_arr)])
all_v = np.concatenate([u, v])
all_v.sort(kind="mergesort")
cu = np.searchsorted(u, all_v[:-1], side="right") / float(u.size)
cv = np.searchsorted(v, all_v[:-1], side="right") / float(v.size)
return float(np.sum(np.abs(cu - cv) * np.diff(all_v)))
def ks_survival_prob(lam: float) -> float:
if lam <= 1e-12:
return 1.0
if lam < 0.27:
# Chuỗi song đối Jacobi theta Poisson chống triệt tiêu số học khi lam nhỏ
s = 0.0
for k in range(1, 20):
term = math.exp(-((2 * k - 1) ** 2) * (math.pi ** 2) / (8.0 * lam * lam))
s += term
if term <= 1e-16:
break
return float(max(0.0, min(1.0, 1.0 - (math.sqrt(2.0 * math.pi) / lam) * s)))
total = 0.0
for k in range(1, 101):
term = ((-1.0) ** (k - 1)) * math.exp(-2.0 * (k * k) * (lam * lam))
total += term
if abs(term) <= 1e-16:
break
return float(max(0.0, min(1.0, 2.0 * total)))
def compute_ks_statistic(u_values: np.ndarray | list[float], v_values: np.ndarray | list[float]) -> dict[str, float]:
u_arr, v_arr = np.asarray(u_values, dtype=np.float64), np.asarray(v_values, dtype=np.float64)
us, vs = np.sort(u_arr[np.isfinite(u_arr)]), np.sort(v_arr[np.isfinite(v_arr)])
av = np.unique(np.concatenate([us, vs]))
d_stat = float(np.max(np.abs(np.searchsorted(us, av, side="right") / float(us.size) - np.searchsorted(vs, av, side="right") / float(vs.size))))
n_eff = (us.size * vs.size) / float(us.size + vs.size)
sq_n = math.sqrt(n_eff)
lam = (sq_n + 0.12 + 0.11 / sq_n) * d_stat
return {"ks_stat": d_stat, "p_value": ks_survival_prob(lam), "n_eff": float(n_eff)}
def compute_roc_auc(y_true: np.ndarray | list[int], y_score: np.ndarray | list[float]) -> float:
y, s = np.asarray(y_true, dtype=np.int64), np.asarray(y_score, dtype=np.float64)
n_pos, n_neg = int(np.sum(y == 1)), int(np.sum(y == 0))
order = np.argsort(s, kind="mergesort")
ss, ranks, i = s[order], np.empty(y.size, dtype=np.float64), 0
while i < y.size:
j = i + 1
while j < y.size and ss[j] == ss[i]:
j += 1
ranks[order[i:j]] = 0.5 * ((i + 1) + j)
i = j
return float((float(np.sum(ranks[y == 1])) - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg))
def _fit_l2_logistic_newton(X: np.ndarray, y: np.ndarray, l2_reg: float = 1.0) -> tuple[np.ndarray, float]:
n, d = X.shape
eye = np.eye(d + 1, dtype=np.float64)
eye[-1, -1] = 0.0
Xb = np.column_stack([X, np.ones(n, dtype=np.float64)])
th = np.zeros(d + 1, dtype=np.float64)
for _ in range(35):
p = 1.0 / (1.0 + np.exp(-np.clip(Xb @ th, -35.0, 35.0)))
g = Xb.T @ (p - y) + l2_reg * np.append(th[:-1], 0.0)
H = (Xb.T * np.maximum(p * (1.0 - p), 1e-8)) @ Xb + l2_reg * eye + 1e-8 * np.eye(d + 1)
step = np.linalg.solve(H, g)
th -= step
if float(np.max(np.abs(step))) < 1e-7:
break
return th[:-1], float(th[-1])
def adversarial_validation_oof_auc(
X_train: np.ndarray, X_test: np.ndarray, n_splits: int = 5, l2_reg: float = 1.0, include_quadratic: bool = False, seed: int = 42
) -> dict[str, Any]:
x_tr, x_te = np.asarray(X_train, dtype=np.float64), np.asarray(X_test, dtype=np.float64)
X_adv = np.vstack([x_tr, x_te])
y_adv = np.concatenate([np.zeros(x_tr.shape[0], dtype=np.int64), np.ones(x_te.shape[0], dtype=np.int64)])
rng = np.random.default_rng(seed)
fold_ids = np.empty(y_adv.size, dtype=np.int64)
for cls_val in (0, 1):
idx = np.flatnonzero(y_adv == cls_val)
rng.shuffle(idx)
for pos, i in enumerate(idx):
fold_ids[i] = pos % n_splits
oof = np.empty(y_adv.size, dtype=np.float64)
for f in range(n_splits):
vm = fold_ids == f
Xf_tr, Xf_val = X_adv[~vm].copy(), X_adv[vm].copy()
# Điền trung vị & chuẩn hóa hoàn toàn bên trong từng nếp trước khi mở rộng bậc hai
col_med = np.array(
[float(np.nanmedian(Xf_tr[:, j])) if np.any(np.isfinite(Xf_tr[:, j])) else 0.0 for j in range(Xf_tr.shape[1])],
dtype=np.float64,
)
Xf_tr = np.where(np.isfinite(Xf_tr), Xf_tr, col_med)
Xf_val = np.where(np.isfinite(Xf_val), Xf_val, col_med)
mu0 = np.mean(Xf_tr, axis=0)
sd0 = np.where(np.std(Xf_tr, axis=0) > 1e-12, np.std(Xf_tr, axis=0), 1.0)
Xf_tr, Xf_val = (Xf_tr - mu0) / sd0, (Xf_val - mu0) / sd0
if include_quadratic:
d = Xf_tr.shape[1]
Xf_tr = np.column_stack([Xf_tr] + [Xf_tr[:, i] * Xf_tr[:, j] for i in range(d) for j in range(i, d)])
Xf_val = np.column_stack([Xf_val] + [Xf_val[:, i] * Xf_val[:, j] for i in range(d) for j in range(i, d)])
mu = np.mean(Xf_tr, axis=0)
sd = np.where(np.std(Xf_tr, axis=0) > 1e-12, np.std(Xf_tr, axis=0), 1.0)
Xf_tr, Xf_val = (Xf_tr - mu) / sd, (Xf_val - mu) / sd
w, b = _fit_l2_logistic_newton(Xf_tr, y_adv[~vm].astype(np.float64), l2_reg=l2_reg)
oof[vm] = 1.0 / (1.0 + np.exp(-np.clip(Xf_val @ w + b, -35.0, 35.0)))
auc = compute_roc_auc(y_adv, oof)
return {"auc_adv": auc, "shift_detected": bool(auc > 0.65), "critical_leakage_alert": bool(auc > 0.80)}
def compute_rbf_mmd_u2(
X_ref: np.ndarray, X_cur: np.ndarray, bandwidth: float | None = None
) -> dict[str, float]:
X = np.asarray(X_ref, dtype=np.float64)
Y = np.asarray(X_cur, dtype=np.float64)
n_ref, n_cur = X.shape[0], Y.shape[0]
if bandwidth is None:
Z = np.vstack([X, Y])
sq = np.sum((Z[:, None, :] - Z[None, :, :]) ** 2, axis=-1)
upper = sq[np.triu_indices(Z.shape[0], k=1)]
pos = upper[upper > 0.0]
bandwidth = math.sqrt(0.5 * float(np.median(pos))) if pos.size else 1.0
gamma = 1.0 / (2.0 * bandwidth * bandwidth)
k_xx = np.exp(-gamma * np.sum((X[:, None, :] - X[None, :, :]) ** 2, axis=-1))
k_yy = np.exp(-gamma * np.sum((Y[:, None, :] - Y[None, :, :]) ** 2, axis=-1))
k_xy = np.exp(-gamma * np.sum((X[:, None, :] - Y[None, :, :]) ** 2, axis=-1))
term_x = (float(np.sum(k_xx)) - n_ref) / float(n_ref * (n_ref - 1))
term_y = (float(np.sum(k_yy)) - n_cur) / float(n_cur * (n_cur - 1))
term_xy = 2.0 * float(np.sum(k_xy)) / float(n_ref * n_cur)
return {"mmd_u2": term_x + term_y - term_xy, "bandwidth": float(bandwidth)}
def build_experiment_manifest(
run_name: str, df: pd.DataFrame, split_contract: SplitContract, split_indices: dict[str, list[int]], config: dict[str, Any], state_dicts: dict[str, dict[str, Any]], root_seed: int = 42
) -> dict[str, Any]:
def _canon(obj: Any) -> str:
return json.dumps(obj, sort_keys=True, separators=(",", ":"), allow_nan=False)
h_df = hashlib.sha256(_canon([(str(c), str(df[c].dtype)) for c in df.columns]).encode("utf-8"))
h_df.update(pd.util.hash_pandas_object(df, index=True).to_numpy(dtype=np.uint64).tobytes())
rng_tree = np.random.SeedSequence(root_seed).spawn(4)
body: dict[str, Any] = {
"run_name": run_name,
"dataset_sha256": h_df.hexdigest(),
"split_contract": split_contract.model_dump(),
"split_sha256": hashlib.sha256(_canon(split_indices).encode("utf-8")).hexdigest(),
"config_sha256": hashlib.sha256(_canon(config).encode("utf-8")).hexdigest(),
"state_dicts_sha256": hashlib.sha256(_canon(state_dicts).encode("utf-8")).hexdigest(),
"spawn_keys": [list(s.spawn_key) for s in rng_tree],
"env": {"python": sys.version.split()[0], "numpy": np.__version__, "pandas": pd.__version__, "pydantic": pydantic.__version__},
}
body["manifest_sha256"] = hashlib.sha256(_canon(body).encode("utf-8")).hexdigest()
return body
Trụ cột 4 — Thực hành Lab 04 (lifecycle_eda_lab) & Kiểm định Chất lượng Pipeline (Hands-On Workbench & 14-Test Verification Rubric)#
Bài thực hành đồng hành tại labs/ch04-lifecycle-oop-and-eda-workbench/ hiện thực hóa toàn bộ các chứng minh, hợp đồng dữ liệu, bộ biến đổi có trạng thái và động cơ phát hiện dịch chuyển từ Trụ cột 1–3 thành gói Python kiểm chứng tự chủ lifecycle_eda_lab với 14 ca kiểm thử hợp đồng pytest.
4.1 Kiến trúc Gói lifecycle_eda_lab, Lõi Tham chiếu Sạch & Hợp đồng Không-Pickle#
labs/ch04-lifecycle-oop-and-eda-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch04_workbench_results.json
├── src/
│ └── lifecycle_eda_lab/
│ ├── __init__.py
│ ├── contracts_and_lineage.py
│ ├── pipelines_and_encoders.py
│ └── eda_and_drift.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_lifecycle_eda_lab.py
Hợp đồng pyproject.toml & Ràng buộc Môi trường (Python >= 3.10):
- Khai báo
name = "lifecycle-eda-lab",version = "0.1.0",requires-python = ">=3.10",dependencies = ["numpy>=1.26", "pandas>=2.0", "pydantic>=2.0"], và[project.optional-dependencies] dev = ["pytest>=8.0", "ruff>=0.4"]. - Cấu hình
[tool.setuptools.packages.find](where = ["src"]) và[tool.pytest.ini_options](testpaths = ["tests"],pythonpath = ["src"],addopts = "-v"). - Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật (
Security-Only AST Deserialization Ban): Toàn bộ bộ biến đổi, kiểm địnhEDA, và công cụ đo dịch chuyển viết thuần Python + NumPy + Pandas + Pydantic v2 (miễn nhiễm với đứt gãy ABI_ARRAY_APItrênNumPy 2.x); đồng thờiTest 14chạy trình quét AST trênsrc/,scripts/, vàtests/cấm tuyệt đối giải tuần tự hóa nguy hiểm (pickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshal), loại bỏ hoàn toàn lỗ hổngCWE-502.
4.2 Hướng dẫn Từng bước Qua 3 Mô-đun Cốt lõi & CLI Workbench#
Mô-đun 1: Hợp đồng Tách tập, Kiểm định Schema & Phả hệ Định danh Nội dung (src/lifecycle_eda_lab/contracts_and_lineage.py)#
- Mô hình
Pydantic v2(ConfigDict(frozen=True, extra="forbid")):SplitContract(tỷ lệ chia tập có tổng1.0, chiến lược"temporal" | "group" | "stratified_iid", kiểm traembargo_secondsvà.verify_splits()),ColumnContract, vàDataContractSchema(kiểm địnhdtype_family,max_null_fraction,+/-inf, khoảng[min_value, max_value]vàforbidden_sentinels). - Hàm chia tập tất định
split_dataframe: Khớp chiến lượctemporal(cắt và gạt bỏ các dòng lọt vào đệmembargo_seconds),group, hoặcstratified_iidquaSeedSequence, sau đó gọi thẳng.verify_splits(). - Cây RNG & Phả hệ
SHA-256:@dataclass(frozen=True, slots=True)ReproducibleRngTree.from_master_seed(master_seed)sinh 4 luồngPCG64độc lập (split_rng,eda_rng,oof_rng,model_rng), cùngcanonical_json,sha256_bytes,hash_dataframe_sha256, vàbuild_experiment_manifest(...).
Mô-đun 2: Bộ biến đổi Có trạng thái, Xử lý MAD/is_missing, OOF m-Estimate & JSON State-Dict (src/lifecycle_eda_lab/pipelines_and_encoders.py)#
- Giao thức & Trạng thái Bất biến Sâu:
NotFittedError,@runtime_checkableStatefulTransformer(Protocol), vàFittedStandardizerStatekhóa chỉ đọc bằngsetflags(write=False). StatefulStandardizer: Chuẩn hóa Z-score bất biến theo lô, xử lý cột hằng sốscale = 1.0, kèm.to_state_dict()/.from_state_dict()và.to_signed_json()/.from_signed_json()kiểm bămpayload_sha256.RobustMADImputer: Khớp trung vị và thang đoMAD\(\to\)1.2533141373155003 * MeanAD\(\to\)constantchỉ trêntrain_df, khóa cứng danh sách cột<col>_is_missingtrongindicator_cols_.OutOfFoldTargetEncoder: ChuyểnNaNsang__MISSING__, gộp tần suất< min_samplessang__RARE__trước khi tính từng nếp, cô lập nếp theogroups, tính làm trơn Empirical-Bayes \(m\)-estimate, và tuần tự hóa thuần JSON.StatefulPipeline&ColumnRouter: Kiểm tra giao thứcisinstance(step, StatefulTransformer), phối hợp biến đổi song song các nhóm cột với chính sách mặc định không nuốt cột mới (remainder="error").
Mô-đun 3: EDA Chống Rò rỉ, Đại số Simpson & Bộ Máy Dịch chuyển SOTA (src/lifecycle_eda_lab/eda_and_drift.py)#
- Chẩn đoán EDA & Phản ví dụ Rò rỉ:
compute_mad_zscore(trả vềMadZScoreResult),diagnose_missingness_mechanisms(chỉ trêntrain_df, kiểm chứng tỷ lệ giữ phương sai1 - p_miss),simpson_paradox_audit(trả vềSimpsonAuditResultthỏawithin_stratum_effect + mix_shift_confounding == agg_diff+ chuẩn hóa trực tiếp), vàsimulate_presplit_leakage_audit(chứng minh \(\rho = -1\) quy tâm tiền tách tập và ảo giác lọc nhiễu trắng \(N=100, d=2{,}000\)). - Thước đo Dịch chuyển Đơn biến & Đa biến:
compute_psi(gắn cờsmall_sample_noise_riskvàexpected_null_psi_bias = (b_eff - 1)*(1/n_ref + 1/n_cur)),compute_jsd(..., base="bits"|"nats"),compute_wasserstein_1d,compute_normalized_wasserstein_1d,ks_survival_prob(chuỗi kép Jacobi theta \(\lambda < 0.27\)) &compute_ks_statistic,compute_roc_auc(Mann–Whitney U đồng hạng),adversarial_validation_oof_auc(trả vềAdversarialAuditResult, hỗ trợinclude_quadratic=Truebằng Newton–Raphson \(L_2\) thuần NumPy),compute_rbf_mmd_u2, vàrun_full_lifecycle_benchmarks.
Thực thi CLI Một Lệnh & Bảng 6 Chỉ số Xác minh (artifacts/ch04_workbench_results.json)#
Từ thư mục gốc labs/ch04-lifecycle-oop-and-eda-workbench/, thực thi:
python scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch04_workbench_results.json
CLI in đủ 4 khối báo cáo trên stdout:
[1] Split-First Contracts, Typed OOP Pipelines & Zero-Pickle JSON State-Dict Lineage[2] Pre-Split Leakage Proofs, Missingness (MCAR/MAR/MNAR), Zero-MAD & Simpson Paradox[3] High-Cardinality OOF m-Estimate Target Encoding & Credit PIT Leakage Benchmark[4] SOTA Distribution Shift Suite (PSI Null Bias, JSD, W1, Dual-Series KS, OOF C2ST & RBF MMD)
Tệp artifacts/ch04_workbench_results.json xuất 5 khóa cấp cao ("config", "workbench_panels", "contracts_and_lineage", "eda_and_encoding", "drift_and_cases"), trong đó "workbench_panels" gồm 6 KPI (kpi_presplit_noise_illusion, kpi_mnar_var_and_indicator, kpi_zipf_oof_generalization, kpi_telemetry_w1_vs_psi, kpi_null_psi_vs_ks_fpr, kpi_adv_val_and_mmd_shift), 4 biểu đồ cột (bar_presplit_screening_illusion, bar_zipf_target_encoding_auc, bar_icu_mnar_and_simpson, bar_drift_blindness_comparison), và 4 bảng (table_presplit_leakage_audit, table_missingness_and_encoding, table_drift_and_shift_matrix, table_multivariate_and_lineage).
Chỉ số KPI (artifacts/ch04_workbench_results.json) |
Giá trị Đo kiểm Thực tế (--seed 42 --quick) |
Trạng thái |
|---|---|---|
kpi_presplit_noise_illusion (N=100, d=2,000 pure noise Corr_te: Pre-split vs. Split-first) |
+0.631 vs. -0.038 (k=10: Pre-split rò R2_te = +0.325 vs. Split-first R2_te = -0.427; quy tâm tiền tách ép Corr = -1.000) |
critical (Chứng minh ảo ảnh rò rỉ) |
kpi_mnar_var_and_indicator (ICU MNAR giữ phương sai \(1 - p_{\text{miss}}\) & phục hồi is_missing AUC) |
0.490 -> 0.793 AUC (p_miss = 0.538: lý thuyết 0.462 vs. thực nghiệm 0.462, tương quan mục tiêu 0.579) |
ok (Đã xác minh) |
kpi_zipf_oof_generalization (Zipf merchant_id 5-fold OOF \(m\)-estimate test AUC vs. quá khớp ngây thơ) |
0.704 (gap +0.008) vs. ngây thơ 0.665 (gap +0.117) trên 1,529 merchant huấn luyện (85.9% < 5 mẫu) |
ok (Đã xác minh) |
kpi_telemetry_w1_vs_psi (iOS v4.2 1000x + -1.0: Global PSI mù vs. Global W_1 & iOS_4.2 sliced PSI) |
Global PSI 0.117 (< 0.25 mù!) vs. W_1 = 62,141.8s & iOS_4.2 sliced PSI = 10.62 (DataContractSchema: 3 lỗi chặn trước suy luận) |
warn (Cảnh báo bắt lệch đơn vị) |
kpi_null_psi_vs_ks_fpr (Lát nhỏ \(H_0\) n_cur=50, B=20: FPR PSI >= 0.25 vs. KS alpha=0.05) |
PSI 94.8% vs. KS 4.0% (trung bình PSI dưới \(H_0\) đạt 1.093, KS giữ đúng ngưỡng alpha=0.05) |
warn (Chặn báo động giả mẫu nhỏ) |
kpi_adv_val_and_mmd_shift (Credit PIT AUC_adv & xoay tương quan \(+0.85 \to -0.85\) bậc hai / MMD_u^2) |
PIT 0.989 / Rot 0.919 AUC_adv (Linear C2ST = 0.539 mù xoay; x1*x2 0.919, RBF MMD_u^2 = 0.0944, PIT clean = 0.719 vs. leaky = 0.595 OOT) |
ok (Đã xác minh) |
(Ngoài ra, lần chạy scripts/run_lab_demo.py --seed 42 --quick ghi nhận bất biến lô hàng batch_invariance_max_abs_diff = 0.0, khớp khứ hồi JSON có chữ ký SHA-256 sai số 0.0, nhánh mean_ad_fallback trên [0,0,0,0,10,NaN] đạt effective_scale = 2.507 / max_z = 3.989, Simpson \(2\times 2\) giải mã agg_diff = +0.470 thành within = -0.050 + mix = +0.520, và trọn bộ 14/14 ca pytest vượt qua trong 5.90s với 0 import cấm.)
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_lifecycle_eda_lab.py)#
Gói lifecycle_eda_lab phải vượt qua toàn bộ 14 ca kiểm thử hợp đồng pytest dưới Python >= 3.10 (chạy không bỏ qua hay nới lỏng bất kỳ khẳng định nào):
| # | 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_split_contract_embargo_group_and_ratio_invariants |
SplitContract bác bỏ tổng tỷ lệ != 1.0, khóa lạ (extra="forbid"), thiếu time_col/group_col, vi phạm embargo_seconds và giao tập group_col; hàm split_dataframe tách đúng và qua .verify_splits(). |
| 2 | test_data_contract_schema_catches_unit_and_sentinel_corruption |
DataContractSchema.validate_dataframe bắt trọn đột biến đơn vị 1000x (max_value), sentinel -1.0/-999.0, cột lạ, +/-inf, sai kiểu dữ liệu, trả về danh sách lỗi có cấu trúc. |
| 3 | test_reproducible_rng_tree_isolation_and_content_addressed_manifest |
Rút 50,000 mẫu từ eda_rng giữ nguyên từng bit của split_rng và model_rng; build_experiment_manifest sinh dataset_sha256, split_sha256, config_sha256, state_dicts_sha256, manifest_sha256 nhạy với thay đổi 1 ô đơn lẻ. |
| 4 | test_stateful_standardizer_protocol_readonly_buffers_and_batch_invariance |
Xác nhận isinstance(..., StatefulTransformer), ném NotFittedError khi chưa khớp, khóa setflags(write=False) (ValueError khi ghi đè), xử lý cột hằng số, bất biến theo lô (1 dòng vs. 200 dòng atol=1e-12), và kiểm định to_signed_json()/from_signed_json() kèm từ chối checksum giả mạo. |
| 5 | test_robust_mad_zscore_breakdown_and_zero_mad_hierarchy |
Xác nhận \(c_{\text{MAD}} \approx 1.4826\) trên mẫu Chuẩn, trụ vững trước \(40\%\) nhiễu \(10^6\) (tính chất đổ vỡ \(50\%\)), chuyển [0, 0, 0, 0, 10, NaN] sang mean_ad_fallback (0 lỗi chia zero), và đưa [5, 5, 5] về scale_mode == "constant". |
| 6 | test_missingness_mcar_variance_shrinkage_and_mnar_indicator_recovery |
diagnose_missingness_mechanisms chỉ chạy trên train_df khớp tỷ lệ bảo toàn phương sai \(1 - p_{\text{miss}}\) (atol=0.025), phân loại đúng mcar_compatible / mar_covariate_coupled / informative_mnar_suspect, và chứng minh RobustMADImputer(..., add_missing_indicators=True) nâng AUC bệnh nhân mới trên ICU (>= 0.78) so với điền trung bình mù (< 0.62). |
| 7 | test_oof_target_encoder_eb_smoothing_rare_pooling_and_zipf_benchmark |
OutOfFoldTargetEncoder gộp < min_samples vào __RARE__, NaN vào __MISSING__, khớp công thức Bayes (n_c*y_bar + m_smooth*mu0)/(n_c + m_smooth), cô lập nếp groups, đọc/ghi JSON sạch, và xóa khoảng hở quá khớp (> 0.08 -> < 0.03) trên dữ liệu Zipf. |
| 8 | test_presplit_leakage_proofs_mean_anticorrelation_and_noise_screening_illusion |
Xác nhận Chứng minh 1 (tương quan trung bình phần dư hai tập bằng -1.0 atol=1e-10 và nén dịch chuyển về \(\alpha_{\text{tr}}\Delta\mu\)) và Chứng minh 2 (N=100, d=2000, top_k=10 trên nhiễu trắng cho corr_te > 0.45, r2_te > 0.15 nếu lọc trước vs. abs(corr_te) < 0.08, r2_te < 0.0 nếu tách tập trước). |
| 9 | test_simpson_paradox_exact_decomposition_and_direct_standardization |
simpson_paradox_audit trên bảng \(N=2{,}000\) (20%/85% -> 26.5% vs. 15%/80% -> 73.5%) thỏa chính xác within_stratum_effect + mix_shift_confounding == agg_diff (-0.05 + 0.52 == +0.47, atol=1e-12), gắn cờ reversal_detected == True, và khôi phục +5.0 pp qua chuẩn hóa trực tiếp. |
| 10 | test_psi_exact_null_bias_coefficient_and_small_sample_alarm_guard |
Mô phỏng Monte Carlo \(H_0\) (\(B=10, n_{\text{ref}}=2000, n_{\text{cur}}=200\)) khẳng định trung bình PSI khớp (B - 1)*(1/n_ref + 1/n_cur) (rtol=0.18) và bác bỏ công thức sai (B - 1)/2; xác nhận B=20, n_cur=50 bật small_sample_noise_risk == True với FPR PSI >= 0.25 vượt 0.70 trong khi KS (alpha=0.05) giữ <= 0.08. |
| 11 | test_jsd_bounds_wasserstein_disjoint_linearity_and_telemetry_slice_catch |
Kiểm tra compute_jsd(..., base="bits") trong [0, 1] và base="nats" trong [0, ln 2] + bất đẳng thức tam giác \(\sqrt{\operatorname{JSD}}\); kiểm tra \(W_1([0,1,2],[3,4]) == 2.500\) và \(W_1(\delta_0, \delta_\Delta) = |\Delta|\) tuyến tính; xác nhận Case 2 (iOS v4.2) cho Global PSI < 0.25, Global W_1 > 10,000, và iOS_4.2 sliced PSI > 1.0. |
| 12 | test_ks_jacobi_theta_dual_series_stability_and_tail_vs_bigdata_traps |
Khẳng định tính liên tục tại \(\lambda = 0.27\) giữa chuỗi song đối Jacobi theta và chuỗi đan dấu (atol=1e-12); \(5\%\) ngoại lai \(+10^6\) vẫn bị kẹp ks_stat <= 0.06 trong khi \(W_1\) bắt được; và dịch chuyển \(0.005\sigma\) ở \(n=100{,}000\) cho p_value < 0.01. |
| 13 | test_adversarial_validation_oof_auc_quadratic_rotation_and_rbf_mmd_u2 |
adversarial_validation_oof_auc giữ [0.43, 0.57] khi dừng, nhảy > 0.90 khi có cột row_id/PIT rò rỉ (xếp hạng #1); trên xoay tương quan \(\rho = +0.85 \to -0.85\), bản tuyến tính giữ <= 0.60 trong khi include_quadratic=True vượt 0.85 và compute_rbf_mmd_u2 báo mmd_u2 > 0.02. |
| 14 | test_cli_demo_script_workbench_json_and_zero_forbidden_imports |
Chạy scripts/run_lab_demo.py --seed 42 --quick --output <tmp> (returncode == 0), kiểm tra đủ 4 khối stdout + workbench_panels (6 KPIs, 4 bars, 4 tables), và rào chắn AST Chỉ Bảo mật quét toàn bộ .py dưới src/, scripts/, tests/ khẳng định 0 import giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực (Curated Reading List & Mastery Exercises)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Sculley, D., et al. (NeurIPS 2015) & Breck, E., et al. (IEEE BigData 2017). Hidden Technical Debt in Machine Learning Systems và The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction.
Vì sao quan trọng: Đặt nền tảng khái niệmCACE, rừng rậm pipeline, lệch huấn luyện–phục vụ và bảng điểm sẵn sàng hợp đồng dữ liệu tự động. - Kaufman, S., Rosset, S., Perlich, C., & Stitelman, O. (ACM TKDD 2012) & Hastie, T., Tibshirani, R., & Friedman, J. (2009, ESL §7.10.2). Leakage in Data Mining: Formulation, Detection, and Avoidance và The Wrong and Right Way to Do Cross-Validation.
Vì sao quan trọng: Thiết lập khuôn khổ nhân quả Point-in-Time chống rò rỉ vận hành và chứng minh phép quay trực giao cho ảo ảnh lọc đặc trưng tiền tách tập. - Rubin, D. B. (Biometrika 1976), Lipton, Z. C., et al. (MLHC 2016), Donoho, D. L., & Huber, P. J. (1983), Micci-Barreca, D. (SIGKDD 2001) & Simpson, E. H. (1951) / Pearl, J. (2014).
Vì sao quan trọng: Chuẩn hóa phân loại thiếuMCAR/MAR/MNARcùng giá trị cờis_missinglâm sàng, chứng minh điểm đổ vỡ \(50\%\) củaMAD, làm trơn Bayes thực nghiệm \(m\)-estimate và giải phẫu đại số Simpson nối sangch-05. - Moreno-Torres, J. G., et al. (Pattern Recognition 2012), Yurdakul, B., & Naranjo, J. D. (J. Risk Model Validation 2020), Endres, D. M., & Schindelin, J. E. (IEEE TIT 2003) & van Zyl, C., & Potgieter, N. (
PRS,arXiv:2307.11878, 2023–2024).
Vì sao quan trọng: Thống nhất 4 lớp dịch chuyển dữ liệu, chứng minh chính xác thiên lệch vô hiệu \((B-1)(n_{\text{ref}}^{-1}+n_{\text{cur}}^{-1})\) củaPSI, chứng minh tính chất metric của \(\sqrt{\operatorname{JSD}}\) và đưa kiểm định tương đương vào giám sátPSI. - Gretton, A., et al. (
MMD, JMLR 2012), Lopez-Paz, D., & Oquab, M. (C2ST, ICLR 2017), Pandeva, T., et al. (E-C2ST, TMLR 2024,arXiv:2210.13027), Kalinke, F., Szabó, Z., & Sriperumbudur, B. (MMDEW, TMLR 2025,arXiv:2205.12706) & Wan, K., et al. (MCD-DD, KDD 2024,arXiv:2407.05375).
Vì sao quan trọng: Đưa kiểm định hai mẫu đa biến từ lô \(O(n^2)\) tĩnh lên giám sát tuần tự hợp lệ mọi thời điểm (e-value) và cửa sổ trượt đa logarit cho luồng dữ liệu lớn. - Astral
uv+PEP 723(2024–2026),MarimoAST DAGs (2024–2026),Pydantic v2/Pandera/Narwhals/MLflow 3.0(2024–2026) & Cảnh báoskops(CVE-2025-54886/>= 0.13.0) +safetensors.
Vì sao quan trọng: Định hình hệ công cụ tái lập tất định, bất khả tri DataFrame và tuần tự hóa không-picklean toàn trướcCWE-502cùng đứt gãyABI.
5.2 Tám Điểm Kiểm tra Tư duy & Nắm vững Khái niệm (Q1–Q8)#
- Q1 (Vòng đời 7 Giai đoạn, Đệm
embargo& Chi phí Sai lỗi): Vì saoCRISP-DMtạo rò rỉ ngay tại Data Understanding, vì sao \(\Delta_{\text{gap}}\) bắt buộc \(\ge \Delta t_{\text{horizon}}\) trong phân tách thời gian, và phép tính nào đẩy chi phí Giai đoạn 6 lên $3,600,000 (> 10,000xso với Giai đoạn 2)? - Q2 (Bố cục
src/, Bất biến Sâu,Protocol&SeedSequence): Giải thích cơ chếsys.path[0]khiến bố cục phẳng giấu lỗi đóng gói; phân biệt bất biến nông vớisetflags(write=False); so sánhtyping.Protocol(@runtime_checkable) vớiBaseEstimator; và giải thích vì saonp.random.seedlàm đổi danh sách tách tập. - Q3 (Chứng minh Rò rỉ Tiền Tách tập): Chứng minh quy tâm tiền tách tập ép tương quan giữa trung bình phần dư huấn luyện và kiểm tra bằng đúng \(\rho = -1\), đồng thời dùng phép quay trực giao \(45^\circ\) giải thích vì sao \(N=100, d=2{,}000\) nhiễu trắng tạo ra \(\operatorname{Corr}_{\text{te}} \approx +0.62\).
- Q4 (Phân loại Rubin, Co rút Phương sai & Ranh giới Nhận dạng): Chứng minh \(\operatorname{Var}(\tilde{X}) = (1 - p_{\text{miss}})\sigma_X^2\) dưới
MCAR, và giải thích vì sao kiểm định thống kê thuần túy trên \((\mathbf{Y}_{\text{obs}}, \mathbf{M})\) phân biệt đượcMCARvớiMARnhưng bất khả phân biệtMARvớiMNAR. - Q5 (
MAD, Điểm Đổ vỡ \(50\%\),MAD == 0&OOFm-Estimate): Suy diễn \(c_{\text{MAD}} = 1/\Phi^{-1}(0.75) \approx 1.4826\), chứng minh điểm đổ vỡ \(50\%\), nêu thang xử lý 3 tầng khiMAD == 0(Hurdle -> MeanAD -> constant), và chứng minh giới hạn co rút khi \(n_c \to 0\) lẫn \(n_c \to \infty\) của bộ mã hóaOOF\(m\)-estimate. - Q6 (Đại số Nghịch lý Simpson & Chuẩn hóa Trực tiếp): Giải thích bằng đẳng thức đại số cách hai biến thể đều thua trong từng phân khúc lại lật kèo cộng gộp thành
26.5%vs.73.5%(+47.0 pp), và dùng tỷ trọng gộp để khôi phục hiệu ứng thật \(+5.0\text{ pp}\) trước khi chuyển sangch-05. - Q7 (
PSIThiên lệch(B-1),JSDvs. \(W_1\) &KSSong đối): Giải thích vì sao hệ số thiên lệch vô hiệu củaPSIlà1chứ không phải1/2; giải thích bão hòa củaJSD/KSso với tăng trưởng tuyến tính \(|\Delta|\) của \(W_1\); và nêu cơ chế chuỗi song đối Jacobi theta củaKStại \(\lambda < 0.27\). - Q8 (Điểm Mù
C2STTuyến tính, An ninhCWE-502&Marimo): Giải thích vì sao xoay tương quan \(\rho = +0.85 \to -0.85\) qua mặt cả 4 thước đo 1D lẫnC2STtuyến tính nhưng bị bắt bởiC2STbậc hai và \(\widehat{\operatorname{MMD}}_u^2\); nêu cơ chế RCE củapickle/skops CVE-2025-54886và lỗ hổngMutation BlindnesscủaMarimo.
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 (
20%— Chứng minh Rò rỉ Tiền Tách tập & Mô phỏng):
Trình bày trọn vẹn Chứng minh 1 (\(\rho = -1\) giữa phần dư hai tập và thiên lệch \(-\alpha_{\text{te}}\Delta\mu\)) và Chứng minh 2 (phép quay trực giao \(45^\circ\) cho \(N=100, d=2{,}000\) nhiễu trắng); đối chiếu quasimulate_presplit_leakage_auditở các mức \(k \in \{1, 5, 10, 20\}\). - Bài tập 2 (
15%— Co rút Phương saiMCAR, Đổ vỡMAD& Tín hiệuMNAR):
Chứng minh Định lý 1.1 (\(\operatorname{Var}(\tilde{X}) = (1-p_{\text{miss}})\sigma_X^2\), \(\rho(\tilde{X}, Z) = \sqrt{1-p_{\text{miss}}}\rho\)); suy diễn \(c_{\text{MAD}}\) và cận đổ vỡ \(50\%\); kiểm chứng khả năng phục hồiAUCcủa cờis_missingtrongRobustMADImputertrên mô phỏngICU MNAR(GroupSplittheopatient_id) và nhánh dự phòngMeanADcho[0, 0, 0, 0, 10, NaN]. - Bài tập 3 (
15%— Mã hóa Mục tiêuOOF\(m\)-Estimate & Đại số Simpson):
Suy diễn công thức hậu nghiệm Beta–Binomial cho \(m\)-estimate; cài đặtOutOfFoldTargetEncodertôn trọnggroupsvà gộp__RARE__trên tập thương mại điện tử Zipf; và kiểm chứng đẳng thức Simpsonwithin_stratum_effect + mix_shift_confounding == agg_diffcùng chuẩn hóa trực tiếp quasimpson_paradox_audit. - Bài tập 4 (
20%— Thiên lệchPSI, CậnJSD, Dạng đóng \(W_1\) &KSSong đối):
Chứng minh \(\mathbb{E}_{H_0}[\widehat{\operatorname{PSI}}] = (B-1)(n_{\text{ref}}^{-1} + n_{\text{cur}}^{-1})\) (giải thích hệ số1so với1/2), chứng minh cận \(\operatorname{JSD}_{\text{nat}} \le \ln 2\) và đối ngẫu bắt cặp đồng biến 1D \(W_1\); kiểm chứng thực nghiệm Case 2 (iOS v4.21000x+-1.0) và cơn bão báo động giản_cur=50, B=20. - Bài tập 5 (
15%— Dịch chuyển Đa biến:C2STTuyến tính vs. Bậc hai &MMD_u^2):
Dựng cặp phân phối Chuẩn 2D xoay tương quan \(\rho = +0.85 \to -0.85\) cùng biên \(\mathcal{N}(0, 1)\); kiểm chứng vì sao mọi thước đo 1D vàC2STtuyến tính thất bại trong khiadversarial_validation_oof_auc(..., include_quadratic=True)vàcompute_rbf_mmd_u2phát hiện tức thì; đồng thời truy vết các cột rò rỉ hậu quảPITtrong Case 1 tín dụng. - Bài tập 6 (
15%— Hợp đồng Định kiểu, Bất biến Lô & Phả hệ Không-pickle):
Lắp ráp chuỗi đầu–cuốiSplitContract\(\to\)DataContractSchema\(\to\)StatefulPipeline(RobustMADImputer+OutOfFoldTargetEncoder+StatefulStandardizer) dùngReproducibleRngTree; chứng minh khóa chỉ đọcsetflags(write=False)cùng bất biến từng dòng (1vs.200dòng); xuấtto_signed_json()có từ chối giả mạo checksum vàbuild_experiment_manifestbămSHA-256.
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 toán học chặt chẽ không nhảy bước (Quy tâm -1, phép quay \(45^\circ\) lọc nhiễu, co rút MCAR \((1-p_{\text{miss}})\), đổ vỡ MAD \(50\%\), thiên lệch PSI hệ số 1, cận JSD \([0,\ln 2]\), \(W_1\) đồng biến, phân rã Simpson); gói lifecycle_eda_lab sạch 0 import giải tuần tự hóa nguy hiểm (AST Test 14) và đạt 14/14 pytest; chẩn đoán sắc bén điểm mù PSI toàn cục của iOS v4.2, bão mẫu nhỏ n_cur=50, MNAR ICU, OOF Zipf, và xoay tương quan C2ST. |
| Senior Standard | 75–89% | Cài đặt đúng thuần Python/NumPy/Pandas/Pydantic và qua 14/14 pytest, nhưng còn thiếu sót nhẹ ở phần dư Taylor bậc ba của PSI, phân tầng Hurdle -> MeanAD -> constant khi MAD == 0, hoặc cảnh báo Mutation Blindness của Marimo. |
| Needs Remediation | < 75% | Dùng pickle/joblib hoặc np.random.seed toàn cục; gọi .fit() trước khi tách tập; điền thiếu MNAR không có cờ is_missing; mã hóa trung bình mục tiêu trong mẫu; hoặc tin mù quáng vào PSI < 0.25 / C2ST tuyến tính mà thiếu \(W_1\), cắt lát chiều, hay kiểm tra bậc hai/MMD. |
Pre-Split vs. Split-First Pure-Noise Test Correlation (N=100, d=2000)
High-Cardinality Zipf Target Encoding (Train vs. Test AUC)
ICU MNAR Recovery (AUC) & Simpson Paradox Magnitude (pp)
Global vs. Sliced PSI & Small-Slice Null False-Alarm Rates
Pre-Split vs. Split-First Screening & Centering Proofs (Pure Noise)
| regime | top_k | r2_in | r2_test | corr_test | status |
|---|---|---|---|---|---|
| pre_split_leaked | 1 | 0.1397 | 0.0373 | 0.3278 | LEAKED_ILLUSION |
| split_first_clean | 1 | 0.2391 | -0.2883 | 0.0163 | HONEST_NULL |
| pre_split_leaked | 10 | 0.5581 | 0.3251 | 0.6314 | LEAKED_ILLUSION |
| split_first_clean | 10 | 0.7223 | -0.427 | -0.0382 | HONEST_NULL |
| presplit_centering | alpha_tr=0.70 | 0.7 | 0.685 | -1.0 | ANTI_CORR_-1.0 |
Missingness (MNAR), Zero-MAD, Simpson Paradox & Zipf OOF Benchmarks
| scenario | p_miss_or_card | var_retention_or_train_auc | test_auc_or_signal | recommended_fix |
|---|---|---|---|---|
| icu_lactate_mnar | p_miss=0.538 | theo=0.462 / emp=0.462 | blind=0.490 -> ind=0.793 | GroupSplit + is_missing |
| zero_mad_sparse | MAD=0.0 | mode=mean_ad_fallback | max_z=3.989 | 1.253314*MeanAD fallback |
| simpson_2x2_audit | N=2000 (2 strata) | within=-0.050 + mix=+0.520 | agg=+0.470 -> std=-0.050 | Direct standardization |
| zipf_naive_insample | 1529 merchants | train_auc=0.781 | test_auc=0.665 (gap=+0.117) | Replace w/ OOF m-est |
| zipf_oof_m15_rare5 | rare=85.9% | train_auc=0.712 | test_auc=0.704 (gap=+0.008) | OOF + __RARE__ pooling |
SOTA Distribution Shift Matrix (Mobility Telemetry, H0 Storm & Rotation)
| scenario | psi | jsd_bits | wasserstein_w1 | ks_stat | ks_p_value | detector_verdict |
|---|---|---|---|---|---|---|
| mobility_global_ios_bug | 0.1175 | 0.0209 | 62141.8 | 0.1336 | 6.12e-20 | PSI_BLIND_W1_CAUGHT |
| mobility_ios_4_2_slice | 10.618 | 0.6239 | 348348.6 | 0.7489 | 1.00e-112 | SLICE_CRITICAL |
| small_n50_b20_h0_null | 1.0932 | 0.0 | 0.0 | 0.948 | 0.04 | PSI_FPR_HIGH_KS_SAFE |
| rotation_plus085_minus085_x1 | 0.0253 | 0.0046 | 0.098 | 0.0629 | 0.4813 | UNIVARIATE_BLIND |
Multivariate Shift (C2ST/MMD), Credit PIT Audit & Zero-Pickle Lineage
| audit_check | metric_name | observed_value | threshold_or_expected | status |
|---|---|---|---|---|
| credit_pit_leaky | adv_auc (post_default_limit^2) | 0.9889 | > 0.80 critical | LEAKAGE_DETECTED |
| credit_pit_clean | adv_auc (post-repair) | 0.4966 | 0.48 - 0.55 clean | PASS_ISOLATED |
| rotation_c2st_linear | oof_auc (linear) | 0.5392 | <= 0.60 blind | BLIND_TO_ROTATION |
| rotation_c2st_quad | oof_auc (x1*x2) | 0.9192 | > 0.85 detected | SHIFT_DETECTED |
| rotation_rbf_mmd | mmd_u2 (median bw) | 0.09436 | > 0.02 detected | SHIFT_DETECTED |
| lineage_and_batch_inv | batch_diff / sha256_match | 0.0e+00 / True | <= 1e-12 / True | VERIFIED_IMMUTABLE |
02-track-1-data-science-and-ai/part-01-math-stats-and-causal/labs/ch04-lifecycle-oop-and-eda-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "lifecycle-eda-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for ML Lifecycle Contracts, Stateful OOP Pipelines, Leakage-Free EDA, and SOTA Distribution Drift Detection (T1-P1-U04)."
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"
[tool.ruff]
line-length = 100
target-version = "py310"
"""Stage 5B Production Workbench for ML Lifecycle Contracts, Stateful OOP Pipelines, and SOTA Drift Detection."""
from lifecycle_eda_lab.contracts_and_lineage import (
ColumnContract,
DataContractSchema,
ReproducibleRngTree,
SplitContract,
build_experiment_manifest,
canonical_json,
hash_dataframe_sha256,
sha256_bytes,
split_dataframe,
)
from lifecycle_eda_lab.eda_and_drift import (
AdversarialAuditResult,
MadZScoreResult,
SimpsonAuditResult,
adversarial_validation_oof_auc,
compute_jsd,
compute_ks_statistic,
compute_mad_zscore,
compute_normalized_wasserstein_1d,
compute_psi,
compute_rbf_mmd_u2,
compute_roc_auc,
compute_wasserstein_1d,
diagnose_missingness_mechanisms,
ks_survival_prob,
run_full_lifecycle_benchmarks,
simpson_paradox_audit,
simulate_presplit_leakage_audit,
)
from lifecycle_eda_lab.pipelines_and_encoders import (
ColumnRouter,
FittedStandardizerState,
NotFittedError,
OutOfFoldTargetEncoder,
RobustMADImputer,
StatefulPipeline,
StatefulStandardizer,
StatefulTransformer,
)
__all__ = [
"AdversarialAuditResult",
"ColumnContract",
"ColumnRouter",
"DataContractSchema",
"FittedStandardizerState",
"MadZScoreResult",
"NotFittedError",
"OutOfFoldTargetEncoder",
"ReproducibleRngTree",
"RobustMADImputer",
"SimpsonAuditResult",
"SplitContract",
"StatefulPipeline",
"StatefulStandardizer",
"StatefulTransformer",
"adversarial_validation_oof_auc",
"build_experiment_manifest",
"canonical_json",
"compute_jsd",
"compute_ks_statistic",
"compute_mad_zscore",
"compute_normalized_wasserstein_1d",
"compute_psi",
"compute_rbf_mmd_u2",
"compute_roc_auc",
"compute_wasserstein_1d",
"diagnose_missingness_mechanisms",
"hash_dataframe_sha256",
"ks_survival_prob",
"run_full_lifecycle_benchmarks",
"sha256_bytes",
"simpson_paradox_audit",
"simulate_presplit_leakage_audit",
"split_dataframe",
]
"""Frozen Pydantic v2 data/split contracts, isolated RNG trees, and content-addressed SHA-256 lineage."""
from __future__ import annotations
import hashlib
import json
import math
import sys
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
import pandas as pd
import pydantic
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
def _to_json_primitive(obj: Any) -> Any:
"""Recursively normalize NumPy/Python objects into finite JSON primitives."""
if obj is None or isinstance(obj, (bool, str, int)):
return obj
if isinstance(obj, float):
if not math.isfinite(obj):
raise ValueError(f"Non-finite float {obj!r} is forbidden in canonical JSON.")
return obj
if isinstance(obj, np.bool_):
return bool(obj)
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
val = float(obj)
if not math.isfinite(val):
raise ValueError(f"Non-finite NumPy float {val!r} is forbidden in canonical JSON.")
return val
if isinstance(obj, np.ndarray):
return [_to_json_primitive(v) for v in obj.tolist()]
if isinstance(obj, (list, tuple)):
return [_to_json_primitive(v) for v in obj]
if isinstance(obj, dict):
return {str(k): _to_json_primitive(v) for k, v in obj.items()}
raise TypeError(f"Unsupported type for canonical JSON serialization: {type(obj).__name__}")
def canonical_json(obj: Any) -> str:
"""Serialize an arbitrary nested structure into deterministic, NaN-free canonical JSON."""
normalized = _to_json_primitive(obj)
return json.dumps(normalized, sort_keys=True, separators=(",", ":"), allow_nan=False)
def sha256_bytes(payload: bytes) -> str:
"""Return lowercase hexadecimal SHA-256 digest for raw byte payloads."""
return hashlib.sha256(payload).hexdigest()
def hash_dataframe_sha256(df: pd.DataFrame) -> str:
"""Compute a content-addressed SHA-256 digest over DataFrame schema and row hashes."""
hasher = hashlib.sha256()
schema_header = [(str(col), str(df[col].dtype)) for col in df.columns]
hasher.update(canonical_json(schema_header).encode("utf-8"))
if not df.empty:
row_hashes = pd.util.hash_pandas_object(df, index=True).to_numpy(dtype=np.uint64)
hasher.update(row_hashes.tobytes())
return hasher.hexdigest()
class SplitContract(BaseModel):
"""Immutable split contract enforcing ratio sum, temporal embargo, and entity isolation."""
model_config = ConfigDict(frozen=True, extra="forbid")
strategy: Literal["temporal", "group", "stratified_iid"]
train_ratio: float = Field(..., gt=0.0, lt=1.0)
val_ratio: float = Field(default=0.0, ge=0.0, lt=1.0)
test_ratio: float = Field(..., gt=0.0, lt=1.0)
time_col: str | None = None
group_col: str | None = None
embargo_seconds: float = Field(default=0.0, ge=0.0)
max_train_ts: float | None = None
min_val_ts: float | None = None
max_val_ts: float | None = None
min_test_ts: float | None = None
@model_validator(mode="after")
def _validate_invariants(self) -> SplitContract:
for ratio_name, ratio_val in (
("train_ratio", self.train_ratio),
("val_ratio", self.val_ratio),
("test_ratio", self.test_ratio),
):
if not math.isfinite(ratio_val):
raise ValueError(f"{ratio_name} must be finite, got {ratio_val!r}.")
if not math.isfinite(self.embargo_seconds):
raise ValueError("embargo_seconds must be finite.")
total = self.train_ratio + self.val_ratio + self.test_ratio
if not math.isclose(total, 1.0, rel_tol=0.0, abs_tol=1e-6):
raise ValueError(f"Split ratios must sum to 1.0, got {total:.8f}.")
if self.strategy == "temporal":
if not self.time_col or not self.time_col.strip():
raise ValueError("temporal split requires a non-empty time_col.")
if (
self.max_train_ts is not None
and self.min_val_ts is not None
and self.min_val_ts < self.max_train_ts + self.embargo_seconds
):
raise ValueError(
f"Embargo violated (train -> val): min_val_ts={self.min_val_ts} "
f"< max_train_ts+embargo={self.max_train_ts + self.embargo_seconds}."
)
if (
self.min_val_ts is not None
and self.max_val_ts is not None
and self.max_val_ts < self.min_val_ts
):
raise ValueError("max_val_ts cannot precede min_val_ts.")
prev_end = self.max_val_ts if self.max_val_ts is not None else self.max_train_ts
if (
prev_end is not None
and self.min_test_ts is not None
and self.min_test_ts < prev_end + self.embargo_seconds
):
raise ValueError(
f"Embargo violated before test: min_test_ts={self.min_test_ts} "
f"< prev_end+embargo={prev_end + self.embargo_seconds}."
)
if self.strategy == "group" and (not self.group_col or not self.group_col.strip()):
raise ValueError("group split requires a non-empty group_col.")
return self
def verify_splits(
self,
train_df: pd.DataFrame,
test_df: pd.DataFrame,
val_df: pd.DataFrame | None = None,
) -> dict[str, Any]:
"""Runtime isolation gate asserting non-empty partitions, zero entity overlap, and embargo."""
if train_df.empty or test_df.empty:
raise ValueError("train_df and test_df must be non-empty.")
if self.val_ratio > 0.0 and (val_df is None or val_df.empty):
raise ValueError("val_ratio > 0 requires a non-empty val_df.")
frames: list[tuple[str, pd.DataFrame]] = [("train", train_df)]
if val_df is not None and not val_df.empty:
frames.append(("val", val_df))
frames.append(("test", test_df))
if self.group_col is not None:
for i in range(len(frames)):
n1, df1 = frames[i]
if self.group_col not in df1.columns:
raise ValueError(f"Missing group_col '{self.group_col}' in {n1}_df.")
g1 = set(df1[self.group_col].dropna().tolist())
for j in range(i + 1, len(frames)):
n2, df2 = frames[j]
if self.group_col not in df2.columns:
raise ValueError(f"Missing group_col '{self.group_col}' in {n2}_df.")
overlap = g1 & set(df2[self.group_col].dropna().tolist())
if overlap:
raise ValueError(
f"Entity/group leakage on '{self.group_col}' ({n1} vs {n2}): "
f"{len(overlap)} overlapping entities."
)
if self.strategy == "temporal":
assert self.time_col is not None
for i in range(len(frames) - 1):
n1, df1 = frames[i]
n2, df2 = frames[i + 1]
for nm, df_ in ((n1, df1), (n2, df2)):
if self.time_col not in df_.columns:
raise ValueError(f"Missing time_col '{self.time_col}' in {nm}_df.")
t1 = pd.to_numeric(df1[self.time_col], errors="coerce")
t2 = pd.to_numeric(df2[self.time_col], errors="coerce")
if t1.isna().any() or t2.isna().any():
raise ValueError(f"Non-numeric or NaN timestamps detected in '{self.time_col}'.")
t1_arr = t1.to_numpy(dtype=np.float64)
t2_arr = t2.to_numpy(dtype=np.float64)
if np.any(np.isinf(t1_arr)) or np.any(np.isinf(t2_arr)):
raise ValueError(f"Infinite timestamps detected in '{self.time_col}'.")
if float(np.min(t2_arr)) < float(np.max(t1_arr)) + self.embargo_seconds:
raise ValueError(
f"Temporal embargo violated ({n1} -> {n2}): "
f"min={float(np.min(t2_arr))} < max+embargo={float(np.max(t1_arr)) + self.embargo_seconds}."
)
return {
"passed": True,
"strategy": self.strategy,
"sizes": {name: len(df) for name, df in frames},
}
def _allocate_group_counts(n_groups: int, contract: SplitContract) -> tuple[int, int, int]:
has_val = contract.val_ratio > 0.0
min_groups = 3 if has_val else 2
if n_groups < min_groups:
raise ValueError(f"Need at least {min_groups} distinct groups for split, got {n_groups}.")
if has_val:
n_tr = max(1, round(n_groups * contract.train_ratio))
n_val = max(1, round(n_groups * contract.val_ratio))
if n_tr + n_val >= n_groups:
overflow = (n_tr + n_val) - (n_groups - 1)
reduce_tr = min(overflow, max(0, n_tr - 1))
n_tr -= reduce_tr
overflow -= reduce_tr
if overflow > 0:
n_val = max(1, n_val - overflow)
n_te = n_groups - n_tr - n_val
return n_tr, n_val, n_te
n_tr = max(1, min(n_groups - 1, round(n_groups * contract.train_ratio)))
return n_tr, 0, n_groups - n_tr
def split_dataframe(
df: pd.DataFrame,
contract: SplitContract,
seed: int = 42,
stratify_col: str | None = None,
) -> tuple[pd.DataFrame, pd.DataFrame | None, pd.DataFrame]:
"""Deterministically partition a DataFrame under SplitContract and verify isolation."""
if df.empty:
raise ValueError("Cannot split an empty DataFrame.")
rng = np.random.default_rng(np.random.SeedSequence(int(seed)))
has_val = contract.val_ratio > 0.0
if contract.strategy == "temporal":
assert contract.time_col is not None
if contract.time_col not in df.columns:
raise ValueError(f"Missing time_col '{contract.time_col}' in DataFrame.")
ts = pd.to_numeric(df[contract.time_col], errors="coerce")
if ts.isna().any():
raise ValueError(f"Non-numeric or NaN timestamps detected in '{contract.time_col}'.")
ts_arr = ts.to_numpy(dtype=np.float64)
if np.any(np.isinf(ts_arr)):
raise ValueError(f"Infinite timestamps detected in '{contract.time_col}'.")
order = np.argsort(ts_arr, kind="mergesort")
sorted_df = df.iloc[order]
sorted_ts = ts_arr[order]
n = len(sorted_df)
if contract.embargo_seconds == 0.0:
n_tr = max(1, round(n * contract.train_ratio))
if has_val:
n_val = max(1, round(n * contract.val_ratio))
if n_tr + n_val >= n:
n_tr = max(1, n - 2)
n_val = 1
train_df = sorted_df.iloc[:n_tr].copy()
val_df: pd.DataFrame | None = sorted_df.iloc[n_tr : n_tr + n_val].copy()
test_df = sorted_df.iloc[n_tr + n_val :].copy()
else:
n_tr = min(n - 1, n_tr)
train_df = sorted_df.iloc[:n_tr].copy()
val_df = None
test_df = sorted_df.iloc[n_tr:].copy()
else:
n_tr = max(1, min(n - 1, round(n * contract.train_ratio)))
t_train_end = float(sorted_ts[n_tr - 1])
train_mask = sorted_ts <= t_train_end
post_train_idx = np.flatnonzero(sorted_ts >= t_train_end + contract.embargo_seconds)
if post_train_idx.size == 0:
raise ValueError("Temporal embargo purged all post-training observations.")
train_df = sorted_df.iloc[train_mask].copy()
if has_val:
if post_train_idx.size < 2:
raise ValueError("Insufficient observations remaining after train embargo for val + test.")
val_share = contract.val_ratio / (contract.val_ratio + contract.test_ratio)
n_val_target = max(1, min(int(post_train_idx.size) - 1, round(post_train_idx.size * val_share)))
t_val_end = float(sorted_ts[post_train_idx[n_val_target - 1]])
val_mask = (sorted_ts >= t_train_end + contract.embargo_seconds) & (sorted_ts <= t_val_end)
test_mask = sorted_ts >= t_val_end + contract.embargo_seconds
val_df = sorted_df.iloc[val_mask].copy()
test_df = sorted_df.iloc[test_mask].copy()
else:
val_df = None
test_df = sorted_df.iloc[post_train_idx].copy()
elif contract.strategy == "group":
assert contract.group_col is not None
if contract.group_col not in df.columns:
raise ValueError(f"Missing group_col '{contract.group_col}' in DataFrame.")
if df[contract.group_col].isna().any():
raise ValueError(f"group_col '{contract.group_col}' must not contain NaN values.")
uniq_groups = sorted(df[contract.group_col].unique().tolist(), key=lambda g: (str(type(g)), str(g)))
n_tr_g, n_val_g, _ = _allocate_group_counts(len(uniq_groups), contract)
if stratify_col is not None and stratify_col in df.columns:
grp_df = df[[contract.group_col, stratify_col]].copy()
if pd.api.types.is_numeric_dtype(grp_df[stratify_col]):
scores = grp_df.groupby(contract.group_col)[stratify_col].mean()
ordered = [g for g in scores.sort_values(kind="mergesort").index.tolist()]
else:
modes = grp_df.groupby(contract.group_col)[stratify_col].agg(
lambda s: str(s.mode().iloc[0]) if not s.mode().empty else ""
)
ordered = [g for g in modes.sort_values(kind="mergesort").index.tolist()]
n_buckets = min(5, max(1, len(ordered) // 3))
bucketed: list[list[Any]] = [[] for _ in range(n_buckets)]
for idx_g, g in enumerate(ordered):
bucketed[idx_g % n_buckets].append(g)
permuted_groups: list[Any] = []
for bucket in bucketed:
b_perm = rng.permutation(len(bucket))
permuted_groups.extend(bucket[int(i)] for i in b_perm)
else:
perm_idx = rng.permutation(len(uniq_groups))
permuted_groups = [uniq_groups[int(i)] for i in perm_idx]
tr_groups = set(permuted_groups[:n_tr_g])
val_groups = set(permuted_groups[n_tr_g : n_tr_g + n_val_g])
te_groups = set(permuted_groups[n_tr_g + n_val_g :])
g_series = df[contract.group_col]
train_df = df[g_series.isin(tr_groups)].copy()
val_df = df[g_series.isin(val_groups)].copy() if has_val else None
test_df = df[g_series.isin(te_groups)].copy()
else:
n = len(df)
min_rows = 3 if has_val else 2
if n < min_rows:
raise ValueError(f"Need at least {min_rows} rows for stratified_iid split, got {n}.")
if stratify_col is not None and stratify_col in df.columns:
strata_vals = df[stratify_col].astype("object").where(df[stratify_col].notna(), "__MISSING__").astype(str)
tr_idx: list[int] = []
val_idx: list[int] = []
te_idx: list[int] = []
for key in sorted(strata_vals.unique().tolist()):
pos = np.flatnonzero((strata_vals == key).to_numpy())
perm_pos = pos[rng.permutation(len(pos))]
m = len(perm_pos)
if m == 1:
tr_idx.extend(perm_pos.tolist())
continue
k_tr = max(1, round(m * contract.train_ratio))
if has_val and m >= 3:
k_val = max(1, round(m * contract.val_ratio))
if k_tr + k_val >= m:
k_tr = max(1, m - 2)
k_val = 1
tr_idx.extend(perm_pos[:k_tr].tolist())
val_idx.extend(perm_pos[k_tr : k_tr + k_val].tolist())
te_idx.extend(perm_pos[k_tr + k_val :].tolist())
elif has_val:
tr_idx.append(int(perm_pos[0]))
te_idx.append(int(perm_pos[1]))
else:
k_tr = min(m - 1, k_tr)
tr_idx.extend(perm_pos[:k_tr].tolist())
te_idx.extend(perm_pos[k_tr:].tolist())
if not te_idx and len(tr_idx) > 1:
te_idx.append(tr_idx.pop())
if has_val and not val_idx and len(tr_idx) > 1:
val_idx.append(tr_idx.pop())
train_df = df.iloc[sorted(tr_idx)].copy()
val_df = df.iloc[sorted(val_idx)].copy() if has_val else None
test_df = df.iloc[sorted(te_idx)].copy()
else:
perm = rng.permutation(n)
n_tr = max(1, round(n * contract.train_ratio))
if has_val:
n_val = max(1, round(n * contract.val_ratio))
if n_tr + n_val >= n:
n_tr = max(1, n - 2)
n_val = 1
train_df = df.iloc[np.sort(perm[:n_tr])].copy()
val_df = df.iloc[np.sort(perm[n_tr : n_tr + n_val])].copy()
test_df = df.iloc[np.sort(perm[n_tr + n_val :])].copy()
else:
n_tr = min(n - 1, n_tr)
train_df = df.iloc[np.sort(perm[:n_tr])].copy()
val_df = None
test_df = df.iloc[np.sort(perm[n_tr:])].copy()
contract.verify_splits(train_df, test_df, val_df=val_df)
return train_df, val_df, test_df
class ColumnContract(BaseModel):
"""Per-column structural, null-fraction, range, and sentinel-rejection contract."""
model_config = ConfigDict(frozen=True, extra="forbid")
name: str = Field(..., min_length=1)
dtype_family: Literal["float", "int", "bool", "str"]
nullable: bool = False
max_null_fraction: float = Field(default=0.0, ge=0.0, le=1.0)
min_value: float | None = None
max_value: float | None = None
forbidden_sentinels: tuple[float | int | str, ...] = ()
@model_validator(mode="after")
def _check_bounds(self) -> ColumnContract:
if not self.nullable and self.max_null_fraction > 0.0:
raise ValueError(f"{self.name}: non-nullable column must have max_null_fraction == 0.0.")
if self.min_value is not None and self.max_value is not None and self.min_value > self.max_value:
raise ValueError(f"{self.name}: min_value > max_value.")
return self
class DataContractSchema(BaseModel):
"""Shift-left schema contract catching unit explosions, dtype drift, and sentinel nulls."""
model_config = ConfigDict(frozen=True, extra="forbid")
schema_version: str = Field(..., min_length=1)
columns: tuple[ColumnContract, ...] = Field(..., min_length=1)
allow_extra_columns: bool = False
min_rows: int = Field(default=1, ge=1)
@field_validator("columns")
@classmethod
def _unique_names(cls, cols: tuple[ColumnContract, ...]) -> tuple[ColumnContract, ...]:
if len({c.name for c in cols}) != len(cols):
raise ValueError("Duplicate column names in DataContractSchema.")
return cols
def validate_dataframe(self, df: pd.DataFrame, fail_fast: bool = True) -> dict[str, Any]:
"""Validate schema, dtypes, null fractions, finiteness, bounds, and forbidden sentinels."""
errors: list[str] = []
if len(df) < self.min_rows:
errors.append(f"Row count {len(df)} < min_rows {self.min_rows}.")
exp_names = {c.name for c in self.columns}
act_names = set(df.columns)
if exp_names - act_names:
errors.append(f"Missing required columns: {sorted(exp_names - act_names)}")
if not self.allow_extra_columns and (act_names - exp_names):
errors.append(f"Unexpected extra columns: {sorted(act_names - exp_names)}")
for col in self.columns:
if col.name not in df.columns:
continue
s = df[col.name]
if col.dtype_family == "float" and not pd.api.types.is_float_dtype(s):
errors.append(f"{col.name}: expected float dtype, got {s.dtype}.")
continue
if col.dtype_family == "int" and (
not pd.api.types.is_integer_dtype(s) or pd.api.types.is_bool_dtype(s)
):
errors.append(f"{col.name}: expected integer dtype, got {s.dtype}.")
continue
if col.dtype_family == "bool" and not pd.api.types.is_bool_dtype(s):
errors.append(f"{col.name}: expected bool dtype, got {s.dtype}.")
continue
if col.dtype_family == "str":
if not (pd.api.types.is_string_dtype(s) or pd.api.types.is_object_dtype(s)):
errors.append(f"{col.name}: expected string dtype, got {s.dtype}.")
continue
if pd.api.types.is_object_dtype(s):
non_null = s.dropna().tolist()
if non_null and not all(isinstance(v, str) for v in non_null):
errors.append(f"{col.name}: object column contains non-string elements.")
continue
null_frac = float(s.isna().mean()) if len(s) > 0 else 0.0
if not col.nullable and null_frac > 0.0:
errors.append(f"{col.name}: non-nullable violation (null_frac={null_frac:.4f}).")
elif null_frac > col.max_null_fraction:
errors.append(f"{col.name}: null_frac={null_frac:.4f} > max={col.max_null_fraction:.4f}.")
if col.dtype_family in ("float", "int") and len(s) > 0:
arr = s.to_numpy(dtype=np.float64, copy=False, na_value=np.nan)
if np.any(np.isinf(arr)):
errors.append(f"{col.name}: contains +/-inf values.")
vals = arr[np.isfinite(arr)]
if vals.size > 0:
if col.min_value is not None and float(np.min(vals)) < col.min_value:
errors.append(f"{col.name}: min={float(np.min(vals)):.4g} < {col.min_value}.")
if col.max_value is not None and float(np.max(vals)) > col.max_value:
errors.append(f"{col.name}: max={float(np.max(vals)):.4g} > {col.max_value}.")
for sent in col.forbidden_sentinels:
if col.dtype_family in ("float", "int") and isinstance(sent, (int, float)) and not isinstance(sent, bool):
arr = s.to_numpy(dtype=np.float64, copy=False, na_value=np.nan)
hits = int(np.sum(np.isfinite(arr) & (arr == float(sent))))
else:
hits = int(s.isin([sent]).sum())
if hits > 0:
errors.append(f"{col.name}: {hits} forbidden sentinel(s) {sent!r}.")
if errors and fail_fast:
raise ValueError("DataContractSchema failed:\n - " + "\n - ".join(errors))
return {"passed": not errors, "schema_version": self.schema_version, "errors": errors}
@dataclass(frozen=True, slots=True)
class ReproducibleRngTree:
"""Hierarchical PCG64 RNG tree preventing cross-stage state coupling."""
master_seed: int
split_rng: np.random.Generator
eda_rng: np.random.Generator
oof_rng: np.random.Generator
model_rng: np.random.Generator
@classmethod
def from_master_seed(cls, master_seed: int) -> ReproducibleRngTree:
"""Spawn four independent PCG64 substreams from a single root SeedSequence."""
if int(master_seed) < 0:
raise ValueError("master_seed must be non-negative.")
root_ss = np.random.SeedSequence(int(master_seed))
children = root_ss.spawn(4)
return cls(
master_seed=int(master_seed),
split_rng=np.random.default_rng(children[0]),
eda_rng=np.random.default_rng(children[1]),
oof_rng=np.random.default_rng(children[2]),
model_rng=np.random.default_rng(children[3]),
)
def build_experiment_manifest(
run_name: str,
df: pd.DataFrame,
split_contract: SplitContract,
split_indices: dict[str, list[int] | np.ndarray],
config: dict[str, Any],
state_dicts: dict[str, dict[str, Any]],
root_seed: int = 42,
git_commit_sha: str = "untracked",
git_is_dirty: bool = False,
) -> dict[str, Any]:
"""Produce a deterministic, zero-pickle content-addressed SHA-256 experiment manifest."""
root_ss = np.random.SeedSequence(int(root_seed))
child_seeds = root_ss.spawn(4)
norm_splits = {str(k): [int(i) for i in v] for k, v in sorted(split_indices.items())}
body: dict[str, Any] = {
"manifest_version": "1.0",
"run_name": str(run_name),
"code_provenance": {
"git_commit_sha": str(git_commit_sha),
"git_is_dirty": bool(git_is_dirty),
},
"dataset_sha256": hash_dataframe_sha256(df),
"dataset_shape": [int(df.shape[0]), int(df.shape[1])],
"split_contract": split_contract.model_dump(),
"split_sha256": sha256_bytes(canonical_json(norm_splits).encode("utf-8")),
"config": _to_json_primitive(config),
"config_sha256": sha256_bytes(canonical_json(config).encode("utf-8")),
"state_dicts_sha256": sha256_bytes(canonical_json(state_dicts).encode("utf-8")),
"seed_provenance": {
"root_seed": int(root_seed),
"root_entropy": int(root_ss.entropy),
"child_spawn_keys": {
"split": list(child_seeds[0].spawn_key),
"eda": list(child_seeds[1].spawn_key),
"oof": list(child_seeds[2].spawn_key),
"model": list(child_seeds[3].spawn_key),
},
},
"environment": {
"python": sys.version.split()[0],
"numpy": np.__version__,
"pandas": pd.__version__,
"pydantic": pydantic.__version__,
},
}
body["manifest_sha256"] = sha256_bytes(canonical_json(body).encode("utf-8"))
return body
"""Protocol-driven stateful OOP transformers, zero-pickle JSON serialization, and OOF encoders."""
from __future__ import annotations
import hmac
import json
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Literal, Protocol, runtime_checkable
import numpy as np
import pandas as pd
from lifecycle_eda_lab.contracts_and_lineage import canonical_json, sha256_bytes
_MEAN_AD_TO_SIGMA: float = math.sqrt(math.pi / 2.0) # ~1.2533141373155003
class NotFittedError(RuntimeError):
"""Raised when transform or serialization is invoked prior to fit()."""
@runtime_checkable
class StatefulTransformer(Protocol):
"""Structural PEP 544 Protocol for stateful fit/transform pipeline components."""
def fit(self, X: pd.DataFrame | np.ndarray, y: np.ndarray | pd.Series | None = None) -> Any:
...
def transform(self, X: pd.DataFrame | np.ndarray) -> Any:
...
@dataclass(frozen=True, slots=True)
class FittedStandardizerState:
"""Deeply immutable fitted standardizer parameters with read-only NumPy C buffers."""
mean: np.ndarray
scale: np.ndarray
constant_mask: tuple[bool, ...]
feature_names: tuple[str, ...]
n_samples_seen: int
def __post_init__(self) -> None:
mean_ro = np.array(self.mean, dtype=np.float64, copy=True)
scale_ro = np.array(self.scale, dtype=np.float64, copy=True)
mean_ro.setflags(write=False)
scale_ro.setflags(write=False)
object.__setattr__(self, "mean", mean_ro)
object.__setattr__(self, "scale", scale_ro)
class StatefulStandardizer:
"""Leakage-free standardizer enforcing read-only state buffers and signed JSON persistence."""
def __init__(self, ignore_nan: bool = False, eps: float = 1e-12) -> None:
if not math.isfinite(eps) or eps <= 0.0:
raise ValueError("eps must be finite and strictly positive.")
self.ignore_nan = bool(ignore_nan)
self.eps = float(eps)
self._state: FittedStandardizerState | None = None
@property
def state(self) -> FittedStandardizerState:
"""Return frozen parameter bundle or raise NotFittedError if unfitted."""
if self._state is None:
raise NotFittedError("StatefulStandardizer must be fitted before accessing state.")
return self._state
@property
def feature_names_(self) -> list[str]:
return list(self.state.feature_names)
@property
def means_(self) -> list[float]:
return [float(v) for v in self.state.mean.tolist()]
@property
def scales_(self) -> list[float]:
return [float(v) for v in self.state.scale.tolist()]
@property
def constant_mask_(self) -> list[bool]:
return list(self.state.constant_mask)
@property
def n_samples_seen_(self) -> int:
return self.state.n_samples_seen
def fit(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
columns: list[str] | None = None,
) -> StatefulStandardizer:
"""Estimate feature means and population standard deviations strictly on training data."""
del y
if isinstance(X, pd.DataFrame):
cols = list(X.columns) if columns is None else list(columns)
missing = [c for c in cols if c not in X.columns]
if missing:
raise ValueError(f"Columns missing from DataFrame during fit: {missing}")
arr = X[cols].to_numpy(dtype=np.float64)
else:
arr = np.asarray(X, dtype=np.float64)
if arr.ndim != 2:
raise ValueError(f"Expected 2D array, got shape {arr.shape}.")
cols = [f"f{i}" for i in range(arr.shape[1])] if columns is None else list(columns)
if len(cols) != arr.shape[1]:
raise ValueError("columns length must match array column count.")
if arr.shape[0] == 0 or arr.shape[1] == 0:
raise ValueError("Cannot fit StatefulStandardizer on empty data.")
if np.any(np.isinf(arr)):
raise ValueError("Input contains +/-inf values.")
if not self.ignore_nan and np.any(np.isnan(arr)):
raise ValueError("Input contains NaN and ignore_nan=False.")
means: list[float] = []
scales: list[float] = []
const_mask: list[bool] = []
for j in range(arr.shape[1]):
col_vals = arr[:, j]
if self.ignore_nan:
col_vals = col_vals[np.isfinite(col_vals)]
if col_vals.size == 0:
raise ValueError(f"Column '{cols[j]}' is all-NaN in training split.")
mu = float(np.mean(col_vals))
sd = float(np.std(col_vals, ddof=0))
is_const = sd <= self.eps
means.append(mu)
scales.append(1.0 if is_const else sd)
const_mask.append(is_const)
self._state = FittedStandardizerState(
mean=np.asarray(means, dtype=np.float64),
scale=np.asarray(scales, dtype=np.float64),
constant_mask=tuple(const_mask),
feature_names=tuple(str(c) for c in cols),
n_samples_seen=int(arr.shape[0]),
)
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> pd.DataFrame | np.ndarray:
"""Apply pure, row-wise batch-invariant centering and scaling using frozen parameters."""
st = self.state
is_df = isinstance(X, pd.DataFrame)
if is_df:
missing = [c for c in st.feature_names if c not in X.columns]
if missing:
raise ValueError(f"Missing columns during transform: {missing}")
arr = X[list(st.feature_names)].to_numpy(dtype=np.float64)
else:
arr = np.asarray(X, dtype=np.float64)
if arr.ndim != 2 or arr.shape[1] != len(st.feature_names):
raise ValueError(f"Expected 2D array with {len(st.feature_names)} columns.")
if arr.shape[0] == 0:
raise ValueError("Cannot transform empty data.")
if np.any(np.isinf(arr)):
raise ValueError("Input contains +/-inf values.")
if not self.ignore_nan and np.any(np.isnan(arr)):
raise ValueError("Input contains NaN and ignore_nan=False.")
scaled = (arr - st.mean) / st.scale
if is_df:
out = X.copy()
for idx, col in enumerate(st.feature_names):
out[col] = scaled[:, idx]
return out
return scaled
def fit_transform(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
columns: list[str] | None = None,
) -> pd.DataFrame | np.ndarray:
"""Fit strictly on X and return transformed output."""
return self.fit(X, y=y, columns=columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
"""Serialize learned state to a JSON-safe declarative dictionary."""
st = self.state
return {
"class": "StatefulStandardizer",
"format_version": "1.0",
"ignore_nan": self.ignore_nan,
"eps": self.eps,
"n_samples_seen": st.n_samples_seen,
"feature_names": list(st.feature_names),
"means": [float(v) for v in st.mean.tolist()],
"scales": [float(v) for v in st.scale.tolist()],
"constant_mask": list(st.constant_mask),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> StatefulStandardizer:
"""Reconstruct a fitted StatefulStandardizer from a declarative state dict."""
if state.get("class") != "StatefulStandardizer" or state.get("format_version") != "1.0":
raise ValueError("Invalid or unsupported StatefulStandardizer state dict.")
obj = cls(ignore_nan=bool(state["ignore_nan"]), eps=float(state["eps"]))
names = [str(c) for c in state["feature_names"]]
means = [float(v) for v in state["means"]]
scales = [float(v) for v in state["scales"]]
cmask = [bool(v) for v in state["constant_mask"]]
if not (len(names) == len(means) == len(scales) == len(cmask) > 0):
raise ValueError("Corrupted state dict array lengths.")
if any(not math.isfinite(v) for v in means) or any(
not math.isfinite(v) or v <= 0.0 for v in scales
):
raise ValueError("State dict contains non-finite means or non-positive scales.")
n_seen = int(state["n_samples_seen"])
if n_seen <= 0:
raise ValueError("n_samples_seen must be positive.")
obj._state = FittedStandardizerState(
mean=np.asarray(means, dtype=np.float64),
scale=np.asarray(scales, dtype=np.float64),
constant_mask=tuple(cmask),
feature_names=tuple(names),
n_samples_seen=n_seen,
)
return obj
def to_signed_json(self) -> str:
"""Export canonical JSON embedded with a SHA-256 integrity checksum."""
state = self.to_state_dict()
payload_sha = sha256_bytes(canonical_json(state).encode("utf-8"))
return canonical_json({**state, "payload_sha256": payload_sha})
@classmethod
def from_signed_json(cls, payload: str) -> StatefulStandardizer:
"""Verify SHA-256 payload digest before reconstructing StatefulStandardizer."""
data = json.loads(payload)
if not isinstance(data, dict) or "payload_sha256" not in data:
raise ValueError("Signed JSON missing 'payload_sha256'.")
expected_sha = str(data["payload_sha256"])
state_body = {k: v for k, v in data.items() if k != "payload_sha256"}
actual_sha = sha256_bytes(canonical_json(state_body).encode("utf-8"))
if not hmac.compare_digest(expected_sha, actual_sha):
raise ValueError("Tampered JSON artifact: payload_sha256 mismatch.")
return cls.from_state_dict(state_body)
class RobustMADImputer:
"""
Train-only median imputer with MAD -> MeanAD -> constant scale estimation
and schema-locked binary <col>_is_missing indicator generation.
"""
def __init__(
self,
numeric_cols: list[str] | tuple[str, ...],
add_missing_indicators: bool = True,
consistency_constant: float = 1.4826022,
eps: float = 1e-12,
scale_features: bool = False,
) -> None:
if not numeric_cols:
raise ValueError("numeric_cols must be non-empty.")
if not math.isfinite(consistency_constant) or consistency_constant <= 0.0:
raise ValueError("consistency_constant must be finite and positive.")
if not math.isfinite(eps) or eps <= 0.0:
raise ValueError("eps must be finite and positive.")
self.numeric_cols: tuple[str, ...] = tuple(str(c) for c in numeric_cols)
self.add_missing_indicators = bool(add_missing_indicators)
self.consistency_constant = float(consistency_constant)
self.eps = float(eps)
self.scale_features = bool(scale_features)
self._fitted = False
self.medians_: dict[str, float] = {}
self.mads_: dict[str, float] = {}
self.effective_scales_: dict[str, float] = {}
self.scale_modes_: dict[str, str] = {}
self.indicator_cols_: tuple[str, ...] = ()
def fit(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
) -> RobustMADImputer:
"""Fit column medians, robust scale hierarchy, and missingness indicator schema on train_df."""
del y
if not isinstance(X, pd.DataFrame):
raise TypeError("RobustMADImputer requires a pandas DataFrame.")
if X.empty:
raise ValueError("Cannot fit RobustMADImputer on an empty DataFrame.")
medians: dict[str, float] = {}
mads: dict[str, float] = {}
scales: dict[str, float] = {}
modes: dict[str, str] = {}
for col in self.numeric_cols:
if col not in X.columns:
raise ValueError(f"Column '{col}' missing from X during fit.")
arr = X[col].to_numpy(dtype=np.float64, na_value=np.nan)
if np.any(np.isinf(arr)):
raise ValueError(f"Column '{col}' contains +/-inf values.")
vals = arr[np.isfinite(arr)]
if vals.size == 0:
raise ValueError(f"Column '{col}' is all-NaN in training split.")
med = float(np.median(vals))
abs_dev = np.abs(vals - med)
mad = float(np.median(abs_dev))
if mad > self.eps:
scale = self.consistency_constant * mad
mode = "mad"
else:
mean_ad = float(np.mean(abs_dev))
if mean_ad > self.eps:
scale = _MEAN_AD_TO_SIGMA * mean_ad
mode = "mean_ad_fallback"
else:
scale = 1.0
mode = "constant"
medians[col] = med
mads[col] = mad
scales[col] = scale
modes[col] = mode
self.medians_ = medians
self.mads_ = mads
self.effective_scales_ = scales
self.scale_modes_ = modes
self.indicator_cols_ = (
tuple(f"{c}_is_missing" for c in self.numeric_cols)
if self.add_missing_indicators
else ()
)
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> pd.DataFrame:
"""Impute missing values with frozen train medians and emit binary <col>_is_missing flags."""
if not self._fitted:
raise NotFittedError("RobustMADImputer must be fitted before transform().")
if not isinstance(X, pd.DataFrame):
raise TypeError("RobustMADImputer requires a pandas DataFrame.")
if X.empty:
raise ValueError("Cannot transform an empty DataFrame.")
out = X.copy()
for col in self.numeric_cols:
if col not in out.columns:
raise ValueError(f"Column '{col}' missing from X during transform.")
arr = out[col].to_numpy(dtype=np.float64, na_value=np.nan)
if np.any(np.isinf(arr)):
raise ValueError(f"Column '{col}' contains +/-inf values.")
miss = np.isnan(arr)
filled = np.where(miss, self.medians_[col], arr)
if self.scale_features:
if self.scale_modes_[col] == "constant":
filled = np.zeros_like(filled)
else:
filled = (filled - self.medians_[col]) / self.effective_scales_[col]
out[col] = filled
if self.add_missing_indicators:
out[f"{col}_is_missing"] = miss.astype(np.float64)
return out
def fit_transform(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
) -> pd.DataFrame:
"""Fit on X and return imputed DataFrame."""
return self.fit(X, y=y).transform(X)
def to_state_dict(self) -> dict[str, Any]:
"""Serialize fitted median/scale/indicator metadata to JSON-safe dictionary."""
if not self._fitted:
raise NotFittedError("Cannot serialize an unfitted RobustMADImputer.")
return {
"class": "RobustMADImputer",
"format_version": "1.0",
"numeric_cols": list(self.numeric_cols),
"add_missing_indicators": self.add_missing_indicators,
"consistency_constant": self.consistency_constant,
"eps": self.eps,
"scale_features": self.scale_features,
"medians": dict(self.medians_),
"mads": dict(self.mads_),
"effective_scales": dict(self.effective_scales_),
"scale_modes": dict(self.scale_modes_),
"indicator_cols": list(self.indicator_cols_),
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> RobustMADImputer:
"""Reconstruct a fitted RobustMADImputer from a JSON state dictionary."""
if state.get("class") != "RobustMADImputer" or state.get("format_version") != "1.0":
raise ValueError("Invalid or unsupported RobustMADImputer state dict.")
obj = cls(
numeric_cols=list(state["numeric_cols"]),
add_missing_indicators=bool(state["add_missing_indicators"]),
consistency_constant=float(state["consistency_constant"]),
eps=float(state["eps"]),
scale_features=bool(state.get("scale_features", False)),
)
obj.medians_ = {str(k): float(v) for k, v in state["medians"].items()}
obj.mads_ = {str(k): float(v) for k, v in state["mads"].items()}
obj.effective_scales_ = {str(k): float(v) for k, v in state["effective_scales"].items()}
obj.scale_modes_ = {str(k): str(v) for k, v in state["scale_modes"].items()}
obj.indicator_cols_ = tuple(str(c) for c in state["indicator_cols"])
for col in obj.numeric_cols:
if not math.isfinite(obj.medians_[col]) or not math.isfinite(obj.effective_scales_[col]):
raise ValueError(f"Non-finite imputer parameter for '{col}'.")
if obj.effective_scales_[col] <= 0.0:
raise ValueError(f"Non-positive scale for '{col}'.")
obj._fitted = True
return obj
class OutOfFoldTargetEncoder:
"""
Out-of-Fold Empirical-Bayes m-estimate Target Encoder with rare-bucket pooling.
Use `.fit_transform(X_train, y_train, groups=...)` for leakage-free training encodings
and `.transform(X_eval)` solely on held-out validation, test, or inference inputs.
"""
def __init__(
self,
cols: list[str] | tuple[str, ...],
smoothing_m: float = 10.0,
min_samples: int = 5,
n_folds: int = 5,
seed: int = 42,
missing_token: str = "__MISSING__",
rare_token: str = "__RARE__",
) -> None:
if not cols:
raise ValueError("cols must be non-empty.")
if smoothing_m < 0.0 or not math.isfinite(smoothing_m):
raise ValueError("smoothing_m must be finite and >= 0.")
if min_samples < 1:
raise ValueError("min_samples must be >= 1.")
if n_folds < 2:
raise ValueError("n_folds must be >= 2.")
self.cols = [str(c) for c in cols]
self.smoothing_m = float(smoothing_m)
self.min_samples = int(min_samples)
self.n_folds = int(n_folds)
self.seed = int(seed)
self.missing_token = str(missing_token)
self.rare_token = str(rare_token)
self._fitted = False
self.global_prior_: float = 0.0
self.mappings_: dict[str, dict[str, float]] = {}
self.fallback_values_: dict[str, float] = {}
def _normalize_col(self, series: pd.Series) -> pd.Series:
return series.astype("object").where(series.notna(), self.missing_token).astype(str)
def _fit_single_col_lookup(self, cats: pd.Series, y: np.ndarray) -> tuple[dict[str, float], float]:
global_mean = float(np.mean(y))
vc = cats.value_counts()
rare_cats = set(vc[vc < self.min_samples].index)
pooled = cats.where(~cats.isin(rare_cats), self.rare_token)
agg = (
pd.DataFrame({"cat": pooled.to_numpy(), "y": y})
.groupby("cat", sort=True)["y"]
.agg(["count", "sum"])
)
m = self.smoothing_m
mapping: dict[str, float] = {}
for cat, row in agg.iterrows():
denom = float(row["count"]) + m
mapping[str(cat)] = (
float((float(row["sum"]) + m * global_mean) / denom) if denom > 0.0 else global_mean
)
return mapping, float(mapping.get(self.rare_token, global_mean))
def fit(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
) -> OutOfFoldTargetEncoder:
"""Fit full-training smoothed lookup dictionaries for held-out/inference transforms."""
if not isinstance(X, pd.DataFrame):
raise TypeError("OutOfFoldTargetEncoder requires a pandas DataFrame.")
if X.empty:
raise ValueError("Cannot fit OutOfFoldTargetEncoder on empty DataFrame.")
if y is None:
raise ValueError("OutOfFoldTargetEncoder.fit requires non-None target y.")
y_arr = np.asarray(y, dtype=np.float64)
if y_arr.ndim != 1 or y_arr.size != len(X) or not np.all(np.isfinite(y_arr)):
raise ValueError("y must be a finite 1D array matching len(X).")
for col in self.cols:
if col not in X.columns:
raise ValueError(f"Column '{col}' missing from X.")
self.global_prior_ = float(np.mean(y_arr))
self.mappings_, self.fallback_values_ = {}, {}
for col in self.cols:
mapping, fallback = self._fit_single_col_lookup(self._normalize_col(X[col]), y_arr)
self.mappings_[col] = mapping
self.fallback_values_[col] = fallback
self._fitted = True
return self
def fit_transform(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
groups: np.ndarray | pd.Series | None = None,
) -> pd.DataFrame:
"""Fit full-train dictionary for evaluation and return strict K-fold OOF encodings."""
self.fit(X, y)
assert isinstance(X, pd.DataFrame)
y_arr = np.asarray(y, dtype=np.float64)
n = len(X)
rng = np.random.default_rng(np.random.SeedSequence(self.seed))
if groups is not None:
grp_raw = pd.Series(np.asarray(groups, dtype=object))
grp = grp_raw.where(grp_raw.notna(), self.missing_token).astype(str).to_numpy()
if grp.size != n:
raise ValueError("groups length must match len(X).")
unique_grps = np.unique(grp)
k_eff = min(self.n_folds, len(unique_grps))
if k_eff < 2:
raise ValueError("Need at least 2 distinct groups for OOF target encoding.")
perm = rng.permutation(unique_grps)
grp_to_fold = {g: int(i % k_eff) for i, g in enumerate(perm)}
fold_ids = np.array([grp_to_fold[g] for g in grp], dtype=np.int64)
else:
k_eff = min(self.n_folds, n)
if k_eff < 2:
raise ValueError("Need at least 2 rows for OOF target encoding.")
idx = rng.permutation(n)
fold_ids = np.empty(n, dtype=np.int64)
for pos, i in enumerate(idx):
fold_ids[i] = pos % k_eff
out = X.copy()
for col in self.cols:
cats = self._normalize_col(X[col])
oof_vals = np.empty(n, dtype=np.float64)
for f in range(k_eff):
val_mask = fold_ids == f
mapping, fallback = self._fit_single_col_lookup(
cats.iloc[~val_mask], y_arr[~val_mask]
)
oof_vals[val_mask] = (
cats.iloc[val_mask].map(mapping).fillna(fallback).to_numpy(dtype=np.float64)
)
out[col] = oof_vals
return out
def transform(self, X: pd.DataFrame | np.ndarray) -> pd.DataFrame:
"""Map evaluation/serving categories deterministically using frozen training lookup tables."""
if not self._fitted:
raise NotFittedError("OutOfFoldTargetEncoder must be fitted before transform().")
if not isinstance(X, pd.DataFrame):
raise TypeError("OutOfFoldTargetEncoder requires a pandas DataFrame.")
if X.empty:
raise ValueError("Cannot transform empty DataFrame.")
out = X.copy()
for col in self.cols:
if col not in out.columns:
raise ValueError(f"Column '{col}' missing from X.")
out[col] = (
self._normalize_col(out[col])
.map(self.mappings_[col])
.fillna(self.fallback_values_[col])
.to_numpy(dtype=np.float64)
)
return out
def to_state_dict(self) -> dict[str, Any]:
"""Serialize lookup tables and config strictly as JSON-safe primitives."""
if not self._fitted:
raise NotFittedError("Cannot serialize an unfitted OutOfFoldTargetEncoder.")
return {
"class": "OutOfFoldTargetEncoder",
"format_version": "1.0",
"cols": list(self.cols),
"smoothing_m": self.smoothing_m,
"min_samples": self.min_samples,
"n_folds": self.n_folds,
"seed": self.seed,
"missing_token": self.missing_token,
"rare_token": self.rare_token,
"global_prior": self.global_prior_,
"fallback_values": dict(self.fallback_values_),
"mappings": {c: dict(m) for c, m in self.mappings_.items()},
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> OutOfFoldTargetEncoder:
"""Reconstruct a fitted OutOfFoldTargetEncoder from a declarative state dict."""
if state.get("class") != "OutOfFoldTargetEncoder" or state.get("format_version") != "1.0":
raise ValueError("Invalid or unsupported OutOfFoldTargetEncoder state dict.")
obj = cls(
cols=list(state["cols"]),
smoothing_m=float(state["smoothing_m"]),
min_samples=int(state["min_samples"]),
n_folds=int(state["n_folds"]),
seed=int(state["seed"]),
missing_token=str(state["missing_token"]),
rare_token=str(state["rare_token"]),
)
obj.global_prior_ = float(state["global_prior"])
obj.fallback_values_ = {str(k): float(v) for k, v in state["fallback_values"].items()}
obj.mappings_ = {
str(c): {str(k): float(v) for k, v in m.items()}
for c, m in state["mappings"].items()
}
obj._fitted = True
return obj
class StatefulPipeline:
"""Sequential Protocol-validated pipeline enforcing train-only fit and OOF propagation."""
def __init__(self, steps: Sequence[tuple[str, StatefulTransformer]]) -> None:
if not steps:
raise ValueError("StatefulPipeline requires at least one (name, transformer) step.")
seen_names: set[str] = set()
validated: list[tuple[str, StatefulTransformer]] = []
for name, step in steps:
sname = str(name).strip()
if not sname or sname in seen_names:
raise ValueError(f"Duplicate or empty step name '{name}'.")
if not isinstance(step, StatefulTransformer):
raise TypeError(
f"Step '{sname}' ({type(step).__name__}) does not satisfy StatefulTransformer Protocol."
)
seen_names.add(sname)
validated.append((sname, step))
self.steps = validated
self._fitted = False
@property
def named_steps(self) -> dict[str, StatefulTransformer]:
"""Return mapping from step name to transformer instance."""
return {name: step for name, step in self.steps}
def fit(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
) -> StatefulPipeline:
"""Fit each step sequentially on training data."""
self.fit_transform(X, y=y)
return self
def fit_transform(
self,
X: pd.DataFrame | np.ndarray,
y: np.ndarray | pd.Series | None = None,
) -> pd.DataFrame | np.ndarray:
"""Fit sequentially (preferring OOF fit_transform when available) and return output."""
cur: pd.DataFrame | np.ndarray = X
for _, step in self.steps:
if hasattr(step, "fit_transform"):
cur = step.fit_transform(cur, y)
else:
step.fit(cur, y)
cur = step.transform(cur)
self._fitted = True
return cur
def transform(self, X: pd.DataFrame | np.ndarray) -> pd.DataFrame | np.ndarray:
"""Transform evaluation/serving batches sequentially through frozen pipeline steps."""
if not self._fitted:
raise NotFittedError("StatefulPipeline must be fitted before transform().")
cur: pd.DataFrame | np.ndarray = X
for _, step in self.steps:
cur = step.transform(cur)
return cur
class ColumnRouter:
"""
Protocol-checked column router enforcing explicit remainder handling
(default remainder='error' forbids silent extra-column drops).
"""
def __init__(
self,
routes: Sequence[tuple[str, StatefulTransformer, Sequence[str]]],
remainder: Literal["error", "drop", "passthrough"] = "error",
) -> None:
if not routes:
raise ValueError("ColumnRouter requires at least one route.")
if remainder not in ("error", "drop", "passthrough"):
raise ValueError(f"Unsupported remainder mode '{remainder}'.")
seen_names: set[str] = set()
seen_cols: set[str] = set()
parsed_routes: list[tuple[str, StatefulTransformer, tuple[str, ...]]] = []
for name, transformer, cols in routes:
rname = str(name).strip()
if not rname or rname in seen_names:
raise ValueError(f"Duplicate or empty route name '{name}'.")
if not isinstance(transformer, StatefulTransformer):
raise TypeError(
f"Route '{rname}' transformer does not satisfy StatefulTransformer Protocol."
)
col_tuple = tuple(str(c) for c in cols)
if not col_tuple:
raise ValueError(f"Route '{rname}' must specify >= 1 column.")
overlap = seen_cols & set(col_tuple)
if overlap:
raise ValueError(f"Columns routed multiple times: {sorted(overlap)}")
seen_names.add(rname)
seen_cols.update(col_tuple)
parsed_routes.append((rname, transformer, col_tuple))
self.routes = parsed_routes
self.remainder = remainder
self._fitted = False
self.expected_columns_: tuple[str, ...] = ()
self.passthrough_cols_: tuple[str, ...] = ()
def _validate_columns(self, X: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError("ColumnRouter requires a pandas DataFrame.")
if X.empty:
raise ValueError("ColumnRouter cannot process an empty DataFrame.")
routed_cols = [c for _, _, cols in self.routes for c in cols]
missing = [c for c in routed_cols if c not in X.columns]
if missing:
raise ValueError(f"Missing routed columns: {missing}")
def _run_fit(
self,
X: pd.DataFrame,
y: np.ndarray | pd.Series | None,
use_fit_transform: bool,
) -> pd.DataFrame | None:
self._validate_columns(X)
routed_set = {c for _, _, cols in self.routes for c in cols}
extra_cols = [str(c) for c in X.columns if str(c) not in routed_set]
if self.remainder == "error" and extra_cols:
raise ValueError(
f"Unexpected columns {extra_cols} encountered with remainder='error'."
)
self.expected_columns_ = tuple(str(c) for c in X.columns)
self.passthrough_cols_ = tuple(extra_cols) if self.remainder == "passthrough" else ()
parts: list[pd.DataFrame] = []
for rname, transformer, cols in self.routes:
sub = X[list(cols)].copy()
if use_fit_transform and hasattr(transformer, "fit_transform"):
res = transformer.fit_transform(sub, y)
elif use_fit_transform:
transformer.fit(sub, y)
res = transformer.transform(sub)
else:
transformer.fit(sub, y)
res = None
if res is not None:
parts.append(self._coerce_part(res, rname, cols, X.index))
self._fitted = True
if not use_fit_transform:
return None
if self.passthrough_cols_:
parts.append(X[list(self.passthrough_cols_)].copy())
return pd.concat(parts, axis=1)
@staticmethod
def _coerce_part(
res: pd.DataFrame | np.ndarray,
route_name: str,
cols: tuple[str, ...],
index: pd.Index,
) -> pd.DataFrame:
if isinstance(res, pd.DataFrame):
out = res.copy()
out.index = index
return out
arr = np.asarray(res)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
if arr.shape[1] == len(cols):
col_names = list(cols)
else:
col_names = [f"{route_name}__{i}" for i in range(arr.shape[1])]
return pd.DataFrame(arr, columns=col_names, index=index)
def fit(
self,
X: pd.DataFrame,
y: np.ndarray | pd.Series | None = None,
) -> ColumnRouter:
"""Fit every routed transformer on its explicit column slice."""
self._run_fit(X, y=y, use_fit_transform=False)
return self
def fit_transform(
self,
X: pd.DataFrame,
y: np.ndarray | pd.Series | None = None,
) -> pd.DataFrame:
"""Fit every routed transformer (using OOF fit_transform if supported) and concatenate."""
out = self._run_fit(X, y=y, use_fit_transform=True)
assert out is not None
return out
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform DataFrame columns using frozen route transformers."""
if not self._fitted:
raise NotFittedError("ColumnRouter must be fitted before transform().")
self._validate_columns(X)
if self.remainder == "error":
extra = [str(c) for c in X.columns if str(c) not in self.expected_columns_]
if extra:
raise ValueError(
f"Unexpected columns {extra} during transform with remainder='error'."
)
for pcol in self.passthrough_cols_:
if pcol not in X.columns:
raise ValueError(f"Missing passthrough column '{pcol}' during transform.")
parts: list[pd.DataFrame] = []
for rname, transformer, cols in self.routes:
res = transformer.transform(X[list(cols)].copy())
parts.append(self._coerce_part(res, rname, cols, X.index))
if self.passthrough_cols_:
parts.append(X[list(self.passthrough_cols_)].copy())
return pd.concat(parts, axis=1)
"""Leakage-free EDA diagnostics, pre-split leakage simulations, and SOTA distribution drift suite."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
import pandas as pd
from lifecycle_eda_lab.contracts_and_lineage import (
ColumnContract,
DataContractSchema,
ReproducibleRngTree,
SplitContract,
build_experiment_manifest,
split_dataframe,
)
from lifecycle_eda_lab.pipelines_and_encoders import (
OutOfFoldTargetEncoder,
RobustMADImputer,
StatefulStandardizer,
)
_MEAN_AD_TO_SIGMA: float = math.sqrt(math.pi / 2.0) # ~1.2533141373155003
@dataclass(frozen=True, slots=True)
class MadZScoreResult:
"""Result bundle for Modified MAD Z-score with MeanAD and constant fallbacks."""
median: float
mad: float
effective_scale: float
scale_mode: str # "mad" | "mean_ad_fallback" | "constant"
z_scores: np.ndarray
outlier_mask: np.ndarray
outlier_count: int
@dataclass(frozen=True, slots=True)
class SimpsonAuditResult:
"""Exact Kitagawa-Oaxaca-Blinder Simpson's Paradox decomposition and direct standardization."""
strata_names: tuple[str, ...]
mix_weights_ctrl: tuple[float, ...]
mix_weights_trt: tuple[float, ...]
agg_rate_ctrl: float
agg_rate_trt: float
agg_diff: float
within_stratum_effect: float
mix_shift_confounding: float
direct_std_rate_ctrl: float
direct_std_rate_trt: float
direct_std_diff: float
reversal_detected: bool
@dataclass(frozen=True, slots=True)
class AdversarialAuditResult:
"""Out-of-fold Classifier Two-Sample Test (C2ST) adversarial validation summary."""
auc_adv: float
shift_detected: bool
critical_leakage_alert: bool
feature_importances: dict[str, float]
top_shift_feature: str
n_folds_used: int
include_quadratic: bool
def compute_mad_zscore(
values: np.ndarray | pd.Series | list[float],
consistency_constant: float = 1.4826022,
outlier_threshold: float = 3.5,
) -> MadZScoreResult:
"""
Compute robust Modified MAD Z-score with zero-MAD MeanAD fallback (1.253314 * MeanAD)
and constant-vector zeroing so ZeroDivisionError and +/-inf never occur.
"""
if not math.isfinite(consistency_constant) or consistency_constant <= 0.0:
raise ValueError("consistency_constant must be finite and positive.")
if not math.isfinite(outlier_threshold) or outlier_threshold <= 0.0:
raise ValueError("outlier_threshold must be finite and positive.")
arr = np.asarray(values, dtype=np.float64)
if arr.ndim != 1 or arr.size == 0:
raise ValueError("values must be a non-empty 1D array.")
if np.any(np.isinf(arr)):
raise ValueError("values must not contain +/-inf.")
fin = np.isfinite(arr)
vals = arr[fin]
if vals.size == 0:
raise ValueError("values must contain at least one finite element.")
med = float(np.median(vals))
abs_dev = np.abs(vals - med)
mad = float(np.median(abs_dev))
if mad > 1e-12:
scale = float(consistency_constant) * mad
mode = "mad"
else:
mean_ad = float(np.mean(abs_dev))
if mean_ad > 1e-12:
scale = _MEAN_AD_TO_SIGMA * mean_ad
mode = "mean_ad_fallback"
else:
scale = 1.0
mode = "constant"
z = np.full(arr.shape, np.nan, dtype=np.float64)
z[fin] = 0.0 if mode == "constant" else (vals - med) / scale
out_mask = np.zeros(arr.shape, dtype=bool)
out_mask[fin] = np.abs(z[fin]) > float(outlier_threshold)
return MadZScoreResult(
median=med,
mad=mad,
effective_scale=float(scale),
scale_mode=mode,
z_scores=z,
outlier_mask=out_mask,
outlier_count=int(np.sum(out_mask)),
)
def diagnose_missingness_mechanisms(
train_df: pd.DataFrame,
numeric_cols: list[str] | None = None,
target_col: str | None = None,
corr_threshold: float = 0.12,
) -> dict[str, dict[str, Any]]:
"""
Leakage-free missingness mechanism probe executed strictly on train_df.
Quantifies (1 - p_miss) variance contraction under naive mean imputation
and classifies MCAR-compatible vs MAR (covariate) vs MNAR (target coupled).
"""
if train_df.empty:
raise ValueError("train_df must be non-empty.")
if numeric_cols is None:
numeric_cols = [
str(c)
for c in train_df.columns
if c != target_col
and pd.api.types.is_numeric_dtype(train_df[c])
and not pd.api.types.is_bool_dtype(train_df[c])
]
y_vals: np.ndarray | None = None
if target_col is not None:
if target_col not in train_df.columns:
raise ValueError(f"target_col '{target_col}' not found in train_df.")
y_vals = pd.to_numeric(train_df[target_col], errors="coerce").to_numpy(dtype=np.float64)
report: dict[str, dict[str, Any]] = {}
for col in numeric_cols:
if col not in train_df.columns:
raise ValueError(f"Column '{col}' not found in train_df.")
s = pd.to_numeric(train_df[col], errors="coerce").to_numpy(dtype=np.float64)
miss_mask = np.isnan(s)
p_miss = float(np.mean(miss_mask))
obs = s[~miss_mask]
obs_var = float(np.var(obs, ddof=1)) if obs.size > 1 else 0.0
imp = np.where(miss_mask, float(np.mean(obs)), s) if obs.size > 0 else s
imp_var = float(np.var(imp, ddof=1)) if imp.size > 1 and obs.size > 0 else 0.0
empirical_var_ratio = (imp_var / obs_var) if obs_var > 1e-15 else 1.0
max_cov_corr = 0.0
top_cov: str | None = None
if 0.0 < p_miss < 1.0:
m_float = miss_mask.astype(np.float64)
for other in numeric_cols:
if other == col:
continue
o_arr = pd.to_numeric(train_df[other], errors="coerce").to_numpy(dtype=np.float64)
valid = np.isfinite(o_arr)
if int(np.sum(valid)) < 5:
continue
mv, ov = m_float[valid], o_arr[valid]
if float(np.std(mv)) <= 1e-12 or float(np.std(ov)) <= 1e-12:
continue
r = abs(float(np.corrcoef(mv, ov)[0, 1]))
if math.isfinite(r) and r > max_cov_corr:
max_cov_corr, top_cov = r, other
target_diff = float("nan")
target_corr = 0.0
if y_vals is not None and 0.0 < p_miss < 1.0:
valid_y = np.isfinite(y_vals)
if np.any(miss_mask & valid_y) and np.any((~miss_mask) & valid_y):
target_diff = float(
np.mean(y_vals[miss_mask & valid_y]) - np.mean(y_vals[(~miss_mask) & valid_y])
)
mv, yv = miss_mask[valid_y].astype(np.float64), y_vals[valid_y]
if float(np.std(mv)) > 1e-12 and float(np.std(yv)) > 1e-12:
r_y = abs(float(np.corrcoef(mv, yv)[0, 1]))
if math.isfinite(r_y):
target_corr = r_y
if p_miss == 0.0:
regime = "complete"
elif p_miss == 1.0:
regime = "all_missing"
elif target_corr >= corr_threshold:
regime = "informative_mnar_suspect"
elif max_cov_corr >= corr_threshold:
regime = "mar_covariate_coupled"
else:
regime = "mcar_compatible"
report[col] = {
"missing_rate": p_miss,
"theoretical_var_retention": 1.0 - p_miss,
"empirical_var_retention": empirical_var_ratio,
"max_covariate_corr": max_cov_corr,
"top_coupled_covariate": top_cov,
"target_mean_shift_when_missing": target_diff,
"target_missingness_corr": target_corr,
"regime_flag": regime,
"recommend_missing_indicator": bool(
0.01 <= p_miss < 1.0
and (target_corr >= corr_threshold or max_cov_corr >= corr_threshold)
),
}
return report
def simpson_paradox_audit(
df: pd.DataFrame,
treatment_col: str,
outcome_col: str,
stratum_col: str,
control_label: Any = 0,
treatment_label: Any = 1,
) -> SimpsonAuditResult:
"""
Compute exact within-stratum + mix-shift confounding decomposition (agg_diff =
within_stratum_effect + mix_shift_confounding) and pooled direct standardization.
"""
for col in (treatment_col, outcome_col, stratum_col):
if col not in df.columns:
raise ValueError(f"Column '{col}' missing from DataFrame.")
if df.empty:
raise ValueError("Input DataFrame must be non-empty.")
sub = df[df[treatment_col].isin([control_label, treatment_label])].copy()
if sub.empty:
raise ValueError("No rows match control_label or treatment_label.")
y_num = pd.to_numeric(sub[outcome_col], errors="coerce")
if y_num.isna().any():
raise ValueError(f"outcome_col '{outcome_col}' contains non-numeric or NaN values.")
sub["_y_num"] = y_num.to_numpy(dtype=np.float64)
ctrl_df = sub[sub[treatment_col] == control_label]
trt_df = sub[sub[treatment_col] == treatment_label]
n_ctrl_total = len(ctrl_df)
n_trt_total = len(trt_df)
if n_ctrl_total == 0 or n_trt_total == 0:
raise ValueError("Both control_label and treatment_label must be present.")
strata_raw = sorted(sub[stratum_col].dropna().unique().tolist(), key=lambda x: str(x))
if not strata_raw:
raise ValueError("stratum_col has no non-null strata.")
strata_names: list[str] = []
w_ctrl: list[float] = []
w_trt: list[float] = []
w_pool: list[float] = []
r_ctrl: list[float] = []
r_trt: list[float] = []
n_total = float(n_ctrl_total + n_trt_total)
for s_val in strata_raw:
c_s = ctrl_df[ctrl_df[stratum_col] == s_val]
t_s = trt_df[trt_df[stratum_col] == s_val]
if c_s.empty or t_s.empty:
raise ValueError(
f"Positivity violated in stratum {s_val!r}: both control and treatment arms required."
)
strata_names.append(str(s_val))
w_ctrl.append(len(c_s) / float(n_ctrl_total))
w_trt.append(len(t_s) / float(n_trt_total))
w_pool.append((len(c_s) + len(t_s)) / n_total)
r_ctrl.append(float(c_s["_y_num"].mean()))
r_trt.append(float(t_s["_y_num"].mean()))
agg_ctrl = float(sum(wc * rc for wc, rc in zip(w_ctrl, r_ctrl)))
agg_trt = float(sum(wt * rt for wt, rt in zip(w_trt, r_trt)))
agg_diff = agg_trt - agg_ctrl
within_eff = float(sum(wt * (rt - rc) for wt, rc, rt in zip(w_trt, r_ctrl, r_trt)))
mix_shift = float(sum((wt - wc) * rc for wt, wc, rc in zip(w_trt, w_ctrl, r_ctrl)))
std_ctrl = float(sum(wp * rc for wp, rc in zip(w_pool, r_ctrl)))
std_trt = float(sum(wp * rt for wp, rt in zip(w_pool, r_trt)))
std_diff = std_trt - std_ctrl
stratum_diffs = [rt - rc for rc, rt in zip(r_ctrl, r_trt)]
unanimous_negative = all(d < -1e-12 for d in stratum_diffs)
unanimous_positive = all(d > 1e-12 for d in stratum_diffs)
reversal = bool(
(agg_diff > 1e-12 and unanimous_negative)
or (agg_diff < -1e-12 and unanimous_positive)
or (agg_diff * std_diff < -1e-12)
)
return SimpsonAuditResult(
strata_names=tuple(strata_names),
mix_weights_ctrl=tuple(w_ctrl),
mix_weights_trt=tuple(w_trt),
agg_rate_ctrl=agg_ctrl,
agg_rate_trt=agg_trt,
agg_diff=agg_diff,
within_stratum_effect=within_eff,
mix_shift_confounding=mix_shift,
direct_std_rate_ctrl=std_ctrl,
direct_std_rate_trt=std_trt,
direct_std_diff=std_diff,
reversal_detected=reversal,
)
def _ols_r2_and_corr(
X_tr: np.ndarray,
y_tr: np.ndarray,
X_te: np.ndarray,
y_te: np.ndarray,
) -> tuple[float, float, float]:
"""Fit unregularized OLS with intercept on train and return (r2_in, r2_te, corr_te)."""
A_tr = np.column_stack([np.ones(len(y_tr), dtype=np.float64), X_tr])
A_te = np.column_stack([np.ones(len(y_te), dtype=np.float64), X_te])
beta, _, _, _ = np.linalg.lstsq(A_tr, y_tr, rcond=None)
pred_tr = A_tr @ beta
pred_te = A_te @ beta
sst_tr = float(np.sum((y_tr - np.mean(y_tr)) ** 2))
r2_in = 1.0 - float(np.sum((y_tr - pred_tr) ** 2)) / sst_tr if sst_tr > 1e-15 else 0.0
sst_te = float(np.sum((y_te - np.mean(y_te)) ** 2))
r2_te = 1.0 - float(np.sum((y_te - pred_te) ** 2)) / sst_te if sst_te > 1e-15 else 0.0
sd_y = float(np.std(y_te))
sd_p = float(np.std(pred_te))
if sd_y > 1e-12 and sd_p > 1e-12:
corr_te = float(np.corrcoef(y_te, pred_te)[0, 1])
else:
corr_te = 0.0
return r2_in, r2_te, corr_te
def simulate_presplit_leakage_audit(
n_samples: int = 100,
n_features: int = 2000,
top_k: int = 10,
n_trials: int = 60,
seed: int = 42,
) -> dict[str, Any]:
"""
Empirically verify Proof 1 (pre-split centering induces -1.0 cross-split residual mean
correlation and attenuates test shift to alpha_tr * delta_mu) and Proof 2 (ESL 7.10.2
high-dimensional pure-noise screening illusion).
"""
if n_samples < 20:
raise ValueError("n_samples must be >= 20.")
if n_features < top_k or top_k < 1:
raise ValueError("Require n_features >= top_k >= 1.")
if n_trials < 5:
raise ValueError("n_trials must be >= 5.")
rng = np.random.default_rng(np.random.SeedSequence(int(seed)))
n_tr = n_samples // 2
if top_k >= n_tr - 1:
raise ValueError("top_k must be < n_samples // 2 - 1 for well-posed OLS.")
# Proof 1: Pre-split global centering anti-correlation & shift compression
n_p1 = max(n_trials, 40)
alpha_tr = 0.70
n_tr_p1 = round(alpha_tr * n_samples)
tr_means = np.empty(n_p1, dtype=np.float64)
te_means = np.empty(n_p1, dtype=np.float64)
delta_mu = 2.0
shifted_te_residuals = np.empty(n_p1, dtype=np.float64)
for t in range(n_p1):
x_iid = rng.standard_normal(n_samples)
x_c = x_iid - float(np.mean(x_iid))
tr_means[t] = float(np.mean(x_c[:n_tr_p1]))
te_means[t] = float(np.mean(x_c[n_tr_p1:]))
x_shift = rng.standard_normal(n_samples)
x_shift[n_tr_p1:] += delta_mu
x_shift_c = x_shift - float(np.mean(x_shift))
shifted_te_residuals[t] = float(np.mean(x_shift_c[n_tr_p1:]))
centering_corr = float(np.corrcoef(tr_means, te_means)[0, 1])
observed_shift_ratio = float(np.mean(shifted_te_residuals)) / delta_mu
# Proof 2: Pure white-noise high-d top-k screening (Pre-Split vs Split-First)
pre_r2_in, pre_r2_te, pre_corr_te = [], [], []
clean_r2_in, clean_r2_te, clean_corr_te = [], [], []
for _ in range(n_trials):
X = rng.standard_normal((n_samples, n_features))
y = rng.standard_normal(n_samples)
X_tr, y_tr = X[:n_tr], y[:n_tr]
X_te, y_te = X[n_tr:], y[n_tr:]
# Leaked pre-split screening across all N rows
Xc_all = X - np.mean(X, axis=0)
yc_all = y - float(np.mean(y))
denom_all = np.sqrt(np.sum(Xc_all * Xc_all, axis=0)) * float(np.linalg.norm(yc_all))
corr_all = np.abs((Xc_all.T @ yc_all) / np.maximum(denom_all, 1e-12))
sel_pre = np.argpartition(corr_all, -top_k)[-top_k:]
r2_i_l, r2_t_l, c_t_l = _ols_r2_and_corr(X_tr[:, sel_pre], y_tr, X_te[:, sel_pre], y_te)
pre_r2_in.append(r2_i_l)
pre_r2_te.append(r2_t_l)
pre_corr_te.append(c_t_l)
# Clean split-first screening strictly inside training fold
Xc_tr = X_tr - np.mean(X_tr, axis=0)
yc_tr = y_tr - float(np.mean(y_tr))
denom_tr = np.sqrt(np.sum(Xc_tr * Xc_tr, axis=0)) * float(np.linalg.norm(yc_tr))
corr_tr = np.abs((Xc_tr.T @ yc_tr) / np.maximum(denom_tr, 1e-12))
sel_clean = np.argpartition(corr_tr, -top_k)[-top_k:]
r2_i_c, r2_t_c, c_t_c = _ols_r2_and_corr(X_tr[:, sel_clean], y_tr, X_te[:, sel_clean], y_te)
clean_r2_in.append(r2_i_c)
clean_r2_te.append(r2_t_c)
clean_corr_te.append(c_t_c)
return {
"n_samples": int(n_samples),
"n_features": int(n_features),
"top_k": int(top_k),
"n_trials": int(n_trials),
"pre_split": {
"r2_in": float(np.mean(pre_r2_in)),
"r2_te": float(np.mean(pre_r2_te)),
"corr_te": float(np.mean(pre_corr_te)),
},
"split_first": {
"r2_in": float(np.mean(clean_r2_in)),
"r2_te": float(np.mean(clean_r2_te)),
"corr_te": float(np.mean(clean_corr_te)),
},
"centering_cross_split_corr": centering_corr,
"centering_expected_shift_ratio": float(n_tr_p1 / float(n_samples)),
"centering_observed_shift_ratio": float(observed_shift_ratio),
}
def _make_bin_edges(expected: np.ndarray, bins: int, strategy: str) -> np.ndarray:
if strategy == "quantile":
edges = np.quantile(expected, np.linspace(0.0, 1.0, bins + 1))
elif strategy == "uniform":
edges = np.linspace(float(np.min(expected)), float(np.max(expected)), bins + 1)
else:
raise ValueError(f"Unknown binning strategy '{strategy}'.")
u = np.unique(edges)
if u.size <= 2:
return np.array([-np.inf, np.inf], dtype=np.float64)
return np.concatenate(([-np.inf], u[1:-1], [np.inf]))
def compute_psi(
expected: np.ndarray | list[float],
actual: np.ndarray | list[float],
bins: int = 10,
strategy: Literal["quantile", "uniform"] = "quantile",
eps: float = 1e-6,
include_nan_bin: bool = True,
) -> dict[str, Any]:
"""
Compute Population Stability Index (Jeffreys KL) using reference-frozen bins,
infinite outer padding, tie deduplication, explicit NaN bin, and exact
leading null bias (B_eff - 1) * (1/n_ref + 1/n_cur).
"""
if bins < 2:
raise ValueError("bins must be >= 2.")
if not math.isfinite(eps) or eps <= 0.0:
raise ValueError("eps must be finite and positive.")
exp = np.asarray(expected, dtype=np.float64)
act = np.asarray(actual, dtype=np.float64)
if exp.ndim != 1 or act.ndim != 1 or exp.size == 0 or act.size == 0:
raise ValueError("expected and actual must be non-empty 1D arrays.")
if np.any(np.isinf(exp)) or np.any(np.isinf(act)):
raise ValueError("Inputs must not contain +/-inf.")
exp_nan, act_nan = int(np.sum(np.isnan(exp))), int(np.sum(np.isnan(act)))
ef, af = exp[~np.isnan(exp)], act[~np.isnan(act)]
if ef.size == 0 or af.size == 0:
raise ValueError("Both expected and actual require >= 1 finite value.")
if float(np.ptp(ef)) <= 1e-15:
c = float(ef[0])
ec = np.array([float(ef.size), 0.0], dtype=np.float64)
m = int(np.sum(np.abs(af - c) <= 1e-12))
ac = np.array([float(m), float(af.size - m)], dtype=np.float64)
else:
edges = _make_bin_edges(ef, bins=bins, strategy=strategy)
ec = np.histogram(ef, bins=edges)[0].astype(np.float64)
ac = np.histogram(af, bins=edges)[0].astype(np.float64)
if include_nan_bin and (exp_nan > 0 or act_nan > 0):
ec = np.append(ec, float(exp_nan))
ac = np.append(ac, float(act_nan))
p = np.clip(ec / float(np.sum(ec)), eps, None)
p /= float(np.sum(p))
q = np.clip(ac / float(np.sum(ac)), eps, None)
q /= float(np.sum(q))
psi = float(np.sum((q - p) * np.log(q / p)))
b_eff = int(p.size)
n_ref = int(exp.size if include_nan_bin else ef.size)
n_cur = int(act.size if include_nan_bin else af.size)
null_bias = float((b_eff - 1) * (1.0 / n_ref + 1.0 / n_cur))
return {
"psi": psi,
"effective_bins": b_eff,
"expected_null_psi_bias": null_bias,
"small_sample_noise_risk": bool(n_cur < 200 or psi < 2.0 * null_bias),
"severity": "critical" if psi >= 0.25 else ("moderate" if psi >= 0.10 else "stable"),
}
def compute_jsd(
expected: np.ndarray | list[float],
actual: np.ndarray | list[float],
bins: int = 10,
strategy: Literal["quantile", "uniform"] = "quantile",
eps: float = 1e-12,
base: Literal["bits", "nats"] = "bits",
) -> float:
"""
Symmetric Jensen-Shannon Divergence strictly bounded in [0.0, 1.0] (base='bits')
or [0.0, ln 2] (base='nats').
"""
if bins < 2:
raise ValueError("bins must be >= 2.")
if base not in ("bits", "nats"):
raise ValueError("base must be 'bits' or 'nats'.")
exp = np.asarray(expected, dtype=np.float64)
act = np.asarray(actual, dtype=np.float64)
if exp.ndim != 1 or act.ndim != 1 or exp.size == 0 or act.size == 0:
raise ValueError("expected and actual must be non-empty 1D arrays.")
if np.any(np.isinf(exp)) or np.any(np.isinf(act)):
raise ValueError("Inputs must not contain +/-inf.")
ef, af = exp[np.isfinite(exp)], act[np.isfinite(act)]
if ef.size == 0 or af.size == 0:
raise ValueError("Inputs must contain finite values.")
if float(np.ptp(ef)) <= 1e-15:
c = float(ef[0])
ec = np.array([float(ef.size), 0.0], dtype=np.float64)
m_cnt = int(np.sum(np.abs(af - c) <= 1e-12))
ac = np.array([float(m_cnt), float(af.size - m_cnt)], dtype=np.float64)
else:
edges = _make_bin_edges(ef, bins=bins, strategy=strategy)
ec = np.histogram(ef, bins=edges)[0].astype(np.float64)
ac = np.histogram(af, bins=edges)[0].astype(np.float64)
p = ec / float(np.sum(ec))
q = ac / float(np.sum(ac))
m_mix = 0.5 * (p + q)
log_fn = np.log2 if base == "bits" else np.log
upper = 1.0 if base == "bits" else math.log(2.0)
kl_pm = float(
np.sum(np.where(p > 0.0, p * log_fn(np.maximum(p, eps) / np.maximum(m_mix, eps)), 0.0))
)
kl_qm = float(
np.sum(np.where(q > 0.0, q * log_fn(np.maximum(q, eps) / np.maximum(m_mix, eps)), 0.0))
)
return float(max(0.0, min(upper, 0.5 * (kl_pm + kl_qm))))
def compute_wasserstein_1d(
u_values: np.ndarray | list[float],
v_values: np.ndarray | list[float],
) -> float:
"""Exact 1D empirical Earth Mover's Distance W_1(P, Q) via merged CDF step integration."""
u = np.asarray(u_values, dtype=np.float64)
v = np.asarray(v_values, dtype=np.float64)
if u.ndim != 1 or v.ndim != 1 or u.size == 0 or v.size == 0:
raise ValueError("Inputs must be non-empty 1D arrays.")
if np.any(np.isinf(u)) or np.any(np.isinf(v)):
raise ValueError("Inputs must not contain +/-inf.")
uf, vf = u[np.isfinite(u)], v[np.isfinite(v)]
if uf.size == 0 or vf.size == 0:
raise ValueError("Both inputs must contain at least one finite value.")
us, vs = np.sort(uf), np.sort(vf)
all_v = np.concatenate([us, vs])
all_v.sort(kind="mergesort")
cu = np.searchsorted(us, all_v[:-1], side="right") / float(us.size)
cv = np.searchsorted(vs, all_v[:-1], side="right") / float(vs.size)
return float(np.sum(np.abs(cu - cv) * np.diff(all_v)))
def compute_normalized_wasserstein_1d(
ref_values: np.ndarray | list[float],
cur_values: np.ndarray | list[float],
) -> float:
"""Dimensionless W_1 scaled by max(IQR_ref, 1.4826 * MAD_ref, 1e-12)."""
w1 = compute_wasserstein_1d(ref_values, cur_values)
ref = np.asarray(ref_values, dtype=np.float64)
rf = ref[np.isfinite(ref)]
q75, q25 = np.percentile(rf, [75.0, 25.0])
iqr = float(q75 - q25)
mad = float(np.median(np.abs(rf - np.median(rf))))
scale = max(iqr, 1.4826022 * mad, 1e-12)
return float(w1 / scale)
def ks_survival_prob(lam: float) -> float:
"""
Evaluate Kolmogorov survival probability Q_KS(lam) in pure Python stdlib:
Jacobi theta Poisson dual series for lam < 0.27 and alternating series for lam >= 0.27.
"""
if math.isnan(lam) or lam < 0.0:
raise ValueError(f"lam must be non-negative and non-NaN, got {lam!r}.")
if math.isinf(lam):
return 0.0
if lam <= 1e-12:
return 1.0
if lam < 0.27:
total = 0.0
inv_denom = 1.0 / (8.0 * lam * lam)
pi_sq = math.pi * math.pi
for k in range(1, 60):
odd = 2 * k - 1
term = math.exp(-(odd * odd) * pi_sq * inv_denom)
total += term
if term <= 1e-16:
break
prob = 1.0 - (math.sqrt(2.0 * math.pi) / lam) * total
return float(max(0.0, min(1.0, prob)))
total = 0.0
lam_sq2 = 2.0 * lam * lam
for k in range(1, 200):
term = ((-1.0) ** (k - 1)) * math.exp(-(k * k) * lam_sq2)
total += term
if abs(term) <= 1e-16:
break
return float(max(0.0, min(1.0, 2.0 * total)))
def compute_ks_statistic(
u_values: np.ndarray | list[float],
v_values: np.ndarray | list[float],
) -> dict[str, float]:
"""Two-sample Kolmogorov-Smirnov supremum statistic with Stephens refinement and dual-series p-value."""
u = np.asarray(u_values, dtype=np.float64)
v = np.asarray(v_values, dtype=np.float64)
if u.ndim != 1 or v.ndim != 1 or u.size == 0 or v.size == 0:
raise ValueError("Inputs must be non-empty 1D arrays.")
if np.any(np.isinf(u)) or np.any(np.isinf(v)):
raise ValueError("Inputs must not contain +/-inf.")
uf, vf = u[np.isfinite(u)], v[np.isfinite(v)]
if uf.size == 0 or vf.size == 0:
raise ValueError("Both inputs must contain at least one finite value.")
us, vs = np.sort(uf), np.sort(vf)
av = np.unique(np.concatenate([us, vs]))
d_stat = float(
np.max(
np.abs(
np.searchsorted(us, av, side="right") / float(us.size)
- np.searchsorted(vs, av, side="right") / float(vs.size)
)
)
)
n_eff = (us.size * vs.size) / float(us.size + vs.size)
sq_n = math.sqrt(n_eff)
lam = (sq_n + 0.12 + 0.11 / sq_n) * d_stat
return {
"ks_stat": d_stat,
"p_value": ks_survival_prob(lam),
"n_eff": float(n_eff),
}
def compute_roc_auc(
y_true: np.ndarray | list[int],
y_score: np.ndarray | list[float],
) -> float:
"""Exact tie-aware Mann-Whitney U rank concordance ROC-AUC."""
y = np.asarray(y_true, dtype=np.int64)
s = np.asarray(y_score, dtype=np.float64)
if y.ndim != 1 or s.ndim != 1 or y.size != s.size or y.size == 0:
raise ValueError("y_true and y_score must be non-empty 1D arrays of equal length.")
if not np.all(np.isfinite(s)):
raise ValueError("y_score contains non-finite values.")
n_pos, n_neg = int(np.sum(y == 1)), int(np.sum(y == 0))
if n_pos == 0 or n_neg == 0 or (n_pos + n_neg) != y.size:
raise ValueError("y_true must be binary {0, 1} with both classes present.")
order = np.argsort(s, kind="mergesort")
ss = s[order]
ranks = np.empty(y.size, dtype=np.float64)
i = 0
while i < y.size:
j = i + 1
while j < y.size and ss[j] == ss[i]:
j += 1
ranks[order[i:j]] = 0.5 * ((i + 1) + j)
i = j
u_stat = float(np.sum(ranks[y == 1])) - n_pos * (n_pos + 1) / 2.0
return float(u_stat / (n_pos * n_neg))
def _logistic_loss(Xb: np.ndarray, y: np.ndarray, th: np.ndarray, l2_reg: float) -> float:
z = Xb @ th
# Overflow-proof softplus(z) = log(1 + exp(z)) = log1p(exp(-|z|)) + max(z, 0)
softplus = np.log1p(np.exp(-np.abs(z))) + np.maximum(z, 0.0)
nll = float(np.sum(softplus - y * z))
reg = 0.5 * l2_reg * float(np.dot(th[:-1], th[:-1]))
return nll + reg
def _fit_l2_logistic_newton(
X: np.ndarray,
y: np.ndarray,
l2_reg: float = 1.0,
max_iter: int = 40,
tol: float = 1e-7,
) -> tuple[np.ndarray, float]:
"""Damped Newton-Raphson solver with Armijo backtracking for L2-regularized logistic regression."""
n, d = X.shape
eye = np.eye(d + 1, dtype=np.float64)
eye[-1, -1] = 0.0
Xb = np.column_stack([X, np.ones(n, dtype=np.float64)])
th = np.zeros(d + 1, dtype=np.float64)
cur_obj = _logistic_loss(Xb, y, th, l2_reg)
for _ in range(max_iter):
z = np.clip(Xb @ th, -35.0, 35.0)
p = 1.0 / (1.0 + np.exp(-z))
g = Xb.T @ (p - y) + l2_reg * np.append(th[:-1], 0.0)
w = np.maximum(p * (1.0 - p), 1e-8)
H = (Xb.T * w) @ Xb + l2_reg * eye + 1e-8 * np.eye(d + 1)
try:
neg_step = np.linalg.solve(H, g)
except np.linalg.LinAlgError:
neg_step, _, _, _ = np.linalg.lstsq(H, g, rcond=None)
direction = -neg_step
slope = float(np.dot(g, direction))
alpha = 1.0
th_next = th + alpha * direction
next_obj = _logistic_loss(Xb, y, th_next, l2_reg)
while next_obj > cur_obj + 1e-4 * alpha * slope and alpha > 1e-6:
alpha *= 0.5
th_next = th + alpha * direction
next_obj = _logistic_loss(Xb, y, th_next, l2_reg)
step_vec = th_next - th
th = th_next
cur_obj = next_obj
if float(np.max(np.abs(step_vec))) < tol:
break
return th[:-1], float(th[-1])
def _expand_quadratic(X: np.ndarray, names: list[str]) -> tuple[np.ndarray, list[str]]:
d = X.shape[1]
cols_list = [X]
out_names = list(names)
sq_cols = [X[:, j : j + 1] ** 2 for j in range(d)]
cols_list.extend(sq_cols)
out_names.extend(f"{names[j]}^2" for j in range(d))
for i in range(d):
for j in range(i + 1, d):
cols_list.append((X[:, i] * X[:, j])[:, None])
out_names.append(f"{names[i]}*{names[j]}")
return np.hstack(cols_list), out_names
def adversarial_validation_oof_auc(
X_train: pd.DataFrame | np.ndarray,
X_test: pd.DataFrame | np.ndarray,
feature_names: list[str] | None = None,
n_splits: int = 5,
l2_reg: float = 1.0,
include_quadratic: bool = False,
seed: int = 42,
) -> AdversarialAuditResult:
"""
Pure-NumPy K-fold Out-of-Fold Adversarial Validation (train=0 vs test=1).
Performs fold-isolated median imputation, standardization, and optional quadratic
feature expansion inside every fold to catch both marginal and rotation shifts.
"""
if isinstance(X_train, pd.DataFrame) and isinstance(X_test, pd.DataFrame):
cols = list(X_train.columns) if feature_names is None else list(feature_names)
missing_tr = [c for c in cols if c not in X_train.columns]
missing_te = [c for c in cols if c not in X_test.columns]
if missing_tr or missing_te:
raise ValueError(f"Missing columns: train={missing_tr}, test={missing_te}")
x_tr = X_train[cols].to_numpy(dtype=np.float64)
x_te = X_test[cols].to_numpy(dtype=np.float64)
else:
x_tr = np.asarray(X_train, dtype=np.float64)
x_te = np.asarray(X_test, dtype=np.float64)
if x_tr.ndim != 2 or x_te.ndim != 2 or x_tr.shape[1] != x_te.shape[1]:
raise ValueError("X_train and X_test must be 2D arrays with equal column count.")
cols = [f"f{i}" for i in range(x_tr.shape[1])] if feature_names is None else list(feature_names)
if len(cols) != x_tr.shape[1]:
raise ValueError("feature_names length must match column count.")
if x_tr.shape[0] < 2 or x_te.shape[0] < 2 or x_tr.shape[1] == 0:
raise ValueError("Need >= 2 rows in both splits and >= 1 feature.")
if np.any(np.isinf(x_tr)) or np.any(np.isinf(x_te)):
raise ValueError("Inputs must not contain +/-inf.")
X_adv = np.vstack([x_tr, x_te])
y_adv = np.concatenate(
[np.zeros(x_tr.shape[0], dtype=np.int64), np.ones(x_te.shape[0], dtype=np.int64)]
)
k_eff = min(max(2, int(n_splits)), x_tr.shape[0], x_te.shape[0])
rng = np.random.default_rng(np.random.SeedSequence(int(seed)))
fold_ids = np.empty(y_adv.size, dtype=np.int64)
for cls_val in (0, 1):
idx = np.flatnonzero(y_adv == cls_val)
rng.shuffle(idx)
for pos, row_i in enumerate(idx):
fold_ids[row_i] = pos % k_eff
if include_quadratic:
_, eval_names = _expand_quadratic(X_adv[:1], cols)
else:
eval_names = list(cols)
oof = np.empty(y_adv.size, dtype=np.float64)
abs_w = np.zeros(len(eval_names), dtype=np.float64)
for f in range(k_eff):
vm = fold_ids == f
tm = ~vm
Xf_tr, Xf_val = X_adv[tm].copy(), X_adv[vm].copy()
for j in range(Xf_tr.shape[1]):
fin = np.isfinite(Xf_tr[:, j])
med = float(np.median(Xf_tr[fin, j])) if np.any(fin) else 0.0
Xf_tr[~fin, j] = med
Xf_val[~np.isfinite(Xf_val[:, j]), j] = med
mu = np.mean(Xf_tr, axis=0)
sd_raw = np.std(Xf_tr, axis=0)
sd = np.where(sd_raw > 1e-12, sd_raw, 1.0)
Xf_tr_std = (Xf_tr - mu) / sd
Xf_val_std = (Xf_val - mu) / sd
if include_quadratic:
Xf_tr_exp, _ = _expand_quadratic(Xf_tr_std, cols)
Xf_val_exp, _ = _expand_quadratic(Xf_val_std, cols)
mu_e = np.mean(Xf_tr_exp, axis=0)
sd_e_raw = np.std(Xf_tr_exp, axis=0)
sd_e = np.where(sd_e_raw > 1e-12, sd_e_raw, 1.0)
Xf_tr_in = (Xf_tr_exp - mu_e) / sd_e
Xf_val_in = (Xf_val_exp - mu_e) / sd_e
else:
Xf_tr_in = Xf_tr_std
Xf_val_in = Xf_val_std
w, b = _fit_l2_logistic_newton(
Xf_tr_in, y_adv[tm].astype(np.float64), l2_reg=float(l2_reg)
)
logits = np.clip(Xf_val_in @ w + b, -35.0, 35.0)
oof[vm] = 1.0 / (1.0 + np.exp(-logits))
abs_w += np.abs(w) / float(k_eff)
auc_adv = compute_roc_auc(y_adv, oof)
ranked = sorted(
[(eval_names[j], float(abs_w[j])) for j in range(len(eval_names))],
key=lambda kv: kv[1],
reverse=True,
)
return AdversarialAuditResult(
auc_adv=float(auc_adv),
shift_detected=bool(auc_adv > 0.65),
critical_leakage_alert=bool(auc_adv > 0.80),
feature_importances=dict(ranked),
top_shift_feature=ranked[0][0],
n_folds_used=int(k_eff),
include_quadratic=bool(include_quadratic),
)
def _pairwise_sq_dists(A: np.ndarray, B: np.ndarray) -> np.ndarray:
a_sq = np.sum(A * A, axis=1, keepdims=True)
b_sq = np.sum(B * B, axis=1, keepdims=True).T
return np.maximum(0.0, a_sq + b_sq - 2.0 * (A @ B.T))
def compute_rbf_mmd_u2(
X_ref: np.ndarray | pd.DataFrame,
X_cur: np.ndarray | pd.DataFrame,
bandwidth: float | None = None,
max_samples: int = 400,
seed: int = 42,
) -> dict[str, float]:
"""
Compute unbiased U-statistic RBF Maximum Mean Discrepancy (MMD_u^2)
with median-heuristic bandwidth selection.
"""
Xr = np.asarray(X_ref, dtype=np.float64)
Xc = np.asarray(X_cur, dtype=np.float64)
if Xr.ndim != 2 or Xc.ndim != 2 or Xr.shape[1] != Xc.shape[1] or Xr.shape[1] == 0:
raise ValueError("X_ref and X_cur must be 2D arrays with equal non-zero feature count.")
if Xr.shape[0] < 2 or Xc.shape[0] < 2:
raise ValueError("Both X_ref and X_cur require >= 2 samples for unbiased U-statistic.")
if not np.all(np.isfinite(Xr)) or not np.all(np.isfinite(Xc)):
raise ValueError("X_ref and X_cur must be strictly finite.")
rng = np.random.default_rng(np.random.SeedSequence(int(seed)))
if Xr.shape[0] > max_samples:
idx_r = rng.choice(Xr.shape[0], size=max_samples, replace=False)
Xr = Xr[idx_r]
if Xc.shape[0] > max_samples:
idx_c = rng.choice(Xc.shape[0], size=max_samples, replace=False)
Xc = Xc[idx_c]
n_r, n_c = Xr.shape[0], Xc.shape[0]
d2_xx = _pairwise_sq_dists(Xr, Xr)
d2_yy = _pairwise_sq_dists(Xc, Xc)
d2_xy = _pairwise_sq_dists(Xr, Xc)
if bandwidth is None:
pool = np.vstack([Xr, Xc])
if pool.shape[0] > max_samples:
pool = pool[rng.choice(pool.shape[0], size=max_samples, replace=False)]
d2_pool = _pairwise_sq_dists(pool, pool)
triu = d2_pool[np.triu_indices(pool.shape[0], k=1)]
pos = np.sqrt(triu[triu > 0.0])
sigma_k = float(np.median(pos)) if pos.size > 0 else 1.0
else:
sigma_k = float(bandwidth)
if not math.isfinite(sigma_k) or sigma_k <= 0.0:
raise ValueError("bandwidth must be finite and positive.")
gamma = 1.0 / (2.0 * sigma_k * sigma_k)
K_xx = np.exp(-gamma * d2_xx)
K_yy = np.exp(-gamma * d2_yy)
K_xy = np.exp(-gamma * d2_xy)
sum_xx_off = float(np.sum(K_xx)) - float(np.trace(K_xx))
sum_yy_off = float(np.sum(K_yy)) - float(np.trace(K_yy))
cross_mean = float(np.mean(K_xy))
mmd_u2 = (sum_xx_off / (n_r * (n_r - 1))) + (sum_yy_off / (n_c * (n_c - 1))) - 2.0 * cross_mean
mmd_b2 = (float(np.sum(K_xx)) / (n_r * n_r)) + (float(np.sum(K_yy)) / (n_c * n_c)) - 2.0 * cross_mean
return {
"mmd_u2": float(mmd_u2),
"mmd_b2": float(max(0.0, mmd_b2)),
"bandwidth": float(sigma_k),
"n_ref_used": float(n_r),
"n_cur_used": float(n_c),
}
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -35.0, 35.0)))
def _fit_and_eval_logistic(
X_tr: np.ndarray,
y_tr: np.ndarray,
X_te: np.ndarray,
y_te: np.ndarray,
l2_reg: float = 1.0,
) -> tuple[float, float]:
std = StatefulStandardizer().fit(X_tr)
Z_tr = np.asarray(std.transform(X_tr), dtype=np.float64)
Z_te = np.asarray(std.transform(X_te), dtype=np.float64)
w, b = _fit_l2_logistic_newton(Z_tr, y_tr.astype(np.float64), l2_reg=l2_reg)
p_tr = _sigmoid(Z_tr @ w + b)
p_te = _sigmoid(Z_te @ w + b)
return compute_roc_auc(y_tr, p_tr), compute_roc_auc(y_te, p_te)
def run_full_lifecycle_benchmarks(quick: bool = False, seed: int = 42) -> dict[str, Any]:
"""
Execute all reproducible Stage 5B case studies and mathematical benchmarks:
contracts/lineage, pre-split leakage proofs, ICU MNAR + Zero-MAD, Simpson 2x2 paradox,
Zipf OOF m-estimate, Credit PIT leakage, Mobility iOS v4.2 W1 vs PSI, H0 small-sample PSI
storm vs KS, and bivariate correlation-rotation C2ST + RBF MMD_u^2.
"""
rng_tree = ReproducibleRngTree.from_master_seed(seed)
# ------------------------------------------------------------------
# 1. Contracts, Batch Invariance & Content-Addressed Zero-Pickle Lineage
# ------------------------------------------------------------------
n_base = 240
base_df = pd.DataFrame(
{
"event_ts": np.arange(n_base, dtype=np.float64) * 10.0,
"entity_id": [f"usr_{i // 3}" for i in range(n_base)],
"f1": rng_tree.eda_rng.normal(10.0, 2.5, size=n_base),
"f2": rng_tree.eda_rng.normal(-4.0, 1.2, size=n_base),
"target": rng_tree.eda_rng.integers(0, 2, size=n_base),
}
)
temporal_contract = SplitContract(
strategy="temporal",
train_ratio=0.7,
val_ratio=0.15,
test_ratio=0.15,
time_col="event_ts",
embargo_seconds=90.0,
)
tr_t, val_t, te_t = split_dataframe(base_df, temporal_contract, seed=seed)
assert val_t is not None
std = StatefulStandardizer().fit(tr_t[["f1", "f2"]])
batch_200 = np.asarray(std.transform(te_t[["f1", "f2"]]), dtype=np.float64)
row_by_row = np.vstack(
[np.asarray(std.transform(te_t[["f1", "f2"]].iloc[[i]]), dtype=np.float64) for i in range(len(te_t))]
)
batch_invariance_max_err = float(np.max(np.abs(batch_200 - row_by_row)))
signed_payload = std.to_signed_json()
restored_std = StatefulStandardizer.from_signed_json(signed_payload)
signed_roundtrip_max_err = float(
np.max(
np.abs(
np.asarray(std.transform(te_t[["f1", "f2"]]), dtype=np.float64)
- np.asarray(restored_std.transform(te_t[["f1", "f2"]]), dtype=np.float64)
)
)
)
split_idx = {
"train": tr_t.index.to_numpy().tolist(),
"val": val_t.index.to_numpy().tolist(),
"test": te_t.index.to_numpy().tolist(),
}
m1 = build_experiment_manifest(
run_name="ch04_lifecycle_audit",
df=base_df,
split_contract=temporal_contract,
split_indices=split_idx,
config={"embargo_seconds": 90.0, "quick": bool(quick)},
state_dicts={"standardizer": std.to_state_dict()},
root_seed=seed,
)
m2 = build_experiment_manifest(
run_name="ch04_lifecycle_audit",
df=base_df,
split_contract=temporal_contract,
split_indices=split_idx,
config={"embargo_seconds": 90.0, "quick": bool(quick)},
state_dicts={"standardizer": std.to_state_dict()},
root_seed=seed,
)
contracts_and_lineage = {
"temporal_split_sizes": {"train": len(tr_t), "val": len(val_t), "test": len(te_t)},
"batch_invariance_max_abs_diff": batch_invariance_max_err,
"signed_json_roundtrip_max_abs_diff": signed_roundtrip_max_err,
"manifest_sha256": m1["manifest_sha256"],
"manifest_deterministic": bool(m1["manifest_sha256"] == m2["manifest_sha256"]),
"dataset_sha256": m1["dataset_sha256"],
"split_sha256": m1["split_sha256"],
}
# ------------------------------------------------------------------
# 2. Pre-Split Leakage Proofs (k=1 and k=10 on N=100, d=2000 Pure Noise)
# ------------------------------------------------------------------
n_leak_trials = 25 if quick else 60
leak_k10 = simulate_presplit_leakage_audit(
n_samples=100, n_features=2000, top_k=10, n_trials=n_leak_trials, seed=seed
)
leak_k1 = simulate_presplit_leakage_audit(
n_samples=100, n_features=2000, top_k=1, n_trials=n_leak_trials, seed=seed + 1
)
# ------------------------------------------------------------------
# 3. ICU MNAR Missingness Contraction & Indicator AUC + Zero-MAD Hierarchy
# ------------------------------------------------------------------
n_patients = 220 if quick else 400
hrs_per_pat = 10
n_icu = n_patients * hrs_per_pat
pat_ids = np.repeat(np.arange(n_patients), hrs_per_pat)
pat_base = np.repeat(rng_tree.eda_rng.normal(0.0, 1.0, size=n_patients), hrs_per_pat)
sev = pat_base + rng_tree.eda_rng.normal(0.0, 0.45, size=n_icu)
sepsis_prob = _sigmoid(2.6 * sev - 0.65)
y_sepsis = (rng_tree.eda_rng.uniform(size=n_icu) < sepsis_prob).astype(np.int64)
# Clinicians order invasive lactate predominantly when bedside severity triggers suspicion (MNAR)
order_prob = _sigmoid(3.4 * sev - 0.75)
observed_mask = rng_tree.eda_rng.uniform(size=n_icu) < order_prob
lactate_raw = np.exp(0.25 + 0.55 * sev + rng_tree.eda_rng.normal(0.0, 0.25, size=n_icu))
lactate_obs = np.where(observed_mask, lactate_raw, np.nan)
hr_noise = rng_tree.eda_rng.normal(82.0, 11.0, size=n_icu) + 0.1 * sev
icu_df = pd.DataFrame(
{
"patient_id": pat_ids,
"lactate_mmol": lactate_obs,
"heart_rate": hr_noise,
"sepsis": y_sepsis,
}
)
icu_contract = SplitContract(
strategy="group", group_col="patient_id", train_ratio=0.7, val_ratio=0.0, test_ratio=0.3
)
icu_tr, _, icu_te = split_dataframe(icu_df, icu_contract, seed=seed)
icu_diag = diagnose_missingness_mechanisms(
icu_tr, numeric_cols=["lactate_mmol", "heart_rate"], target_col="sepsis"
)
lac_diag = icu_diag["lactate_mmol"]
lac_tr_raw = icu_tr["lactate_mmol"].to_numpy(dtype=np.float64)
lac_te_raw = icu_te["lactate_mmol"].to_numpy(dtype=np.float64)
tr_mean_lac = float(np.nanmean(lac_tr_raw))
X_icu_blind_tr = np.column_stack([np.where(np.isnan(lac_tr_raw), tr_mean_lac, lac_tr_raw), icu_tr["heart_rate"].to_numpy()])
X_icu_blind_te = np.column_stack([np.where(np.isnan(lac_te_raw), tr_mean_lac, lac_te_raw), icu_te["heart_rate"].to_numpy()])
_, icu_blind_auc = _fit_and_eval_logistic(
X_icu_blind_tr, icu_tr["sepsis"].to_numpy(), X_icu_blind_te, icu_te["sepsis"].to_numpy()
)
imp = RobustMADImputer(numeric_cols=["lactate_mmol", "heart_rate"], add_missing_indicators=True)
icu_tr_imp = imp.fit_transform(icu_tr)
icu_te_imp = imp.transform(icu_te)
feat_cols_icu = ["lactate_mmol", "heart_rate", "lactate_mmol_is_missing", "heart_rate_is_missing"]
_, icu_ind_auc = _fit_and_eval_logistic(
icu_tr_imp[feat_cols_icu].to_numpy(dtype=np.float64),
icu_tr["sepsis"].to_numpy(),
icu_te_imp[feat_cols_icu].to_numpy(dtype=np.float64),
icu_te["sepsis"].to_numpy(),
)
zero_mad_res = compute_mad_zscore([0.0, 0.0, 0.0, 0.0, 10.0, float("nan")])
const_mad_res = compute_mad_zscore([5.0, 5.0, 5.0])
# ------------------------------------------------------------------
# 4. Simpson's Paradox 2x2 Worked Benchmark (N = 2,000)
# ------------------------------------------------------------------
simpson_rows: list[tuple[int, str, int]] = []
simpson_rows.extend((0, "Cold_Mobile", 1) for _ in range(180))
simpson_rows.extend((0, "Cold_Mobile", 0) for _ in range(720))
simpson_rows.extend((0, "Returning_Desktop", 1) for _ in range(85))
simpson_rows.extend((0, "Returning_Desktop", 0) for _ in range(15))
simpson_rows.extend((1, "Cold_Mobile", 1) for _ in range(15))
simpson_rows.extend((1, "Cold_Mobile", 0) for _ in range(85))
simpson_rows.extend((1, "Returning_Desktop", 1) for _ in range(720))
simpson_rows.extend((1, "Returning_Desktop", 0) for _ in range(180))
simpson_df = pd.DataFrame(simpson_rows, columns=["variant", "segment", "converted"])
simp_res = simpson_paradox_audit(
simpson_df, treatment_col="variant", outcome_col="converted", stratum_col="segment"
)
# ------------------------------------------------------------------
# 5. Zipf High-Cardinality merchant_id OOF m-Estimate Benchmark
# ------------------------------------------------------------------
n_zipf = 18000 if quick else 50000
n_merch = 4500 if quick else 12000
ranks = np.arange(1, n_merch + 1, dtype=np.float64)
zipf_probs = ranks ** (-1.18)
zipf_probs /= float(np.sum(zipf_probs))
merch_idx = rng_tree.oof_rng.choice(n_merch, size=n_zipf, p=zipf_probs)
merch_effects = rng_tree.oof_rng.normal(0.0, 0.55, size=n_merch)
# Give head merchants reliable signal and tail noise
merch_effects[50:] = rng_tree.oof_rng.normal(0.0, 0.15, size=n_merch - 50)
tenure_z = rng_tree.oof_rng.normal(0.0, 1.0, size=n_zipf)
amount_z = rng_tree.oof_rng.normal(0.0, 1.0, size=n_zipf)
logits_zipf = 0.72 * tenure_z - 0.35 * amount_z + merch_effects[merch_idx]
y_zipf = (rng_tree.oof_rng.uniform(size=n_zipf) < _sigmoid(logits_zipf)).astype(np.int64)
zipf_df = pd.DataFrame(
{
"merchant_id": [f"m_{m}" for m in merch_idx],
"tenure_z": tenure_z,
"amount_z": amount_z,
"refund": y_zipf,
}
)
zipf_contract = SplitContract(
strategy="stratified_iid", train_ratio=0.65, val_ratio=0.0, test_ratio=0.35
)
z_tr, _, z_te = split_dataframe(zipf_df, zipf_contract, seed=seed, stratify_col="refund")
rare_frac = float((z_tr["merchant_id"].value_counts() < 5).mean())
naive_enc = OutOfFoldTargetEncoder(
cols=["merchant_id"], smoothing_m=0.0, min_samples=1, n_folds=5, seed=seed
)
naive_enc.fit(z_tr[["merchant_id", "tenure_z", "amount_z"]], z_tr["refund"])
z_tr_naive = naive_enc.transform(z_tr[["merchant_id", "tenure_z", "amount_z"]])
z_te_naive = naive_enc.transform(z_te[["merchant_id", "tenure_z", "amount_z"]])
naive_tr_auc, naive_te_auc = _fit_and_eval_logistic(
z_tr_naive.to_numpy(dtype=np.float64),
z_tr["refund"].to_numpy(),
z_te_naive.to_numpy(dtype=np.float64),
z_te["refund"].to_numpy(),
l2_reg=0.5,
)
oof_enc = OutOfFoldTargetEncoder(
cols=["merchant_id"], smoothing_m=15.0, min_samples=5, n_folds=5, seed=seed
)
z_tr_oof = oof_enc.fit_transform(z_tr[["merchant_id", "tenure_z", "amount_z"]], z_tr["refund"])
z_te_oof = oof_enc.transform(z_te[["merchant_id", "tenure_z", "amount_z"]])
oof_tr_auc, oof_te_auc = _fit_and_eval_logistic(
z_tr_oof.to_numpy(dtype=np.float64),
z_tr["refund"].to_numpy(),
z_te_oof.to_numpy(dtype=np.float64),
z_te["refund"].to_numpy(),
l2_reg=1.0,
)
# ------------------------------------------------------------------
# 6. Credit PIT Backfill Leakage & Adversarial Validation Benchmark
# ------------------------------------------------------------------
n_cred = 2000 if quick else 5000
ts_cred = np.arange(n_cred, dtype=np.float64)
dti = rng_tree.model_rng.normal(0.0, 1.0, size=n_cred)
util = rng_tree.model_rng.normal(0.0, 1.0, size=n_cred)
income_z = rng_tree.model_rng.normal(0.0, 1.0, size=n_cred)
y_def = (rng_tree.model_rng.uniform(size=n_cred) < _sigmoid(0.85 * dti + 0.65 * util - 0.55 * income_z - 0.8)).astype(
np.int64
)
# Historical training rows had post-default account limit adjustments backfilled; live OOT does not
cut_idx = int(0.7 * n_cred)
post_default_limit = np.empty(n_cred, dtype=np.float64)
post_default_limit[:cut_idx] = np.where(
y_def[:cut_idx] == 1,
-2.2 + rng_tree.model_rng.normal(0.0, 0.35, size=cut_idx),
1.1 + rng_tree.model_rng.normal(0.0, 0.35, size=cut_idx),
)
post_default_limit[cut_idx:] = rng_tree.model_rng.normal(0.0, 0.35, size=n_cred - cut_idx)
cred_df = pd.DataFrame(
{
"decision_ts": ts_cred,
"dti": dti,
"util": util,
"income_z": income_z,
"post_default_limit": post_default_limit,
"default": y_def,
}
)
cred_contract = SplitContract(
strategy="temporal", time_col="decision_ts", train_ratio=0.7, val_ratio=0.0, test_ratio=0.3, embargo_seconds=90.0
)
c_tr, _, c_te = split_dataframe(cred_df, cred_contract, seed=seed)
leaky_cols = ["dti", "util", "income_z", "post_default_limit"]
clean_cols = ["dti", "util", "income_z"]
cred_leaky_tr_auc, cred_leaky_oot_auc = _fit_and_eval_logistic(
c_tr[leaky_cols].to_numpy(dtype=np.float64),
c_tr["default"].to_numpy(),
c_te[leaky_cols].to_numpy(dtype=np.float64),
c_te["default"].to_numpy(),
)
_, cred_clean_oot_auc = _fit_and_eval_logistic(
c_tr[clean_cols].to_numpy(dtype=np.float64),
c_tr["default"].to_numpy(),
c_te[clean_cols].to_numpy(dtype=np.float64),
c_te["default"].to_numpy(),
)
adv_credit_leaky = adversarial_validation_oof_auc(
c_tr[leaky_cols], c_te[leaky_cols], include_quadratic=True, seed=seed
)
adv_credit_clean = adversarial_validation_oof_auc(
c_tr[clean_cols], c_te[clean_cols], include_quadratic=False, seed=seed
)
# ------------------------------------------------------------------
# 7. Mobility Telemetry iOS v4.2 Unit Mismatch (1000x) + Sentinel (-1.0)
# ------------------------------------------------------------------
n_mob = 2500 if quick else 5000
is_ios_ref = rng_tree.eda_rng.uniform(size=n_mob) < 0.18
eta_ref = np.exp(rng_tree.eda_rng.normal(6.0, 0.45, size=n_mob))
is_ios_cur = rng_tree.eda_rng.uniform(size=n_mob) < 0.18
eta_cur = np.exp(rng_tree.eda_rng.normal(6.0, 0.45, size=n_mob))
sentinel_mask = is_ios_cur & (rng_tree.eda_rng.uniform(size=n_mob) < 0.25)
scale_mask = is_ios_cur & (~sentinel_mask)
eta_cur = np.where(scale_mask, eta_cur * 1000.0, eta_cur)
eta_cur = np.where(sentinel_mask, -1.0, eta_cur)
mob_contract = DataContractSchema(
schema_version="mobility_eta_v1",
columns=(
ColumnContract(
name="eta_seconds",
dtype_family="float",
nullable=False,
min_value=0.0,
max_value=14400.0,
forbidden_sentinels=(-1.0, -999.0),
),
ColumnContract(name="app_version", dtype_family="str", nullable=False),
),
)
mob_cur_df = pd.DataFrame(
{
"eta_seconds": eta_cur,
"app_version": np.where(is_ios_cur, "iOS_4.2", "Android_4.1"),
}
)
mob_contract_diag = mob_contract.validate_dataframe(mob_cur_df, fail_fast=False)
mob_global_psi = compute_psi(eta_ref, eta_cur, bins=10)
mob_global_jsd = compute_jsd(eta_ref, eta_cur, bins=10, base="bits")
mob_global_w1 = compute_wasserstein_1d(eta_ref, eta_cur)
mob_global_w1_norm = compute_normalized_wasserstein_1d(eta_ref, eta_cur)
mob_global_ks = compute_ks_statistic(eta_ref, eta_cur)
mob_slice_psi = compute_psi(eta_ref[is_ios_ref], eta_cur[is_ios_cur], bins=10)
mob_slice_jsd = compute_jsd(eta_ref[is_ios_ref], eta_cur[is_ios_cur], bins=10, base="bits")
mob_slice_w1 = compute_wasserstein_1d(eta_ref[is_ios_ref], eta_cur[is_ios_cur])
mob_slice_ks = compute_ks_statistic(eta_ref[is_ios_ref], eta_cur[is_ios_cur])
# ------------------------------------------------------------------
# 8. Small-Sample H0 PSI False-Alarm Storm vs KS
# ------------------------------------------------------------------
n_mc = 250 if quick else 1000
h0_ref_big = rng_tree.eda_rng.standard_normal(5000)
psi_hits = 0
ks_hits = 0
null_psis = np.empty(n_mc, dtype=np.float64)
for m_i in range(n_mc):
cur_50 = rng_tree.eda_rng.standard_normal(50)
p_res = compute_psi(h0_ref_big, cur_50, bins=20)
k_res = compute_ks_statistic(h0_ref_big, cur_50)
null_psis[m_i] = p_res["psi"]
if p_res["psi"] >= 0.25:
psi_hits += 1
if k_res["p_value"] < 0.05:
ks_hits += 1
small_sample_h0 = {
"n_trials": n_mc,
"n_ref": 5000,
"n_cur": 50,
"bins": 20,
"mean_null_psi": float(np.mean(null_psis)),
"psi_fpr_at_025": psi_hits / float(n_mc),
"ks_fpr_at_005": ks_hits / float(n_mc),
"sample_null_bias": compute_psi(h0_ref_big, rng_tree.eda_rng.standard_normal(50), bins=20)[
"expected_null_psi_bias"
],
}
# ------------------------------------------------------------------
# 9. Multivariate Correlation Rotation (+0.85 -> -0.85): Linear vs Quadratic C2ST & MMD_u^2
# ------------------------------------------------------------------
n_rot = 350 if quick else 500
cov_pos = np.array([[1.0, 0.85], [0.85, 1.0]], dtype=np.float64)
cov_neg = np.array([[1.0, -0.85], [-0.85, 1.0]], dtype=np.float64)
X_rot_ref = rng_tree.model_rng.multivariate_normal([0.0, 0.0], cov_pos, size=n_rot)
X_rot_cur = rng_tree.model_rng.multivariate_normal([0.0, 0.0], cov_neg, size=n_rot)
rot_df_ref = pd.DataFrame(X_rot_ref, columns=["x1", "x2"])
rot_df_cur = pd.DataFrame(X_rot_cur, columns=["x1", "x2"])
rot_x1_psi = compute_psi(X_rot_ref[:, 0], X_rot_cur[:, 0])
rot_x1_ks = compute_ks_statistic(X_rot_ref[:, 0], X_rot_cur[:, 0])
rot_x1_w1 = compute_wasserstein_1d(X_rot_ref[:, 0], X_rot_cur[:, 0])
rot_x1_jsd = compute_jsd(X_rot_ref[:, 0], X_rot_cur[:, 0])
rot_adv_linear = adversarial_validation_oof_auc(
rot_df_ref, rot_df_cur, include_quadratic=False, seed=seed
)
rot_adv_quad = adversarial_validation_oof_auc(
rot_df_ref, rot_df_cur, include_quadratic=True, seed=seed
)
rot_mmd = compute_rbf_mmd_u2(X_rot_ref, X_rot_cur, max_samples=n_rot, seed=seed)
return {
"contracts_and_lineage": contracts_and_lineage,
"eda_and_encoding": {
"presplit_leakage_k10": leak_k10,
"presplit_leakage_k1": leak_k1,
"icu_mnar": {
"missing_rate": float(lac_diag["missing_rate"]),
"theoretical_var_retention": float(lac_diag["theoretical_var_retention"]),
"empirical_var_retention": float(lac_diag["empirical_var_retention"]),
"target_missingness_corr": float(lac_diag["target_missingness_corr"]),
"regime_flag": lac_diag["regime_flag"],
"blind_mean_auc": float(icu_blind_auc),
"is_missing_indicator_auc": float(icu_ind_auc),
},
"zero_mad_audit": {
"zero_mad_mode": zero_mad_res.scale_mode,
"zero_mad_effective_scale": zero_mad_res.effective_scale,
"zero_mad_max_z": float(np.nanmax(np.abs(zero_mad_res.z_scores))),
"constant_mode": const_mad_res.scale_mode,
"constant_max_z": float(np.max(np.abs(const_mad_res.z_scores))),
},
"simpson_paradox": {
"agg_rate_ctrl": simp_res.agg_rate_ctrl,
"agg_rate_trt": simp_res.agg_rate_trt,
"agg_diff": simp_res.agg_diff,
"within_stratum_effect": simp_res.within_stratum_effect,
"mix_shift_confounding": simp_res.mix_shift_confounding,
"direct_std_rate_ctrl": simp_res.direct_std_rate_ctrl,
"direct_std_rate_trt": simp_res.direct_std_rate_trt,
"direct_std_diff": simp_res.direct_std_diff,
"reversal_detected": simp_res.reversal_detected,
},
"zipf_encoding": {
"n_train": len(z_tr),
"n_test": len(z_te),
"n_unique_train_merchants": int(z_tr["merchant_id"].nunique()),
"rare_merchant_fraction": rare_frac,
"naive_train_auc": float(naive_tr_auc),
"naive_test_auc": float(naive_te_auc),
"naive_overfit_gap": float(naive_tr_auc - naive_te_auc),
"oof_train_auc": float(oof_tr_auc),
"oof_test_auc": float(oof_te_auc),
"oof_overfit_gap": float(oof_tr_auc - oof_te_auc),
},
},
"drift_and_cases": {
"credit_pit_leakage": {
"leaky_cv_train_auc": float(cred_leaky_tr_auc),
"leaky_oot_auc": float(cred_leaky_oot_auc),
"clean_oot_auc": float(cred_clean_oot_auc),
"adv_auc_leaky": float(adv_credit_leaky.auc_adv),
"adv_top_feature_leaky": adv_credit_leaky.top_shift_feature,
"adv_auc_clean": float(adv_credit_clean.auc_adv),
},
"mobility_telemetry": {
"contract_passed": bool(mob_contract_diag["passed"]),
"contract_error_count": len(mob_contract_diag["errors"]),
"contract_errors": mob_contract_diag["errors"],
"global": {
"psi": mob_global_psi["psi"],
"jsd_bits": mob_global_jsd,
"wasserstein_w1": mob_global_w1,
"normalized_w1": mob_global_w1_norm,
"ks_stat": mob_global_ks["ks_stat"],
"ks_p_value": mob_global_ks["p_value"],
},
"ios_4_2_slice": {
"psi": mob_slice_psi["psi"],
"jsd_bits": mob_slice_jsd,
"wasserstein_w1": mob_slice_w1,
"ks_stat": mob_slice_ks["ks_stat"],
"ks_p_value": mob_slice_ks["p_value"],
},
},
"small_sample_h0": small_sample_h0,
"multivariate_rotation": {
"univariate_x1_psi": rot_x1_psi["psi"],
"univariate_x1_jsd_bits": rot_x1_jsd,
"univariate_x1_w1": rot_x1_w1,
"univariate_x1_ks_stat": rot_x1_ks["ks_stat"],
"univariate_x1_ks_p_value": rot_x1_ks["p_value"],
"linear_c2st_auc": float(rot_adv_linear.auc_adv),
"quadratic_c2st_auc": float(rot_adv_quad.auc_adv),
"quadratic_top_feature": rot_adv_quad.top_shift_feature,
"rbf_mmd_u2": float(rot_mmd["mmd_u2"]),
"rbf_mmd_bandwidth": float(rot_mmd["bandwidth"]),
},
},
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 04 (lifecycle_eda_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 lifecycle_eda_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 lifecycle_eda_lab.eda_and_drift import run_full_lifecycle_benchmarks
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy arrays, scalars, and non-finite floats into JSON-safe values."""
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(val: float, floor: float = 0.001) -> float:
"""Ensure bar chart values are strictly positive finite floats."""
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 Lifecycle, OOP & EDA Workbench demo."""
parser = argparse.ArgumentParser(
description="Run Lab 04: Lifecycle Contracts, Stateful OOP Pipelines, Leakage-Free EDA & Drift."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--quick",
action="store_true",
help="Use reduced Monte Carlo & sample budgets for sub-3s execution.",
)
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Optional output JSON file path (e.g., artifacts/ch04_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
lineage = bench["contracts_and_lineage"]
eda = bench["eda_and_encoding"]
drift = bench["drift_and_cases"]
leak10 = eda["presplit_leakage_k10"]
leak1 = eda["presplit_leakage_k1"]
icu = eda["icu_mnar"]
zmad = eda["zero_mad_audit"]
simp = eda["simpson_paradox"]
zipf = eda["zipf_encoding"]
cred = drift["credit_pit_leakage"]
mob = drift["mobility_telemetry"]
h0 = drift["small_sample_h0"]
rot = drift["multivariate_rotation"]
kpis = [
{
"id": "kpi_presplit_noise_illusion",
"label": "Pre-Split Pure-Noise Screening (k=10)",
"value": f"{leak10['pre_split']['corr_te']:+.3f} vs {leak10['split_first']['corr_te']:+.3f}",
"unit": "Corr_te",
"status": "critical",
"detail": (
f"Pre-split leaks R2_te={leak10['pre_split']['r2_te']:+.3f} on N=100, d=2000 noise; "
f"split-first yields R2_te={leak10['split_first']['r2_te']:+.3f}; "
f"centering corr={leak10['centering_cross_split_corr']:.3f}."
),
},
{
"id": "kpi_mnar_var_and_indicator",
"label": "ICU MNAR Retention & Indicator Recovery",
"value": f"{icu['blind_mean_auc']:.3f} -> {icu['is_missing_indicator_auc']:.3f}",
"unit": "AUC",
"status": "ok",
"detail": (
f"p_miss={icu['missing_rate']:.3f}: theo 1-p={icu['theoretical_var_retention']:.3f} "
f"vs emp={icu['empirical_var_retention']:.3f}; is_missing restores unseen-patient AUC."
),
},
{
"id": "kpi_zipf_oof_generalization",
"label": "Zipf OOF m-Estimate Test AUC (Gap)",
"value": f"{zipf['oof_test_auc']:.3f} ({zipf['oof_overfit_gap']:+.3f})",
"unit": "AUC",
"status": "ok",
"detail": (
f"Naive mean memorizes {zipf['n_unique_train_merchants']} merchants "
f"(gap={zipf['naive_overfit_gap']:+.3f}, test={zipf['naive_test_auc']:.3f}); "
"5-fold OOF + __RARE__ eliminates overfit."
),
},
{
"id": "kpi_telemetry_w1_vs_psi",
"label": "Mobility iOS v4.2: Global PSI vs W1",
"value": f"PSI {mob['global']['psi']:.3f} | W1 {mob['global']['wasserstein_w1']:,.0f}s",
"unit": "iOS 1000x",
"status": "warn",
"detail": (
f"Global PSI={mob['global']['psi']:.3f} (<0.25 misses 1000x unit spike!), "
f"while W1={mob['global']['wasserstein_w1']:,.1f}s & iOS_4.2 slice "
f"PSI={mob['ios_4_2_slice']['psi']:.2f} catch it; schema caught {mob['contract_error_count']} errors."
),
},
{
"id": "kpi_null_psi_vs_ks_fpr",
"label": "Small-Slice H0 (n=50, B=20) FPR",
"value": f"PSI {h0['psi_fpr_at_025']*100:.1f}% vs KS {h0['ks_fpr_at_005']*100:.1f}%",
"unit": "False Alarm",
"status": "warn",
"detail": (
f"Zero-drift mean PSI={h0['mean_null_psi']:.3f} triggers {h0['psi_fpr_at_025']*100:.1f}% "
"false alarms at 0.25; dual-series KS holds nominal alpha=0.05."
),
},
{
"id": "kpi_adv_val_and_mmd_shift",
"label": "PIT Leak & Rotation Quadratic C2ST",
"value": f"PIT {cred['adv_auc_leaky']:.3f} | Rot {rot['quadratic_c2st_auc']:.3f}",
"unit": "AUC_adv",
"status": "ok",
"detail": (
f"Linear C2ST={rot['linear_c2st_auc']:.3f} misses +0.85->-0.85 rotation; "
f"quadratic C2ST={rot['quadratic_c2st_auc']:.3f} ({rot['quadratic_top_feature']}) & "
f"RBF MMD_u2={rot['rbf_mmd_u2']:.4f} catch it."
),
},
]
bars = [
{
"id": "bar_presplit_screening_illusion",
"title": "Pre-Split vs. Split-First Pure-Noise Test Correlation (N=100, d=2000)",
"metric_label": "|Corr_test|",
"items": [
{
"label": "pre_split_k1_corr",
"value": round(_pos_bar_val(leak1["pre_split"]["corr_te"]), 4),
"display": f"{leak1['pre_split']['corr_te']:+.3f}",
"css_class": "is-slow",
},
{
"label": "pre_split_k10_corr",
"value": round(_pos_bar_val(leak10["pre_split"]["corr_te"]), 4),
"display": f"{leak10['pre_split']['corr_te']:+.3f}",
"css_class": "is-slow",
},
{
"label": "split_first_k1_corr",
"value": round(_pos_bar_val(leak1["split_first"]["corr_te"]), 4),
"display": f"{leak1['split_first']['corr_te']:+.3f}",
"css_class": "is-fast",
},
{
"label": "split_first_k10_corr",
"value": round(_pos_bar_val(leak10["split_first"]["corr_te"]), 4),
"display": f"{leak10['split_first']['corr_te']:+.3f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_zipf_target_encoding_auc",
"title": "High-Cardinality Zipf Target Encoding (Train vs. Test AUC)",
"metric_label": "ROC-AUC",
"items": [
{
"label": "naive_train_auc",
"value": round(_pos_bar_val(zipf["naive_train_auc"]), 4),
"display": f"{zipf['naive_train_auc']:.3f}",
"css_class": "is-slow",
},
{
"label": "naive_test_auc",
"value": round(_pos_bar_val(zipf["naive_test_auc"]), 4),
"display": f"{zipf['naive_test_auc']:.3f}",
"css_class": "is-mid",
},
{
"label": "oof_m_train_auc",
"value": round(_pos_bar_val(zipf["oof_train_auc"]), 4),
"display": f"{zipf['oof_train_auc']:.3f}",
"css_class": "is-fast",
},
{
"label": "oof_m_test_auc",
"value": round(_pos_bar_val(zipf["oof_test_auc"]), 4),
"display": f"{zipf['oof_test_auc']:.3f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_icu_mnar_and_simpson",
"title": "ICU MNAR Recovery (AUC) & Simpson Paradox Magnitude (pp)",
"metric_label": "Score / |pp|",
"items": [
{
"label": "icu_blind_mean_auc",
"value": round(_pos_bar_val(icu["blind_mean_auc"]), 4),
"display": f"{icu['blind_mean_auc']:.3f} AUC",
"css_class": "is-slow",
},
{
"label": "icu_is_missing_auc",
"value": round(_pos_bar_val(icu["is_missing_indicator_auc"]), 4),
"display": f"{icu['is_missing_indicator_auc']:.3f} AUC",
"css_class": "is-fast",
},
{
"label": "simpson_naive_diff_pp",
"value": round(_pos_bar_val(simp["agg_diff"] * 100.0), 3),
"display": f"{simp['agg_diff']*100.0:+.1f} pp",
"css_class": "is-slow",
},
{
"label": "simpson_std_diff_pp",
"value": round(_pos_bar_val(simp["direct_std_diff"] * 100.0), 3),
"display": f"{simp['direct_std_diff']*100.0:+.1f} pp",
"css_class": "is-fast",
},
],
},
{
"id": "bar_drift_blindness_comparison",
"title": "Global vs. Sliced PSI & Small-Slice Null False-Alarm Rates",
"metric_label": "PSI / FPR%",
"items": [
{
"label": "global_psi_ios_bug",
"value": round(_pos_bar_val(mob["global"]["psi"]), 4),
"display": f"{mob['global']['psi']:.3f} (missed)",
"css_class": "is-mid",
},
{
"label": "sliced_psi_ios_bug",
"value": round(_pos_bar_val(mob["ios_4_2_slice"]["psi"]), 4),
"display": f"{mob['ios_4_2_slice']['psi']:.2f} (caught)",
"css_class": "is-fast",
},
{
"label": "null_h0_psi_fpr_pct",
"value": round(_pos_bar_val(h0["psi_fpr_at_025"] * 100.0), 2),
"display": f"{h0['psi_fpr_at_025']*100.0:.1f}%",
"css_class": "is-slow",
},
{
"label": "null_h0_ks_fpr_pct",
"value": round(_pos_bar_val(h0["ks_fpr_at_005"] * 100.0), 2),
"display": f"{h0['ks_fpr_at_005']*100.0:.1f}%",
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "table_presplit_leakage_audit",
"title": "Pre-Split vs. Split-First Screening & Centering Proofs (Pure Noise)",
"columns": ["regime", "top_k", "r2_in", "r2_test", "corr_test", "status"],
"rows": [
[
"pre_split_leaked",
1,
round(leak1["pre_split"]["r2_in"], 4),
round(leak1["pre_split"]["r2_te"], 4),
round(leak1["pre_split"]["corr_te"], 4),
"LEAKED_ILLUSION",
],
[
"split_first_clean",
1,
round(leak1["split_first"]["r2_in"], 4),
round(leak1["split_first"]["r2_te"], 4),
round(leak1["split_first"]["corr_te"], 4),
"HONEST_NULL",
],
[
"pre_split_leaked",
10,
round(leak10["pre_split"]["r2_in"], 4),
round(leak10["pre_split"]["r2_te"], 4),
round(leak10["pre_split"]["corr_te"], 4),
"LEAKED_ILLUSION",
],
[
"split_first_clean",
10,
round(leak10["split_first"]["r2_in"], 4),
round(leak10["split_first"]["r2_te"], 4),
round(leak10["split_first"]["corr_te"], 4),
"HONEST_NULL",
],
[
"presplit_centering",
"alpha_tr=0.70",
round(leak10["centering_expected_shift_ratio"], 3),
round(leak10["centering_observed_shift_ratio"], 3),
round(leak10["centering_cross_split_corr"], 6),
"ANTI_CORR_-1.0",
],
],
},
{
"id": "table_missingness_and_encoding",
"title": "Missingness (MNAR), Zero-MAD, Simpson Paradox & Zipf OOF Benchmarks",
"columns": [
"scenario",
"p_miss_or_card",
"var_retention_or_train_auc",
"test_auc_or_signal",
"recommended_fix",
],
"rows": [
[
"icu_lactate_mnar",
f"p_miss={icu['missing_rate']:.3f}",
f"theo={icu['theoretical_var_retention']:.3f} / emp={icu['empirical_var_retention']:.3f}",
f"blind={icu['blind_mean_auc']:.3f} -> ind={icu['is_missing_indicator_auc']:.3f}",
"GroupSplit + is_missing",
],
[
"zero_mad_sparse",
"MAD=0.0",
f"mode={zmad['zero_mad_mode']}",
f"max_z={zmad['zero_mad_max_z']:.3f}",
"1.253314*MeanAD fallback",
],
[
"simpson_2x2_audit",
"N=2000 (2 strata)",
f"within={simp['within_stratum_effect']:+.3f} + mix={simp['mix_shift_confounding']:+.3f}",
f"agg={simp['agg_diff']:+.3f} -> std={simp['direct_std_diff']:+.3f}",
"Direct standardization",
],
[
"zipf_naive_insample",
f"{zipf['n_unique_train_merchants']} merchants",
f"train_auc={zipf['naive_train_auc']:.3f}",
f"test_auc={zipf['naive_test_auc']:.3f} (gap={zipf['naive_overfit_gap']:+.3f})",
"Replace w/ OOF m-est",
],
[
"zipf_oof_m15_rare5",
f"rare={zipf['rare_merchant_fraction']*100:.1f}%",
f"train_auc={zipf['oof_train_auc']:.3f}",
f"test_auc={zipf['oof_test_auc']:.3f} (gap={zipf['oof_overfit_gap']:+.3f})",
"OOF + __RARE__ pooling",
],
],
},
{
"id": "table_drift_and_shift_matrix",
"title": "SOTA Distribution Shift Matrix (Mobility Telemetry, H0 Storm & Rotation)",
"columns": [
"scenario",
"psi",
"jsd_bits",
"wasserstein_w1",
"ks_stat",
"ks_p_value",
"detector_verdict",
],
"rows": [
[
"mobility_global_ios_bug",
round(mob["global"]["psi"], 4),
round(mob["global"]["jsd_bits"], 4),
round(mob["global"]["wasserstein_w1"], 1),
round(mob["global"]["ks_stat"], 4),
f"{mob['global']['ks_p_value']:.2e}",
"PSI_BLIND_W1_CAUGHT",
],
[
"mobility_ios_4_2_slice",
round(mob["ios_4_2_slice"]["psi"], 3),
round(mob["ios_4_2_slice"]["jsd_bits"], 4),
round(mob["ios_4_2_slice"]["wasserstein_w1"], 1),
round(mob["ios_4_2_slice"]["ks_stat"], 4),
f"{mob['ios_4_2_slice']['ks_p_value']:.2e}",
"SLICE_CRITICAL",
],
[
"small_n50_b20_h0_null",
round(h0["mean_null_psi"], 4),
0.0,
0.0,
round(h0["psi_fpr_at_025"], 3),
round(h0["ks_fpr_at_005"], 3),
"PSI_FPR_HIGH_KS_SAFE",
],
[
"rotation_plus085_minus085_x1",
round(rot["univariate_x1_psi"], 4),
round(rot["univariate_x1_jsd_bits"], 4),
round(rot["univariate_x1_w1"], 4),
round(rot["univariate_x1_ks_stat"], 4),
round(rot["univariate_x1_ks_p_value"], 4),
"UNIVARIATE_BLIND",
],
],
},
{
"id": "table_multivariate_and_lineage",
"title": "Multivariate Shift (C2ST/MMD), Credit PIT Audit & Zero-Pickle Lineage",
"columns": [
"audit_check",
"metric_name",
"observed_value",
"threshold_or_expected",
"status",
],
"rows": [
[
"credit_pit_leaky",
f"adv_auc ({cred['adv_top_feature_leaky']})",
round(cred["adv_auc_leaky"], 4),
"> 0.80 critical",
"LEAKAGE_DETECTED",
],
[
"credit_pit_clean",
"adv_auc (post-repair)",
round(cred["adv_auc_clean"], 4),
"0.48 - 0.55 clean",
"PASS_ISOLATED",
],
[
"rotation_c2st_linear",
"oof_auc (linear)",
round(rot["linear_c2st_auc"], 4),
"<= 0.60 blind",
"BLIND_TO_ROTATION",
],
[
"rotation_c2st_quad",
f"oof_auc ({rot['quadratic_top_feature']})",
round(rot["quadratic_c2st_auc"], 4),
"> 0.85 detected",
"SHIFT_DETECTED",
],
[
"rotation_rbf_mmd",
"mmd_u2 (median bw)",
round(rot["rbf_mmd_u2"], 5),
"> 0.02 detected",
"SHIFT_DETECTED",
],
[
"lineage_and_batch_inv",
"batch_diff / sha256_match",
f"{lineage['batch_invariance_max_abs_diff']:.1e} / {lineage['manifest_deterministic']}",
"<= 1e-12 / True",
"VERIFIED_IMMUTABLE",
],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
"""Execute Lab 04 benchmark suite, print 4 summary blocks, and export JSON if requested."""
args = parse_args(argv)
bench = run_full_lifecycle_benchmarks(quick=bool(args.quick), seed=int(args.seed))
panels = _build_workbench_panels(bench)
lin = bench["contracts_and_lineage"]
eda = bench["eda_and_encoding"]
drift = bench["drift_and_cases"]
print("[1] Split-First Contracts, Typed OOP Pipelines & Zero-Pickle JSON State-Dict Lineage")
print(
f" Temporal embargo split sizes: {lin['temporal_split_sizes']} | "
f"Batch invariance max |diff| = {lin['batch_invariance_max_abs_diff']:.2e}"
)
print(
f" Signed JSON roundtrip max |diff| = {lin['signed_json_roundtrip_max_abs_diff']:.2e} | "
f"Manifest deterministic = {lin['manifest_deterministic']} ({lin['manifest_sha256'][:16]}...)"
)
print("\n[2] Pre-Split Leakage Proofs, Missingness (MCAR/MAR/MNAR), Zero-MAD & Simpson Paradox")
l10 = eda["presplit_leakage_k10"]
icu = eda["icu_mnar"]
zmad = eda["zero_mad_audit"]
simp = eda["simpson_paradox"]
print(
f" Proof 1 centering cross-split corr = {l10['centering_cross_split_corr']:.6f} | "
f"Proof 2 (k=10): pre-split Corr_te={l10['pre_split']['corr_te']:+.3f} (R2={l10['pre_split']['r2_te']:+.3f}) "
f"vs split-first Corr_te={l10['split_first']['corr_te']:+.3f} (R2={l10['split_first']['r2_te']:+.3f})"
)
print(
f" ICU MNAR (p_miss={icu['missing_rate']:.3f}): theo_var={icu['theoretical_var_retention']:.3f} vs "
f"emp_var={icu['empirical_var_retention']:.3f} | blind_mean_AUC={icu['blind_mean_auc']:.3f} -> "
f"is_missing_AUC={icu['is_missing_indicator_auc']:.3f}"
)
print(
f" Zero-MAD fallback mode={zmad['zero_mad_mode']} (scale={zmad['zero_mad_effective_scale']:.3f}, "
f"max_z={zmad['zero_mad_max_z']:.3f}) | Constant mode={zmad['constant_mode']}"
)
print(
f" Simpson 2x2: agg_diff={simp['agg_diff']:+.3f} == within={simp['within_stratum_effect']:+.3f} + "
f"mix={simp['mix_shift_confounding']:+.3f} | direct_std_diff={simp['direct_std_diff']:+.3f} "
f"(reversal={simp['reversal_detected']})"
)
print("\n[3] High-Cardinality OOF m-Estimate Target Encoding & Credit PIT Leakage Benchmark")
zipf = eda["zipf_encoding"]
cred = drift["credit_pit_leakage"]
print(
f" Zipf ({zipf['n_unique_train_merchants']} merchants, {zipf['rare_merchant_fraction']*100:.1f}% <5 obs): "
f"naive train/test={zipf['naive_train_auc']:.3f}/{zipf['naive_test_auc']:.3f} | "
f"OOF m=15 train/test={zipf['oof_train_auc']:.3f}/{zipf['oof_test_auc']:.3f}"
)
print(
f" Credit PIT leak: leaky CV={cred['leaky_cv_train_auc']:.3f} -> live OOT={cred['leaky_oot_auc']:.3f} "
f"(clean OOT={cred['clean_oot_auc']:.3f}) | AUC_adv leaky={cred['adv_auc_leaky']:.3f} "
f"(top={cred['adv_top_feature_leaky']}) -> clean={cred['adv_auc_clean']:.3f}"
)
print("\n[4] SOTA Distribution Shift Suite (PSI Null Bias, JSD, W1, Dual-Series KS, OOF C2ST & RBF MMD)")
mob = drift["mobility_telemetry"]
h0 = drift["small_sample_h0"]
rot = drift["multivariate_rotation"]
print(
f" Mobility iOS v4.2 (contract errors={mob['contract_error_count']}): "
f"Global PSI={mob['global']['psi']:.3f}, W1={mob['global']['wasserstein_w1']:,.1f}s | "
f"Slice iOS_4.2 PSI={mob['ios_4_2_slice']['psi']:.3f}, JSD={mob['ios_4_2_slice']['jsd_bits']:.3f} bits"
)
print(
f" Small-sample H0 (n_cur=50, B=20): mean_PSI={h0['mean_null_psi']:.3f}, "
f"PSI>=0.25 FPR={h0['psi_fpr_at_025']*100:.1f}% vs KS(alpha=0.05) FPR={h0['ks_fpr_at_005']*100:.1f}%"
)
print(
f" Rotation (+0.85->-0.85): 1D KS={rot['univariate_x1_ks_stat']:.3f} (p={rot['univariate_x1_ks_p_value']:.3f}), "
f"linear C2ST={rot['linear_c2st_auc']:.3f}, quadratic C2ST={rot['quadratic_c2st_auc']:.3f} "
f"({rot['quadratic_top_feature']}), RBF MMD_u2={rot['rbf_mmd_u2']:.4f}"
)
if args.output is not None:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"config": vars(args),
"workbench_panels": panels,
"contracts_and_lineage": lin,
"eda_and_encoding": eda,
"drift_and_cases": drift,
}
sanitized = _sanitize_json_value(payload)
out_path.write_text(
json.dumps(sanitized, indent=2, allow_nan=False) + "\n",
encoding="utf-8",
newline="\n",
)
print(f"\nSaved structured JSON report to: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14-test verification suite for lifecycle_eda_lab (Stage 5B, Unit T1-P1-U04)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from pydantic import ValidationError
from lifecycle_eda_lab.contracts_and_lineage import (
ColumnContract,
DataContractSchema,
ReproducibleRngTree,
SplitContract,
build_experiment_manifest,
hash_dataframe_sha256,
split_dataframe,
)
from lifecycle_eda_lab.eda_and_drift import (
_fit_l2_logistic_newton,
adversarial_validation_oof_auc,
compute_jsd,
compute_ks_statistic,
compute_mad_zscore,
compute_psi,
compute_rbf_mmd_u2,
compute_roc_auc,
compute_wasserstein_1d,
diagnose_missingness_mechanisms,
ks_survival_prob,
run_full_lifecycle_benchmarks,
simpson_paradox_audit,
simulate_presplit_leakage_audit,
)
from lifecycle_eda_lab.pipelines_and_encoders import (
ColumnRouter,
NotFittedError,
OutOfFoldTargetEncoder,
RobustMADImputer,
StatefulPipeline,
StatefulStandardizer,
StatefulTransformer,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
# ---------------------------------------------------------------------------
# Test 1: SplitContract embargo, group isolation, and ratio invariants
# ---------------------------------------------------------------------------
def test_split_contract_embargo_group_and_ratio_invariants() -> None:
with pytest.raises(ValidationError):
SplitContract(strategy="stratified_iid", train_ratio=0.7, val_ratio=0.2, test_ratio=0.2)
with pytest.raises(ValidationError):
SplitContract(
strategy="stratified_iid",
train_ratio=0.8,
val_ratio=0.0,
test_ratio=0.2,
unknown_typo_field="bad", # type: ignore[call-arg]
)
with pytest.raises(ValidationError):
SplitContract(strategy="temporal", train_ratio=0.8, test_ratio=0.2, time_col=None)
with pytest.raises(ValidationError):
SplitContract(strategy="group", train_ratio=0.8, test_ratio=0.2, group_col=" ")
with pytest.raises(ValidationError):
SplitContract(
strategy="temporal",
train_ratio=0.7,
val_ratio=0.1,
test_ratio=0.2,
time_col="ts",
embargo_seconds=20.0,
max_train_ts=100.0,
min_val_ts=110.0,
)
t_contract = SplitContract(
strategy="temporal",
train_ratio=0.6,
val_ratio=0.2,
test_ratio=0.2,
time_col="ts",
embargo_seconds=25.0,
)
df_time = pd.DataFrame(
{
"ts": np.arange(100, dtype=np.float64) * 5.0,
"x": np.linspace(0.0, 1.0, 100),
"y": np.arange(100) % 2,
}
)
tr_t, val_t, te_t = split_dataframe(df_time, t_contract, seed=42)
assert val_t is not None
assert float(val_t["ts"].min()) >= float(tr_t["ts"].max()) + 25.0
assert float(te_t["ts"].min()) >= float(val_t["ts"].max()) + 25.0
bad_te = te_t.copy()
bad_te.iloc[0, bad_te.columns.get_loc("ts")] = float(val_t["ts"].max()) + 5.0
with pytest.raises(ValueError, match="embargo violated"):
t_contract.verify_splits(tr_t, bad_te, val_df=val_t)
g_contract = SplitContract(
strategy="group",
train_ratio=0.7,
val_ratio=0.0,
test_ratio=0.3,
group_col="patient_id",
)
df_grp = pd.DataFrame(
{
"patient_id": np.repeat(np.arange(30), 4),
"val": np.arange(120, dtype=np.float64),
}
)
tr_g, val_g, te_g = split_dataframe(df_grp, g_contract, seed=42)
assert val_g is None
assert set(tr_g["patient_id"]).isdisjoint(set(te_g["patient_id"]))
leaky_te_g = pd.concat([te_g, tr_g.iloc[[0]]], ignore_index=True)
with pytest.raises(ValueError, match="Entity/group leakage"):
g_contract.verify_splits(tr_g, leaky_te_g)
# ---------------------------------------------------------------------------
# Test 2: DataContractSchema catches unit spikes, sentinels, extra cols, inf
# ---------------------------------------------------------------------------
def test_data_contract_schema_catches_unit_and_sentinel_corruption() -> None:
schema = DataContractSchema(
schema_version="1.0",
columns=(
ColumnContract(
name="eta_seconds",
dtype_family="float",
nullable=False,
min_value=0.0,
max_value=14400.0,
forbidden_sentinels=(-1.0, -999.0),
),
ColumnContract(name="order_count", dtype_family="int", nullable=False, min_value=1),
ColumnContract(name="app_version", dtype_family="str", nullable=False),
),
allow_extra_columns=False,
min_rows=2,
)
clean_df = pd.DataFrame(
{
"eta_seconds": [420.5, 610.0, 515.2],
"order_count": [1, 3, 2],
"app_version": ["iOS_4.1", "Android_4.1", "iOS_4.1"],
}
)
assert schema.validate_dataframe(clean_df)["passed"] is True
corrupted_df = pd.DataFrame(
{
"eta_seconds": [-1.0, 480_000.0, float("inf")],
"order_count": [1.5, 2.0, 3.0], # float instead of int
"app_version": ["iOS_4.2", "iOS_4.2", "iOS_4.2"],
"unexpected_debug_col": [0, 1, 2],
}
)
res = schema.validate_dataframe(corrupted_df, fail_fast=False)
assert res["passed"] is False
joined = "\n".join(res["errors"])
assert "Unexpected extra columns" in joined
assert "forbidden sentinel" in joined
assert "4.8e+05" in joined or "max=" in joined
assert "+/-inf" in joined
assert "expected integer dtype" in joined
with pytest.raises(ValueError, match="DataContractSchema failed"):
schema.validate_dataframe(corrupted_df, fail_fast=True)
# ---------------------------------------------------------------------------
# Test 3: ReproducibleRngTree isolation & SHA-256 content-addressed manifest
# ---------------------------------------------------------------------------
def test_reproducible_rng_tree_isolation_and_content_addressed_manifest() -> None:
tree_a = ReproducibleRngTree.from_master_seed(42)
tree_b = ReproducibleRngTree.from_master_seed(42)
# Heavy sampling on eda_rng must never perturb split_rng or model_rng
_ = tree_a.eda_rng.standard_normal(50_000)
assert np.array_equal(tree_a.split_rng.random(128), tree_b.split_rng.random(128))
assert np.array_equal(tree_a.model_rng.integers(0, 10_000, size=64), tree_b.model_rng.integers(0, 10_000, size=64))
df = pd.DataFrame({"ts": [1.0, 2.0, 3.0, 4.0], "x": [10.0, 20.0, 30.0, 40.0]})
sc = SplitContract(strategy="temporal", train_ratio=0.75, test_ratio=0.25, time_col="ts")
m1 = build_experiment_manifest(
run_name="unit_test_run",
df=df,
split_contract=sc,
split_indices={"train": [0, 1, 2], "test": [3]},
config={"l2_reg": 1.0},
state_dicts={"scaler": {"means": [20.0]}},
root_seed=42,
)
m2 = build_experiment_manifest(
run_name="unit_test_run",
df=df.copy(),
split_contract=sc,
split_indices={"test": [3], "train": [0, 1, 2]},
config={"l2_reg": 1.0},
state_dicts={"scaler": {"means": [20.0]}},
root_seed=42,
)
for key in ("dataset_sha256", "split_sha256", "config_sha256", "state_dicts_sha256", "manifest_sha256"):
assert len(m1[key]) == 64
assert m1[key] == m2[key]
df_edited = df.copy()
df_edited.loc[1, "x"] = 20.0001
m3 = build_experiment_manifest(
run_name="unit_test_run",
df=df_edited,
split_contract=sc,
split_indices={"train": [0, 1, 2], "test": [3]},
config={"l2_reg": 1.0},
state_dicts={"scaler": {"means": [20.0]}},
root_seed=42,
)
assert m3["dataset_sha256"] != m1["dataset_sha256"]
assert m3["manifest_sha256"] != m1["manifest_sha256"]
assert hash_dataframe_sha256(df) == m1["dataset_sha256"]
# ---------------------------------------------------------------------------
# Test 4: StatefulStandardizer Protocol, read-only buffers, batch invariance
# ---------------------------------------------------------------------------
def test_stateful_standardizer_protocol_readonly_buffers_and_batch_invariance() -> None:
std = StatefulStandardizer()
assert isinstance(std, StatefulTransformer)
with pytest.raises(NotFittedError):
std.transform(np.ones((3, 2)))
with pytest.raises(NotFittedError):
std.to_signed_json()
rng = np.random.default_rng(42)
X_tr = pd.DataFrame(
{
"a": rng.normal(10.0, 3.0, size=100),
"const_col": np.full(100, 7.5),
}
)
std.fit(X_tr)
assert std.state.constant_mask == (False, True)
assert math.isclose(std.scales_[1], 1.0, abs_tol=1e-12)
with pytest.raises(ValueError):
std.state.mean[0] = 999.0
with pytest.raises(ValueError):
std.state.scale[0] = 2.0
X_te = pd.DataFrame(
{
"a": rng.normal(12.0, 4.0, size=200),
"const_col": np.full(200, 7.5),
}
)
out_batch = std.transform(X_te)
assert np.allclose(out_batch["const_col"].to_numpy(), 0.0, atol=1e-12)
out_single = std.transform(X_te.iloc[[37]])
assert np.allclose(out_batch.iloc[[37]].to_numpy(), out_single.to_numpy(), atol=1e-12)
signed = std.to_signed_json()
restored = StatefulStandardizer.from_signed_json(signed)
assert np.allclose(restored.transform(X_te).to_numpy(), out_batch.to_numpy(), atol=1e-12)
tampered_obj = json.loads(signed)
tampered_obj["means"][0] += 0.01
with pytest.raises(ValueError, match="Tampered JSON"):
StatefulStandardizer.from_signed_json(json.dumps(tampered_obj))
router = ColumnRouter(
routes=[("num", StatefulStandardizer(), ["a"])],
remainder="error",
)
assert isinstance(router, StatefulTransformer)
with pytest.raises(ValueError, match="Unexpected columns"):
router.fit(X_tr)
pipe = StatefulPipeline([("std", StatefulStandardizer())])
assert isinstance(pipe, StatefulTransformer)
assert np.allclose(pipe.fit_transform(X_tr).to_numpy(), std.transform(X_tr).to_numpy(), atol=1e-12)
# ---------------------------------------------------------------------------
# Test 5: Robust MAD Z-score consistency, 50% breakdown, and zero-MAD fallback
# ---------------------------------------------------------------------------
def test_robust_mad_zscore_breakdown_and_zero_mad_hierarchy() -> None:
rng = np.random.default_rng(42)
gauss = rng.normal(10.0, 2.5, size=5000)
res_g = compute_mad_zscore(gauss)
assert res_g.scale_mode == "mad"
assert abs(res_g.effective_scale - 2.5) < 0.12
# 40% extreme corruption (below 50% breakdown point)
corrupted = gauss.copy()
corrupted[:2000] = 1e6
assert np.std(corrupted) > 1e5
res_c = compute_mad_zscore(corrupted)
assert res_c.scale_mode == "mad"
assert abs(res_c.median - 10.0) < 3.0
assert res_c.effective_scale < 8.0
assert res_c.outlier_count >= 2000
# Zero-MAD fallback to 1.253314 * MeanAD with NaN preservation
sparse_vec = np.array([0.0, 0.0, 0.0, 0.0, 10.0, float("nan")])
res_z = compute_mad_zscore(sparse_vec)
assert res_z.mad == 0.0
assert res_z.scale_mode == "mean_ad_fallback"
expected_scale = math.sqrt(math.pi / 2.0) * 2.0
assert math.isclose(res_z.effective_scale, expected_scale, rel_tol=1e-12)
assert math.isnan(res_z.z_scores[-1])
assert math.isclose(res_z.z_scores[4], 10.0 / expected_scale, rel_tol=1e-12)
res_const = compute_mad_zscore([5.0, 5.0, 5.0])
assert res_const.scale_mode == "constant"
assert np.array_equal(res_const.z_scores, np.zeros(3))
# ---------------------------------------------------------------------------
# Test 6: Missingness MCAR variance shrinkage & ICU MNAR indicator recovery
# ---------------------------------------------------------------------------
def test_missingness_mcar_variance_shrinkage_and_mnar_indicator_recovery() -> None:
rng = np.random.default_rng(42)
n = 3000
driver = rng.normal(0.0, 1.0, size=n)
x_mcar = rng.normal(5.0, 2.0, size=n)
x_mcar[rng.uniform(size=n) < 0.35] = np.nan
x_mar = rng.normal(0.0, 1.0, size=n)
x_mar[driver > 0.3] = np.nan
y_bin = rng.integers(0, 2, size=n).astype(np.float64)
x_mnar = rng.normal(0.0, 1.0, size=n)
x_mnar[(y_bin == 0) & (rng.uniform(size=n) < 0.75)] = np.nan
diag_df = pd.DataFrame(
{"driver": driver, "mcar_col": x_mcar, "mar_col": x_mar, "mnar_col": x_mnar, "y": y_bin}
)
diag = diagnose_missingness_mechanisms(diag_df, target_col="y")
assert diag["mcar_col"]["regime_flag"] == "mcar_compatible"
assert diag["mar_col"]["regime_flag"] == "mar_covariate_coupled"
assert diag["mnar_col"]["regime_flag"] == "informative_mnar_suspect"
assert abs(diag["mcar_col"]["empirical_var_retention"] - diag["mcar_col"]["theoretical_var_retention"]) < 0.025
bench = run_full_lifecycle_benchmarks(quick=True, seed=42)
icu = bench["eda_and_encoding"]["icu_mnar"]
assert icu["regime_flag"] == "informative_mnar_suspect"
assert abs(icu["empirical_var_retention"] - icu["theoretical_var_retention"]) < 0.025
assert icu["blind_mean_auc"] < 0.62
assert icu["is_missing_indicator_auc"] >= 0.78
imp = RobustMADImputer(numeric_cols=["mcar_col"], add_missing_indicators=True)
with pytest.raises(NotFittedError):
imp.transform(diag_df[["mcar_col"]])
imp.fit(diag_df[["mcar_col"]])
restored = RobustMADImputer.from_state_dict(imp.to_state_dict())
t1 = imp.transform(diag_df[["mcar_col"]].iloc[:10])
t2 = restored.transform(diag_df[["mcar_col"]].iloc[:10])
assert np.allclose(t1.to_numpy(), t2.to_numpy(), atol=1e-12)
# ---------------------------------------------------------------------------
# Test 7: OutOfFoldTargetEncoder EB smoothing, rare pooling, groups, & Zipf
# ---------------------------------------------------------------------------
def test_oof_target_encoder_eb_smoothing_rare_pooling_and_zipf_benchmark() -> None:
df = pd.DataFrame(
{
"cat": ["A"] * 6 + ["B"] * 6 + ["rare1", "rare2", np.nan, np.nan, np.nan, np.nan, np.nan],
"grp": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 1, 2, 3, 4, 5, 6, 1],
}
)
y = np.array([1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0], dtype=np.float64)
mu0 = float(np.mean(y))
enc = OutOfFoldTargetEncoder(cols=["cat"], smoothing_m=10.0, min_samples=5, n_folds=3, seed=42)
enc.fit(df, y)
# Exact Empirical-Bayes formula verification
expected_a = (4.0 + 10.0 * mu0) / (6.0 + 10.0)
expected_rare = (2.0 + 10.0 * mu0) / (2.0 + 10.0)
expected_miss = (0.0 + 10.0 * mu0) / (5.0 + 10.0)
assert math.isclose(enc.mappings_["cat"]["A"], expected_a, abs_tol=1e-12)
assert math.isclose(enc.mappings_["cat"]["__RARE__"], expected_rare, abs_tol=1e-12)
assert math.isclose(enc.mappings_["cat"]["__MISSING__"], expected_miss, abs_tol=1e-12)
# Groups-aware OOF isolation: group 4 has both rows of B with y=0 -> OOF must not see those 0s
oof_df = enc.fit_transform(df, y, groups=df["grp"])
assert not np.allclose(oof_df["cat"].to_numpy(), enc.transform(df)["cat"].to_numpy())
# JSON state dict roundtrip including unseen fallback
restored = OutOfFoldTargetEncoder.from_state_dict(enc.to_state_dict())
eval_df = pd.DataFrame({"cat": ["A", "UNSEEN_MERCHANT", None]})
t_orig = enc.transform(eval_df)["cat"].to_numpy()
t_rest = restored.transform(eval_df)["cat"].to_numpy()
assert np.allclose(t_orig, t_rest, atol=1e-12)
assert math.isclose(t_orig[1], expected_rare, abs_tol=1e-12)
assert math.isclose(t_orig[2], expected_miss, abs_tol=1e-12)
bench = run_full_lifecycle_benchmarks(quick=True, seed=42)
zipf = bench["eda_and_encoding"]["zipf_encoding"]
assert zipf["naive_overfit_gap"] > 0.08
assert zipf["oof_overfit_gap"] < 0.03
assert zipf["oof_test_auc"] > zipf["naive_test_auc"]
# ---------------------------------------------------------------------------
# Test 8: Pre-split leakage proofs (centering -1.0 & noise screening illusion)
# ---------------------------------------------------------------------------
def test_presplit_leakage_proofs_mean_anticorrelation_and_noise_screening_illusion() -> None:
res = simulate_presplit_leakage_audit(n_samples=100, n_features=2000, top_k=10, n_trials=40, seed=42)
assert math.isclose(res["centering_cross_split_corr"], -1.0, abs_tol=1e-10)
assert abs(res["centering_observed_shift_ratio"] - res["centering_expected_shift_ratio"]) < 0.08
assert res["pre_split"]["corr_te"] > 0.45
assert res["pre_split"]["r2_te"] > 0.15
assert abs(res["split_first"]["corr_te"]) < 0.08
assert res["split_first"]["r2_te"] < 0.0
# ---------------------------------------------------------------------------
# Test 9: Simpson's Paradox exact decomposition & direct standardization
# ---------------------------------------------------------------------------
def test_simpson_paradox_exact_decomposition_and_direct_standardization() -> None:
rows: list[tuple[int, str, int]] = []
rows.extend((0, "Cold_Mobile", 1) for _ in range(180))
rows.extend((0, "Cold_Mobile", 0) for _ in range(720))
rows.extend((0, "Returning_Desktop", 1) for _ in range(85))
rows.extend((0, "Returning_Desktop", 0) for _ in range(15))
rows.extend((1, "Cold_Mobile", 1) for _ in range(15))
rows.extend((1, "Cold_Mobile", 0) for _ in range(85))
rows.extend((1, "Returning_Desktop", 1) for _ in range(720))
rows.extend((1, "Returning_Desktop", 0) for _ in range(180))
df = pd.DataFrame(rows, columns=["variant", "segment", "converted"])
res = simpson_paradox_audit(df, "variant", "converted", "segment")
assert math.isclose(res.agg_rate_ctrl, 0.265, abs_tol=1e-12)
assert math.isclose(res.agg_rate_trt, 0.735, abs_tol=1e-12)
assert math.isclose(res.within_stratum_effect, -0.05, abs_tol=1e-12)
assert math.isclose(res.mix_shift_confounding, 0.52, abs_tol=1e-12)
assert math.isclose(
res.agg_diff, res.within_stratum_effect + res.mix_shift_confounding, abs_tol=1e-12
)
assert res.reversal_detected is True
assert math.isclose(res.direct_std_rate_ctrl, 0.525, abs_tol=1e-12)
assert math.isclose(res.direct_std_rate_trt, 0.475, abs_tol=1e-12)
assert math.isclose(res.direct_std_diff, -0.05, abs_tol=1e-12)
# ---------------------------------------------------------------------------
# Test 10: PSI exact null bias (B-1) vs (B-1)/2 & small-sample alarm guard
# ---------------------------------------------------------------------------
def test_psi_exact_null_bias_coefficient_and_small_sample_alarm_guard() -> None:
rng = np.random.default_rng(42)
b_bins, n_ref, n_cur = 10, 2000, 200
n_mc = 250
psis = np.empty(n_mc, dtype=np.float64)
for i in range(n_mc):
ref = rng.standard_normal(n_ref)
cur = rng.standard_normal(n_cur)
psis[i] = compute_psi(ref, cur, bins=b_bins)["psi"]
empirical_mean = float(np.mean(psis))
exact_bias = (b_bins - 1) * (1.0 / n_ref + 1.0 / n_cur)
wrong_half_bias = 0.5 * exact_bias
assert math.isclose(empirical_mean, exact_bias, rel_tol=0.18)
assert abs(empirical_mean - exact_bias) < abs(empirical_mean - wrong_half_bias)
# Small-sample storm: B=20, n_cur=50
ref_big = rng.standard_normal(5000)
psi_hits = 0
ks_hits = 0
for _ in range(250):
cur_50 = rng.standard_normal(50)
p_res = compute_psi(ref_big, cur_50, bins=20)
assert p_res["small_sample_noise_risk"] is True
if p_res["psi"] >= 0.25:
psi_hits += 1
if compute_ks_statistic(ref_big, cur_50)["p_value"] < 0.05:
ks_hits += 1
assert (psi_hits / 250.0) > 0.70
assert (ks_hits / 250.0) <= 0.08
# Constant reference + NaN-bin preservation
const_res = compute_psi([5.0] * 50, [5.0] * 40 + [9.0] * 10, bins=10)
assert const_res["effective_bins"] == 2
assert const_res["psi"] > 1.0
nan_ref = np.concatenate([rng.normal(0.0, 1.0, 100), [np.nan] * 2])
nan_cur = np.concatenate([rng.normal(0.0, 1.0, 100), [np.nan] * 40])
nan_res = compute_psi(nan_ref, nan_cur, bins=5, include_nan_bin=True)
assert nan_res["effective_bins"] == 6
assert nan_res["psi"] > 0.25
# ---------------------------------------------------------------------------
# Test 11: JSD bounds/metric, W1 disjoint linearity & mobility slice catch
# ---------------------------------------------------------------------------
def test_jsd_bounds_wasserstein_disjoint_linearity_and_telemetry_slice_catch() -> None:
rng = np.random.default_rng(42)
p = rng.normal(0.0, 1.0, 400)
q = rng.normal(0.8, 1.0, 400)
r = rng.normal(2.2, 1.2, 400)
j_pq_bits = compute_jsd(p, q, base="bits")
j_pq_nats = compute_jsd(p, q, base="nats")
assert 0.0 <= j_pq_bits <= 1.0
assert 0.0 <= j_pq_nats <= math.log(2.0) + 1e-12
assert math.isclose(j_pq_bits * math.log(2.0), j_pq_nats, rel_tol=1e-9)
d_pq = math.sqrt(compute_jsd(p, q, bins=10, strategy="uniform", base="nats"))
d_qr = math.sqrt(compute_jsd(q, r, bins=10, strategy="uniform", base="nats"))
d_pr = math.sqrt(compute_jsd(p, r, bins=10, strategy="uniform", base="nats"))
assert d_pr <= d_pq + d_qr + 0.05 # empirical bin-edge consistency check
assert math.isclose(compute_wasserstein_1d([0.0, 1.0, 2.0], [3.0, 4.0]), 2.5, abs_tol=1e-12)
d0 = np.zeros(50)
for delta in (0.1, 10.0, 1000.0):
d_delta = np.full(50, delta)
assert math.isclose(compute_wasserstein_1d(d0, d_delta), delta, rel_tol=1e-12)
assert math.isclose(compute_jsd(d0, d_delta, base="bits"), 1.0, abs_tol=1e-12)
assert math.isclose(compute_ks_statistic(d0, d_delta)["ks_stat"], 1.0, abs_tol=1e-12)
bench = run_full_lifecycle_benchmarks(quick=True, seed=42)
mob = bench["drift_and_cases"]["mobility_telemetry"]
assert mob["global"]["psi"] < 0.25
assert mob["global"]["wasserstein_w1"] > 10_000.0
assert mob["ios_4_2_slice"]["psi"] > 1.0
# ---------------------------------------------------------------------------
# Test 12: KS Jacobi theta dual-series stability & tail vs big-data traps
# ---------------------------------------------------------------------------
def test_ks_jacobi_theta_dual_series_stability_and_tail_vs_bigdata_traps() -> None:
left = ks_survival_prob(0.27 - 1e-8)
right = ks_survival_prob(0.27)
assert math.isclose(left, right, abs_tol=1e-12)
assert 0.0 <= ks_survival_prob(0.05) <= 1.0
assert ks_survival_prob(0.05) >= ks_survival_prob(0.15) >= ks_survival_prob(0.5)
rng = np.random.default_rng(42)
ref = rng.standard_normal(1000)
cur_spike = ref.copy()
cur_spike[:50] = 1e6 # 5% extreme tail explosion
ks_spike = compute_ks_statistic(ref, cur_spike)
w1_spike = compute_wasserstein_1d(ref, cur_spike)
assert ks_spike["ks_stat"] <= 0.06
assert w1_spike > 10_000.0
# Big-data false-alarm sensitivity: 0.005*sigma drift at n=100,000
big_ref = rng.normal(0.0, 1.0, size=100_000)
big_cur = rng.normal(0.015, 1.0, size=100_000)
ks_big = compute_ks_statistic(big_ref, big_cur)
assert ks_big["ks_stat"] < 0.02
assert ks_big["p_value"] < 0.01
# ---------------------------------------------------------------------------
# Test 13: Adversarial validation OOF AUC, quadratic rotation & RBF MMD_u^2
# ---------------------------------------------------------------------------
def test_adversarial_validation_oof_auc_quadratic_rotation_and_rbf_mmd_u2() -> None:
rng = np.random.default_rng(42)
X_tr = pd.DataFrame(
{
"f1": rng.normal(0.0, 1.0, 300),
"f2": rng.normal(5.0, 2.0, 300),
"row_id": np.arange(300, dtype=np.float64),
}
)
X_te = pd.DataFrame(
{
"f1": rng.normal(0.0, 1.0, 300),
"f2": rng.normal(5.0, 2.0, 300),
"row_id": np.arange(300, 600, dtype=np.float64),
}
)
clean_adv = adversarial_validation_oof_auc(X_tr[["f1", "f2"]], X_te[["f1", "f2"]], seed=42)
assert 0.43 <= clean_adv.auc_adv <= 0.57
assert clean_adv.critical_leakage_alert is False
leaky_adv = adversarial_validation_oof_auc(X_tr, X_te, seed=42)
assert leaky_adv.auc_adv > 0.90
assert leaky_adv.critical_leakage_alert is True
assert leaky_adv.top_shift_feature == "row_id"
# Bivariate correlation rotation (+0.85 -> -0.85) with identical 1D marginals
cov_pos = np.array([[1.0, 0.85], [0.85, 1.0]])
cov_neg = np.array([[1.0, -0.85], [-0.85, 1.0]])
rot_ref = rng.multivariate_normal([0.0, 0.0], cov_pos, size=350)
rot_cur = rng.multivariate_normal([0.0, 0.0], cov_neg, size=350)
lin_rot = adversarial_validation_oof_auc(
rot_ref, rot_cur, feature_names=["x1", "x2"], include_quadratic=False, seed=42
)
quad_rot = adversarial_validation_oof_auc(
rot_ref, rot_cur, feature_names=["x1", "x2"], include_quadratic=True, seed=42
)
mmd_rot = compute_rbf_mmd_u2(rot_ref, rot_cur, max_samples=350, seed=42)
assert lin_rot.auc_adv <= 0.60
assert quad_rot.auc_adv > 0.85
assert quad_rot.top_shift_feature == "x1*x2"
assert mmd_rot["mmd_u2"] > 0.02
# Tie-aware Mann-Whitney ROC-AUC check & in-fold NaN handling in quadratic C2ST
rot_ref_nan = rot_ref.copy()
rot_cur_nan = rot_cur.copy()
rot_ref_nan[:10, 0] = np.nan
rot_cur_nan[:10, 1] = np.nan
quad_nan = adversarial_validation_oof_auc(
rot_ref_nan, rot_cur_nan, feature_names=["x1", "x2"], include_quadratic=True, seed=42
)
assert quad_nan.auc_adv > 0.80
assert math.isclose(compute_roc_auc([0, 0, 1, 1], [0.5, 0.5, 0.5, 0.5]), 0.5, abs_tol=1e-12)
w, b = _fit_l2_logistic_newton(np.array([[-2.0], [-1.0], [1.0], [2.0]]), np.array([0.0, 0.0, 1.0, 1.0]))
assert float(w[0]) > 0.0 and math.isfinite(b)
# ---------------------------------------------------------------------------
# Test 14: CLI demo execution, workbench_panels JSON schema & AST import guard
# ---------------------------------------------------------------------------
def test_cli_demo_script_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch04_workbench_results.json"
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
proc = subprocess.run(
[sys.executable, str(script_path), "--seed", "42", "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
for section_hdr in (
"[1] Split-First Contracts",
"[2] Pre-Split Leakage Proofs",
"[3] High-Cardinality OOF",
"[4] SOTA Distribution Shift Suite",
):
assert section_hdr in proc.stdout
assert out_json.is_file()
payload = json.loads(out_json.read_text(encoding="utf-8"))
for key in (
"config",
"workbench_panels",
"contracts_and_lineage",
"eda_and_encoding",
"drift_and_cases",
):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert isinstance(kpi["value"], str) and kpi["value"]
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 Ban across src/, scripts/, and tests/
# (Reference Core zero-scipy/sklearn/polars parity is documented separately as informational.)
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"Forbidden unsafe 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"Forbidden unsafe from-import '{node.module}' in {py_file}"
)
src/, Bất biến Sâu & Tách luồng SeedSequence
src/<pkg>/, khóa buffer bằng arr.setflags(write=False), và tạo cây RNG bằng SeedSequence.spawn() thay vì np.random.seed(42) toàn cục?frozen=True của Python chỉ khóa việc gán lại thuộc tính (bất biến nông), còn mảng NumPy vẫn sửa được tại chỗ nếu thiếu setflags(write=False). Bố cục src/ ép kiểm thử chạy trên gói đã cài đặt thật và SeedSequence.spawn ngăn hiệu ứng cánh bướm sang bộ tách tập.
MCAR/MAR/MNAR) & Co rút Phương sai
MCAR với xác suất \(p_{\text{miss}} = 0.50\) và ta điền toàn bộ giá trị khuyết bằng trung bình (không thêm cờ is_missing), phương sai \(\operatorname{Var}(\tilde{X})\) và tương quan \(\rho(\tilde{X}, Z)\) biến đổi thế nào? Nếu thực tế dữ liệu là MNAR (xét nghiệm lactate chỉ đo khi nghi nhiễm trùng huyết), rủi ro là gì?MAR khỏi MNAR; giữ cờ is_missing là bắt buộc.
MAD, Xử lý MAD == 0 & Mã hóa Mục tiêu OOF \(m\)-Estimate
MAD là \(c_{\text{MAD}} = 1/\Phi^{-1}(0.75) \approx 1.4826\). Khi một cột chi tiêu có >50% giá trị bằng 0 ([0, 0, 0, 0, 10, NaN]) làm MAD == 0, và khi cột merchant_id có hàng nghìn nhãn Zipf hiếm (n_c = 1..4), xử lý đúng đắn là gì?MAD + 1e-12 khi MAD == 0 thổi phồng z-score lên hàng tỷ lần; thang xử lý đúng là Hurdle -> 1.2533 * MeanAD -> constant. Trong mã hóa mục tiêu, gộp __RARE__ + OOF + co rút Bayes loại bỏ ghi nhớ nhãn 0/1.
+5.0 pp ở CẢ Stratum 1 (20% vs 15%) VÀ Stratum 2 (85% vs 80%), nhưng do 90% lưu lượng của A rơi vào Stratum 1 còn 90% lưu lượng của B rơi vào Stratum 2, tỷ lệ cộng gộp thô cho A = 26.5% và B = 73.5% (B hơn +47.0 pp). Nhờ đẳng thức nào ta nhận diện và giải ảo hiện tượng này?-5.0 pp) khỏi số hạng nhiễu chuyển dịch cơ cấu tầng (+52.0 pp). Chuẩn hóa trực tiếp theo tỷ trọng gộp trung lập hóa nhiễu cơ cấu trước khi chuyển sang suy luận nhân quả ở Chương 05.
PSI, Cận JSD, \(W_1\) & KS Song đối
PSI, phản ứng khi iOS v4.2 (18% lưu lượng) nhân nhầm đơn vị lên 1000x, và đánh giá KS khi \(\lambda < 0.27\)?PSI là phân kỳ Jeffreys (tổng đối xứng của hai phân kỳ KL nên \(1/2 + 1/2 = 1\)), dẫn tới bão báo động giả khi n_cur nhỏ. Hộp phân vị đóng băng nhốt đột biến 1000x vào hộp cuối cùng [Q90, +inf), nên cần 1D \(W_1\) và cắt lát chiều; KS cần chuỗi song đối Jacobi theta để tránh triệt tiêu số học khi \(\lambda < 0.27\).
C2ST, Rủi ro pickle (CVE-2025-54886) & Marimo
.pkl hoặc skops <= 0.12.0 không đáng tin cậy; (3) đột biến df['x'] = ... tại chỗ trong notebook phản ứng Marimo. Kết luận nào ĐÚNG?C2ST phi tuyến/bậc hai hoặc MMD nhân RBF mới bắt được. Trong sản xuất, hãy loại bỏ hoàn toàn pickle để chặn CWE-502/ABI break và viết hàm thuần trả về đối tượng mới trong Marimo.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Rò rỉ Tiền Tách tập (Quy tâm -1 & Phép quay 45° Sàng lọc Nhiễu) 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Với Chứng minh 1, xuất phát từ \(\bar{X}_{\text{all}} = \alpha_{\text{tr}}\bar{X}_{\text{tr}} + \alpha_{\text{te}}\bar{X}_{\text{te}}\) suy ra đồng nhất thức \(\alpha_{\text{tr}}\bar{\tilde{X}}_{\text{tr}} + \alpha_{\text{te}}\bar{\tilde{X}}_{\text{te}} \equiv 0\) và viết hiệp phương sai \(\operatorname{Cov}(X_i - \bar{X}_{\text{all}}, X_k)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với Chứng minh 2, đặt \(u_j^{\text{tr}} = \sqrt{n_{\text{tr}}} r_j^{\text{tr}}\) và \(u_j^{\text{te}} = \sqrt{n_{\text{te}}} r_j^{\text{te}}\), xoay trực giao \(S_j = (u_j^{\text{tr}} + u_j^{\text{te}})/\sqrt{2}\) và \(D_j = (u_j^{\text{tr}} - u_j^{\text{te}})/\sqrt{2}\), rồi gọi simulate_presplit_leakage_audit ở k in {1, 5, 10, 20}.
Tiêu chí Đáp án & Số đối chứng
Hai trung bình phần dư sau quy tâm toàn cục phản tương quan đúng bằng -1.000. Khi chọn top_k=10 trên nhiễu N=100, d=2000, sàng lọc tiền tách tập tạo Corr_te = +0.631 và R2_te = +0.325 vì cả hai nửa chia sẻ cùng đỉnh nhiễu r_all, trong khi tách tập trước lột trần Corr_te = -0.038 và R2_te = -0.427.
Bài tập 2 — Co rút Phương sai MCAR, Cận Đổ vỡ MAD 50% & Cờ is_missing Lâm sàng MNAR
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết \(\tilde{X} - \mu = (1 - M)(X - \mu)\), dùng \((1 - M)^2 = 1 - M\) và tính độc lập MCAR \(M \perp (X, Z)\) để chứng minh \(\operatorname{Var}(\tilde{X}) = (1 - p_{\text{miss}})\sigma_X^2\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với MAD, đặt \(m_{\text{err}} < n/2\) để thấy hơn một nửa mẫu sạch vẫn kẹp trung vị bên trong đường kính sạch \(R_{\text{clean}}\); kiểm chứng RobustMADImputer trên mô phỏng ICU tách theo patient_id và compute_mad_zscore([0,0,0,0,10,NaN]).
Tiêu chí Đáp án & Số đối chứng
Thực nghiệm trên ICU (p_miss = 0.538) khớp lý thuyết 1 - p_miss = 0.462 chính xác tới 3 chữ số; thêm cờ is_missing nâng AUC trên bệnh nhân mới từ 0.490 lên 0.793. Nhánh mean_ad_fallback trên [0,0,0,0,10,NaN] tránh chia 0 mượt mà với effective_scale = 2.507, max_z = 3.989.
Bài tập 3 — Mã hóa Mục tiêu OOF \(m\)-Estimate & Đại số Nghịch lý Simpson
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Liên hệ công thức \(\hat{e}_c = \frac{n_c\bar{y}_c + m_{\text{smooth}}\mu_0}{n_c + m_{\text{smooth}}}\) với kỳ vọng hậu nghiệm Beta–Binomial từ Chương 03 (alpha = m_smooth * mu_0, beta = m_smooth * (1 - mu_0)).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng OutOfFoldTargetEncoder(..., min_samples=5, smoothing_m=15) tôn trọng groups trên dữ liệu Zipf merchant_id, và chạy simpson_paradox_audit kiểm tra tổng within_stratum_effect + mix_shift_confounding == agg_diff.
Tiêu chí Đáp án & Số đối chứng
Trên 1,529 merchant Zipf (85.9% hiếm <5), OOF \(m\)-estimate giảm khoảng cách quá khớp từ +0.117 (test=0.665) xuống còn +0.008 (test=0.704). Hàm Simpson giải mã agg_diff = +0.470 = -0.050 (within) + 0.520 (mix) và khôi phục chuẩn hóa trực tiếp -0.050.
Bài tập 4 — Chứng minh Thiên lệch PSI, Cận JSD, Dạng đóng \(W_1\) & Đột biến iOS v4.2
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khai triển bậc hai \(\ln(\hat{p}_b/\hat{q}_b) \approx (\delta_b - \eta_b)/p_b - (\delta_b^2 - \eta_b^2)/(2p_b^2)\) nhân với \(\delta_b - \eta_b\) để thấy hệ số trước \((\delta_b - \eta_b)^2/p_b\) là 1, tổng hóa \(\sum (1 - p_b) = B - 1\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chứng minh \(\ln(p/(0.5p + 0.5q)) \le \ln 2\) cho JSD, chứng minh tích phân từng lớp \(W_1 = \int |F_P - F_Q|\,dx\) qua cặp đồng biến \((F_P^{-1}(U), F_Q^{-1}(U))\), và đối chiếu PSI vs W_1 trên kịch bản iOS v4.2 + n_cur=50, B=20.
Tiêu chí Đáp án & Số đối chứng
Monte Carlo \(H_0\) xác nhận kỳ vọng PSI khớp (B - 1)(1/n_ref + 1/n_cur), còn n_cur=50, B=20 gây 94.8% báo động giả ở PSI >= 0.25 (so với KS 4.0%). Trên iOS v4.2 (1000x + -1.0), Global PSI = 0.117 (<0.25!) bị đánh lừa trong khi W1 = 62,141.8s và iOS_4.2 slice PSI = 10.62 bắt trọn.
Bài tập 5 — Điểm mù C2ST Tuyến tính trước Xoay Tương quan & Kiểm toán Tín dụng PIT
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tạo hai phân phối 2D Chuẩn \(\Sigma_{+0.85}\) và \(\Sigma_{-0.85}\) có biên \(\mathcal{N}(0, 1)\) y hệt nhau; quan sát các chỉ số 1D và bộ phân loại tuyến tính \(w_1 x_1 + w_2 x_2 + b\) không có thông tin phân tách.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Bật include_quadratic=True trong adversarial_validation_oof_auc để bổ sung \(x_1^2, x_2^2, x_1 x_2\) và đối chiếu với compute_rbf_mmd_u2; đồng thời quét tập tín dụng PIT Case 1 để gỡ các đặc trưng hậu quả tương lai.
Tiêu chí Đáp án & Số đối chứng
Bản tuyến tính C2ST chỉ đạt AUC = 0.539 trên xoay tương quan, nhưng bật bậc hai nhảy vọt lên AUC = 0.919 với cột đứng đầu x1*x2 và MMD_u^2 = 0.0944. Trong tín dụng PIT, gỡ post_default_limit hạ AUC_adv từ 0.989 về 0.497 và khôi phục OOT AUC thật 0.719.
Bài tập 6 — Hợp đồng Định kiểu, Bất biến Lô & Phả hệ State-Dict Không-pickle
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khởi tạo SplitContract, DataContractSchema và ReproducibleRngTree.from_master_seed(42), xâu chuỗi RobustMADImputer + OutOfFoldTargetEncoder + StatefulStandardizer vào StatefulPipeline.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra transform(single_row) khớp transform(batch)[0:1] tới 1e-12; sửa 1 chữ số trong JSON của to_signed_json() để xác nhận from_signed_json() báo lỗi checksum giả mạo; và xuất build_experiment_manifest.
Tiêu chí Đáp án & Số đối chứng
Hệ thống đạt batch_invariance_max_abs_diff = 0.0, chặn mọi sửa đổi tại chỗ bằng ValueError: assignment destination is read-only, phát hiện sửa đổi JSON trái phép qua SHA-256, và quét AST xác nhận 0 import pickle, joblib, scipy, sklearn hay polars.