Chương 08 — Kỹ thuật Đặc trưng (Feature Engineering) & Đường ống Học máy Tự động Chống Rò rỉ
Từ 4 Thang đo Stevens, Bộ Năm Cải thiện/Kiến tạo/Chọn lọc/Trích xuất/Biểu diễn (MLE Box-Cox có Jacobian, Yeo-Johnson, KSG/Miller-Madow MI, Boruta/Null-Importance PIMP, PAVA WoE/IV, Signed Hashing, OOF James-Stein, PLR Embeddings) đến ColumnTransformer & PIT Causal DAG.
Unit ID:
T1-P2-U03
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Truy xuất Giáo trình Gốc (R31,E29:E31): Lesson 6 (Feature Engineering: Basic to Advanced Topics — 2 buổi, phủ trọn vẹn 100% cả 6 mục:Data types,4 levels of measurements,The big five of feature engineering,Statistical feature evaluation metrics,ML pipelines,Industrial tips), gắn kết miền Tài chính/Ngân hàng (Credit Scoring WoE/IV) & Marketing/E-Commerce (Ranh giới không chồng lấn: chẩn đoánMCAR/MAR/MNAR& dịch chuyểnPSI/JSD/W_1/KS/MMDkế thừa từch-04; tối ưu hóa tuyến tính/logistic & bộ tách kiểm chứng kế thừa từch-06; phân loại 6 lớp rò rỉ#1& hiệu chuẩn chi phí#2chuyển giao sangch-07-leakage-proof-evaluation-and-calibration.md; hạ tầng Feature Store phân tánKafka/Flink/Feast/ClickHousecầu nối sang Track 2ch-11#15)
Bài thực hành Song hành (Lab 08):labs/ch08-feature-engineering-workbench/(feature_eng_lab)
Tình huống Mở đầu: Bốn Thảm họa Đặc trưng & Đường ống Khiến Mô hình Sụp đổ Khi Ra Sản xuất#
Trong học máy dữ liệu bảng (tabular ML), chất lượng của không gian biểu diễn đặc trưng \(\Phi_{\hat{\theta}}(\mathbf{X})\) và tính kỷ luật của đường ống biến đổi (Feature Pipeline) quyết định ranh giới giữa một mô hình bền vững ngoài sản xuất và một ảo ảnh phòng thí nghiệm sụp đổ ngay giờ đầu tiên phục vụ:
- Vi phạm Thang đo Stevens & Sụp đổ
Box–CoxBỏ quên Jacobian: Gán mã số nguyên1..12cho mã vùngNominalhoặc tính trung bình điểm khảo sátOrdinalLikert phá hủy hoàn toàn tính bất biến đo lường (R^2biến thiên giả0.00 -> 0.75, hiệu hai nhóm đảo dấu+0.50 -> -0.75). Song song đó, tối ưu hóa tham số lũy thừaBox–Coxbằng cách cực tiểu hóa phương sai phần dư mà bỏ qua số hạng Jacobian \((\lambda - 1)\sum_{i=1}^n \ln x_i\) đẩy \(\hat{\lambda}\) sụp về biên âm (-1.279thay vì MLE đúng-0.045cắtskewtừ4.00xuống0.001), còn việc đưa số dư âm/bằng0vàolog/Box–Coxgây sập chuỗi xử lý nếu thiếuYeo–Johnson. - Điểm mù Tương quan (
Y = X^2,XOR) & BẫyTree-Gain (MDI)Tôn vinh NhiễuK = 200: Bộ lọc tuyến tínhPearsonvà đơn điệuSpearmanđều mù tịt trên quan hệ hình chữ U đối xứng \(Y = X^2\) (|r| = 0.077,rho = 0.043), trong khiKSG-1Mutual Information bắt gọn1.792 nats. Ngược lại, dùngMean Decrease in Impurity (MDI)của cây quyết định CART trên biến phân loại nhiễu nhiều mức (high-cardinality,K = 200) tạo ra thiên lệch \(\mathcal{O}(K/n)\), thổi phồng tầm quan trọng của nhiễu lên0.622— gấp4xtín hiệu nhị phân thật (0.154) — cho đến khi bị vạch trần bởiOOF Permutation(+0.302vs.-0.151) vàNull-Importance (PIMP)(pimp_z = -7.91,q = 1.0). - Ảo giác Rò rỉ Tương lai
PIT(0.857 -> 0.788), Thẻ điểm Răng cưa & Ghi nhớ Nội mẫu: Dùnggroupby().transform('mean')hoặc cửa sổrollingkhông loại điểm hiện tại/tương lai cho phép các đợt giao dịch gian lận xảy ra sau \(t_{\text{obs}}\) chảy ngược về quá khứ (Leaky AUC = 0.857vs.Causal PIT AUC = 0.788ngoài đời). Trong chấm điểm tín dụng ngân hàng (SR 11-7), chia khoảng đều tạo đường cong rủi ro răng cưa chữ U và lỗi chia0ở ô không có vỡ nợ nếu thiếuPAVAđơn điệu + làm mượt Laplace (IV = 0.4039, phát hiện canaryIV = 3.94 > 0.50). Tương tự, mã hóa trung bình mục tiêu nội mẫu ghi nhớ ID hiếm (Train AUC = 0.836 -> Test 0.710), đòi hỏiOOF James–Steintôn trọng nhóm (0.692 -> 0.702). - Ảo ảnh Tiền Tách tập
0.878, Rủi ropickle(CWE-502) & Điểm mù Phổ của Mạng Nơ-ron (PLR): Lọc top-15đặc trưng tương quan trên dữ liệu nhiễu Gaussian trắng hoàn toàn (n = 110, d = 1000) trước khi chia nếp CV bịa raAUC = 0.878(trong khi đường ống khép kín trong nếp lột trầnAUC = 0.387). Ở chiều mô hình hóa, mạng nơ-ron thô thất bại trên các ngưỡng bậc thang sắc nét (AUC = 0.491) cho đến khi được trang bị nhúng tuần hoànPLR(AUC = 0.977), còn triển khai thực tế đòi hỏi đóng góiColumnTransformerDAGbằngJSON State-DictkýHMAC-SHA256khôngpicklevới sai khác lô–đơn1.11e-16tại0.044 msp99.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn Chương 08 và bài thực hành feature_eng_lab (T1-P2-U03), học viên có đủ năng lực để:
- Làm chủ Phân loại Dữ liệu & Lý thuyết Bất biến Đo lường Stevens (Math & Scale Rigor): Phân biệt rạch ròi dữ liệu có cấu trúc (tabular, relational \(1:M\), event logs, time series), bán cấu trúc (
JSON/Parquetlồng) và phi cấu trúc (text/image/embeddings); chứng minh các nhóm tự đẳng cấu \(G_{\text{rat}} \subsetneq G_{\text{int}} \subsetneq G_{\text{ord}} \subsetneq G_{\text{nom}}\) và định lý phản ví dụ trênOrdinalLikert,Nominalmã nguyên vàIntervaltỷ lệ/log. - Triển khai Thành thạo Ngũ trụ Kỹ thuật Đặc trưng ("The Big Five"):
- Cải thiện (
Improvement): Cờ báo thiếu, cắt ngưỡng1.4826 * MAD(nhánh dự phòngMeanAD), tối ưu hợp lýBox–Cox(chứng minh hạng tử Jacobian),Yeo–Johnsontrên \(\mathbb{R}\), và chuẩn hóaRankGaussqua nghịch đảo Acklam \(\Phi^{-1}\). - Kiến tạo (
Construction): Tỷ lệ miền bảo vệ mẫu số, định điều kiện đa thức, mã hóa chu kỳ \((\sin, \cos)\) bảo toàn khoảng cách trắc địa \(S^1\), cửa sổ cuộn nhân quảPIT\([t_{\text{obs}} - W, t_{\text{obs}})\) +EWMAdòng sự kiện, vàWoE/IVNgân hàng đơn điệuPAVA+ làm mượt Laplace + cờIV > 0.50+CSI. - Chọn lọc (
Selection): Phân tích điểm mùPearson/Spearman, ước lượngMIMiller–Madow &KSG-1(\(L_\infty\) + digamma \(\psi\)),Pearson\(\chi^2\) & Bergsma Cramér's \(\tilde{V}\), bẫy \(\mathcal{O}(K/n)\) củaCART MDI,OOF Permutation,Collinearity-Cluster Permutation,Null-Importance (PIMP + BH-FDR), vàBorutakiểm định nhị thức trước ngưỡngMZSA. - Trích xuất (
Extraction):PCA/TruncatedSVDtrong nếp,OOF James–Stein(\(m^* = \sigma_{\text{within}}^2 / \sigma_{\text{between}}^2\)) tôn trọnggroups, vàSigned Feature Hashing(Weinberger ±1) chứng minh kỳ vọng không chệch & phương sai va chạm \(\mathcal{O}(1/m_{\text{hash}})\). - Học Biểu diễn 2026 (
Representation Learning): Nhúng thực thể, Nhúng Số học Tuần hoànPLR(Gorishniy et al. 2022;TabMICLR 2025), Mô hình Nền tảng Bảng (TabPFN v2/2.5,TabICL), và Cổng Kiểm chứng 4 tầng choLLM AutoFE(CAAFE/FeatLLM/OCTree) chống quá khớp đa kiểm định.
- Cải thiện (
- Kiến trúc Đường ống Chống Rò rỉ & Hệ sinh thái 2026 (
Systems & Parity Rigor): Chứng minh đại số rò rỉ tiền tách tập (ESL §7.10.2), xây dựngColumnTransformerDAG+FeaturePipelineđịnh tuyến theo tên cột (bất biến hoán vị cột), tuân thủ hợp đồngJSON State-DictkýHMAC-SHA256không-pickle(CWE-502), tối ưu thông lượng bằngPolars 2.0lazy streaming +skrub, và khóa đồng bộ Lô–Đơn (< 1e-12,< 1 ms) kết nối sang Feature Store Track 2 (#15).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U03, Dòng R31 & E29:E31)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R31, E29:E31) |
Nâng cấp Chuẩn SOTA 2026 (ch-08) |
Mục trong Chương 08 | Mô-đun & Hợp đồng Kiểm thử (feature_eng_lab) |
|---|---|---|---|
R31.1 Data Types (structured vs. unstructured, qualitative vs. quantitative) |
Phân loại theo tính tất định lược đồ (flat, relational \(1:M\), event logs, time series, JSON, embeddings) & cấu trúc phân phối (nominal, ordinal, discrete, continuous) | Trụ cột 1 (§1.1) + Mermaid 1 | pipeline_dag.py (ColumnBranchSpec, ScaleLevel), Test 1 |
R31.2 4 Levels of Measurements (nominal, ordinal, interval, ratio) |
Nhóm tự đẳng cấu đại diện \(G_{\text{rat}} \subsetneq G_{\text{int}} \subsetneq G_{\text{ord}} \subsetneq G_{\text{nom}}\) + 3 Định lý chứng minh đảo dấu Likert, sụp đổ mã nguyên Nominal, và vỡ tỷ lệ Interval |
Trụ cột 1 (§1.2) + Mermaid 1 + Widget measurement-scales-boxcox-explorer |
transforms_and_woe.py (audit_stevens_scale_violations), Test 1 |
| R31.3 Big Five — (1) Improvement | Cờ báo thiếu (ch-04 bridge), cắt 1.4826 * MAD (MeanAD fallback), Box–Cox MLE có Jacobian \((\lambda-1)\sum \ln x_i\), Yeo–Johnson \(C^2(\mathbb{R})\), RankGauss \(\Phi^{-1}\) |
Trụ cột 1 (§1.3.1) + Widget measurement-scales-boxcox-explorer |
transforms_and_woe.py (MissingnessAndMadClipper, BoxCoxTransformer, YeoJohnsonTransformer, RankGaussTransformer), Tests 2, 3 |
R31.3 Big Five — (2) Construction (E29:E31) |
Tỷ lệ bảo vệ mẫu số, đa thức khử cộng tuyến, chu kỳ \((\sin,\cos)\) trên \(S^1\), cửa sổ nhân quả PIT \([t_{\text{obs}}-W, t_{\text{obs}})\) + EWMA, Banking Monotonic PAVA WoE & IV (>0.50 leak canary) + CSI |
Trụ cột 1 (§1.3.2) + Trụ cột 3 (§3.1 Cases 1, 2) + Widget woe-iv-pipeline-dag-explorer |
transforms_and_woe.py (CyclicalTimeEncoder, CausalRollingFeatureBuilder, OnlineSlidingWindowState, MonotonicWoEEncoder), Tests 4, 5 |
| R31.3–4 Big Five — (3) Selection & Statistical Metrics | Filter (Pearson vs. Spearman vs. MI Miller–Madow & KSG-1 vs. \(\chi^2\) & Bergsma Cramér's \(\tilde{V}\)); Wrapper (SFS/RFE & Boruta binomial MZSA); Embedded & Permutation (\(L_1\), bẫy CART MDI \(\mathcal{O}(K/n)\), OOF Permutation, Cluster Permutation, Null-Importance PIMP + BH-FDR) |
Trụ cột 1 (§1.3.3) + Mermaid 2 + Widget feature-selection-mi-null-importance |
selection_and_metrics.py (compute_discrete_mi, compute_ksg_mi, chi2_independence_and_cramers_v, compute_tree_mdi_bias_demo, oof_permutation_importance, collinearity_cluster_permutation, null_importance_pimp, boruta_shadow_selection), Tests 6, 7, 8, 9 |
| R31.3 Big Five — (4) Extraction | PCA/TruncatedSVD trong nếp, OOF James–Stein / m-Estimate tôn trọng GroupKFold, Signed Feature Hashing (Weinberger ±1) |
Trụ cột 1 (§1.3.4) + Trụ cột 3 (§3.1 Case 3) + Widget woe-iv-pipeline-dag-explorer |
transforms_and_woe.py (OOFJamesSteinEncoder, SignedFeatureHasher, FoldPCAExtractor), Tests 10, 11 |
| R31.3 Big Five — (5) Representation Learning | Entity Embeddings, Periodic Numerical Embeddings (PLR, TabM 2025) trị spectral bias, TabPFN v2/2.5 / TabICL, và Cổng 4 tầng chống quá khớp LLM AutoFE (CAAFE/OCTree) |
Trụ cột 1 (§1.3.5) + Trụ cột 3 (§3.1 Case 4) | transforms_and_woe.py (PeriodicPLREncoder), selection_and_metrics.py (verify_llm_candidate_features_gate), Tests 11, 12 |
| R31.5–6 ML Pipelines & Industrial Tips | Chứng minh rò rỉ tiền tách tập (ESL §7.10.2), ColumnTransformerDAG -> FeaturePipeline, bất biến hoán vị cột & lô–đơn < 1e-12, Signed JSON State-Dict (HMAC-SHA256) không pickle, Polars 2.0 + skrub, Cầu nối Feature Store (#15), 8 Phản mẫu & Checklist thực chiến |
Trụ cột 2 (§2.1–§2.4) + Mermaid 3 + Trụ cột 3 (§3.2–§3.4) + Trụ cột 4 | pipeline_dag.py (ColumnTransformerDAG, FeaturePipeline, audit_presplit_vs_infold_leakage, run_full_ch08_benchmarks), scripts/run_lab_demo.py, Tests 12, 13, 14 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-08) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (feature_eng_lab) |
|---|---|---|---|---|
| \(n, d, d'\) | \(\mathbb{N}_+\) | Số quan sát \(n\), số cột thô \(d\), số chiều sau biến đổi đặc trưng \(d'\) | Phân biệt chiều thô \(d\) với chiều mở rộng \(d'\) sau OHE/Hash/PLR | n_samples, n_raw, n_out |
| \(G_{\text{nom}}, G_{\text{ord}}, G_{\text{int}}, G_{\text{rat}}\) | Nhóm | Nhóm tự đẳng cấu bất biến theo 4 thang đo Stevens (1946) | Chuỗi nhóm con thực sự \(G_{\text{rat}} \subsetneq G_{\text{int}} \subsetneq G_{\text{ord}} \subsetneq G_{\text{nom}}\) | ScaleLevel (NOMINAL, ORDINAL, INTERVAL, RATIO) |
| \(\lambda_{\text{bc}}, \lambda_{\text{yj}}\) | \(\mathbb{R}\) | Tham số lũy thừa trong Box–Cox (\(x>0\)) và Yeo–Johnson (\(x\in\mathbb{R}\)) | Tách rời khỏi hệ số co rút \(\lambda_c\) của OOF James–Stein |
lambdas_, lmbda |
| \(c_{\text{MAD}}\) | \(\mathbb{R}_{>0}\) | Hằng số nhất quán Chuẩn \(1/\Phi^{-1}(0.75) \approx 1.4826022\) | Khớp chuẩn điểm đổ vỡ \(\epsilon^* = 0.5\) của MAD |
MAD_CONSISTENCY |
| \(g_b, b_b, \operatorname{WoE}_b, \operatorname{IV}\) | \((0,1), \mathbb{R}, \mathbb{R}_{\ge 0}\) | Tỷ trọng Good (\(Y=0\)) \(g_b\), Bad (\(Y=1\)) \(b_b\), \(\ln(g_b/b_b)\), \(\sum (g_b-b_b)\operatorname{WoE}_b\) | Khóa dấu chuẩn: \(\operatorname{WoE}_b\) cao \(\iff\) tỷ lệ Good cao / rủi ro thấp | good_share, bad_share, woe, iv |
| \(\alpha_{\text{lap}}, B\) | \(\mathbb{R}_{>0}, \mathbb{N}_{\ge 2}\) | Giả đếm làm mượt Laplace/Haldane (\(\alpha_{\text{lap}}=0.5\)); số bin \(B\) | Phân biệt khỏi tốc độ suy giảm EWMA \(\alpha_{\text{ewma}}\) |
laplace_alpha, n_bins |
| \(\hat{I}_{\text{plug}}, \hat{I}_{\text{MM}}, \hat{I}_{\text{KSG}}\) | \(\mathbb{R}_{\ge 0}\) | MI plug-in, MI hiệu chỉnh Miller–Madow, MI \(k\)-NN KSG-1 (nats/bits) |
Luôn ghi rõ đơn vị nats hay bits (\(1\text{ nat} = \frac{1}{\ln 2}\text{ bits}\)) |
mi_plugin, mi_miller_madow, compute_ksg_mi |
| \(\chi^2, V, \tilde{V}\) | \(\mathbb{R}_{\ge 0}, [0,1]\) | Thống kê độc lập Pearson \(\chi^2\), Cramér's \(V\) thô, Cramér's \(\tilde{V}\) Bergsma | \(\tilde{V}\) khử thiên lệch mẫu hữu hạn \(\frac{(r-1)(c-1)}{n-1}\) | chi2_stat, cramers_v, cramers_v_corrected |
| \(\text{MZSA}, H_j, p_j^{\text{PIMP}}\) | \(\mathbb{R}, \mathbb{N}_0, (0,1]\) | Z-score cực đại biến bóng (Boruta), số lần thắng \(H_j\), \(p\)-value thực nghiệm PIMP |
Khác với cỡ mẫu \(n\) và số chiều \(d\) | avg_mzsa, hits, p_value |
| \(m_{\text{smooth}}, m_{\text{hash}}, \xi(i)\) | \(\mathbb{R}_{>0}, \mathbb{N}_+, \{\pm 1\}\) | Cường độ tiên nghiệm m-estimate; số bucket băm; hàm dấu băm Weinberger |
Giữ tách biệt \(m_{\text{smooth}}\) (TE) với \(m_{\text{hash}}\) (Hashing) | smoothing_m, n_buckets, sign_hash |
| \(t_{\text{obs}}, t_{\text{avail}}, \delta_{\text{lag}}, W\) | \(\mathbb{R}_{\ge 0}\) | Thời điểm quan sát, thời điểm dữ liệu sẵn sàng, độ trễ tối thiểu, bề rộng cửa sổ | Điều kiện nhân quả: \(t_{\text{event}} \in [t_{\text{obs}}-W, t_{\text{obs}})\) & \(t_{\text{avail}} \le t_{\text{obs}}-\delta_{\text{lag}}\) | obs_ts, avail_ts, lag_seconds, window_seconds |
Trụ cột 1 — Phân loại Dữ liệu, Lý thuyết Thang đo Stevens & Toán học Ngũ trụ Kỹ thuật Đặc trưng (First-Principles Rigor)#
1.1 Phân loại Học dữ liệu: Có cấu trúc vs. Phi cấu trúc & Định tính vs. Định lượng (R31.1)#
Dưới góc nhìn đại số hệ thống và thống kê, mọi dữ liệu thô đi vào bài toán học máy được phân tầng theo hai trục trực giao: tính tất định lược đồ (schema determinism) và cấu trúc miền giá trị (support & distributional law):
-
Dữ liệu Có cấu trúc (Structured Data): Tuân thủ lược đồ quan hệ định kiểu tường minh \(\mathcal{S} = \{(c_j, \tau_j, \mathcal{C}_j)\}_{j=1}^d\) gồm tên cột \(c_j\), kiểu dữ liệu tĩnh \(\tau_j\) (
float64,int64,utf8,timestamp[us, UTC]) và bất biến miền \(\mathcal{C}_j\):- Bảng phẳng (Flat Tabular): Ma trận ảnh chụp \(\mathbf{X} \in \prod_{j=1}^d \mathcal{X}_j\), trong đó các hàng thường được giả định trao đổi được (exchangeable), trừ khi tồn tại lặp thực thể hoặc trục thời gian.
- Quan hệ Đa bảng (\(1\text{-to-}M\) / \(M\text{-to-}N\)): Liên kết qua khóa chính/khóa ngoại
(user_id, account_id, merchant_id). Để chiếu bảng con biến động kích thước \(M_i \in \mathbb{Z}_{\ge 0}\) lên một hàng đặc trưng có chiều cố định \(d'\), bắt buộc dùng toán tử tổng hợp tập nhân quả \(\mathcal{A}(\{e \in \mathcal{E}_u : t_{\text{avail}}(e) \le t_{\text{obs}} - \delta_{\text{lag}}\})\). - Nhật ký Sự kiện (Event Logs / Ledgers): Chuỗi bất biến nối đuôi \(\{(u_k, t_k, a_k, \mathbf{m}_k)\}_{k=1}^M\) có khoảng cách thời gian giữa các sự kiện bất quy tắc \(\Delta t_k = t_k - t_{k-1} \in \mathbb{R}_{\ge 0}\) và tính bùng nổ đuôi nặng.
- Chuỗi Thời gian (Time-Series & Panel): Chuỗi có thứ tự \(\{(\mathbf{x}_{u, t}, y_{u, t})\}_{t \in \mathcal{T}}\) trên lưới rời rạc (\(\Delta t = \text{const}\)) nơi tự tương quan \(\operatorname{Cov}(X_{u,t}, X_{u, t-h}) \neq 0\) cấm hoàn toàn việc xáo trộn ngẫu nhiên các hàng.
2. Dữ liệu Bán cấu trúc (Semi-Structured Data): Các gói tự mô tả lồng ghép (
JSON,Protobuf,Parquet struct) có tập khóa thay đổi theo từng bản ghi (\(\text{Schema}_i \neq \text{Schema}_j\)). Bảng hóa đòi hỏi ánh xạ đường dẫn tất định, cờ báo thiếu khóa hoặc Feature Hashing. 3. Dữ liệu Phi cấu trúc (Unstructured Data): Văn bản chuỗi token \(\mathbf{w} \in \mathcal{V}^L\), ảnh lưới không gian \(\mathbf{I} \in \mathbb{R}^{H \times W \times C}\), hoặc âm thanh phổ \(\mathbf{S} \in \mathbb{R}^{T \times F}\). Sau khi đi qua bộ mã hóa đóng băng \(f_\theta\), chúng nhập vào đường ống bảng dưới dạng vector nhúng đặc \(\mathbf{z} \in \mathbb{R}^D\) — làm phát sinh đa cộng tuyến và bùng nổ chiều \(D \gg n\) nếu thiếu trích xuấtPCA/SVDtrong nếp hoặc chính quy hóa.
| Lớp Phân loại | Phân nhóm | Miền Giá trị \(\mathcal{X}\) | Quy luật Phân phối Tiêu biểu | Ví dụ Sản xuất Điển hình | Rủi ro Đặc trưng Cốt lõi |
|---|---|---|---|---|---|
| Định tính (Qualitative) | Danh định (Nominal) | Tập hữu hạn/đếm được \(\mathcal{C}=\{c_1,\dots,c_K\}\), không có thứ tự | Multinomial \(\mathbf{p} \in \Delta^{K-1}\) | merchant_id, country_iso, device_os |
Đuôi dài Zipf (\(K \gg 10^3\)), mã lạ khi phục vụ, giả thứ tự nếu gán số nguyên |
| Định tính (Qualitative) | Thứ bậc (Ordinal) | Tập có thứ tự toàn phần \(c_1 \prec \dots \prec c_K\), khoảng cách không đều | Ordered Categorical / Cumulative Link | credit_tier (A..G), plan_tier, likert_1_5 |
Lấy trung bình mã nguyên giả định khoảng cách tuyến tính đều nhau |
| Định lượng (Quantitative) | Rời rạc (Discrete) | Tập đếm được \(\mathbb{Z}_{\ge 0}\) hoặc mạng \(a + h\mathbb{Z}\) | Poisson, Negative Binomial, ZIP | num_delinquencies_90d, chargeback_count |
Dư thừa số 0 (MAD == 0), quá phân tán (\(\operatorname{Var} \gg \mathbb{E}\)), mẫu số chia 0 |
| Định lượng (Quantitative) | Liên tục (Continuous) | Khoảng hoặc nửa trục \(\subseteq \mathbb{R}\) (\(\mathbb{R}_{>0}\)) | Log-Normal, Pareto, Gamma | transaction_amount, balance, latency_ms |
Độ lệch phải cực đại (\(\gamma_1 \gg 2\)), ngoại lai luật lũy thừa, bẫy log(x <= 0) |
1.2 Bốn Thang đo Stevens (1946) dưới Góc nhìn Nhóm Tự đẳng cấu & Các Định lý Đổ vỡ (R31.2)#
Theo Lý thuyết Đo lường Đại diện (Representational Measurement Theory — Stevens, 1946; Krantz et al., 1971), mỗi thang đo là một đồng cấu \(\phi: \mathcal{E} \to \mathbb{R}\) kèm theo nhóm phép biến đổi hợp lệ (permissible transformation group) \(G \le \operatorname{Sym}(\mathbb{R})\) bảo toàn trọn vẹn cấu trúc thực nghiệm. Một thống kê hay phép toán \(P(\phi(x_1), \dots, \phi(x_n))\) chỉ có nghĩa thực nghiệm khi bất biến dưới mọi \(g \in G\):
| Thang đo | Cấu trúc Bảo toàn | Nhóm Tự đẳng cấu \(G\) | Thống kê & Kiểm định Hợp lệ | Mã hóa & Mô hình Tương thích | Phép toán Bị cấm |
|---|---|---|---|---|---|
| Nominal | Quan hệ tương đương (\(x \sim y\)) | Nhóm Song ánh: \(G_{\text{nom}} = \{g \text{ là song ánh}\}\) | Yếu vị (Mode), tần suất, Entropy \(H(X)\), \(\chi^2\), Cramér's \(V\), \(I(X;Y)\) |
One-Hot, Signed Hashing, OOF James–Stein, Entity Embeddings |
Trung bình, trung vị, so sánh <, hồi quy tuyến tính mã nguyên, Euclidean |
| Ordinal | Tương đương + Thứ tự (\(x \preceq y\)) | Nhóm Đơn điệu Tăng: \(G_{\text{ord}} = \{u < v \implies g(u) < g(v)\}\) | Trung vị, phân vị \(Q_\alpha\), hạng, Spearman \(\rho_S\), Kendall \(\tau\), KS |
Chia nút cây (\(x \le \tau\)), RankGauss, dummy nhiệt kế tích lũy |
Trung bình cộng, phương sai, \(z\)-score, Pearson r, OLS tuyến tính trên mã thô |
| Interval | Thứ tự + Hiệu bằng nhau (\(0\) tùy ý) | Nhóm Affine Dương: \(G_{\text{int}} = \{ax + b \mid a > 0, b \in \mathbb{R}\}\) | Trung bình, độ lệch chuẩn, \(z\)-score (bất biến tuyệt đối!), Pearson r, OLS |
StandardScaler, hiệu số \(\Delta x\), cặp chu kỳ \((\sin,\cos)\), WoE |
Tỷ số \(x_i/x_j\), % thay đổi, Trung bình nhân, CV \(=\sigma/\mu\), ln x, Box–Cox |
| Ratio | Hiệu bằng nhau + Số 0 thật |
Nhóm Tỷ lệ Dương: \(G_{\text{rat}} = \{ax \mid a > 0\}\) | Toàn bộ Interval cộng thêm Trung bình nhân, CV, tỷ số \(x_i/x_j\), % thay đổi |
Phép lũy thừa (\(\ln x\), Box–Cox), tỷ lệ miền \(a/b\), độ co giãn \(\ln y \sim \ln x\) |
Tịnh tiến tùy tiện \(x + c\) trước khi lấy log/tỷ lệ (phá hủy điểm 0 thật!) |
(Chuỗi nhóm con thực sự: \(G_{\text{rat}} \subsetneq G_{\text{int}} \subsetneq G_{\text{ord}} \subsetneq G_{\text{nom}}\). Khi nhóm \(G\) thu hẹp, nhiều cấu trúc đại số hơn trở nên bất biến.)
Định lý 1.1 (Đảo chiều Thứ tự Khi Lấy Trung bình Điểm Likert Thứ bậc)#
Phép tính trung bình cộng, kiểm định \(t\) và hồi quy tuyến tính trực tiếp trên mã thứ bậc \(\phi: \mathcal{E} \to \{1, \dots, K\}\) vi phạm tính bất biến dưới \(G_{\text{ord}}\).
-
Chứng minh bằng Phản ví dụ Chính xác: Xét hai nhóm đánh giá mức độ hài lòng \(c_1 \prec c_2 \prec c_3 \prec c_4 \prec c_5\): nhóm \(A = (c_1, c_4, c_4, c_4)\) và nhóm \(B = (c_2, c_2, c_2, c_5)\). Dưới hai phép mã hóa đơn điệu tăng đều hợp lệ thuộc \(G_{\text{ord}}\):
- Mã đều \(g_1 = (1, 2, 3, 4, 5)\): \(\bar{x}_A^{(g_1)} = 3.25 > 2.75 = \bar{x}_B^{(g_1)} \implies \bar{x}_A - \bar{x}_B = \mathbf{+0.50} > 0\).
- Mã giãn đỉnh \(g_2 = (1, 2, 3, 4, 10)\) (\(1 < 2 < 3 < 4 < 10\)): \(\bar{x}_A^{(g_2)} = 3.25 < 4.00 = \bar{x}_B^{(g_2)} \implies \bar{x}_A - \bar{x}_B = \mathbf{-0.75} < 0\).
Ngược lại, trung vị bảo toàn \(\operatorname{med}_A = c_4 \succ c_2 = \operatorname{med}_B\) dưới mọi \(g \in G_{\text{ord}}\). (Kiểm chứng trong
audit_stevens_scale_violations()!) \(\blacksquare\)
Định lý 1.2 (Sụp đổ Tuyến tính & Méo Khoảng cách Euclidean của Mã nguyên Danh định)#
Xét biến danh định \(X \in \{\text{NYC}, \text{London}, \text{Tokyo}\}\) với kỳ vọng mục tiêu phi đơn điệu \(Y = (10, 2, 10)\). Mã hóa số nguyên \(\phi = (1, 2, 3)\) ép bề mặt dự báo tuyến tính nằm trên một đường thẳng 1D cho \(\operatorname{Cov}(\phi(X), Y) = 0 \implies R^2 = \mathbf{0.00}\); chỉ cần đổi thứ tự chữ cái thành \(\tilde{\phi} = (1, 3, 2)\) lại thu được \(R^2 = \mathbf{0.75}\) hoàn toàn vô nghĩa, và làm méo khoảng cách Euclidean \(d(c_1, c_3) = 2 \cdot d(c_1, c_2)\). Trái lại, ánh xạ One-Hot \(\mathbf{e}_c \in \{0, 1\}^K\) giữ bất biến hoán vị tuyệt đối với \(\|\mathbf{e}_{c_a} - \mathbf{e}_{c_b}\|_2 = \sqrt{2}\,\mathbb{I}[c_a \neq c_b]\) và đạt \(R^2 = \mathbf{1.00}\). \(\blacksquare\)
Định lý 1.3 (Phá vỡ Ngữ nghĩa 0-Ratio trong % Thay đổi, log và Box–Cox)#
Trên thang Khoảng (Interval) với nhóm affine \(g(x) = ax + b\), tỷ lệ thay đổi \(\frac{x_2 - x_1}{x_1}\) phụ thuộc vào gốc \(b\): một mức tăng nhiệt độ vật lý giống hệt nhau từ \(10^\circ\text{C} \to 20^\circ\text{C}\) cho kết quả +100.0% (Celsius), +36.0% (\(50^\circ\text{F} \to 68^\circ\text{F}\)), và +3.53% (\(283.15\text{ K} \to 293.15\text{ K}\)). Tương tự, ln x và Box–Cox \((x^\lambda - 1)/\lambda\) đòi hỏi điểm 0 tuyệt đối (\(x > 0\)); phép tịnh tiến tùy tiện \(x + b\) để né \(x \le 0\) phá vỡ tính đẳng phương nghiệm MLE \(\hat{\lambda}\) với mọi \(\lambda \notin \{0, 1\}\). Ngược lại, trên thang Tỷ lệ (Ratio) (\(g(x) = ax\)), \(\frac{(ax)^\lambda - 1}{\lambda} = a^\lambda \frac{x^\lambda - 1}{\lambda} + \frac{a^\lambda - 1}{\lambda} \in G_{\text{int}}\), chứng minh log và Box–Cox ánh xạ đúng Ratio -> Interval. \(\blacksquare\)
1.3 Ngũ trụ Kỹ thuật Đặc trưng (The Big Five of Feature Engineering, R31.3–R31.4)#
1.3.1 Trụ thứ Nhất: Cải thiện Đặc trưng (Feature Improvement)#
- Cờ báo Thiếu dữ liệu (Missingness Flags — Cầu nối
ch-04§1.3): Trước khi điền thiếu bằng trung vị đóng băng trên \(\mathcal{D}_{\text{tr}}\), luôn xuất chỉ báo nhị phân \(m_{i,j} = \mathbb{I}[x_{i,j} \text{ là NaN}]\). DùGBDThọc nhánhNaNtự nhiên, \(m_{i,j}\) bắt buộc phải có cho mô hình tuyến tính, mạng nơ-ron và tách tín hiệuMNAR(bệnh nhân thiếu xét nghiệm hoặc người vay giấu thu nhập). - Cắt Ngoại lai Bền vững (
Winsorization&MADClipping — Dẫn xuất \(1.4826\)): Trung bình và độ lệch chuẩn có điểm đổ vỡ \(\epsilon^* = 0\). Thước đo độ lệch tuyệt đối trung vị \(\operatorname{MAD}(\mathbf{x}) := \operatorname{median}_i |x_i - \operatorname{median}(\mathbf{x})|\) đạt điểm đổ vỡ tối ưu \(\epsilon^* = 0.50\). Với \(X \sim \mathcal{N}(\mu, \sigma^2)\):\[\mathbb{P}(|X - \mu| \le \operatorname{MAD}) = \frac{1}{2} \iff 2\Phi\!\left(\frac{\operatorname{MAD}}{\sigma}\right) - 1 = \frac{1}{2} \iff \Phi\!\left(\frac{\operatorname{MAD}}{\sigma}\right) = \frac{3}{4},\]suy ra hệ số nhất quán \(\hat{\sigma}_{\text{MAD}} = c_{\text{MAD}} \cdot \operatorname{MAD}\) với \(c_{\text{MAD}} = \frac{1}{\Phi^{-1}(0.75)} \approx \mathbf{1.4826022}\). Nếu dư thừa số0làm \(\operatorname{MAD} = 0\), tự động chuyển sang nhánh dự phòng \(c_{\text{MeanAD}} \cdot \operatorname{MeanAD}\) (\(c_{\text{MeanAD}} = \sqrt{\pi/2} \approx 1.2533\)). Cắt giá trị ngoài \(\operatorname{med}_{\text{tr}} \pm c \cdot \hat{\sigma}_{\text{MAD, tr}}\) (\(c \in [3.5, 4.0]\)) chỉ học biên từ \(\mathcal{D}_{\text{tr}}\). - Biến đổi
Box–Cox(1964) & Chứng minh Hạng tử Jacobian: Với \(x_i > 0\), xét họ hàm \(y_i^{(\lambda)} = \frac{x_i^\lambda - 1}{\lambda}\) (\(\lambda \neq 0\)) và \(\ln x_i\) (\(\lambda = 0\)).- Vì sao Cực tiểu hóa Phương sai Phần dư \(\hat{\sigma}^2(\lambda)\) Thuần túy bị Sụp đổ? Khi \(x_i > 1\), cho \(\lambda \to -\infty\) kéo \(x_i^\lambda \to 0 \implies y_i^{(\lambda)} \to -1/\lambda\) (hằng số!), đẩy \(\hat{\sigma}^2(\lambda) \to 0\) bất chấp phân phối có Chuẩn hay không! Để so sánh hợp lý trên cùng không gian gốc \(x\), phải nhân định thức Jacobian \(\left|\frac{dy_i^{(\lambda)}}{dx_i}\right| = x_i^{\lambda - 1} > 0\):
\[f_X(x_i \mid \lambda, \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left(-\frac{(y_i^{(\lambda)} - \mu)^2}{2\sigma^2}\right) x_i^{\lambda - 1}.\]Lấy logarit và thế \(\hat{\mu}(\lambda) = \bar{y}^{(\lambda)}\), \(\hat{\sigma}^2(\lambda) = \frac{1}{n}\sum_i (y_i^{(\lambda)} - \bar{y}^{(\lambda)})^2\) cho Hàm Hợp lý Hồ sơ (Profile Log-Likelihood)
Box–Cox:\[\ell_{\max}(\lambda) = -\frac{n}{2}\ln(2\pi e) - \frac{n}{2}\ln \hat{\sigma}^2(\lambda) + \underbrace{(\lambda - 1)\sum_{i=1}^n \ln x_i}_{\ln J(\lambda;\,\mathbf{x})}.\]Kiểm chứng thực nghiệm (BoxCoxTransformertrongfeature_eng_lab): Trên phân phối Log-Normal (skew = 4.00, \(\lambda_{\text{true}} = 0\)), bản có Jacobian tìm chính xác \(\hat{\lambda} = -0.045\) đưa độ lệch về0.001, còn bản bỏ Jacobian sụp về biên-1.279.
- Vì sao Cực tiểu hóa Phương sai Phần dư \(\hat{\sigma}^2(\lambda)\) Thuần túy bị Sụp đổ? Khi \(x_i > 1\), cho \(\lambda \to -\infty\) kéo \(x_i^\lambda \to 0 \implies y_i^{(\lambda)} \to -1/\lambda\) (hằng số!), đẩy \(\hat{\sigma}^2(\lambda) \to 0\) bất chấp phân phối có Chuẩn hay không! Để so sánh hợp lý trên cùng không gian gốc \(x\), phải nhân định thức Jacobian \(\left|\frac{dy_i^{(\lambda)}}{dx_i}\right| = x_i^{\lambda - 1} > 0\):
- Biến đổi
Yeo–Johnson(2000) trên Toàn bộ \(\mathbb{R}\): Hỗ trợ \(C^2\)-trơn cho cả giá trị âm, \(0\) và dương mà không cần dịch hằng số tùy tiện:\[\psi_\lambda(x) = \begin{cases} \dfrac{(1+x)^\lambda - 1}{\lambda}, & x \ge 0,\; \lambda \neq 0, \\[4pt] \ln(1+x), & x \ge 0,\; \lambda = 0, \\[4pt] -\dfrac{(1-x)^{2-\lambda} - 1}{2-\lambda}, & x < 0,\; \lambda \neq 2, \\[4pt] -\ln(1-x), & x < 0,\; \lambda = 2, \end{cases} \qquad \ln J_{\text{YJ}}(\lambda;\mathbf{x}) = (\lambda - 1)\sum_{i=1}^n \operatorname{sgn}(x_i)\ln(1 + |x_i|).\]Trong workbench,YeoJohnsonTransformerhạ độ lệch dữ liệu lẫn số âm (skew = 1.90) xuống0.308(\(\hat{\lambda} = 0.761\)). Quantile / RankGauss: Ánh xạ \(z_i^{\text{RG}} = \Phi^{-1}\!\left(\frac{\operatorname{rank}(x_i)}{n+1}\right)\) qua phép xấp xỉ hữu tỷAcklam(norm_ppf, sai số< 1.2e-9), ép ngoại lai về cận \(O(\sqrt{2\ln n})\) và giữskew = 0.065trên tập kiểm tra nội suy tuyến tính từng đoạn (lưu ý:RankGaussxóa bỏ khoảng cách tỷ lệRatiovà dồn điểm trùng lặp bằng0vào cùng một nút).
1.3.2 Trụ thứ Hai: Kiến tạo Đặc trưng (Feature Construction)#
- Tỷ lệ Miền Bảo vệ Mẫu số & Bayes Thực nghiệm: Với tỷ lệ không âm \(a/b\), dùng \(r_\varepsilon = \frac{a}{b + \varepsilon}\) kèm cờ \(\mathbb{I}[b=0]\); với mẫu số có dấu \(b \in \mathbb{R}\), cấm cộng \(+\varepsilon\) mù (sẽ chia
0tại \(b=-\varepsilon\)!) mà dùng \(\frac{a}{\operatorname{sgn}^+(b)\max(|b|, \varepsilon)}\). Với tỷ lệ đếm nhị thức \(k/N\), ổn định bằng co rút \(\frac{k + m\bar{r}_0}{N + m}\). - Đa thức / Tương tác & Quy tâm: Mở rộng bậc \(k\) tạo \(\Theta(d^k)\) cột; trên biến dương không quy tâm (ví dụ \([1, 2]\)), \(\operatorname{Corr}(X, X^2) \approx 0.996\) làm bình phương \(\kappa_2(\mathbf{X})\). Luôn quy tâm/chuẩn hóa trước khi tạo tương tác.
- Mã hóa Chu kỳ Đơn vị Tròn (
sin/costrên \(S^1\)): Mã hóa tuyến tính giờ trong ngày \(t \in [0, 24)\) tạo bước nhảy giả \(|23 - 0| = 23\) tại nửa đêm. Nhúng \(\phi_{\text{cyc}}(t) = (\sin(2\pi t/T), \cos(2\pi t/T))\) thỏa:\[\|\phi_{\text{cyc}}(t_1) - \phi_{\text{cyc}}(t_2)\|_2^2 = 4\sin^2\!\left(\frac{\pi\, d_{S^1}(t_1, t_2)}{T}\right),\]bảo đảm khoảng cách Euclidean tỷ lệ đơn điệu với khoảng cách trắc địa trên vòng tròn (\(d(23, 0) = d(0, 1)\) tuyệt đối!). - Cửa sổ Cuộn Nhân quả
Point-in-Time (PIT)&EWMASự kiện: Mọi đặc trưng tổng hợp tại thời điểm quan sát \(t_{\text{obs}}\) của thực thể \(u\) chỉ được đọc tập lịch sử nhân quả nửa mở:\[\mathcal{H}_u(t_{\text{obs}}; \delta_{\text{lag}}) = \big\{e \in \mathcal{E}_u \;\big|\; t_{\text{obs}} - W \le t_{\text{event}}(e) < t_{\text{obs}} \;\land\; t_{\text{avail}}(e) \le t_{\text{obs}} - \delta_{\text{lag}}\big\}.\]Đối với dòng sự kiện đến bất quy tắc,EWMAliên tục suy giảm \(\tilde{\mu}_\tau(t_{\text{obs}}) = \frac{\sum_{t_k < t_{\text{obs}}} e^{-(t_{\text{obs}} - t_k)/\tau} v_k}{\sum_{t_k < t_{\text{obs}}} e^{-(t_{\text{obs}} - t_k)/\tau}}\) cập nhật trạng thái trực tuyến chỉ trong \(\mathcal{O}(1)\) bộ nhớ! -
Trọng số Bằng chứng (
WoE) & Giá trị Thông tin (IV) Ngân hàng (E29:E31): Chia \(X\) thành \(B\) khoảng tách biệt (dành riêng 1 khoảngMISSINGchoMNAR). Gọi \(G_b, B_b\) là số Good (\(Y=0\)) và Bad (\(Y=1\)) trong khoảng \(b\), với tổng \(G, B\) và tỷ trọng làm mượt Laplace/Haldane (\(\alpha_{\text{lap}} \ge 0.5\)):\[g_b^{(\alpha)} = \frac{G_b + \alpha_{\text{lap}}}{G + B\alpha_{\text{lap}}}, \qquad b_b^{(\alpha)} = \frac{B_b + \alpha_{\text{lap}}}{B + B\alpha_{\text{lap}}}, \qquad \operatorname{WoE}_b = \ln\!\left(\frac{g_b^{(\alpha)}}{b_b^{(\alpha)}}\right), \qquad \operatorname{IV} = \sum_{b=1}^B (g_b^{(\alpha)} - b_b^{(\alpha)})\operatorname{WoE}_b.\]- Liên kết Bayes Log-Odds & Phân kỳ Jeffreys: \(\ln\frac{P(Y=\text{Good}\mid X\in b)}{P(Y=\text{Bad}\mid X\in b)} = \ln\frac{G}{B} + \operatorname{WoE}_b\), còn \(\operatorname{IV} = D_{\mathrm{KL}}(P_G \| P_B) + D_{\mathrm{KL}}(P_B \| P_G) \ge 0\).
- Thuật toán Gộp Đơn điệu
PAVAtrên Tỷ lệ Đã Làm mượt: Lưu ý tinh tế: nếu chạyPAVAtrên tỷ lệ thô \(B_b/(G_b + B_b)\), bước làm mượt Laplace \(\alpha_{\text{lap}}\) sau đó có thể đảo ngược nhẹ \(\operatorname{WoE}\) giữa hai bin ít vỡ nợ (\(2\) vs. \(4\)). Thực thiPAVAtrực tiếp trên tỷ lệ rủi ro đã làm mượt \(\frac{B_b + \alpha_{\text{lap}}}{G_b + B_b + 2\alpha_{\text{lap}}}\) bảo đảm 100% tính đơn điệu toán học của \(\operatorname{WoE}_b\) cuối cùng! - Ngưỡng Sàng lọc Chuẩn Siddiqi & Cờ Rò rỉ: \(\text{IV} < 0.02\) (nhiễu — loại),
0.02–0.10(yếu),0.10–0.30(trung bình),0.30–0.50(mạnh — lõi thẻ điểm),IV > 0.50(cờ cảnh báo rò rỉ hậu quả — kiểm toán bắt buộc!). Giám sát trôi phân khoảng bằng \(\operatorname{CSI} = \sum_b (q_b - p_b)\ln(q_b/p_b)\).
1.3.3 Trụ thứ Ba: Chọn lọc Đặc trưng & Độ đo Đánh giá Thống kê (R31.3–R31.4)#
-
Bộ lọc (Filter Methods — Luôn khớp trên \(\mathcal{D}_{\text{tr}}\)):
- Điểm mù
Pearson r&Spearman\(\rho_S\): Nếu \(X\) đối xứng quanh \(0\) và \(Y = X^2\), \(\mathbb{E}[X] = \mathbb{E}[X^3] = 0 \implies r(X, Y) = 0\) và cả \(\rho_S(X, Y) = 0\)! TrênXOR(\(Y = X_1 X_2\), \(X_i \in \{\pm 1\}\)), \(\operatorname{Cov}(X_1, Y) = 0\) khiến mọi bộ lọc đơn biến đều mù tịt (r = -0.059trong lab). Mutual InformationRời rạc & Hiệu chỉnh Thiên lệchMiller–Madow(1955): Bộ ước lượng tần suất thô \(\hat{I}_{\text{plug}}(X; Y)\) chịu thiên lệch dương bậc nhất \(\frac{(|\mathcal{X}_+|-1)(|\mathcal{Y}_+|-1)}{2n}\) (vì entropy ước lượng hụt xuống theo tính lõm của \(-u\ln u\)). Công thức hiệu chỉnh:\[\hat{I}_{\text{MM}}(X; Y) = \max\!\left(0,\; \hat{I}_{\text{plug}}(X; Y) - \frac{(|\mathcal{X}_+| - 1)(|\mathcal{Y}_+| - 1)}{2n}\right) \quad (\text{nats}; \text{ chia }\ln 2 \text{ sang bits}).\]Trong lab với hai biến \(K=25\) độc lập (\(n=300\)), \(\hat{I}_{\text{plug}} = \mathbf{0.926\text{ nats}}\) bịMiller–Madowcắt sạch về đúng0.000 nats.KSG-1\(k\)-NN Mutual Information (Kraskov, Stögbauer & Grassberger, 2004): Thay vì chia bin độ rộng bằng nhau (gây dồn cục đầu phân phối lệch),KSG-1chọn \(\varepsilon(i)/2 := \max(\|x_i - x_{i_k}\|_\infty, \|y_i - y_{i_k}\|_\infty)\) là khoảng cách chuẩn cực đại Chebyshev \(L_\infty\) từ điểm \((x_i, y_i)\) tới láng giềng thứ \(k\) trong không gian chung, rồi đếm số láng giềng chặt bên trong hộp mở biên độ \(\varepsilon(i)/2\) trên từng trục biên:\[n_x(i) := \#\big\{j \neq i \;\big|\; \|x_i - x_j\|_\infty < \varepsilon(i)/2\big\}, \qquad n_y(i) := \#\big\{j \neq i \;\big|\; \|y_i - y_j\|_\infty < \varepsilon(i)/2\big\}.\]Với bất đẳng thức nghiêm ngặt \(< \varepsilon(i)/2\), hệ số thể tích không gian trong \(3H\) triệt tiêu chính xác qua công thức digamma \(\psi(u) = \Gamma'(u)/\Gamma(u)\):\[\hat{I}^{(1)}(X; Y) = \psi(k) - \frac{1}{N}\sum_{i=1}^N \big[\psi(n_x(i) + 1) + \psi(n_y(i) + 1)\big] + \psi(N).\](Lưu ý dữ liệu hỗn hợp rời rạc–liên tục/dư thừa số0: dùng ước lượngRoss 2014hoặcGao et al. 2017thay vì thêm nhiễu rung nhân tạo vào điểm0.)- Kiểm định Độc lập Pearson \(\chi^2\) & Bergsma (2013) Cramér's \(\tilde{V}\): Trên bảng chéo \(r \times c\), \(\chi^2 = \sum \frac{(O_{ij}-E_{ij})^2}{E_{ij}} \sim \chi^2_{(r-1)(c-1)}\) và \(V = \sqrt{\frac{\chi^2}{n \min(r-1, c-1)}}\). Vì \(\mathbb{E}[\chi^2/n] = \frac{(r-1)(c-1)}{n} > 0\) dưới \(H_0\), Bergsma trừ thiên lệch mẫu hữu hạn bằng \(\tilde{\phi}^2 = \max(0, \frac{\chi^2}{n} - \frac{(r-1)(c-1)}{n-1})\) và hiệu chỉnh bậc tự do \(\tilde{r}, \tilde{c}\), kéo nhiễu \(K=25\) từ \(V = \mathbf{0.279}\) về \(\tilde{V} = \mathbf{0.000}\).
- Điểm mù
-
Phương pháp Bao bọc (Wrapper) & Thuật toán
Boruta: Tìm tập con vét cạn tốn \(\mathcal{O}(2^d)\) lần huấn luyện,SFS/SBStốn \(\mathcal{O}(d^2)\), cònRFEtốn \(\mathcal{O}(d)\).Boruta(Kursa & Rudnicki, 2010) nhân bản các đặc trưng thật thành các cột bóng xáo trộn hàng \(\tilde{\mathbf{X}}^{(t)}\) (tối thiểu \(\max(5, p)\) bóng), lấy ngưỡngMZSA= \(\max_s Z_s^{\text{shadow}}\) qua \(T\) vòng OOB và kiểm định hai phía phân phối nhị thức \(\text{Binomial}(T, 0.5)\) để chốt ba vùngCONFIRMED,TENTATIVEvàREJECTED(kiểm soát đa kiểm định). -
Nhúng (Embedded) & Giải pháp Chống Thiên lệch Chọn Đặc trưng:
- Bẫy
Tree-Gain (MDI)\(\mathcal{O}(K/n)\) (Strobl et al., 2007; Chi et al., 2022; Klusowski, 2024): Khi xét biến nhiễu danh mục \(X \sim \operatorname{Uniform}\{1, \dots, K\}\) độc lập hoàn toàn với \(Y\) trên \(n\) mẫu nút cây (phương sai mục tiêu \(\sigma^2\)), việc sắp xếp trung bình mẫu từng nhóm \(\bar{Y}_{(1)} \le \dots \le \bar{Y}_{(K)}\) để tìm phép phân đôi nhị phân tối ưu tạo ra giảm tạp chất giả tỷ lệ tiệm cận \(\mathcal{O}(K/n)\): trong chế độ tiệm cận \(1 \ll K \ll n\), kỳ vọng giảm phương sai giả tiệm cận bằng\[\mathbb{E}[\Delta I_{\text{CART}}(X)] \approx \frac{2}{\pi}\frac{K - 1}{n}\sigma^2 = \mathcal{O}\!\left(\frac{K}{n}\right).\]Bởi vậy nhiễu nhiều mứcK = 200tự động đánh bại tín hiệu thật cóK = 2(0.622vs.0.154trong lab)! - Ba Vũ khí Khắc phục Chuẩn 2026:
OOF Permutation Importance: Đo mức tăng mất mát trên nếp kiểm định ngoài mẫu (hoán vị \(K=200\) giảm hiệu suất-0.151, lộ nguyên hình nhiễu).Collinearity-Cluster Permutation&CPI(NeurIPS 2023): Nhóm các biến có \(|\rho_S| \ge 0.80\) rồi hoán vị đồng thời cả cụm (khôi phục tầm quan trọng cụmsig_linear + sig_twin = 6.881so với0.416đơn lẻ củasig_twin), hoặc hoán vị phần dư có điều kiệnCPIđể giữ điểm dữ liệu nằm trên đa tạp hợp lệ.Null-Importance (PIMP)+BH-FDR(Altmann et al., 2010): Hoán vị \(\mathbf{y}\) \(B\) lần dựng phân phối vô hiệu riêng cho từng cột, tính \(p_j = \frac{1 + \sum_b \mathbb{I}(I_j^{(0,b)} \ge I_j^{\text{obs}})}{B+1}\) và lọc theoBenjamini–Hochberg(\(q \le 0.05\)). Biến nhiễuK = 150cóobserved_mdi = 1.8213nhưngnull_mean = 3.4641(\(\implies p_{\text{PIMP}} = 1.0, z = -7.91\)), bị loại tuyệt đối!
- Bẫy
1.3.4 Trụ thứ Tư: Trích xuất Đặc trưng (Feature Extraction)#
PCA&TruncatedSVDTrong Nếp: Chiếu \(\tilde{\mathbf{X}}_{\text{tr}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) giữ \(\mathbf{Z} = (\mathbf{X} - \mathbf{1}\bar{\mathbf{x}}_{\text{tr}}^\top)\mathbf{V}_k\) tốn \(\mathcal{O}(\min(nd^2, n^2d))\); với ma trận thưa,TruncatedSVDbỏ quy tâm tốn \(\mathcal{O}(k \cdot \operatorname{nnz}(\mathbf{X}) + (n+d)k^2)\). Tuyệt đối chỉ khớp trên \(\mathcal{D}_{\text{tr}}\).OOF James–Stein/m-Estimate Target &WoEEncoding Tôn trọngGroupKFold: Mô hình phân tầng \(Y_{ci} \mid \mu_c \sim (\mu_c, \sigma_{\text{within}}^2)\), \(\mu_c \sim (\bar{y}, \sigma_{\text{between}}^2)\) dẫn xuất trọng số co rút MMSE tối ưu (Micci-Barreca 2001; Pargent et al. 2022):\[\hat{e}_c = \lambda_c \bar{y}_c + (1 - \lambda_c)\bar{y}, \qquad \lambda_c = \frac{n_c}{n_c + m^*}, \qquad m^* = \frac{\sigma_{\text{within}}^2}{\sigma_{\text{between}}^2}.\]Nếu cùng mộtaccount_idlặp lại qua nhiều hàng, bắt buộc dùngGroupKFold(hoặc thống kê thứ tự kiểuCatBoost) khi tínhfit_transformđể chặn rò rỉ nhãn anh em cùng thực thể.Signed Feature Hashing(Weinberger et al., ICML 2009): Dùng hàm băm vị trí \(h: \Sigma^* \to \{0, \dots, m_{\text{hash}}-1\}\) và hàm dấu độc lập \(\xi: \Sigma^* \to \{-1, +1\}\) (\(\mathbb{E}[\xi(i)\xi(j)] = \delta_{ij}\)):\[\phi_b(\mathbf{x}) = \sum_{i : h(i)=b} \xi(i)\, x_i \quad \Longrightarrow \quad \mathbb{E}\big[\langle \phi(\mathbf{x}), \phi(\mathbf{x}') \rangle\big] = \langle \mathbf{x}, \mathbf{x}' \rangle, \qquad \operatorname{Var}\big(\langle \phi(\mathbf{x}), \phi(\mathbf{x}') \rangle\big) \le \frac{2\|\mathbf{x}\|_2^2\|\mathbf{x}'\|_2^2}{m_{\text{hash}}}.\]Không có \(\xi(i)\) (Unsigned), mọi va chạm trên vector không âm cộng thêm sai số dương hệ thống \(+\frac{1}{m_{\text{hash}}}\sum_{i\neq j}x_i x'_j\) (+1.10trong lab vs.-0.20ởSigned Hashing).
1.3.5 Trụ thứ Năm: Học Biểu diễn Bảng 2026 (Representation Learning)#
- Vượt qua Nút thắt Phổ của Mạng Nơ-ron Bảng bằng Nhúng Tuần hoàn
PLR(Gorishniy et al., NeurIPS 2022) &TabM(ICLR 2025): MạngMLPthuần chịu spectral bias: hội tụ cực chậm trên các ngưỡng cắt sắc nét phi đơn điệu (ví dụ ngưỡng phí/tín dụng).PLR(Periodic \(\to\) Linear \(\to\) ReLU) biến đổi từng đại lượng số chuẩn hóa \(z_j\) qua tần số học được \(c_{j,r} \sim \mathcal{N}(0, \sigma_{\text{plr}}^2)\):\[\mathbf{v}_j(z_j) = \big[\sin(2\pi c_{j,1}z_j), \cos(2\pi c_{j,1}z_j), \dots\big]^\top \in \mathbb{R}^{2k}, \qquad \mathbf{e}_j(z_j) = \operatorname{ReLU}(\mathbf{W}_j \mathbf{v}_j(z_j) + \mathbf{b}_j).\]Theo định lý Bochner, lúc khởi tạo \(\mathbb{E}[\frac{1}{k}\mathbf{v}_j(x)^\top\mathbf{v}_j(x')] = \exp(-2\pi^2\sigma_{\text{plr}}^2(x-x')^2)\), biến nhân tiếp tuyếnNTKcủa mạng nơ-ron thành hạt nhân RBF có thể điều chỉnh băng thông! Kiến trúcTabM(2025) kết hợpPLR/PLEvới BatchEnsemble hạng 1 \(\mathbf{W}_i = \mathbf{W} \odot (\mathbf{s}_i \mathbf{r}_i^\top)\) cân bằng trực diện vớiGBDT. Trong lab,PeriodicPLREncodernângAUCbài toán ngưỡng bậc thang đối xứng từ0.491lên0.977. - Mô hình Nền tảng Bảng (
TabPFN v2/2.5,TabICL) & Sinh đặc trưng bằngLLMCó Cổng Chống Quá khớp:TabPFN v2(Nature 2025) /v2.5(50K hàng \(\times\) 2K cột) vàTabICL(ICML 2025, 500K hàng) thực hiện học trong ngữ cảnh (In-Context Learning) qua tự chú ý hai chiều cột–hàng để tự tổng hợp tương tác ẩn. Với các hệ thống dùngLLMđề xuất biểu thức đặc trưng miền (CAAFE,FeatLLM,OCTree), bắt buộc phải đi qua Cổng Xác thực 4 tầng (Prompt chỉ đọc \(\mathcal{D}_{\text{tr}}\) \(\to\) Sandbox AST cấm IO/mục tiêu \(\to\)Nested OOF CVvượt1 SE\(\to\)Null-Importance BH-FDR\(q \le 0.05\)). Trong lab, cổng này giữ lại đúngllm_true_dti_ratiovà loại sạch4/5ứng viên nhiễu.
Trụ cột 2 — Kiến trúc Đường ống Chống Rò rỉ, Tuần tự hóa Bảo mật & Đồng bộ Lô–Trực tuyến (Production Systems Architecture)#
2.1 Chứng minh Rò rỉ Tiền Tách tập & Hợp đồng ColumnTransformerDAG#
Xét tập dữ liệu nhiễu Gaussian trắng độc lập hoàn toàn \(X_j \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(0, 1) \perp Y \in \{0, 1\}\) với \(n = 110\), \(d = 1{,}000\) (Elements of Statistical Learning, §7.10.2). Nếu lọc top-\(k = 15\) cột có \(|r_j|\) cao nhất trước khi chia nếp K-Fold, giá trị cực đại lý thuyết đạt \(\max_j |r_j^{\text{all}}| \approx \sqrt{\frac{2\ln d}{n}} \approx 0.35\) (0.301 thực đo trong lab), và vì \(r_j^{\text{all}} = \frac{n_{\text{tr}}}{n}r_j^{\text{tr}} + \frac{n_{\text{val}}}{n}r_j^{\text{val}}\), tập kiểm định bị ràng buộc tương quan dương với tập huấn luyện! Hệ quả: presplit_leaky_cv_auc = 0.878 trên nhiễu thuần túy, trong khi đóng gói chọn lọc vào bên trong từng nếp của Pipeline khôi phục infold_clean_cv_auc = 0.387.
Mọi thành phần biến đổi trong hệ thống sản xuất phải thỏa mãn 3 Bất biến Hình thức:
- Cô lập Tách tập (
Split Isolation):.fit(df_tr, y_tr, groups)tuyệt đối không bao giờ nhìn thấy \(\mathcal{D}_{\text{val}}\) hoặc \(\mathcal{D}_{\text{te}}\). - Định tuyến Theo Tên Cột (
Name-Indexed Routing):ColumnTransformerDAGtra cứu cột theo tên tường minh (Pydantic v2ConfigDict(extra="forbid")), hoàn toàn bất biến nếu bảng đầu vào bị xáo trộn thứ tự cột (shuffled_columns_max_diff = 0.0). - Bất biến Lô vs. Hàng Đơn (
Batch-vs-Single-Row Parity): Với mọi hàng \(\mathbf{x}_i\), kết quảtransform(X)[i]vàtransform_row(row_i)sai khác< 1e-12(1.11e-16thực đo ở0.044 msp99 CPU).
2.2 Bảo mật Tuần tự hóa (JSON State-Dict + HMAC-SHA256) vs. Lỗ hổng pickle (CWE-502)#
Lưu bộ tiền xử lý bằng pickle hay joblib mở ra hai lỗ hổng nghiêm trọng: (1) Thực thi mã từ xa RCE (CWE-502) do pickle.load() chạy bytecode __reduce__ tùy ý, và (2) Gãy ABI khi nâng cấp phiên bản NumPy/scikit-learn (numpy._core). Kiến trúc chuẩn 2026 thay thế hoàn toàn bằng SignedStateEnvelope thuần JSON (hoặc skops.io với danh sách kiểu tin cậy): lưu trữ schema_version, feature_names_in, toàn bộ tham số số học (lambdas, means, stds, woe_map, ohe_vocab, mapping), mã băm toàn vẹn SHA-256 của payload chuẩn tắc, và chữ ký HMAC-SHA256 kiểm chứng bằng hmac.compare_digest trước khi giải mã (từ chối tức thì mọi sửa đổi 1-byte trái phép).
2.3 Ngăn xếp Sản xuất 2026 (Polars 2.0 Lazy Streaming & skrub) và Cầu nối Feature Store (#15)#
| Công nghệ / Chế độ | Mô hình Thực thi & Bộ nhớ | RAM Đỉnh (100M hàng \(\times\) 20 cột) |
Thời gian GroupBy / ASOF |
Vai trò & Quy tắc An toàn |
|---|---|---|---|---|
Pandas (Eager) |
Vật chất hóa từng bước (GIL đơn luồng phần lớn groupby/apply) |
18 – 35 GB (dễ OOM khi nối bảng lớn) |
45 – 120 s |
Phân tích nhanh < 1–2 GB; tránh .apply(axis=1) và ASOF quy mô lớn |
Polars 2.0 Lazy + Streaming |
Rust + Apache Arrow zero-copy; đẩy chiếu/lọc (pushdown); mặc định engine="streaming" |
2.5 – 6.0 GB (giảm 3x–6x) |
3 – 10 s (nhanh hơn 5x–15x) |
Đường ống lô 1M–500M hàng; luôn kèm .sort() hoặc maintain_order=True trước khi tách thời gian |
skrub (0.9–0.11) |
TableVectorizer, GapEncoder (Gamma-Poisson), MinHashEncoder (\(\mathcal{O}(1)\) fit) |
Tuyến tính theo lô / \(O(1)\) MinHash | < 2 s cho 100K chuỗi bẩn |
Tự động hóa vector chuỗi bẩn & ngày tháng trong scikit-learn / Polars |
Cầu nối sang Track 2 ch-11 (Article #15 — Feature Store Parity): Track 1 (ch-08) khóa hợp đồng toán học cho cửa sổ nhân quả [t_obs - W, t_obs) và phép biến đổi Signed JSON State-Dict hàng đơn (< 1 ms, sai khác < 1e-12); còn Track 2 (ch-11) triển khai tầng hạ tầng phân tán Kafka -> Flink Watermark -> Iceberg/ClickHouse (Offline Feast get_historical_features) đồng bộ sang Redis (< 2 ms HMGET Online).
2.4 Kiến trúc Control Plane vs. Data Plane, Ngân sách RAM/Độ trễ & Xử lý Lệch Thực thể (Entity-Aggregation Skew)#
Trong các nền tảng dữ liệu lớn phục vụ ngân hàng và thương mại điện tử (10^7–10^9 sự kiện), tách bạch Control Plane (biên soạn & xác thực) khỏi Data Plane (thực thi lô/trực tuyến) ngăn ngừa rò rỉ và đảm bảo độ trễ p99 < 1 ms:
| Mặt phẳng & Tầng Xử lý | Trách nhiệm Kiến trúc | Ngân sách RAM & Độ trễ (p99) |
Cơ chế Phòng vệ & Chống Lệch (Skew Mitigation) |
|---|---|---|---|
Control Plane: Khớp & Đăng ký (Fit & Registry) |
Khớp Box–Cox/WoE/OOF James–Stein bên trong nếp GroupKFold; kiểm tra canary IV > 0.50, Perm-Null <= 0.55; ký HMAC-SHA256 JSON State-Dict |
50–300 MB; artifact < 500 KB (dù OHE + WoE + PLR); build CI < 30 s |
Khóa phiên bản lược đồ Pydantic v2, từ chối ghi sai tên cột, lưu danh mục mới về tiên nghiệm \(\bar{y}_{\text{global}}\) |
Offline Data Plane: Kết nối & Cửa sổ Polars 2.0 |
Quét Parquet, sắp xếp ["entity_id", "event_ts", "tx_id"], chạy rolling(closed="left") & join_asof nhân quả |
2.5–6.0 GB (cho 100M hàng); thông lượng 3–10 s |
Two-Stage Salted Aggregation (thêm salt = tx_id % S) cho thực thể nóng (hot merchants chiếm 15% lưu lượng) tránh tràn một worker |
Online Data Plane: Suy luận Hàng đơn < 1 ms |
Giải mã trạng thái JSON lúc khởi động worker (0 I/O khi serve); cập nhật hàng đợi trượt deque & EWMA \(\mathcal{O}(1)\) |
< 15 MB RAM/worker; 0.044–0.074 ms p99 CPU (parity < 1e-12 với lô) |
Cắt đỉnh sự kiện theo Bounded Ring Buffer (max_events = 500 gần nhất) để một bot spam hàng nghìn req/phút không gây OOM Redis/deque |
2.5 Bốn Phép tính Tay Minh họa Từng bước (Worked Numerical Hand-Traces)#
-
Box–Cox Jacobian vs. Phương sai Phần dư Ngây thơ (
x = (1, 2, 10),n = 3):- Tại \(\lambda = 0\): \(\mathbf{y}^{(0)} = (\ln 1, \ln 2, \ln 10) = (0.000, 0.693, 2.303)\), \(\bar{y}^{(0)} = 0.999\), \(\hat{\sigma}^2(0) = 0.935\), \(\sum \ln x_i = 2.996\). Hợp lý hồ sơ (bỏ hằng số \(-\frac{n}{2}\ln(2\pi e)\)):
\[\ell_{\max}(0) \propto -\frac{3}{2}\ln(0.935) + (0 - 1)(2.996) = +0.101 - 2.996 = \mathbf{-2.895}.\]
- Thử kéo \(\lambda = -3\) (bỏ Jacobian): \(\mathbf{y}^{(-3)} = \frac{x^{-3}-1}{-3} = (0.000, 0.292, 0.333)\), phương sai sụp xuống \(\hat{\sigma}^2(-3) = 0.0227 \ll 0.935\) (
41xnhỏ hơn!), đánh lừa bộ tối ưu không có Jacobian chọn \(\lambda \to -\infty\)! Nhưng khi cộng đúng hạng tử Jacobian:\[\ell_{\max}(-3) \propto -\frac{3}{2}\ln(0.0227) + (-3 - 1)(2.996) = +5.678 - 11.984 = \mathbf{-6.306} < -2.895!\]Hạng tử Jacobian phạt nặng-11.984, bảo vệ chính xác \(\hat{\lambda}\) gần0(-0.045trong lab)!
- Tại \(\lambda = 0\): \(\mathbf{y}^{(0)} = (\ln 1, \ln 2, \ln 10) = (0.000, 0.693, 2.303)\), \(\bar{y}^{(0)} = 0.999\), \(\hat{\sigma}^2(0) = 0.935\), \(\sum \ln x_i = 2.996\). Hợp lý hồ sơ (bỏ hằng số \(-\frac{n}{2}\ln(2\pi e)\)):
-
Monotonic
PAVAWoE&IVNgân hàng (G = 900,B = 100, \(\alpha_{\text{lap}} = 0.5\)): Xét 3 bin rủi ro tăng dần theo tỷ lệ sử dụng hạn mức (0–30%,30–70%,>70%):- Bin 1 (
G_1=500, B_1=10): \(g_1 = \frac{500.5}{901.5} = 0.5552\), \(b_1 = \frac{10.5}{101.5} = 0.1034 \implies \operatorname{WoE}_1 = \ln\!\left(\frac{0.5552}{0.1034}\right) = \mathbf{+1.680}\), đóng góp \(\operatorname{IV}_1 = (0.5552 - 0.1034)(1.680) = \mathbf{0.759}\). - Bin 2 (
G_2=300, B_2=30): \(g_2 = \frac{300.5}{901.5} = 0.3333\), \(b_2 = \frac{30.5}{101.5} = 0.3005 \implies \operatorname{WoE}_2 = \ln\!\left(\frac{0.3333}{0.3005}\right) = \mathbf{+0.104}\), đóng góp \(\operatorname{IV}_2 = (0.3333 - 0.3005)(0.104) = \mathbf{0.003}\). - Bin 3 (
G_3=100, B_3=60): \(g_3 = \frac{100.5}{901.5} = 0.1115\), \(b_3 = \frac{60.5}{101.5} = 0.5961 \implies \operatorname{WoE}_3 = \ln\!\left(\frac{0.1115}{0.5961}\right) = \mathbf{-1.676}\), đóng góp \(\operatorname{IV}_3 = (0.1115 - 0.5961)(-1.676) = \mathbf{0.812}\). - Kiểm tra: \(\operatorname{WoE}_1 (+1.680) > \operatorname{WoE}_2 (+0.104) > \operatorname{WoE}_3 (-1.676)\) đơn điệu nghiêm ngặt tuyệt đối và \(\operatorname{IV} = 0.759 + 0.003 + 0.812 = 1.574 > 0.50 \implies\) bật cờ kiểm toán ngay vì biến quá mạnh nghi rò rỉ hoặc tách quá sâu!
- Bin 1 (
-
Co rút
OOF James–Stein(y_bar = 0.05,m* = 20):- Với danh mục hiếm (
n_c = 5, tỷ lệ vỡ nợ mẫu \(\bar{y}_c = 0.40\) từ2/5ca): \(\lambda_c = \frac{5}{5 + 20} = 0.20 \implies \hat{e}_c = 0.20(0.40) + 0.80(0.05) = \mathbf{0.120}\) (kéo tụt3.3xkhỏi giá trị ghi nhớ0.40!). - Với danh mục phổ biến (
n_c = 500, \(\bar{y}_c = 0.12\)): \(\lambda_c = \frac{500}{500 + 20} = 0.9615 \implies \hat{e}_c = 0.9615(0.12) + 0.0385(0.05) = \mathbf{0.1173}\) (tin cậy mẫu lớn).
- Với danh mục hiếm (
-
Signed Feature Hashing(Weinberger ±1) Dưới Va chạm Bucket (m_hash = 8): Xét vector \(\mathbf{x}\) có"promo": 2(\(h=3, \xi=+1\)) và"fraud": 1(\(h=3, \xi=-1\)) va chạm vào đúng bucketb = 3:- Unsigned (
+1): \(\phi^{\text{unsign}}_3(\mathbf{x}) = 2 + 1 = 3\); khi nhân với vector \(\mathbf{x}'\) chỉ có"promo": 1, "fraud": 0, tích vô hướng là \(3 \times 1 = 3 \neq 2\) (cộng sai số dương \(+1\)!). - Signed (
±1): \(\phi_3(\mathbf{x}) = (+1)(2) + (-1)(1) = +1\), còn \(\phi_3(\mathbf{x}') = (+1)(1) = +1\); qua các hạt giống hàm băm \(\xi\) độc lập (\(\mathbb{P}(\xi(\text{promo})\xi(\text{fraud}) = +1) = \mathbb{P}(-1) = 0.5\)), kỳ vọng thành phần chéo \(2 \cdot 1 \cdot \mathbb{E}[\xi(\text{promo})\xi(\text{fraud})] = \mathbf{0}\), bảo toàn chính xác \(\mathbb{E}[\langle\phi(\mathbf{x}),\phi(\mathbf{x}')\rangle] = 2 \cdot 1 = \mathbf{2.0}\)!
- Unsigned (
Trụ cột 3 — Bốn Tình huống Công nghiệp, Ma trận Phản mẫu & Mã nguồn Sản xuất 2026 (Stack & Industry Cases)#
3.1 Bốn Tình huống Công nghiệp Thực tế (R31, E29:E31)#
Tình huống 1 — Thẻ điểm Tín dụng Ngân hàng (WoE Đơn điệu PAVA, Làm mượt Laplace & Cổng Rò rỉ IV > 0.50)#
- Bối cảnh & Lỗi sơ khai (
E29:E31): Ngân hàng bán lẻ xây dựng mô hìnhPD12 tháng tuân thủSR 11-7&EU AI Act. Chia khoảng đềupd.cutlên biến lệchrevolving_utilizationnhét> 90%hồ sơ vào 2 bin đầu, để lại các bin cao không có mẫu vỡ nợ gây \(\text{WoE} = +\infty\) và tạo đường cong rủi ro chữ U trái quy định kiểm toán, đồng thời vô tình đưa biến hậu xử lý nợ vào (IV = 3.94). - Khắc phục Thực nghiệm (
feature_eng_lab): TáchNaN/sentinel vào binMISSING(92hồ sơ, tỷ lệ xấu7.61%,WoE = -0.7264), gộp các khoảng phân vị bằngPAVAtrên tỷ lệ rủi ro làm mượt Laplace (\(\alpha_{\text{lap}} = 0.5\)) thu được4bin đơn điệu tuyệt đối (IV = 0.4039,+0.8400 -> +0.3144 -> -0.6810, tỷ lệ xấu1.68% -> 2.89% -> 7.58%), kích hoạt cờ cảnh báo rò rỉ ngay tại ngưỡngIV > 0.50, và theo dõi trôi phân bố OOT bằngCSI = 1.002.
Tình huống 2 — Phát hiện Gian lận Thanh toán Thời gian thực (Causal PIT vs. Future Bleed dưới < 2 ms p99)#
- Bối cảnh & Lỗi sơ khai: Tính
user_tx_avg_amountbằnggroupby().transform('mean')hoặcrolling(closed='both')làm bùng nổ chi tiêu sau thời điểm gian lận chảy ngược về giao dịch hiện tại, thổi phồngLeaky AUC = 0.857ngoại tuyến rồi sụp đổ ngay khi chạy thật. - Khắc phục Thực nghiệm (
feature_eng_lab): Siết cửa sổ nửa mở \([t_{\text{obs}} - W, t_{\text{obs}})\) kèm kiểm traavail_ts <= obs_ts - lag_secondsvà khóa sắp xếp(entity_id, event_ts, tx_id). Thực thi trực tuyến qua hàng đợidequetrạng thái tăng dần \(\mathcal{O}(1)\) (OnlineSlidingWindowState), giữAUCtrung thực0.788, sai khác khi làm nhiễu tương lai50xbằng0.0, lệch lô–đơn5.68e-14, và độ trễ0.074 msp99 (< 2 msSLA).
Tình huống 3 — Quảng cáo Trực tuyến CTR & ID Phân loại Nhiều mức (High-Cardinality, MDI Trap, PIMP & Signed Hashing)#
- Bối cảnh & Lỗi sơ khai (
E29:E31): Tập dữ liệu chứamerchant_idvàsession_uuidngẫu nhiên (K = 150–200).One-Hotdày đặc gây tràn RAM;Unsigned Hashing (+1)làm lệch dương tích vô hướng (+1.10);CART MDIxếpnoise_cat_K200(0.622) đứng đầu bảng vượt xa tín hiệu thật (0.154), cònIn-Sample Target Encodingghi nhớ quá khớp (0.836train \(\to\)0.710test). - Khắc phục Thực nghiệm (
feature_eng_lab): DùngSigned Feature Hashing(±1) giữ độ chệch gần0(-0.20),OOF James–Steintôn trọnggroups(0.692 -> 0.702,m* = 2.37), và chọn lọc bằngPIMP+BH-FDRloại sạchnoise_cat_150(pimp_z = -7.91,q = 1.0) kết hợpCluster Permutation(6.881) &Boruta(23/24 CONFIRMED) giải cứu cụm tín hiệu cộng tuyến.
Tình huống 4 — Dự báo Rời bỏ SaaS & Định giá (Stevens, Yeo–Johnson, PLR & Cổng LLM AutoFE)#
- Bối cảnh & Lỗi sơ khai: Đưa số dư hoàn tiền âm và tổng chi tiêu lệch nặng trực tiếp vào mô hình tuyến tính/
MLPgây bão hòa và hỏng ngưỡng bậc thang giá (raw AUC = 0.491), trong khi vòng lặpLLMđề xuất đặc trưng tự do không qua kiểm định làm quá khớp tập thẩm định. - Khắc phục Thực nghiệm (
feature_eng_lab):ColumnTransformerDAGkiểm tra nghiêm ngặt tương thích thang đo Stevens (cấmBox–Coxtrên cộtNOMINAL), dùngYeo–Johnsonhạ độ lệch có dấu (1.90 -> 0.308),PeriodicPLREncoderbứt phá ngưỡng bậc thang (0.491 -> 0.977), cổng 4 tầng loại4/5ứng viênLLMgiả mạo, và xuấtHMAC-SHA256 JSON State-Dictđạt lệch lô–đơn1.11e-16tại0.044 msp99.
3.2 Ma trận 8 Phản mẫu Sản xuất (Production Anti-Patterns Matrix)#
| # | Phản mẫu | Triệu chứng Sản xuất | Nguyên nhân Gốc | Cổng Phát hiện | Biện pháp Khắc phục Chuẩn |
|---|---|---|---|---|---|
| 1 | Khớp Tiền Tách tập (Impute/Scale/Select trước CV) |
AUC CV thổi phồng +0.08–+0.49 trên nhiễu thuần (0.878 vs. 0.387) |
Thống kê tập kiểm định hoặc tương quan mục tiêu rò rỉ vào biến đổi | Kiểm toán Nested CV & kiểm tra AST không có .fit() ngoài Pipeline |
Đưa 100% biến đổi vào ColumnTransformerDAG chỉ .fit() bên trong nếp train |
| 2 | Cửa sổ Cuộn Không Nhân quả (groupby().transform('mean')) |
Offline 0.857–0.94 sụp xuống live |
Dữ liệu tương lai (\(t > t_{\text{obs}}\)) hoặc chưa sẵn sàng chảy ngược | Kiểm thử Nhiễu Tương lai (max |diff| > 0) |
Dùng [t_obs - W, t_obs) (closed='left') + avail_ts <= t_obs - lag + deque trực tuyến |
| 3 | CART MDI trên Biến Phân loại Nhiều mức (High-Cardinality ID) |
Nhiễu UUID K=200 lọt Top-1 quan trọng (0.622 vs. 0.154) |
Tìm cắt nhị phân tối ưu tạo thiên lệch \(\mathcal{O}(K/n)\) (Strobl 2007; Klusowski 2024) |
PIMP (\(p \ge 0.05\)) & OOF Permutation (\(\le 0\)) |
Thay MDI bằng OOF Permutation + Null-Importance (PIMP) + Boruta |
| 4 | Target Encoding Nội mẫu / Bỏ qua groups |
Train AUC 0.836+ rơi mạnh trên khách hàng mới |
Hàng đơn lẻ hoặc giao dịch cùng account_id tự nhìn thấy nhãn mình |
Khoảng cách Train - Val > 0.10 trên ID |
Dùng OOF James–Stein tôn trọng GroupKFold + co về tiên nghiệm \(\bar{y}_{\text{global}}\) |
| 5 | Vi phạm Thang đo Stevens & Thời gian Tuyến tính | Đảo dấu hiệu trung bình; nhảy bậc 23:59 -> 00:00 |
Coi mã Nominal/Ordinal như Ratio hoặc giờ 0..23 tuyến tính |
Lỗi kiểm tra ScaleLevel & sai số đột biến lúc nửa đêm |
Định tuyến theo ScaleLevel: OHE/Hash/OOF cho Nominal, (sin, cos) cho chu kỳ |
| 6 | Bỏ quên Jacobian Box–Cox & Sentinel -999 |
\(\hat{\lambda} \to -\infty\) (-1.279), scaler méo vì -999 |
So sánh phương sai phần dư khác miền thang đo; trộn sentinel vào giá trị thật | |lambda_bc| chạm biên; đỉnh tần suất tại -1/-999 |
Luôn cộng \((\lambda - 1)\sum \ln x_i\); chuẩn hóa -999 -> NaN + xuất cờ _is_missing |
| 7 | Chia 0, Cột Hằng số & Lệch Vị trí iloc |
Lỗi ZeroDivisionError, inf ở WoE, tráo cột thầm lặng |
Độ lệch chuẩn = 0 trên nếp nhỏ; bin 0 vỡ nợ; lấy cột theo vị trí |
Kiểm thử hoán vị cột & dữ liệu chứa NaN/bin 0 |
Bảo vệ std < 1e-12 -> 1.0, làm mượt Laplace >= 0.5, lập chỉ mục theo tên cột |
| 8 | Lưu pickle (CWE-502) & Vòng lặp LLM Không Cổng |
Lỗ hổng RCE, vỡ ABI khi nâng NumPy, giảm AUC thật |
Thực thi bytecode tùy ý; thử trăm biểu thức trên cùng tập val | Quét cấm .pkl trong CI; BH-FDR bác bỏ ứng viên |
Dùng JSON State-Dict ký HMAC-SHA256; khóa LLM AutoFE qua Cổng 4 tầng |
3.3 Mã nguồn Thực thi Hệ sinh thái 2026 (Polars 2.0 Causal PIT, Box–Cox Jacobian, PAVA WoE/IV & TargetEncoder ColumnTransformer)#
(Ghi chú rạch ròi: Mã minh họa dưới đây chạy trực tiếp trên .venv dùng Polars, NumPy, Pandas và scikit-learn; còn gói thực hành feature_eng_lab ở Trụ cột 4 cài đặt toàn bộ từ đầu bằng Python stdlib + NumPy + Pandas + Pydantic v2 và được khóa bảo mật deserialization qua AST scan.)
from __future__ import annotations
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import polars as pl
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PowerTransformer, StandardScaler, TargetEncoder
def demo_polars_pit_rolling(n_events: int = 8, seed: int = 42) -> pl.DataFrame:
"""Compute strict half-open [t_obs - W, t_obs) Point-in-Time features in Polars."""
rng = np.random.default_rng(seed)
base = datetime(2026, 1, 1, 8, 0, 0)
raw = pl.DataFrame(
{
"entity_id": ["acct_1"] * (n_events // 2) + ["acct_2"] * (n_events - n_events // 2),
"event_ts": [base + timedelta(hours=int(h)) for h in (0, 2, 5, 9, 1, 3, 6, 8)[:n_events]],
"tx_id": list(range(1, n_events + 1)),
"amount": np.round(rng.lognormal(mean=3.5, sigma=0.8, size=n_events), 2).tolist(),
}
).sort(["entity_id", "event_ts", "tx_id"])
return raw.rolling(index_column="event_ts", period="4h", group_by="entity_id", closed="left").agg(
pl.col("amount").mean().fill_null(0.0).alias("pit_mean_4h"),
pl.len().alias("pit_cnt_4h"),
)
def demo_boxcox_jacobian_and_pava_woe(seed: int = 42) -> dict[str, float]:
"""Compare MLE Box-Cox (with vs without Jacobian) and monotonic PAVA WoE/IV."""
rng = np.random.default_rng(seed)
x_pos = np.exp(rng.normal(2.0, 1.0, size=600))
grid = np.linspace(-2.5, 2.0, 91)
def _bc_transform(lam: float) -> np.ndarray:
return np.log(x_pos) if abs(lam) < 1e-8 else (np.power(x_pos, lam) - 1.0) / lam
ll_with_jac = [
-0.5 * len(x_pos) * np.log(max(float(np.var(_bc_transform(lam_val))), 1e-12))
+ (lam_val - 1.0) * float(np.sum(np.log(x_pos)))
for lam_val in grid
]
ll_no_jac = [
-0.5 * len(x_pos) * np.log(max(float(np.var(_bc_transform(lam_val))), 1e-12))
for lam_val in grid
]
# Monotonic PAVA WoE/IV with Laplace smoothing alpha=0.5
util = np.clip(rng.beta(2.0, 4.0, size=1000), 0.01, 0.99)
y_bad = (rng.uniform(size=1000) < 1.0 / (1.0 + np.exp(-(-2.2 + 3.0 * util)))).astype(np.int64)
edges = np.quantile(util, np.linspace(0.0, 1.0, 9))
idx = np.clip(np.searchsorted(edges[1:-1], util, side="right"), 0, 7)
blocks = [
[float(np.sum(y_bad[idx == b] == 0)) + 0.5, float(np.sum(y_bad[idx == b] == 1)) + 0.5]
for b in range(8)
]
merged: list[list[float]] = []
for blk in blocks:
merged.append(blk)
while len(merged) >= 2 and (merged[-2][1] / sum(merged[-2])) >= (merged[-1][1] / sum(merged[-1])):
left, right = merged[-2], merged[-1]
merged.pop()
merged[-1] = [left[0] + right[0], left[1] + right[1]]
g_arr = np.array([b[0] for b in merged])
b_arr = np.array([b[1] for b in merged])
dist_g, dist_b = g_arr / g_arr.sum(), b_arr / b_arr.sum()
woe = np.log(dist_g / dist_b)
iv = float(np.sum((dist_g - dist_b) * woe))
return {
"lambda_with_jacobian": round(float(grid[int(np.argmax(ll_with_jac))]), 3),
"lambda_without_jacobian": round(float(grid[int(np.argmax(ll_no_jac))]), 3),
"woe_monotonic": float(np.all(np.diff(woe) < 0.0)),
"pava_iv": round(iv, 4),
}
def demo_oof_pipeline_sklearn(seed: int = 42) -> float:
"""Build leakage-free ColumnTransformer with PowerTransformer + OOF TargetEncoder."""
rng = np.random.default_rng(seed)
n = 400
df = pd.DataFrame(
{
"amount": rng.lognormal(3.0, 0.9, size=n),
"net_balance": rng.normal(0.0, 1.5, size=n),
"merchant_id": [f"m_{i}" for i in rng.integers(0, 25, size=n)],
}
)
y = (rng.uniform(size=n) < 1.0 / (1.0 + np.exp(-(0.6 * np.log1p(df["amount"]) - 2.0)))).astype(int)
prep = ColumnTransformer(
[
(
"num",
Pipeline([("yj", PowerTransformer(method="yeo-johnson")), ("sc", StandardScaler())]),
["amount", "net_balance"],
),
(
"cat",
TargetEncoder(cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=seed), smooth="auto"),
["merchant_id"],
),
]
)
clf = Pipeline([("prep", prep), ("lr", LogisticRegression(max_iter=500))])
clf.fit(df.iloc[:300], y[:300])
return float(clf.score(df.iloc[300:], y[300:]))
if __name__ == "__main__":
print(demo_polars_pit_rolling().head(4))
print("Box-Cox & PAVA WoE/IV:", demo_boxcox_jacobian_and_pava_woe())
print("OOF Pipeline Holdout Acc:", round(demo_oof_pipeline_sklearn(), 4))
3.4 Cẩm nang Công nghiệp (R31.6 Industrial Tips Checklists)#
- Phân loại & Tiền xử lý: Phân loại Stevens cho mọi cột trước khi viết mã; chuyển mọi sentinel (
-1,-999,"") vềNaNvà xuất cờ_is_missingkhi tỷ lệ thiếu \(> 0.5\%\) hoặc mang tín hiệuMNAR. Kiểm tra bất kỳ biến nào cóIV > 0.50hoặcAUC đơn biến > 0.90để bắt rò rỉ hậu quả. - Thời gian & Cửa sổ: Chuẩn hóa mọi mốc thời gian sang
UTCtránh nhảy giờ mùa hè (DST); luôn đặtclosed="left"(\(t_{\text{event}} < t_{\text{obs}}\)) kèmavail_ts <= obs_ts - delta_slavà khóa sắp xếp phụtx_id; kiểm chứng bằng phép thử Nhiễu Tương lai (max |diff| == 0.0). - Danh mục & Đề phòng Bền vững: Gộp nhóm hiếm
< max(20, 0.5% * n)vào__RARE__bên trong nếp train; bậthandle_unknown="ignore"hoặc fallback tiên nghiệm \(\bar{y}_{\text{global}}\); bảo vệ mẫu số chia (std < 1e-12 -> 1.0); làm mượt Laplace \(\alpha_{\text{lap}} \ge 0.5\) cho mọi tỷ lệ đếm rời rạc (WoE,CTR). - Triển khai & Parity: Tuyệt đối cấm
picklekhi phục vụ; kiểm thử tự động trong CI: (1) bất biến hoán vị thứ tự cột, (2) sai khác lô vs. hàng đơn< 1e-12, (3) độ trễ hàng đơnp99 < 1 ms, và (4) từ chối artifact giả mạo chữ kýHMAC-SHA256.
Trụ cột 4 — Phòng thí nghiệm Công nghiệp (feature_eng_lab) & Chuẩn Nghiệm thu (Lab Workbench)#
4.1 Kiến trúc Gói feature_eng_lab (Python stdlib + NumPy + Pandas + Pydantic v2)#
Gói ch08-feature-engineering-workbench triển khai toàn bộ thuật toán từ đầu bằng Python chuẩn + NumPy + Pandas + Pydantic v2 (uv.lock), kèm kiểm soát AST bảo mật deserialization (0 import pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal):
ch08-feature-engineering-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch08_workbench_results.json
├── src/
│ └── feature_eng_lab/
│ ├── __init__.py
│ ├── transforms_and_woe.py # Stevens Audits, MAD/Missing, Box-Cox (Jacobian), Yeo-Johnson, RankGauss, Cyclical, PLR, Causal PIT & Online State, Monotonic PAVA WoE/IV, OOF James-Stein, Signed Hashing, Fold PCA
│ ├── selection_and_metrics.py # Digamma, Chi2 SF, Bergsma V, Miller-Madow & KSG-1 MI, Pure-NumPy CART MDI Trap, OOF/Cluster Permutation, PIMP + BH-FDR, Boruta, LLM Gate
│ └── pipeline_dag.py # Pydantic v2 Contracts, ColumnTransformerDAG, FeaturePipeline, HMAC-SHA256 Signed JSON, Pre-Split Audit, Benchmark Runner
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_feature_eng_lab.py # 14/14 kiểm thử hợp đồng (gồm AST quét cấm import)
4.2 Kết quả Thực nghiệm CLI (artifacts/ch08_workbench_results.json)#
Thực thi một lệnh từ thư mục gốc của Lab:
python scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch08_workbench_results.json
Báo cáo artifacts/ch08_workbench_results.json xuất trọn vẹn workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% với các thông số thực đo sau:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm (--seed 42 --quick) |
Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_boxcox_jacobian_and_skew |
4.00 -> 0.001 (lam=-0.05 / -0.045) |
ok — Có Jacobian MLE cắt skew từ 4.00 -> 0.001 (\(\hat{\lambda}=-0.045\)), còn bỏ Jacobian sụp về -1.28 (-1.279); Yeo–Johnson cắt có dấu 1.90 -> 0.308; RankGauss đạt 0.065. |
kpi_mi_ksg_vs_pearson_u_shape |
\(|r|=0.077\) | KSG=1.792 (nats) |
ok — Spearman rho=0.043 cũng mù trên \(Y=X^2\); trên nhiễu K=25 độc lập, Miller–Madow sửa MI 0.926 -> 0.000 & Bergsma Cramér's V 0.279 -> 0.000. |
kpi_mdi_trap_vs_pimp_fdr |
MDI 0.622 vs 0.154 (Trap Fixed) |
warn — CART MDI đẩy nhiễu K=200 lên 0.622 vượt tín hiệu thật 0.154, còn OOF Perm trả đúng +0.302 vs -0.151; PIMP loại noise_cat_150 (z=-7.91, q=1.0), Cluster (6.881) & Boruta (23/24) cứu sig_twin. |
kpi_woe_iv_and_leak_canary |
IV 0.404 | Leak 3.94 (4 bins) |
ok — PAVA trên tỷ lệ làm mượt Laplace cho 4 bin đơn điệu tuyệt đối (is_monotonic=True, IV=0.4039, MISSING WoE=-0.7264), bắt canary 3.94 > 0.50, đo CSI=1.002. |
kpi_pit_causal_vs_leaky_auc |
Leak 0.857 -> PIT 0.788 (0.074 ms) |
critical — Nhờ cửa sổ nửa mở PIT, nhiễu tương lai 50x cho sai khác 0.0e+00, đồng bộ deque trực tuyến lệch 5.68e-14 (0.074 ms p99). |
kpi_signed_hash_and_pipeline_parity |
PLR 0.977 vs 0.491 (0.044 ms) |
ok — Signed Hash lệch -0.20 (vs Unsigned +1.10), OOF James–Stein ổn định 0.692 -> 0.702 (vs nội mẫu 0.836 -> 0.710), cổng LLM giữ 1/5, In-Fold CV phá ảo ảnh tiền tách tập 0.878 -> 0.387, lô/đơn lệch 1.11e-16 (JSON HMAC-SHA256). |
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_feature_eng_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_01_stevens_measurement_scale_invariance_failures |
Kiểm chứng đảo dấu Likert (+0.50 vs -0.75), sụp đổ R^2 mã nguyên Nominal (0.00 vs 0.75 vs 1.00), sai lệch % Interval (1.0 vs 0.36 vs <0.05), và chặn boxcox_scale trên cột NOMINAL. |
| 2 | test_02_box_cox_profile_ll_jacobian_vs_naive_and_yeo_johnson |
Khẳng định Box–Cox có Jacobian tìm |lambda| < 0.25 (bỏ Jacobian < -1.5), từ chối x <= 0, và Yeo–Johnson xử lý ổn định số âm/0 giảm |skew| < 0.35x. |
| 3 | test_03_rankgauss_and_missingness_mad_clipping |
Kiểm chứng hằng số norm_ppf(0.75) khớp 1.4826, RankGauss kéo |skew| < 0.35 trên holdout, cờ _is_missing và nhánh MeanAD khi MAD == 0. |
| 4 | test_04_cyclical_encoding_and_causal_pit_window_vs_online_parity |
Khẳng định dist(23, 0) == dist(0, 1), bất biến nhiễu tương lai == 0.0, và OnlineSlidingWindowState khớp lô < 1e-12 dưới < 2.0 ms p99. |
| 5 | test_05_monotonic_woe_iv_laplace_smoothing_and_leak_canary |
Khẳng định is_monotonic_ == True, tách bin MISSING, 0.05 < IV < 0.50, làm mượt chống inf, leak_proxy IV > 0.50 bật canary và CSI > 0.25. |
| 6 | test_06_mi_miller_madow_and_ksg_vs_pearson_spearman_blind_spots |
Kiểm chứng digamma(1), digamma(2) chuẩn 1e-12, Miller–Madow < plug-in, chuyển đổi nats/bits, Pearson/Spearman mù trên \(Y=X^2\) (<0.12) còn KSG-1 > 0.80, và Pearson mù trên XOR. |
| 7 | test_07_chi2_independence_and_bergsma_corrected_cramers_v |
Khẳng định chi2_sf(3.841459, 1) == 0.05, Bergsma \(\tilde{V} < V_{\text{naive}}\) trên nhiễu độc lập, và p < 1e-12 / \(\tilde{V} > 0.70\) trên cặp phụ thuộc. |
| 8 | test_08_tree_mdi_cardinality_trap_and_null_importance_pimp |
Chứng minh CART MDI xếp K=200 nhiễu cao hơn tín hiệu thật, còn OOF Perm đảo lại và PIMP BH-FDR chọn đúng true_sig & loại noise_cat_150. |
| 9 | test_09_collinearity_cluster_permutation_and_boruta_binomial |
Khẳng định Cluster Permutation khôi phục cụm x1 + x2_twin vượt đơn lẻ, và Boruta chốt x1 = CONFIRMED, noise = REJECTED. |
| 10 | test_10_oof_james_stein_respecting_groups_vs_in_sample_overfit |
Chứng minh mã hóa nội mẫu ghi nhớ (AUC > 0.78), trong khi OOFJamesSteinEncoder(groups=...) chống rò rỉ và co danh mục mới về global_prior_. |
| 11 | test_11_signed_feature_hashing_unbiasedness_and_plr_spectral_gap |
Chứng minh Unsigned lệch dương > 0.80 còn Signed không chệch với phương sai giảm theo n_buckets; PLR nâng AUC ngưỡng bậc thang từ <0.65 lên >0.85; kiểm tra FoldPCAExtractor. |
| 12 | test_12_llm_feature_verification_gate_and_presplit_leakage_audit |
Khẳng định cổng 4 tầng giữ llm_true_dti và loại >= 3 nhiễu; lọc tiền tách tập tạo AUC > 0.78 trên nhiễu trắng còn trong nếp CV giữ [0.35, 0.65]. |
| 13 | test_13_column_transformer_dag_parity_shuffled_cols_and_signed_json |
Kiểm chứng Pydantic extra="forbid", coef_ chỉ đọc, bất biến hoán vị cột 0.0, parity lô/đơn < 1e-12, khôi phục HMAC-SHA256 JSON và chặn tệp sửa đổi (ValueError). |
| 14 | test_14_cli_demo_script_workbench_json_and_zero_forbidden_imports |
Chạy run_lab_demo.py (returncode == 0), xác nhận 6 KPI, 4 bar, 4 bảng và quét AST bảo mật deserialization khẳng định 0 import không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bộ Đánh giá Năng lực (SOTA Reading List & Mastery Assessment)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Stevens, S. S. (1946); Box, G. E. P. & Cox, D. R. (1964); Yeo, I.-K. & Johnson, R. A. (2000). On the Theory of Scales of Measurement (
Science); An Analysis of Transformations (JRSS-B); A new family of power transformations (Biometrika).
Vì sao quan trọng: Đặt nền móng đại số cho tính bất biến theo nhóm tự đẳng cấu thang đo và chuẩn xác hóa hàm hợp lý hồ sơ kèm nhân tử Jacobian trên miền dương lẫn toàn trục thực. - Kraskov, A., Stögbauer, H., & Grassberger, P. (2004); Miller, G. A. (1955); Bergsma, W. (2013); Gao, W., et al. (NeurIPS 2017).
Vì sao quan trọng: Giải quyết thiên lệch mẫu hữu hạn trong ước lượng thông tin rời rạc (Miller–Madow), bảng chéo \(\chi^2\) (Cramér's Vhiệu chỉnh), và không gian liên tục/hỗn hợp không cần chia khoảng cố định (KSG-1& hỗn hợp nguyên tử). - Strobl, C., et al. (2007); Altmann, A., et al. (
PIMP, 2010); Kursa, M. B., & Rudnicki, W. R. (Boruta, 2010); Chamma, A., et al. (CPI, NeurIPS 2023); Agarwal, A., et al. (MDI+, 2023).
Vì sao quan trọng: Vạch trần thiên lệch \(\mathcal{O}(K/n)\) của độ quan trọng câyMDIvà cung cấp bộ chuẩn thống kê loại bỏ biến giả dưới đa cộng tuyến (PIMP,Boruta,CPI,MDI+). - Weinberger, K., et al. (ICML 2009); Freksen, C. B., et al. (NeurIPS 2018); Pargent, F., et al. (2022); Siddiqi, N. (2017); Navas-Palencia, G. (
OptBinning, 2020).
Vì sao quan trọng: Chứng minh tính không chệch của băm dấu \(\pm 1\), tối ưu hóa mã hóa mục tiêuOOFchính quy hóa cho biến phân loại nhiều mức (high-cardinality), và chuẩn mực thẻ điểm tín dụngWoE/IVđơn điệu. - Gorishniy, Y., et al. (
PLR, NeurIPS 2022;TabM, ICLR 2025); Hollmann, N., et al. (TabPFN v2, Nature 2025); Qu, J., et al. (TabICL, ICML 2025); Nam, J., et al. (OCTree, NeurIPS 2024).
Vì sao quan trọng: Định hình ranh giới 2024–2026 của học biểu diễn dữ liệu bảng: nhúng tuần hoànPLR, kiến trúc ghépTabM, mô hình nền tảngTabPFN/TabICLvà cổng chống quá khớp choLLM AutoFE.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Chứng minh bằng phản ví dụ vì sao lấy trung bình điểm Likert
Ordinalcó thể đảo dấu kết quả (+0.50 -> -0.75), mã nguyênNominallàm biến thiên giảR^2, và% thay đổivô nghĩa trênInterval. - Q2: Tại sao tối ưu
Box–Coxbằng cực tiểu hóa phương sai phần dư mà bỏ qua \((\lambda - 1)\sum \ln x_i\) lại đẩy \(\hat{\lambda}\) sụp về \(-\infty\) (-1.279vs.-0.045), và trường hợp nào bắt buộc dùngYeo–JohnsonhoặcRankGauss? - Q3: Trình bày mối liên hệ log-odds Bayes của
WoE, giải thích vì sao phải chạyPAVAtrên tỷ lệ rủi ro đã làm mượt Laplace (\(\alpha_{\text{lap}} = 0.5\)) và ý nghĩa cảnh báoIV > 0.50(3.94vs.0.404). - Q4: Giải thích vì sao
PearsonvàSpearmancùng mù trên \(Y = X^2\) (0.077,0.043) trong khiKSG-1đạt1.792 nats; đồng thời nêu công thức sửa thiên lệchMiller–Madow(0.926 -> 0.000) và Bergsma Cramér'sV(0.279 -> 0.000). - Q5: Trình bày cơ chế tối ưu phân tách của Fisher (1958) tạo ra bẫy
CART MDI\(\mathcal{O}(K/n)\) (0.622vs.0.154), và giải thích cáchOOF Permutation,Cluster Permutation,PIMP BH-FDRvàBorutaphối hợp xử lý nhiễu lẫn biến cộng tuyếnsig_twin. - Q6: Chứng minh định lý không chệch của
Signed Feature Hashing(-0.20vs.Unsigned +1.10) và lý giải vì saoOOF James–Steinbắt buộc phải truyềngroups(GroupKFold) khi cùng một thực thể lặp lại nhiều dòng. - Q7: Giải thích cơ chế Random Fourier Features của tầng nhúng
PLRgiúp mạng nơ-ron vượt qua ngưỡng bậc thang đối xứng (0.491 -> 0.977) và nêu thiết kế 4 tầng ngănLLM AutoFEquá khớp tập thẩm định. - Q8: Giải thích cơ chế rò rỉ tiền tách tập (ESL §7.10.2:
0.878vs.0.387), sự cố rò rỉ tương lai ởgroupby().transform('mean')(0.857 -> 0.788), và vì saoSigned JSON State-Dict(HMAC-SHA256) giải quyết cảCWE-502lẫn parity< 1 ms.
5.3 Sáu Bài tập Thực hành & Chứng minh Tính điểm (Ex1–Ex6)#
- Bài tập 1 (
15%): Chứng minh bất biến nhóm Stevens và chạyaudit_stevens_scale_violations()+ kiểm tra bảo vệ thang đo trongColumnTransformerDAG. - Bài tập 2 (
15%): Dẫn xuất hàm hợp lý hồ sơBox–Coxcó Jacobian và hằng sốMAD 1.4826; đối chiếuBoxCoxTransformer(use_jacobian=True/False),YeoJohnsonTransformer,RankGaussTransformervàMissingnessAndMadClipper. - Bài tập 3 (
20%): Chứng minh khoảng cách dây cung \(S^1\), xây dựngCausalRollingFeatureBuilder&OnlineSlidingWindowState(kiểm tra nhiễu tương lai0.0và parity< 1e-12), vàMonotonicWoEEncoderđơn điệuPAVA+ Laplace. - Bài tập 4 (
15%): Chứng minh điểm mù \(\operatorname{Cov}(X, X^2)=0\) và thiên lệchMiller–Madow; kiểm chứngcompute_discrete_mi,compute_ksg_mi, vàchi2_independence_and_cramers_v(Bergsma). - Bài tập 5 (
15%): Dẫn xuất \(\mathcal{O}(K/n)\) cho bẫyMDIvà kiểm định nhị thứcBoruta; thực thicompute_tree_mdi_bias_demo,null_importance_pimp,collinearity_cluster_permutationvàboruta_shadow_selection. - Bài tập 6 (
20%): Chứng minh tích vô hướngSigned Hashing, thực nghiệmOOFJamesSteinEncoder(groups=...),PeriodicPLREncoder,verify_llm_candidate_features_gate,audit_presplit_vs_infold_leakage, vàFeaturePipelinelưu kýHMAC-SHA256hoàn chỉnh qua14/14pytest.
5.4 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh chặt chẽ không nhảy bước (Stevens automorphisms, Box–Cox Jacobian, WoE PAVA Laplace, Miller–Madow/KSG-1, MDI \(\mathcal{O}(K/n)\), Signed Hashing & ESL §7.10.2); feature_eng_lab đạt 14/14 pytest với 0 import deserialization không an toàn (Test 14); parity lô/đơn < 1e-12 dưới < 1 ms bằng JSON State-Dict HMAC-SHA256 và chặn rò rỉ tương lai 0.0. |
| Senior Standard | 75–89% | Triển khai thông suốt 14/14 pytest thuần NumPy/Pandas/Pydantic, nắm vững đường ống chống rò rỉ và WoE/PIMP/OOF, nhưng thiếu chiều sâu chứng minh bẫy Jacobian, Bergsma Cramér's V, hoặc cơ chế RFF/NTK trong PLR. |
| Needs Remediation | < 75% | Mã hóa danh mục bằng số nguyên hoặc lấy trung bình thang Ordinal; lọc đặc trưng/chuẩn hóa trước khi chia tập CV; dùng CART MDI chọn biến phân loại nhiễu nhiều mức (high-cardinality) hoặc groupby tương lai; tuần tự hóa bằng pickle/joblib (CWE-502). |
Non-Linear Detection (Y=X^2) & Noise Bias Removal (MI Miller-Madow / KSG-1)
High-Cardinality Impurity Trap (CART MDI K=200 Noise vs OOF Permutation)
Representation & Extraction: PLR Pricing Cliff & OOF James-Stein Generalization
Pre-Split Screening Hallucination (White Noise) vs Inside-Fold Pipeline CV
Stevens Scale Violations & Power/Quantile Conditioning Benchmarks
| benchmark | raw_or_naive | remediated_or_invariant | secondary_check | verdict |
|---|---|---|---|---|
| ordinal_likert_reversal | mean_diff=+0.50 -> -0.75 | median_preserved=True | G_ord invariant | USE_MEDIAN_OR_RANK |
| nominal_integer_coding | R2(123)=0.00 vs R2(132)=0.75 | OneHot R2=1.00 | G_nom invariant | NEVER_INT_ENCODE |
| box_cox_lognormal | skew=4.00 (no-Jac lam=-1.28) | skew=0.001 (MLE lam=-0.045) | x > 0 required | JACOBIAN_MANDATORY |
| yeo_johnson_signed | skew=1.90 | skew=0.308 (lam=0.761) | RankGauss skew=0.065 | SIGNED_SAFE |
Banking Monotonic PAVA WoE Scorecard (Total IV = 0.4039, Leak Proxy IV = 3.94)
| bin | count | bad_rate | woe_laplace | iv_contrib |
|---|---|---|---|---|
| [-inf, 0.2165) | 416 | 1.68% | +0.8400 | 0.1692 |
| [0.2165, 0.4557) | 415 | 2.89% | +0.3144 | 0.0296 |
| [0.4557, +inf) | 277 | 7.58% | -0.6810 | 0.1476 |
| MISSING | 92 | 7.61% | -0.7264 | 0.0574 |
Feature Selection Audit: PIMP Null-Importance (BH-FDR) & Boruta Shadow Decisions
| feature | observed_mdi | pimp_z | bh_q_value | pimp_and_boruta_verdict |
|---|---|---|---|---|
| sig_linear | 2.4083 | +74.94 | 0.0417 | ACCEPT / CONFIRMED |
| sig_twin | 0.1174 | +0.92 | 0.2500 | REJECT / CONFIRMED |
| sig_nonlinear | 1.1108 | +30.29 | 0.0417 | ACCEPT / CONFIRMED |
| noise_gaussian | 0.0084 | -2.90 | 1.0000 | REJECT / REJECTED |
| noise_cat_150 | 1.8213 | -7.91 | 1.0000 | REJECT / EXCLUDED_CAT |
Pipeline DAG Train-Serving Parity, Causal PIT Windows & Signed JSON Security
| gate_check | measured_value | threshold_or_baseline | latency_or_count | status |
|---|---|---|---|---|
| batch_vs_single_row_parity | 1.11e-16 | < 1e-12 | p99=0.036 ms (<1 ms) | PARITY_VERIFIED |
| shuffled_column_invariance | 0.00e+00 | == 0.0 | d_out=25 | NAME_INDEXED_SAFE |
| hmac_json_roundtrip_parity | 0.00e+00 | < 1e-12 (0 pickle) | HMAC-SHA256 verified | CWE_502_IMMUNE |
| causal_pit_online_parity | 5.68e-14 | future_pert=0.0e+00 | p99=0.039 ms | ZERO_FUTURE_BLEED |
| llm_candidate_4stage_gate | kept=['llm_true_dti_ratio'] | rejected=4/5 | Nested OOF + BH-FDR | OVERFIT_BLOCKED |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/ch08-feature-engineering-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "feature-eng-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for Measurement Scales, Big-5 Feature Engineering, MI/PIMP/Boruta Selection, Banking WoE/IV, Causal PIT Windows, PLR Embeddings, and Signed JSON Pipeline DAGs (T1-P2-U03)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.4",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
"""Public exports for Lab 08 Feature Engineering & Automated Leakage-Free Pipelines (`feature_eng_lab`)."""
from feature_eng_lab.pipeline_dag import (
ColumnBranchSpec,
ColumnTransformerDAG,
FeaturePipeline,
PipelineConfig,
SignedStateEnvelope,
audit_presplit_vs_infold_leakage,
roc_auc_binary,
run_full_ch08_benchmarks,
)
from feature_eng_lab.selection_and_metrics import (
benjamini_hochberg,
binomial_lower_tail,
binomial_upper_tail,
boruta_shadow_selection,
chi2_independence_and_cramers_v,
chi2_sf,
collinearity_cluster_permutation,
compute_discrete_mi,
compute_ksg_mi,
compute_tree_mdi_bias_demo,
digamma,
null_importance_pimp,
oof_permutation_importance,
pearson_and_spearman,
verify_llm_candidate_features_gate,
)
from feature_eng_lab.transforms_and_woe import (
MAD_CONSISTENCY,
MEANAD_CONSISTENCY,
BoxCoxTransformer,
CausalRollingFeatureBuilder,
CyclicalTimeEncoder,
FoldPCAExtractor,
MissingnessAndMadClipper,
MonotonicWoEEncoder,
OnlineSlidingWindowState,
OOFJamesSteinEncoder,
PeriodicPLREncoder,
RankGaussTransformer,
ScaleLevel,
SignedFeatureHasher,
YeoJohnsonTransformer,
audit_stevens_scale_violations,
norm_ppf,
sample_skewness,
)
__all__ = [
"MAD_CONSISTENCY",
"MEANAD_CONSISTENCY",
"BoxCoxTransformer",
"CausalRollingFeatureBuilder",
"ColumnBranchSpec",
"ColumnTransformerDAG",
"CyclicalTimeEncoder",
"FeaturePipeline",
"FoldPCAExtractor",
"MissingnessAndMadClipper",
"MonotonicWoEEncoder",
"OOFJamesSteinEncoder",
"OnlineSlidingWindowState",
"PeriodicPLREncoder",
"PipelineConfig",
"RankGaussTransformer",
"ScaleLevel",
"SignedFeatureHasher",
"SignedStateEnvelope",
"YeoJohnsonTransformer",
"audit_presplit_vs_infold_leakage",
"audit_stevens_scale_violations",
"benjamini_hochberg",
"binomial_lower_tail",
"binomial_upper_tail",
"boruta_shadow_selection",
"chi2_independence_and_cramers_v",
"chi2_sf",
"collinearity_cluster_permutation",
"compute_discrete_mi",
"compute_ksg_mi",
"compute_tree_mdi_bias_demo",
"digamma",
"norm_ppf",
"null_importance_pimp",
"oof_permutation_importance",
"pearson_and_spearman",
"roc_auc_binary",
"run_full_ch08_benchmarks",
"sample_skewness",
"verify_llm_candidate_features_gate",
]
"""Pure NumPy/Pandas implementations of Stevens scale audits, Big-5 transforms, causal PIT rolling windows, and Monotonic WoE/IV."""
from __future__ import annotations
import hashlib
import math
from collections import deque
from enum import Enum
from typing import Any
import numpy as np
import pandas as pd
MAD_CONSISTENCY = 1.482602218505602
MEANAD_CONSISTENCY = 1.2533141373155003
_GOLDEN_RATIO_INV = (math.sqrt(5.0) - 1.0) / 2.0
class ScaleLevel(str, Enum):
"""Stevens' four levels of measurement ordered by decreasing automorphism group size."""
NOMINAL = "nominal"
ORDINAL = "ordinal"
INTERVAL = "interval"
RATIO = "ratio"
def norm_ppf(p: float | np.ndarray) -> float | np.ndarray:
"""Compute standard normal inverse CDF (probit) via Peter Acklam's rational approximation."""
is_scalar = np.isscalar(p)
arr = np.asarray(p, dtype=np.float64)
arr = np.clip(arr, 1e-15, 1.0 - 1e-15)
out = np.empty_like(arr, dtype=np.float64)
a = (
-3.969683028665376e01,
2.209460984245205e02,
-2.759285104469687e02,
1.383577518672690e02,
-3.066479806614716e01,
2.506628277459239e00,
)
b = (
-5.447609879822406e01,
1.615858368580409e02,
-1.556989798598866e02,
6.680131188771972e01,
-1.328068155288572e01,
)
c = (
-7.784894002430293e-03,
-3.223964580411365e-01,
-2.400758277161838e00,
-2.549732539343734e00,
4.374664141464968e00,
2.938163982698783e00,
)
d = (
7.784695709041462e-03,
3.224671290700398e-01,
2.445134137142996e00,
3.754408661907416e00,
)
p_low = 0.02425
p_high = 1.0 - p_low
mask_low = arr < p_low
mask_high = arr > p_high
mask_mid = (~mask_low) & (~mask_high)
if np.any(mask_low):
q = np.sqrt(-2.0 * np.log(arr[mask_low]))
num = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5])
den = ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0)
out[mask_low] = num / den
if np.any(mask_mid):
q = arr[mask_mid] - 0.5
r = q * q
num = (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q
den = (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1.0)
out[mask_mid] = num / den
if np.any(mask_high):
q = np.sqrt(-2.0 * np.log(1.0 - arr[mask_high]))
num = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5])
den = ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0)
out[mask_high] = -(num / den)
return float(out.item()) if is_scalar else out
def sample_skewness(x: np.ndarray) -> float:
"""Compute finite-sample adjusted Fisher-Pearson skewness of finite 1D values."""
arr = np.asarray(x, dtype=np.float64)
arr = arr[np.isfinite(arr)]
n = arr.size
if n < 3:
return 0.0
centered = arr - float(np.mean(arr))
m2 = float(np.mean(centered**2))
if m2 <= 1e-18:
return 0.0
m3 = float(np.mean(centered**3))
g1 = m3 / (m2**1.5)
return float(g1 * math.sqrt(n * (n - 1)) / (n - 2))
def audit_stevens_scale_violations() -> dict[str, Any]:
"""Reproduce quantitative invariance failures across Nominal, Ordinal, and Interval scales."""
# 1. Ordinal Likert reversal under two valid strictly monotone encodings
cohort_a = np.array([0, 3, 3, 3], dtype=np.int64) # ratings c1, c4, c4, c4
cohort_b = np.array([1, 1, 1, 4], dtype=np.int64) # ratings c2, c2, c2, c5
g1 = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
g2 = np.array([1.0, 2.0, 3.0, 4.0, 10.0])
diff_g1 = float(np.mean(g1[cohort_a]) - np.mean(g1[cohort_b]))
diff_g2 = float(np.mean(g2[cohort_a]) - np.mean(g2[cohort_b]))
med_a_g1 = float(np.median(g1[cohort_a]))
med_b_g1 = float(np.median(g1[cohort_b]))
med_a_g2 = float(np.median(g2[cohort_a]))
med_b_g2 = float(np.median(g2[cohort_b]))
# 2. Nominal integer coding linear regression collapse vs One-Hot invariance
y_nom = np.array([10.0, 2.0, 10.0], dtype=np.float64)
ss_tot = float(np.sum((y_nom - np.mean(y_nom)) ** 2))
def _ols_r2(X_mat: np.ndarray) -> float:
coef, *_ = np.linalg.lstsq(X_mat, y_nom, rcond=None)
resid = y_nom - X_mat @ coef
return float(1.0 - np.sum(resid**2) / ss_tot)
r2_int_abc = _ols_r2(np.column_stack([np.ones(3), np.array([1.0, 2.0, 3.0])]))
r2_int_acb = _ols_r2(np.column_stack([np.ones(3), np.array([1.0, 3.0, 2.0])]))
r2_onehot = _ols_r2(np.eye(3, dtype=np.float64))
# 3. Interval percentage-change failure (Celsius vs Fahrenheit vs Kelvin)
c_start, c_end = 10.0, 20.0
f_start, f_end = c_start * 1.8 + 32.0, c_end * 1.8 + 32.0
k_start, k_end = c_start + 273.15, c_end + 273.15
pct_c = (c_end - c_start) / c_start
pct_f = (f_end - f_start) / f_start
pct_k = (k_end - k_start) / k_start
return {
"ordinal_likert": {
"mean_diff_linear_codes": diff_g1,
"mean_diff_monotone_stretched": diff_g2,
"sign_reversed": (diff_g1 > 0.0) and (diff_g2 < 0.0),
"median_order_preserved": (med_a_g1 > med_b_g1) and (med_a_g2 > med_b_g2),
},
"nominal_integer_coding": {
"r2_alpha_123": r2_int_abc,
"r2_permuted_132": r2_int_acb,
"r2_onehot": r2_onehot,
},
"interval_pct_change": {
"pct_celsius": float(pct_c),
"pct_fahrenheit": float(pct_f),
"pct_kelvin": float(pct_k),
},
}
def _golden_section_max(fn: Any, lo: float, hi: float, n_grid: int = 41, n_iter: int = 48) -> float:
"""Find global 1D maximizer over [lo, hi] via coarse grid scan followed by golden-section refinement."""
grid = np.linspace(lo, hi, n_grid)
vals = [float(fn(float(g))) for g in grid]
best_idx = int(np.argmax(vals))
a = float(grid[max(0, best_idx - 1)])
b = float(grid[min(n_grid - 1, best_idx + 1)])
if b <= a:
return float(grid[best_idx])
c = b - _GOLDEN_RATIO_INV * (b - a)
d = a + _GOLDEN_RATIO_INV * (b - a)
fc = float(fn(c))
fd = float(fn(d))
for _ in range(n_iter):
if fc < fd:
a = c
c = d
fc = fd
d = a + _GOLDEN_RATIO_INV * (b - a)
fd = float(fn(d))
else:
b = d
d = c
fd = fc
c = b - _GOLDEN_RATIO_INV * (b - a)
fc = float(fn(c))
return 0.5 * (a + b)
class MissingnessAndMadClipper:
"""Emit binary missingness flags, clip outliers via train-frozen MAD bounds, and median-impute."""
def __init__(self, clip_z: float = 3.5, add_missing_flags: bool = True) -> None:
if clip_z <= 0.0:
raise ValueError("clip_z must be strictly positive.")
self.clip_z = float(clip_z)
self.add_missing_flags = bool(add_missing_flags)
self.feature_names_: list[str] = []
self.medians_: list[float] = []
self.scales_: list[float] = []
self.lower_: list[float] = []
self.upper_: list[float] = []
self.used_meanad_fallback_: list[bool] = []
self._fitted = False
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> MissingnessAndMadClipper:
arr, cols = _to_2d_float(X, columns)
self.feature_names_ = cols
self.medians_.clear()
self.scales_.clear()
self.lower_.clear()
self.upper_.clear()
self.used_meanad_fallback_.clear()
for j in range(arr.shape[1]):
col = arr[:, j]
valid = col[np.isfinite(col)]
if valid.size == 0:
med, scale, fallback = 0.0, 1.0, False
else:
med = float(np.median(valid))
mad = float(np.median(np.abs(valid - med)))
if mad > 1e-12:
scale = MAD_CONSISTENCY * mad
fallback = False
else:
meanad = float(np.mean(np.abs(valid - med)))
if meanad > 1e-12:
scale = MEANAD_CONSISTENCY * meanad
else:
std = float(np.std(valid))
scale = std if std > 1e-12 else 1.0
fallback = True
self.medians_.append(med)
self.scales_.append(scale)
self.lower_.append(med - self.clip_z * scale)
self.upper_.append(med + self.clip_z * scale)
self.used_meanad_fallback_.append(fallback)
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("MissingnessAndMadClipper must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
n_rows, n_cols = arr.shape
out_cols: list[np.ndarray] = []
flags: list[np.ndarray] = []
for j in range(n_cols):
col = arr[:, j].copy()
is_miss = ~np.isfinite(col)
col[is_miss] = self.medians_[j]
col = np.clip(col, self.lower_[j], self.upper_[j])
out_cols.append(col)
if self.add_missing_flags:
flags.append(is_miss.astype(np.float64))
blocks = out_cols + flags
return np.column_stack(blocks) if blocks else np.empty((n_rows, 0), dtype=np.float64)
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def get_feature_names_out(self) -> list[str]:
names = list(self.feature_names_)
if self.add_missing_flags:
names.extend(f"{c}_is_missing" for c in self.feature_names_)
return names
def to_state_dict(self) -> dict[str, Any]:
return {
"clip_z": self.clip_z,
"add_missing_flags": self.add_missing_flags,
"feature_names": self.feature_names_,
"medians": self.medians_,
"scales": self.scales_,
"lower": self.lower_,
"upper": self.upper_,
"used_meanad_fallback": self.used_meanad_fallback_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> MissingnessAndMadClipper:
obj = cls(clip_z=float(state["clip_z"]), add_missing_flags=bool(state["add_missing_flags"]))
obj.feature_names_ = list(state["feature_names"])
obj.medians_ = [float(v) for v in state["medians"]]
obj.scales_ = [float(v) for v in state["scales"]]
obj.lower_ = [float(v) for v in state["lower"]]
obj.upper_ = [float(v) for v in state["upper"]]
obj.used_meanad_fallback_ = [bool(v) for v in state["used_meanad_fallback"]]
obj._fitted = True
return obj
class BoxCoxTransformer:
"""Strictly positive Box-Cox MLE power transformer with exact profile log-likelihood Jacobian."""
def __init__(self, use_jacobian: bool = True, lam_bounds: tuple[float, float] = (-3.0, 3.0), standardize: bool = True) -> None:
self.use_jacobian = bool(use_jacobian)
self.lam_bounds = (float(lam_bounds[0]), float(lam_bounds[1]))
self.standardize = bool(standardize)
self.feature_names_: list[str] = []
self.lambdas_: list[float] = []
self.naive_no_jacobian_lambdas_: list[float] = []
self.means_: list[float] = []
self.stds_: list[float] = []
self.profile_ll_: list[float] = []
self._fitted = False
@staticmethod
def _apply_power(x: np.ndarray, lmbda: float) -> np.ndarray:
if abs(lmbda) < 1e-8:
return np.log(x)
return (np.power(x, lmbda) - 1.0) / lmbda
@staticmethod
def _profile_ll(x: np.ndarray, lmbda: float, log_x_sum: float, include_jacobian: bool) -> float:
y = BoxCoxTransformer._apply_power(x, lmbda)
var = float(np.var(y))
if not math.isfinite(var) or var <= 1e-18:
var = 1e-18
n = float(x.size)
ll = -0.5 * n * math.log(var)
if include_jacobian:
ll += (lmbda - 1.0) * log_x_sum
return ll
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> BoxCoxTransformer:
arr, cols = _to_2d_float(X, columns)
if not np.all(np.isfinite(arr)):
raise ValueError("BoxCoxTransformer expects finite inputs; impute missing values first.")
if np.any(arr <= 0.0):
raise ValueError("BoxCoxTransformer requires strictly positive inputs (x > 0). Use YeoJohnsonTransformer for x <= 0.")
self.feature_names_ = cols
self.lambdas_.clear()
self.naive_no_jacobian_lambdas_.clear()
self.means_.clear()
self.stds_.clear()
self.profile_ll_.clear()
lo, hi = self.lam_bounds
for j in range(arr.shape[1]):
col = arr[:, j]
log_x_sum = float(np.sum(np.log(col)))
lam_mle = _golden_section_max(
lambda lam, c=col, s=log_x_sum: self._profile_ll(c, lam, s, self.use_jacobian),
lo,
hi,
)
lam_naive = _golden_section_max(
lambda lam, c=col, s=log_x_sum: self._profile_ll(c, lam, s, False),
lo,
hi,
)
transformed = self._apply_power(col, lam_mle)
mean_j = float(np.mean(transformed))
std_j = float(np.std(transformed))
if std_j < 1e-12:
std_j = 1.0
self.lambdas_.append(float(lam_mle))
self.naive_no_jacobian_lambdas_.append(float(lam_naive))
self.means_.append(mean_j)
self.stds_.append(std_j)
self.profile_ll_.append(self._profile_ll(col, lam_mle, log_x_sum, True))
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("BoxCoxTransformer must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
if np.any(arr <= 0.0):
raise ValueError("BoxCoxTransformer received non-positive values at transform.")
out = np.empty_like(arr, dtype=np.float64)
for j, lmbda in enumerate(self.lambdas_):
z = self._apply_power(arr[:, j], lmbda)
if self.standardize:
z = (z - self.means_[j]) / self.stds_[j]
out[:, j] = z
return out
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
return {
"use_jacobian": self.use_jacobian,
"lam_bounds": list(self.lam_bounds),
"standardize": self.standardize,
"feature_names": self.feature_names_,
"lambdas": self.lambdas_,
"naive_no_jacobian_lambdas": self.naive_no_jacobian_lambdas_,
"means": self.means_,
"stds": self.stds_,
"profile_ll": self.profile_ll_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> BoxCoxTransformer:
obj = cls(
use_jacobian=bool(state["use_jacobian"]),
lam_bounds=(float(state["lam_bounds"][0]), float(state["lam_bounds"][1])),
standardize=bool(state["standardize"]),
)
obj.feature_names_ = list(state["feature_names"])
obj.lambdas_ = [float(v) for v in state["lambdas"]]
obj.naive_no_jacobian_lambdas_ = [float(v) for v in state["naive_no_jacobian_lambdas"]]
obj.means_ = [float(v) for v in state["means"]]
obj.stds_ = [float(v) for v in state["stds"]]
obj.profile_ll_ = [float(v) for v in state["profile_ll"]]
obj._fitted = True
return obj
class YeoJohnsonTransformer:
"""C^2-smooth Yeo-Johnson MLE power transformer supporting full real support (negative, zero, positive)."""
def __init__(self, lam_bounds: tuple[float, float] = (-3.0, 3.0), standardize: bool = True) -> None:
self.lam_bounds = (float(lam_bounds[0]), float(lam_bounds[1]))
self.standardize = bool(standardize)
self.feature_names_: list[str] = []
self.lambdas_: list[float] = []
self.means_: list[float] = []
self.stds_: list[float] = []
self._fitted = False
@staticmethod
def _apply_power(x: np.ndarray, lmbda: float) -> np.ndarray:
out = np.empty_like(x, dtype=np.float64)
pos = x >= 0.0
neg = ~pos
if np.any(pos):
xp = x[pos]
if abs(lmbda) < 1e-8:
out[pos] = np.log1p(xp)
else:
out[pos] = (np.power(1.0 + xp, lmbda) - 1.0) / lmbda
if np.any(neg):
xn = x[neg]
if abs(lmbda - 2.0) < 1e-8:
out[neg] = -np.log1p(-xn)
else:
out[neg] = -(np.power(1.0 - xn, 2.0 - lmbda) - 1.0) / (2.0 - lmbda)
return out
@staticmethod
def _profile_ll(x: np.ndarray, lmbda: float, signed_log_sum: float) -> float:
y = YeoJohnsonTransformer._apply_power(x, lmbda)
var = float(np.var(y))
if not math.isfinite(var) or var <= 1e-18:
var = 1e-18
n = float(x.size)
return -0.5 * n * math.log(var) + (lmbda - 1.0) * signed_log_sum
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> YeoJohnsonTransformer:
arr, cols = _to_2d_float(X, columns)
if not np.all(np.isfinite(arr)):
raise ValueError("YeoJohnsonTransformer expects finite inputs.")
self.feature_names_ = cols
self.lambdas_.clear()
self.means_.clear()
self.stds_.clear()
lo, hi = self.lam_bounds
for j in range(arr.shape[1]):
col = arr[:, j]
signed_log = float(np.sum(np.sign(col) * np.log1p(np.abs(col))))
lam_mle = _golden_section_max(
lambda lam, c=col, s=signed_log: self._profile_ll(c, lam, s),
lo,
hi,
)
z = self._apply_power(col, lam_mle)
m_j = float(np.mean(z))
s_j = float(np.std(z))
if s_j < 1e-12:
s_j = 1.0
self.lambdas_.append(float(lam_mle))
self.means_.append(m_j)
self.stds_.append(s_j)
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("YeoJohnsonTransformer must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
out = np.empty_like(arr, dtype=np.float64)
for j, lmbda in enumerate(self.lambdas_):
z = self._apply_power(arr[:, j], lmbda)
if self.standardize:
z = (z - self.means_[j]) / self.stds_[j]
out[:, j] = z
return out
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
return {
"lam_bounds": list(self.lam_bounds),
"standardize": self.standardize,
"feature_names": self.feature_names_,
"lambdas": self.lambdas_,
"means": self.means_,
"stds": self.stds_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> YeoJohnsonTransformer:
obj = cls(
lam_bounds=(float(state["lam_bounds"][0]), float(state["lam_bounds"][1])),
standardize=bool(state["standardize"]),
)
obj.feature_names_ = list(state["feature_names"])
obj.lambdas_ = [float(v) for v in state["lambdas"]]
obj.means_ = [float(v) for v in state["means"]]
obj.stds_ = [float(v) for v in state["stds"]]
obj._fitted = True
return obj
class RankGaussTransformer:
"""Order-invariant quantile normalizer mapping empirical ranks into standard normal scores."""
def __init__(self, n_quantiles: int = 256, eps: float = 1e-5) -> None:
self.n_quantiles = max(4, int(n_quantiles))
self.eps = float(eps)
self.feature_names_: list[str] = []
self.quantiles_x_: list[list[float]] = []
self.normal_y_: list[list[float]] = []
self._fitted = False
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> RankGaussTransformer:
arr, cols = _to_2d_float(X, columns)
self.feature_names_ = cols
self.quantiles_x_.clear()
self.normal_y_.clear()
for j in range(arr.shape[1]):
col = arr[:, j]
valid = np.sort(col[np.isfinite(col)])
if valid.size == 0:
self.quantiles_x_.append([0.0, 1.0])
self.normal_y_.append([0.0, 0.0])
continue
m = min(valid.size, self.n_quantiles)
probs = np.linspace(self.eps, 1.0 - self.eps, m)
x_grid = np.quantile(valid, probs)
# Collapse exact duplicate x_grid anchors cleanly for strict interpolation
uniq_x, idx = np.unique(x_grid, return_index=True)
if uniq_x.size == 1:
self.quantiles_x_.append([float(uniq_x[0]), float(uniq_x[0]) + 1.0])
self.normal_y_.append([0.0, 0.0])
else:
z_grid = norm_ppf(probs[idx])
self.quantiles_x_.append([float(v) for v in uniq_x])
self.normal_y_.append([float(v) for v in z_grid])
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("RankGaussTransformer must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
out = np.empty_like(arr, dtype=np.float64)
for j in range(arr.shape[1]):
qx = np.asarray(self.quantiles_x_[j], dtype=np.float64)
zy = np.asarray(self.normal_y_[j], dtype=np.float64)
col = arr[:, j]
res = np.interp(np.nan_to_num(col, nan=float(qx[len(qx) // 2])), qx, zy)
out[:, j] = res
return out
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
return {
"n_quantiles": self.n_quantiles,
"eps": self.eps,
"feature_names": self.feature_names_,
"quantiles_x": self.quantiles_x_,
"normal_y": self.normal_y_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> RankGaussTransformer:
obj = cls(n_quantiles=int(state["n_quantiles"]), eps=float(state["eps"]))
obj.feature_names_ = list(state["feature_names"])
obj.quantiles_x_ = [[float(v) for v in row] for row in state["quantiles_x"]]
obj.normal_y_ = [[float(v) for v in row] for row in state["normal_y"]]
obj._fitted = True
return obj
class CyclicalTimeEncoder:
"""Stateless unit-circle S^1 -> R^2 encoder eliminating periodic wrap-around discontinuities."""
def __init__(self, period: float) -> None:
if period <= 0.0:
raise ValueError("period must be strictly positive.")
self.period = float(period)
def transform(self, values: np.ndarray | pd.Series | float) -> np.ndarray:
arr = np.asarray(values, dtype=np.float64)
theta = (2.0 * math.pi * arr) / self.period
return np.column_stack([np.sin(theta), np.cos(theta)]) if arr.ndim >= 1 else np.array([math.sin(float(theta)), math.cos(float(theta))], dtype=np.float64)
class PeriodicPLREncoder:
"""Gorishniy et al. (2022) Periodic -> Linear -> ReLU (PLR) numerical embedding layer in pure NumPy."""
def __init__(
self,
n_frequencies: int = 16,
freq_std: float = 1.5,
embed_dim: int = 16,
seed: int = 42,
) -> None:
self.n_frequencies = int(n_frequencies)
self.freq_std = float(freq_std)
self.embed_dim = int(embed_dim)
self.seed = int(seed)
self.feature_names_: list[str] = []
self.means_: list[float] = []
self.stds_: list[float] = []
self.freqs_: list[list[float]] = []
self.weights_: list[list[list[float]]] = []
self.biases_: list[list[float]] = []
self._fitted = False
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> PeriodicPLREncoder:
arr, cols = _to_2d_float(X, columns)
rng = np.random.default_rng(np.random.SeedSequence(self.seed))
self.feature_names_ = cols
self.means_.clear()
self.stds_.clear()
self.freqs_.clear()
self.weights_.clear()
self.biases_.clear()
in_dim = 2 * self.n_frequencies
scale = math.sqrt(2.0 / in_dim)
for j in range(arr.shape[1]):
col = arr[:, j]
m_j = float(np.mean(col))
s_j = float(np.std(col))
if s_j < 1e-12:
s_j = 1.0
c_j = rng.normal(0.0, self.freq_std, size=self.n_frequencies)
W_j = rng.normal(0.0, scale, size=(in_dim, self.embed_dim))
b_j = np.zeros(self.embed_dim, dtype=np.float64)
self.means_.append(m_j)
self.stds_.append(s_j)
self.freqs_.append([float(v) for v in c_j])
self.weights_.append([[float(v) for v in row] for row in W_j])
self.biases_.append([float(v) for v in b_j])
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("PeriodicPLREncoder must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
blocks: list[np.ndarray] = []
for j in range(arr.shape[1]):
z = ((arr[:, j] - self.means_[j]) / self.stds_[j])[:, None]
c_j = np.asarray(self.freqs_[j], dtype=np.float64)[None, :]
phase = 2.0 * math.pi * z * c_j
v_j = np.hstack([np.sin(phase), np.cos(phase)])
W_j = np.asarray(self.weights_[j], dtype=np.float64)
b_j = np.asarray(self.biases_[j], dtype=np.float64)
e_j = np.maximum(0.0, v_j @ W_j + b_j)
blocks.append(e_j)
return np.hstack(blocks) if blocks else np.empty((arr.shape[0], 0), dtype=np.float64)
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
return {
"n_frequencies": self.n_frequencies,
"freq_std": self.freq_std,
"embed_dim": self.embed_dim,
"seed": self.seed,
"feature_names": self.feature_names_,
"means": self.means_,
"stds": self.stds_,
"freqs": self.freqs_,
"weights": self.weights_,
"biases": self.biases_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> PeriodicPLREncoder:
obj = cls(
n_frequencies=int(state["n_frequencies"]),
freq_std=float(state["freq_std"]),
embed_dim=int(state["embed_dim"]),
seed=int(state["seed"]),
)
obj.feature_names_ = list(state["feature_names"])
obj.means_ = [float(v) for v in state["means"]]
obj.stds_ = [float(v) for v in state["stds"]]
obj.freqs_ = [[float(v) for v in row] for row in state["freqs"]]
obj.weights_ = [[[float(v) for v in col] for col in mat] for mat in state["weights"]]
obj.biases_ = [[float(v) for v in row] for row in state["biases"]]
obj._fitted = True
return obj
class CausalRollingFeatureBuilder:
"""Strictly causal Point-in-Time [obs_ts - W, obs_ts) window feature generator with avail_ts SLA gate."""
def __init__(self, window_seconds: float, lag_seconds: float = 0.0, ewma_half_life: float = 3600.0) -> None:
if window_seconds <= 0.0 or lag_seconds < 0.0 or ewma_half_life <= 0.0:
raise ValueError("Invalid window, lag, or half-life parameter.")
self.window_seconds = float(window_seconds)
self.lag_seconds = float(lag_seconds)
self.ewma_half_life = float(ewma_half_life)
def transform_batch(self, df: pd.DataFrame) -> pd.DataFrame:
"""Compute strictly causal rolling count, sum, mean, and EWMA per entity without future bleed."""
required = {"entity_id", "event_ts", "avail_ts", "tx_id", "amount"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Missing required columns: {sorted(missing)}")
work = df.copy()
work["_orig_idx"] = np.arange(len(work))
work = work.sort_values(["entity_id", "event_ts", "tx_id"], kind="mergesort")
n = len(work)
counts = np.zeros(n, dtype=np.float64)
sums = np.zeros(n, dtype=np.float64)
means = np.zeros(n, dtype=np.float64)
ewmas = np.zeros(n, dtype=np.float64)
ent_vals = work["entity_id"].to_numpy()
ev_ts = work["event_ts"].to_numpy(dtype=np.float64)
av_ts = work["avail_ts"].to_numpy(dtype=np.float64)
amts = work["amount"].to_numpy(dtype=np.float64)
decay_ln2 = math.log(2.0) / self.ewma_half_life
# Process grouped contiguous runs after deterministic sort
start = 0
while start < n:
ent = ent_vals[start]
end = start + 1
while end < n and ent_vals[end] == ent:
end += 1
for i in range(start, end):
obs_t = ev_ts[i]
t_lo = obs_t - self.window_seconds
max_avail = obs_t - self.lag_seconds
c_sum = 0.0
c_cnt = 0
w_num = 0.0
w_den = 0.0
for j in range(i - 1, start - 1, -1):
t_j = ev_ts[j]
if t_j < t_lo:
break
if t_j < obs_t and av_ts[j] <= max_avail:
amt_j = amts[j]
c_sum += amt_j
c_cnt += 1
wt = math.exp(-decay_ln2 * (obs_t - t_j))
w_num += wt * amt_j
w_den += wt
counts[i] = float(c_cnt)
sums[i] = c_sum
means[i] = c_sum / c_cnt if c_cnt > 0 else 0.0
ewmas[i] = w_num / w_den if w_den > 0.0 else 0.0
start = end
work["pit_tx_count"] = counts
work["pit_tx_sum"] = sums
work["pit_tx_mean"] = means
work["pit_tx_ewma"] = ewmas
work = work.sort_values("_orig_idx", kind="mergesort").drop(columns=["_orig_idx"])
return work
@staticmethod
def transform_leaky_naive(df: pd.DataFrame) -> pd.DataFrame:
"""Deliberately flawed non-causal baseline leaking future entity transactions."""
work = df.copy()
work["leaky_entity_mean"] = work.groupby("entity_id")["amount"].transform("mean")
work["leaky_entity_count"] = work.groupby("entity_id")["amount"].transform("count").astype(np.float64)
return work
class OnlineSlidingWindowState:
"""O(1)-amortized streaming window state preserving exact < 1e-12 parity with CausalRollingFeatureBuilder."""
def __init__(self, window_seconds: float, lag_seconds: float = 0.0, ewma_half_life: float = 3600.0) -> None:
self.window_seconds = float(window_seconds)
self.lag_seconds = float(lag_seconds)
self.ewma_half_life = float(ewma_half_life)
self._decay_ln2 = math.log(2.0) / self.ewma_half_life
self._buffers: dict[Any, deque[tuple[float, float, float]]] = {}
def score_before_ingest(self, entity_id: Any, obs_ts: float) -> dict[str, float]:
"""Compute strictly causal features using only prior ingested events satisfying window and SLA lag."""
buf = self._buffers.get(entity_id)
if not buf:
return {"pit_tx_count": 0.0, "pit_tx_sum": 0.0, "pit_tx_mean": 0.0, "pit_tx_ewma": 0.0}
t_lo = obs_ts - self.window_seconds
while buf and buf[0][0] < t_lo:
buf.popleft()
max_avail = obs_ts - self.lag_seconds
c_sum = 0.0
c_cnt = 0
w_num = 0.0
w_den = 0.0
for ev_t, av_t, amt in buf:
if ev_t < obs_ts and av_t <= max_avail:
c_sum += amt
c_cnt += 1
wt = math.exp(-self._decay_ln2 * (obs_ts - ev_t))
w_num += wt * amt
w_den += wt
return {
"pit_tx_count": float(c_cnt),
"pit_tx_sum": float(c_sum),
"pit_tx_mean": float(c_sum / c_cnt) if c_cnt > 0 else 0.0,
"pit_tx_ewma": float(w_num / w_den) if w_den > 0.0 else 0.0,
}
def ingest(self, entity_id: Any, event_ts: float, avail_ts: float, amount: float) -> None:
"""Append finalized event after scoring to prevent current/future bleed."""
buf = self._buffers.setdefault(entity_id, deque())
buf.append((float(event_ts), float(avail_ts), float(amount)))
class MonotonicWoEEncoder:
"""Banking Weight-of-Evidence (WoE) & Information Value (IV) encoder with PAVA monotonicity & Laplace smoothing."""
def __init__(
self,
n_bins: int = 8,
laplace_alpha: float = 0.5,
enforce_monotonic: bool = True,
leak_iv_threshold: float = 0.50,
) -> None:
self.n_bins = max(2, int(n_bins))
self.laplace_alpha = float(laplace_alpha)
self.enforce_monotonic = bool(enforce_monotonic)
self.leak_iv_threshold = float(leak_iv_threshold)
self.edges_: list[float] = []
self.bin_labels_: list[str] = []
self.woe_map_: dict[str, float] = {}
self.ref_shares_: dict[str, float] = {}
self.iv_: float = 0.0
self.is_leakage_canary_: bool = False
self.is_monotonic_: bool = True
self.bin_table_: list[dict[str, Any]] = []
self._fitted = False
@staticmethod
def _pava_merge(
goods: np.ndarray,
bads: np.ndarray,
increasing: bool,
laplace_alpha: float = 0.5,
) -> list[tuple[int, int, int, int]]:
"""Pool Adjacent Violators Algorithm on Laplace-smoothed risk ratios ensuring final WoE monotonicity."""
blocks: list[list[Any]] = []
for idx in range(goods.size):
g = int(goods[idx])
b = int(bads[idx])
blocks.append([idx, idx, g, b])
while len(blocks) >= 2:
prev = blocks[-2]
curr = blocks[-1]
r_prev = (prev[3] + laplace_alpha) / (prev[2] + prev[3] + 2.0 * laplace_alpha)
r_curr = (curr[3] + laplace_alpha) / (curr[2] + curr[3] + 2.0 * laplace_alpha)
violates = (r_prev > r_curr) if increasing else (r_prev < r_curr)
if violates:
prev[1] = curr[1]
prev[2] += curr[2]
prev[3] += curr[3]
blocks.pop()
else:
break
return [(b[0], b[1], b[2], b[3]) for b in blocks]
def _compute_woe_iv(
self,
bin_counts: list[tuple[str, int, int]],
) -> tuple[list[dict[str, Any]], float]:
tot_g = sum(g for _, g, _ in bin_counts)
tot_b = sum(b for _, _, b in bin_counts)
tot_all = max(1, tot_g + tot_b)
n_b = len(bin_counts)
alpha = self.laplace_alpha
rows: list[dict[str, Any]] = []
iv_total = 0.0
for label, g, b in bin_counts:
p_g = (g + alpha) / (tot_g + n_b * alpha)
p_b = (b + alpha) / (tot_b + n_b * alpha)
woe = math.log(p_g / p_b)
iv_c = (p_g - p_b) * woe
iv_total += iv_c
cnt = g + b
rows.append(
{
"bin": label,
"count": cnt,
"share": cnt / tot_all,
"good": g,
"bad": b,
"bad_rate": b / max(1, cnt),
"good_share": p_g,
"bad_share": p_b,
"woe": woe,
"iv_contrib": iv_c,
}
)
return rows, iv_total
def fit(self, x: pd.Series | np.ndarray, y: pd.Series | np.ndarray) -> MonotonicWoEEncoder:
arr = np.asarray(x, dtype=np.float64)
y_bin = np.asarray(y, dtype=np.int64)
if arr.size != y_bin.size:
raise ValueError("x and y must share the same length.")
miss_mask = ~np.isfinite(arr)
valid_x = arr[~miss_mask]
valid_y = y_bin[~miss_mask]
if valid_x.size == 0:
self.edges_ = []
counts = [("MISSING", int(np.sum(y_bin == 0)), int(np.sum(y_bin == 1)))]
self.bin_table_, self.iv_ = self._compute_woe_iv(counts)
else:
qs = np.linspace(0.0, 1.0, self.n_bins + 1)[1:-1]
interior = np.unique(np.quantile(valid_x, qs))
bin_ids = np.searchsorted(interior, valid_x, side="right")
k_raw = interior.size + 1
goods = np.zeros(k_raw, dtype=np.int64)
bads = np.zeros(k_raw, dtype=np.int64)
for idx in range(k_raw):
mask = bin_ids == idx
goods[idx] = int(np.sum(valid_y[mask] == 0))
bads[idx] = int(np.sum(valid_y[mask] == 1))
if self.enforce_monotonic and k_raw > 1:
inc_blocks = self._pava_merge(goods, bads, increasing=True, laplace_alpha=self.laplace_alpha)
dec_blocks = self._pava_merge(goods, bads, increasing=False, laplace_alpha=self.laplace_alpha)
# Evaluate both monotonic orientations and pick higher IV (fallback to 2+ bins if possible)
cand_inc = [(f"B{i}", g, b) for i, (_, _, g, b) in enumerate(inc_blocks)]
cand_dec = [(f"B{i}", g, b) for i, (_, _, g, b) in enumerate(dec_blocks)]
_, iv_inc = self._compute_woe_iv(cand_inc)
_, iv_dec = self._compute_woe_iv(cand_dec)
chosen = inc_blocks if (len(inc_blocks) >= len(dec_blocks) and iv_inc >= iv_dec) or (len(dec_blocks) == 1 and len(inc_blocks) > 1) else dec_blocks
else:
chosen = [(i, i, int(goods[i]), int(bads[i])) for i in range(k_raw)]
new_edges: list[float] = []
counts = []
for idx, (s_i, e_i, g, b) in enumerate(chosen):
lo_str = "-inf" if idx == 0 else f"{interior[s_i - 1]:.4g}"
hi_str = "+inf" if e_i >= interior.size else f"{interior[e_i]:.4g}"
counts.append((f"[{lo_str}, {hi_str})", g, b))
if e_i < interior.size:
new_edges.append(float(interior[e_i]))
self.edges_ = new_edges
if np.any(miss_mask):
miss_y = y_bin[miss_mask]
counts.append(("MISSING", int(np.sum(miss_y == 0)), int(np.sum(miss_y == 1))))
self.bin_table_, self.iv_ = self._compute_woe_iv(counts)
self.bin_labels_ = [row["bin"] for row in self.bin_table_]
self.woe_map_ = {row["bin"]: float(row["woe"]) for row in self.bin_table_}
self.ref_shares_ = {row["bin"]: float(row["share"]) for row in self.bin_table_}
self.is_leakage_canary_ = bool(self.iv_ > self.leak_iv_threshold)
valid_woes = [r["woe"] for r in self.bin_table_ if r["bin"] != "MISSING"]
if len(valid_woes) <= 1:
self.is_monotonic_ = True
else:
diffs = np.diff(valid_woes)
self.is_monotonic_ = bool(np.all(diffs >= -1e-12) or np.all(diffs <= 1e-12))
self._fitted = True
return self
def _assign_bin(self, val: float) -> str:
if not math.isfinite(val):
return "MISSING" if "MISSING" in self.woe_map_ else self.bin_labels_[0]
if not self.edges_:
return self.bin_labels_[0]
idx = int(np.searchsorted(self.edges_, val, side="right"))
return self.bin_labels_[idx]
def transform(self, x: pd.Series | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("MonotonicWoEEncoder must be fitted before transform.")
arr = np.asarray(x, dtype=np.float64)
out = np.empty(arr.size, dtype=np.float64)
edges = np.asarray(self.edges_, dtype=np.float64)
valid_labels = [lbl for lbl in self.bin_labels_ if lbl != "MISSING"]
miss_val = self.woe_map_.get("MISSING", float(np.mean(list(self.woe_map_.values()))))
miss_mask = ~np.isfinite(arr)
out[miss_mask] = miss_val
if np.any(~miss_mask):
if edges.size == 0:
out[~miss_mask] = self.woe_map_[valid_labels[0]]
else:
idxs = np.searchsorted(edges, arr[~miss_mask], side="right")
woe_vals = np.asarray([self.woe_map_[lbl] for lbl in valid_labels], dtype=np.float64)
out[~miss_mask] = woe_vals[idxs]
return out
def fit_transform(self, x: pd.Series | np.ndarray, y: pd.Series | np.ndarray) -> np.ndarray:
return self.fit(x, y).transform(x)
def compute_csi(self, x_new: pd.Series | np.ndarray) -> float:
"""Compute Characteristic Stability Index (CSI) monitoring bin population shift."""
if not self._fitted:
raise RuntimeError("MonotonicWoEEncoder must be fitted before compute_csi.")
arr = np.asarray(x_new, dtype=np.float64)
n = max(1, arr.size)
counts: dict[str, int] = {lbl: 0 for lbl in self.bin_labels_}
for val in arr:
lbl = self._assign_bin(float(val))
counts[lbl] = counts.get(lbl, 0) + 1
eps = 1e-6
csi = 0.0
for lbl in self.bin_labels_:
p = max(eps, self.ref_shares_.get(lbl, eps))
q = max(eps, counts.get(lbl, 0) / n)
csi += (q - p) * math.log(q / p)
return float(csi)
def to_state_dict(self) -> dict[str, Any]:
return {
"n_bins": self.n_bins,
"laplace_alpha": self.laplace_alpha,
"enforce_monotonic": self.enforce_monotonic,
"leak_iv_threshold": self.leak_iv_threshold,
"edges": self.edges_,
"bin_labels": self.bin_labels_,
"woe_map": self.woe_map_,
"ref_shares": self.ref_shares_,
"iv": self.iv_,
"is_leakage_canary": self.is_leakage_canary_,
"is_monotonic": self.is_monotonic_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> MonotonicWoEEncoder:
obj = cls(
n_bins=int(state["n_bins"]),
laplace_alpha=float(state["laplace_alpha"]),
enforce_monotonic=bool(state["enforce_monotonic"]),
leak_iv_threshold=float(state["leak_iv_threshold"]),
)
obj.edges_ = [float(v) for v in state["edges"]]
obj.bin_labels_ = list(state["bin_labels"])
obj.woe_map_ = {str(k): float(v) for k, v in state["woe_map"].items()}
obj.ref_shares_ = {str(k): float(v) for k, v in state["ref_shares"].items()}
obj.iv_ = float(state["iv"])
obj.is_leakage_canary_ = bool(state["is_leakage_canary"])
obj.is_monotonic_ = bool(state["is_monotonic"])
obj._fitted = True
return obj
class OOFJamesSteinEncoder:
"""Out-of-fold Empirical-Bayes / James-Stein target encoder strictly isolating groups."""
def __init__(self, smoothing_m: float | None = None, n_splits: int = 5, seed: int = 42) -> None:
self.smoothing_m = smoothing_m
self.n_splits = max(2, int(n_splits))
self.seed = int(seed)
self.global_prior_: float = 0.0
self.learned_m_: float = 10.0
self.mapping_: dict[str, float] = {}
self._fitted = False
@staticmethod
def _fit_mapping(cats: np.ndarray, y: np.ndarray, smoothing_m: float | None) -> tuple[float, float, dict[str, float]]:
global_mean = float(np.mean(y))
global_var = float(np.var(y))
uniq, inv, counts = np.unique(cats, return_inverse=True, return_counts=True)
sums = np.bincount(inv, weights=y, minlength=uniq.size)
means = sums / counts
if smoothing_m is None:
# Empirical Bayes variance ratio m* = sigma_within^2 / sigma_between^2
pred_means = means[inv]
ss_within = float(np.sum((y - pred_means) ** 2))
within_var = ss_within / max(1, y.size - uniq.size)
between_var = max(1e-6, float(np.var(means)) if uniq.size > 1 else global_var * 0.25)
m_val = float(np.clip(within_var / between_var, 1.0, 200.0))
else:
m_val = float(smoothing_m)
encoded_vals = (counts * means + m_val * global_mean) / (counts + m_val)
mapping = {str(uniq[i]): float(encoded_vals[i]) for i in range(uniq.size)}
return global_mean, m_val, mapping
def fit(self, categories: pd.Series | np.ndarray, y: pd.Series | np.ndarray) -> OOFJamesSteinEncoder:
cats = np.asarray(categories, dtype=str)
y_arr = np.asarray(y, dtype=np.float64)
self.global_prior_, self.learned_m_, self.mapping_ = self._fit_mapping(cats, y_arr, self.smoothing_m)
self._fitted = True
return self
def fit_transform(
self,
categories: pd.Series | np.ndarray,
y: pd.Series | np.ndarray,
groups: pd.Series | np.ndarray | None = None,
) -> np.ndarray:
"""Fit full mapping while returning strictly out-of-fold encoded values respecting entity groups."""
cats = np.asarray(categories, dtype=str)
y_arr = np.asarray(y, dtype=np.float64)
n = cats.size
self.fit(cats, y_arr)
rng = np.random.default_rng(np.random.SeedSequence(self.seed))
if groups is None:
perm = rng.permutation(n)
fold_ids = np.empty(n, dtype=np.int64)
fold_ids[perm] = np.arange(n) % self.n_splits
else:
grp_arr = np.asarray(groups, dtype=str)
uniq_g, grp_inv = np.unique(grp_arr, return_inverse=True)
perm_g = rng.permutation(uniq_g.size)
g_fold = np.empty(uniq_g.size, dtype=np.int64)
g_fold[perm_g] = np.arange(uniq_g.size) % self.n_splits
fold_ids = g_fold[grp_inv]
out = np.empty(n, dtype=np.float64)
for f in range(self.n_splits):
val_mask = fold_ids == f
tr_mask = ~val_mask
if not np.any(val_mask):
continue
if not np.any(tr_mask):
out[val_mask] = self.global_prior_
continue
g_prior, _, f_map = self._fit_mapping(cats[tr_mask], y_arr[tr_mask], self.smoothing_m)
out[val_mask] = np.asarray([f_map.get(c, g_prior) for c in cats[val_mask]], dtype=np.float64)
return out
def transform(self, categories: pd.Series | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("OOFJamesSteinEncoder must be fitted before transform.")
cats = np.asarray(categories, dtype=str)
return np.asarray([self.mapping_.get(c, self.global_prior_) for c in cats], dtype=np.float64)
def to_state_dict(self) -> dict[str, Any]:
return {
"smoothing_m": self.smoothing_m,
"n_splits": self.n_splits,
"seed": self.seed,
"global_prior": self.global_prior_,
"learned_m": self.learned_m_,
"mapping": self.mapping_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> OOFJamesSteinEncoder:
obj = cls(
smoothing_m=state["smoothing_m"],
n_splits=int(state["n_splits"]),
seed=int(state["seed"]),
)
obj.global_prior_ = float(state["global_prior"])
obj.learned_m_ = float(state["learned_m"])
obj.mapping_ = {str(k): float(v) for k, v in state["mapping"].items()}
obj._fitted = True
return obj
class SignedFeatureHasher:
"""Weinberger et al. (2009) Signed Feature Hashing preserving unbiased inner products."""
def __init__(self, n_buckets: int = 256, signed: bool = True, seed: int = 42) -> None:
if n_buckets < 2:
raise ValueError("n_buckets must be >= 2.")
self.n_buckets = int(n_buckets)
self.signed = bool(signed)
self.seed = int(seed)
self._bucket_salt = f"bkt:{self.seed}".encode()
self._sign_salt = f"sgn:{self.seed}".encode()
def _hash_token(self, token: str) -> tuple[int, float]:
raw = token.encode("utf-8")
h_idx = int.from_bytes(hashlib.blake2b(raw, person=self._bucket_salt[:16], digest_size=8).digest(), "little")
bucket = h_idx % self.n_buckets
if not self.signed:
return bucket, 1.0
h_sgn = int.from_bytes(hashlib.blake2b(raw, person=self._sign_salt[:16], digest_size=8).digest(), "little")
sign = 1.0 if (h_sgn & 1) == 0 else -1.0
return bucket, sign
def transform_dicts(self, records: list[dict[str, float]]) -> np.ndarray:
"""Hash sparse token-weight dictionaries into dense (n_samples, n_buckets) matrix."""
out = np.zeros((len(records), self.n_buckets), dtype=np.float64)
for i, rec in enumerate(records):
for key, val in rec.items():
b, s = self._hash_token(str(key))
out[i, b] += s * float(val)
return out
def transform_tokens(self, tokens: pd.Series | np.ndarray, prefix: str = "cat") -> np.ndarray:
"""Hash a single categorical column into fixed signed projection buckets."""
arr = np.asarray(tokens, dtype=str)
out = np.zeros((arr.size, self.n_buckets), dtype=np.float64)
for i, tok in enumerate(arr):
b, s = self._hash_token(f"{prefix}={tok}")
out[i, b] += s
return out
def to_state_dict(self) -> dict[str, Any]:
return {"n_buckets": self.n_buckets, "signed": self.signed, "seed": self.seed}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> SignedFeatureHasher:
return cls(n_buckets=int(state["n_buckets"]), signed=bool(state["signed"]), seed=int(state["seed"]))
class FoldPCAExtractor:
"""Strictly train-fold centered SVD PCA projection without test covariance leakage."""
def __init__(self, n_components: int = 2, standardize: bool = True) -> None:
self.n_components = max(1, int(n_components))
self.standardize = bool(standardize)
self.feature_names_: list[str] = []
self.means_: list[float] = []
self.stds_: list[float] = []
self.components_: list[list[float]] = []
self.explained_variance_ratio_: list[float] = []
self._fitted = False
def fit(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> FoldPCAExtractor:
arr, cols = _to_2d_float(X, columns)
self.feature_names_ = cols
means = np.mean(arr, axis=0)
stds = np.std(arr, axis=0) if self.standardize else np.ones(arr.shape[1], dtype=np.float64)
stds = np.where(stds < 1e-12, 1.0, stds)
Z = (arr - means) / stds
_, svals, vt = np.linalg.svd(Z, full_matrices=False)
k = min(self.n_components, vt.shape[0])
tot_var = float(np.sum(svals**2))
ratios = (svals[:k] ** 2) / tot_var if tot_var > 1e-18 else np.zeros(k)
self.means_ = [float(v) for v in means]
self.stds_ = [float(v) for v in stds]
self.components_ = [[float(v) for v in row] for row in vt[:k]]
self.explained_variance_ratio_ = [float(v) for v in ratios]
self._fitted = True
return self
def transform(self, X: pd.DataFrame | np.ndarray) -> np.ndarray:
if not self._fitted:
raise RuntimeError("FoldPCAExtractor must be fitted before transform.")
arr, _ = _to_2d_float(X, self.feature_names_)
means = np.asarray(self.means_, dtype=np.float64)
stds = np.asarray(self.stds_, dtype=np.float64)
comp = np.asarray(self.components_, dtype=np.float64)
Z = (arr - means) / stds
return Z @ comp.T
def fit_transform(self, X: pd.DataFrame | np.ndarray, columns: list[str] | None = None) -> np.ndarray:
return self.fit(X, columns).transform(X)
def to_state_dict(self) -> dict[str, Any]:
return {
"n_components": self.n_components,
"standardize": self.standardize,
"feature_names": self.feature_names_,
"means": self.means_,
"stds": self.stds_,
"components": self.components_,
"explained_variance_ratio": self.explained_variance_ratio_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> FoldPCAExtractor:
obj = cls(n_components=int(state["n_components"]), standardize=bool(state["standardize"]))
obj.feature_names_ = list(state["feature_names"])
obj.means_ = [float(v) for v in state["means"]]
obj.stds_ = [float(v) for v in state["stds"]]
obj.components_ = [[float(v) for v in row] for row in state["components"]]
obj.explained_variance_ratio_ = [float(v) for v in state["explained_variance_ratio"]]
obj._fitted = True
return obj
def _to_2d_float(X: pd.DataFrame | np.ndarray, columns: list[str] | None) -> tuple[np.ndarray, list[str]]:
"""Coerce DataFrame or 1D/2D NumPy array into contiguous float64 matrix plus column names."""
if isinstance(X, pd.DataFrame):
cols = list(columns) if columns is not None else list(X.columns)
arr = X[cols].to_numpy(dtype=np.float64)
return arr, [str(c) for c in cols]
arr = np.asarray(X, dtype=np.float64)
if arr.ndim == 1:
arr = arr[:, None]
cols = [str(c) for c in columns] if columns is not None else [f"f{j}" for j in range(arr.shape[1])]
return arr, cols
"""Pure NumPy/Pandas statistical feature selection, MI (Miller-Madow & KSG-1), Chi2/Cramer's V, CART MDI trap, PIMP, and Boruta."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
import pandas as pd
def digamma(x: float | np.ndarray) -> float | np.ndarray:
"""Evaluate psi(x) = d/dx ln Gamma(x) via exact recurrence and asymptotic series (< 1e-14 error)."""
is_scalar = np.isscalar(x)
arr = np.asarray(x, dtype=np.float64).copy()
if np.any(arr <= 0.0):
raise ValueError("digamma is defined for strictly positive arguments (x > 0).")
acc = np.zeros_like(arr, dtype=np.float64)
# Shift small x up to >= 12.0 via psi(x) = psi(x + 1) - 1/x
while np.any(arr < 12.0):
mask = arr < 12.0
acc[mask] -= 1.0 / arr[mask]
arr[mask] += 1.0
inv = 1.0 / arr
inv2 = inv * inv
# Euler-Maclaurin asymptotic expansion for psi(x)
series = (
np.log(arr)
- 0.5 * inv
- inv2 * (1.0 / 12.0 - inv2 * (1.0 / 120.0 - inv2 * (1.0 / 252.0 - inv2 * (1.0 / 240.0))))
)
out = acc + series
return float(out.item()) if is_scalar else out
def _gamma_p_series(a: float, x: float) -> float:
"""Lower regularized incomplete gamma P(a, x) via power series (x < a + 1)."""
if x <= 0.0:
return 0.0
gln = math.lgamma(a)
ap = a
summ = 1.0 / a
delta = summ
for _ in range(300):
ap += 1.0
delta *= x / ap
summ += delta
if abs(delta) < abs(summ) * 1e-14:
break
return summ * math.exp(-x + a * math.log(x) - gln)
def _gamma_q_cf(a: float, x: float) -> float:
"""Upper regularized incomplete gamma Q(a, x) via modified Lentz continued fraction (x >= a + 1)."""
gln = math.lgamma(a)
tiny = 1e-30
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b if abs(b) > tiny else 1.0 / tiny
h = d
for i in range(1, 300):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-14:
break
return math.exp(-x + a * math.log(x) - gln) * h
def chi2_sf(x: float, df: int) -> float:
"""Compute survival function P(Chi2_df >= x) = Q(df/2, x/2) without scipy."""
if df <= 0:
raise ValueError("df must be >= 1.")
if x <= 0.0:
return 1.0
a = 0.5 * float(df)
z = 0.5 * float(x)
if z < a + 1.0:
return float(max(0.0, min(1.0, 1.0 - _gamma_p_series(a, z))))
return float(max(0.0, min(1.0, _gamma_q_cf(a, z))))
def _binomial_pmf(k: int, n: int, p: float = 0.5) -> float:
if k < 0 or k > n:
return 0.0
if p <= 0.0:
return 1.0 if k == 0 else 0.0
if p >= 1.0:
return 1.0 if k == n else 0.0
log_p = math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * math.log(p) + (n - k) * math.log(1.0 - p)
return math.exp(log_p)
def binomial_upper_tail(k_min: int, n: int, p: float = 0.5) -> float:
"""Compute P(Binomial(n, p) >= k_min)."""
return float(min(1.0, sum(_binomial_pmf(i, n, p) for i in range(max(0, k_min), n + 1))))
def binomial_lower_tail(k_max: int, n: int, p: float = 0.5) -> float:
"""Compute P(Binomial(n, p) <= k_max)."""
return float(min(1.0, sum(_binomial_pmf(i, n, p) for i in range(min(n, k_max) + 1))))
def benjamini_hochberg(p_values: np.ndarray | list[float], q: float = 0.05) -> dict[str, Any]:
"""Apply Benjamini-Hochberg step-up FDR control returning adjusted q-values and rejection mask."""
p = np.asarray(p_values, dtype=np.float64)
m = p.size
if m == 0:
return {"adjusted_q": np.array([], dtype=np.float64), "rejected": np.array([], dtype=bool)}
order = np.argsort(p)
ranked_p = p[order]
ranks = np.arange(1, m + 1, dtype=np.float64)
raw_q = (ranked_p * m) / ranks
# Enforce monotonicity from largest rank down to 1
adj_sorted = np.minimum.accumulate(raw_q[::-1])[::-1]
adj_sorted = np.clip(adj_sorted, 0.0, 1.0)
adj_q = np.empty(m, dtype=np.float64)
adj_q[order] = adj_sorted
rejected = adj_q <= q
return {"adjusted_q": adj_q, "rejected": rejected}
def _average_ranks(x: np.ndarray) -> np.ndarray:
"""Compute 1-based fractional average ranks for Spearman correlation without pandas overhead."""
n = x.size
order = np.argsort(x, kind="mergesort")
sorted_x = x[order]
ranks = np.empty(n, dtype=np.float64)
i = 0
while i < n:
j = i + 1
while j < n and sorted_x[j] == sorted_x[i]:
j += 1
avg_rank = 0.5 * (i + 1 + j)
ranks[order[i:j]] = avg_rank
i = j
return ranks
def pearson_and_spearman(x: np.ndarray | pd.Series, y: np.ndarray | pd.Series) -> dict[str, float]:
"""Compute Pearson linear correlation r and Spearman rank correlation rho_S."""
x_arr = np.asarray(x, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
mask = np.isfinite(x_arr) & np.isfinite(y_arr)
x_arr = x_arr[mask]
y_arr = y_arr[mask]
def _corr(a: np.ndarray, b: np.ndarray) -> float:
da = a - float(np.mean(a))
db = b - float(np.mean(b))
den = math.sqrt(float(np.sum(da * da)) * float(np.sum(db * db)))
return float(np.sum(da * db) / den) if den > 1e-18 else 0.0
r_pearson = _corr(x_arr, y_arr)
r_spearman = _corr(_average_ranks(x_arr), _average_ranks(y_arr))
return {"pearson_r": r_pearson, "spearman_rho": r_spearman}
def compute_discrete_mi(
x: np.ndarray | pd.Series,
y: np.ndarray | pd.Series,
unit: str = "nats",
) -> dict[str, float]:
"""Compute plug-in discrete MI and Miller-Madow finite-sample bias-corrected MI."""
x_arr = np.asarray(x)
y_arr = np.asarray(y)
n = x_arr.size
if n != y_arr.size or n == 0:
raise ValueError("x and y must be non-empty arrays of identical length.")
ux, inv_x, cx = np.unique(x_arr, return_inverse=True, return_counts=True)
uy, inv_y, cy = np.unique(y_arr, return_inverse=True, return_counts=True)
kx, ky = ux.size, uy.size
joint_counts = np.zeros((kx, ky), dtype=np.int64)
np.add.at(joint_counts, (inv_x, inv_y), 1)
px = cx / float(n)
py = cy / float(n)
pxy = joint_counts / float(n)
nz = pxy > 0.0
expected_prod = np.outer(px, py)
mi_nats = float(np.sum(pxy[nz] * np.log(pxy[nz] / expected_prod[nz])))
bias_nats = ((kx - 1) * (ky - 1)) / (2.0 * float(n))
mi_mm_nats = max(0.0, mi_nats - bias_nats)
scale = 1.0 if unit == "nats" else (1.0 / math.log(2.0) if unit == "bits" else None)
if scale is None:
raise ValueError("unit must be 'nats' or 'bits'.")
return {
"mi_plugin": mi_nats * scale,
"mi_miller_madow": mi_mm_nats * scale,
"bias_correction": bias_nats * scale,
"active_x": float(kx),
"active_y": float(ky),
}
def compute_ksg_mi(
x: np.ndarray | pd.Series,
y: np.ndarray | pd.Series,
k: int = 3,
unit: str = "nats",
batch_size: int = 256,
) -> float:
"""Compute Kraskov-Stogbauer-Grassberger Algorithm 1 (KSG-1) k-NN Mutual Information using L_inf metric."""
x_arr = np.asarray(x, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
mask = np.isfinite(x_arr) & np.isfinite(y_arr)
x_arr = x_arr[mask]
y_arr = y_arr[mask]
n = x_arr.size
if n <= k + 1:
raise ValueError("Sample size must exceed k + 1.")
# Standardize marginals for numeric conditioning (KSG L_inf is scale-invariant up to marginal scaling)
sx = float(np.std(x_arr))
sy = float(np.std(y_arr))
if sx < 1e-12 or sy < 1e-12:
return 0.0
xz = (x_arr - float(np.mean(x_arr))) / sx
yz = (y_arr - float(np.mean(y_arr))) / sy
nx_counts = np.empty(n, dtype=np.float64)
ny_counts = np.empty(n, dtype=np.float64)
for start in range(0, n, batch_size):
end = min(n, start + batch_size)
dx = np.abs(xz[start:end, None] - xz[None, :])
dy = np.abs(yz[start:end, None] - yz[None, :])
d_inf = np.maximum(dx, dy)
# k-th neighbor excluding self (distance 0 at diagonal -> index k in partitioned array)
part = np.partition(d_inf, kth=k, axis=1)
eps_half = np.maximum(part[:, k], 1e-15)[:, None]
# Strict open count minus self (since self distance 0 < eps_half)
nx_counts[start:end] = np.sum(dx < eps_half, axis=1) - 1
ny_counts[start:end] = np.sum(dy < eps_half, axis=1) - 1
mi_nats = float(digamma(float(k)) + digamma(float(n)) - np.mean(digamma(nx_counts + 1.0) + digamma(ny_counts + 1.0)))
mi_nats = max(0.0, mi_nats)
if unit == "nats":
return mi_nats
if unit == "bits":
return mi_nats / math.log(2.0)
raise ValueError("unit must be 'nats' or 'bits'.")
def chi2_independence_and_cramers_v(
x_cat: np.ndarray | pd.Series,
y_cat: np.ndarray | pd.Series,
) -> dict[str, float]:
"""Compute Pearson Chi-Square independence test, naive Cramer's V, and Bergsma (2013) bias-corrected V."""
x_arr = np.asarray(x_cat)
y_arr = np.asarray(y_cat)
n = x_arr.size
ux, inv_x, row_sums = np.unique(x_arr, return_inverse=True, return_counts=True)
uy, inv_y, col_sums = np.unique(y_arr, return_inverse=True, return_counts=True)
r, c = ux.size, uy.size
obs = np.zeros((r, c), dtype=np.float64)
np.add.at(obs, (inv_x, inv_y), 1.0)
exp = np.outer(row_sums, col_sums) / float(n)
valid = exp > 0.0
chi2_stat = float(np.sum(((obs[valid] - exp[valid]) ** 2) / exp[valid]))
dof = max(1, (r - 1) * (c - 1))
p_val = chi2_sf(chi2_stat, dof)
phi2 = chi2_stat / float(n)
min_dim = max(1, min(r - 1, c - 1))
cramers_v = math.sqrt(max(0.0, phi2 / float(min_dim)))
# Bergsma (2013) finite-sample bias correction
if n > 1:
phi2_corr = max(0.0, phi2 - ((r - 1) * (c - 1)) / float(n - 1))
r_corr = r - ((r - 1) ** 2) / float(n - 1)
c_corr = c - ((c - 1) ** 2) / float(n - 1)
denom = min(r_corr - 1.0, c_corr - 1.0)
v_corr = math.sqrt(phi2_corr / denom) if denom > 1e-12 else 0.0
else:
v_corr = 0.0
return {
"chi2_stat": chi2_stat,
"dof": float(dof),
"p_value": p_val,
"cramers_v": cramers_v,
"cramers_v_corrected": v_corr,
"rows": float(r),
"cols": float(c),
}
class _FastCARTNode:
"""Compact binary CART tree node supporting both continuous and Fisher-sorted categorical splits."""
__slots__ = ("cat_left_set", "feature_idx", "left", "right", "threshold", "value")
def __init__(
self,
feature_idx: int = -1,
threshold: float = 0.0,
cat_left_set: frozenset[int] | None = None,
value: float = 0.0,
left: _FastCARTNode | None = None,
right: _FastCARTNode | None = None,
) -> None:
self.feature_idx = feature_idx
self.threshold = threshold
self.cat_left_set = cat_left_set
self.value = value
self.left = left
self.right = right
class _FastCARTRegressor:
"""Pure-NumPy CART regressor supporting Fisher (1958) optimal categorical subset splits."""
def __init__(
self,
max_depth: int = 5,
min_samples_leaf: int = 5,
max_features: int | None = None,
categorical_indices: set[int] | None = None,
seed: int = 42,
) -> None:
self.max_depth = int(max_depth)
self.min_samples_leaf = int(min_samples_leaf)
self.max_features = max_features
self.categorical_indices = set(categorical_indices or set())
self.seed = int(seed)
self.root_: _FastCARTNode | None = None
self.feature_importances_: np.ndarray = np.array([], dtype=np.float64)
self._n_total = 1
def fit(self, X: np.ndarray, y: np.ndarray) -> _FastCARTRegressor:
n, p = X.shape
self._n_total = max(1, n)
self.feature_importances_ = np.zeros(p, dtype=np.float64)
rng = np.random.default_rng(self.seed)
self.root_ = self._build(X, y, depth=0, rng=rng)
return self
def _best_continuous_split(
self,
col: np.ndarray,
y: np.ndarray,
total_sum: float,
total_sq: float,
) -> tuple[float, float | None]:
n = col.size
c_min = float(np.min(col))
c_max = float(np.max(col))
if c_max - c_min <= 1e-12:
return 0.0, None
parent_sse = total_sq - (total_sum * total_sum) / n
if n <= 24:
cands = np.unique(col)
if cands.size <= 1:
return 0.0, None
thresholds = 0.5 * (cands[:-1] + cands[1:])
else:
thresholds = np.linspace(c_min, c_max, 17)[1:-1]
left = col[:, None] <= thresholds[None, :]
nl = np.sum(left, axis=0)
nr = n - nl
valid = (nl >= self.min_samples_leaf) & (nr >= self.min_samples_leaf)
if not np.any(valid):
return 0.0, None
sl = y @ left.astype(np.float64)
sr = total_sum - sl
child_sse = np.where(
valid,
total_sq - (sl * sl) / np.maximum(nl, 1) - (sr * sr) / np.maximum(nr, 1),
parent_sse + 1.0,
)
gains = parent_sse - child_sse
best_idx = int(np.argmax(gains))
best_gain = float(gains[best_idx])
if best_gain <= 0.0:
return 0.0, None
return best_gain, float(thresholds[best_idx])
def _best_categorical_split(
self,
col: np.ndarray,
y: np.ndarray,
total_sum: float,
total_sq: float,
) -> tuple[float, frozenset[int] | None]:
n = col.size
cats_int = col.astype(np.int64)
uniq, inv, counts = np.unique(cats_int, return_inverse=True, return_counts=True)
if uniq.size <= 1:
return 0.0, None
cat_sums = np.bincount(inv, weights=y, minlength=uniq.size)
cat_means = cat_sums / counts
order = np.argsort(cat_means)
sorted_cats = uniq[order]
sorted_counts = counts[order]
sorted_sums = cat_sums[order]
nl = np.cumsum(sorted_counts[:-1])
nr = n - nl
valid = (nl >= self.min_samples_leaf) & (nr >= self.min_samples_leaf)
if not np.any(valid):
return 0.0, None
sl = np.cumsum(sorted_sums[:-1])
sr = total_sum - sl
parent_sse = total_sq - (total_sum * total_sum) / n
child_sse = np.where(
valid,
total_sq - (sl * sl) / np.maximum(nl, 1) - (sr * sr) / np.maximum(nr, 1),
parent_sse + 1.0,
)
gains = parent_sse - child_sse
best_pos = int(np.argmax(gains))
best_gain = float(gains[best_pos])
if best_gain <= 0.0:
return 0.0, None
left_set = frozenset(int(c) for c in sorted_cats[: best_pos + 1])
return best_gain, left_set
def _build(self, X: np.ndarray, y: np.ndarray, depth: int, rng: np.random.Generator) -> _FastCARTNode:
n, p = X.shape
mean_val = float(np.mean(y))
if depth >= self.max_depth or n < 2 * self.min_samples_leaf or float(np.var(y)) <= 1e-12:
return _FastCARTNode(value=mean_val)
if self.max_features is not None and self.max_features < p:
feat_pool = rng.choice(p, size=self.max_features, replace=False)
else:
feat_pool = np.arange(p)
total_sum = float(np.sum(y))
total_sq = float(np.sum(y * y))
best_gain = 0.0
best_feat = -1
best_thr = 0.0
best_cat_set: frozenset[int] | None = None
for j in feat_pool:
j_int = int(j)
if j_int in self.categorical_indices:
gain, cset = self._best_categorical_split(X[:, j_int], y, total_sum, total_sq)
if gain > best_gain and cset is not None:
best_gain = gain
best_feat = j_int
best_cat_set = cset
else:
gain, thr = self._best_continuous_split(X[:, j_int], y, total_sum, total_sq)
if gain > best_gain and thr is not None:
best_gain = gain
best_feat = j_int
best_thr = thr
best_cat_set = None
if best_feat < 0 or best_gain <= 1e-12:
return _FastCARTNode(value=mean_val)
self.feature_importances_[best_feat] += best_gain / float(self._n_total)
if best_cat_set is not None:
col_int = X[:, best_feat].astype(np.int64)
left_mask = np.isin(col_int, list(best_cat_set))
else:
left_mask = X[:, best_feat] <= best_thr
left_node = self._build(X[left_mask], y[left_mask], depth + 1, rng)
right_node = self._build(X[~left_mask], y[~left_mask], depth + 1, rng)
return _FastCARTNode(
feature_idx=best_feat,
threshold=best_thr,
cat_left_set=best_cat_set,
value=mean_val,
left=left_node,
right=right_node,
)
def predict(self, X: np.ndarray) -> np.ndarray:
if self.root_ is None:
raise RuntimeError("Tree must be fitted before predict.")
out = np.empty(X.shape[0], dtype=np.float64)
self._predict_batch(self.root_, X, np.arange(X.shape[0]), out)
return out
def _predict_batch(self, node: _FastCARTNode, X: np.ndarray, idxs: np.ndarray, out: np.ndarray) -> None:
if idxs.size == 0:
return
if node.left is None or node.right is None or node.feature_idx < 0:
out[idxs] = node.value
return
if node.cat_left_set is not None:
vals = X[idxs, node.feature_idx].astype(np.int64)
go_left = np.isin(vals, list(node.cat_left_set))
else:
go_left = X[idxs, node.feature_idx] <= node.threshold
self._predict_batch(node.left, X, idxs[go_left], out)
self._predict_batch(node.right, X, idxs[~go_left], out)
class _FastRandomForest:
"""Lightweight bagged CART ensemble for fast MDI, OOF Permutation, PIMP, and Boruta audits."""
def __init__(
self,
n_trees: int = 12,
max_depth: int = 5,
min_samples_leaf: int = 6,
categorical_indices: set[int] | None = None,
seed: int = 42,
) -> None:
self.n_trees = int(n_trees)
self.max_depth = int(max_depth)
self.min_samples_leaf = int(min_samples_leaf)
self.categorical_indices = set(categorical_indices or set())
self.seed = int(seed)
self.trees_: list[_FastCARTRegressor] = []
self.mdi_importances_: np.ndarray = np.array([], dtype=np.float64)
def fit(self, X: np.ndarray, y: np.ndarray) -> _FastRandomForest:
n, p = X.shape
rng = np.random.default_rng(np.random.SeedSequence(self.seed))
max_feat = max(1, math.ceil(0.75 * p))
self.trees_.clear()
mdi_acc = np.zeros(p, dtype=np.float64)
for t in range(self.n_trees):
boot = rng.integers(0, n, size=n)
tree = _FastCARTRegressor(
max_depth=self.max_depth,
min_samples_leaf=self.min_samples_leaf,
max_features=max_feat,
categorical_indices=self.categorical_indices,
seed=int(rng.integers(0, 2**31 - 1)),
)
tree.fit(X[boot], y[boot])
self.trees_.append(tree)
mdi_acc += tree.feature_importances_
self.mdi_importances_ = mdi_acc / float(self.n_trees)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
preds = np.zeros(X.shape[0], dtype=np.float64)
for tree in self.trees_:
preds += tree.predict(X)
return preds / float(len(self.trees_))
def _prepare_forest_inputs(
X_df: pd.DataFrame,
categorical_cols: list[str] | None = None,
) -> tuple[np.ndarray, list[str], set[int]]:
cols = [str(c) for c in X_df.columns]
cat_set = set(categorical_cols or [])
cat_indices: set[int] = set()
mat = np.empty((len(X_df), len(cols)), dtype=np.float64)
for j, col in enumerate(cols):
series = X_df[col]
if col in cat_set or not pd.api.types.is_numeric_dtype(series):
codes, _ = pd.factorize(series, sort=False)
mat[:, j] = codes.astype(np.float64)
cat_indices.add(j)
else:
mat[:, j] = series.to_numpy(dtype=np.float64)
return mat, cols, cat_indices
def compute_tree_mdi_bias_demo(
n_samples: int = 800,
cardinalities: tuple[int, ...] = (2, 20, 200),
seed: int = 42,
) -> dict[str, Any]:
"""Reproduce O(K/n) CART MDI bias where high-cardinality pure noise beats a true binary signal."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
x_signal = rng.integers(0, 2, size=n_samples)
y = 0.9 * x_signal + rng.normal(0.0, 1.0, size=n_samples)
data: dict[str, Any] = {"true_binary_signal": x_signal}
cat_cols = ["true_binary_signal"]
for k in cardinalities:
col_name = f"noise_cat_K{k}"
data[col_name] = rng.integers(0, k, size=n_samples)
cat_cols.append(col_name)
X_df = pd.DataFrame(data)
X_mat, cols, cat_idxs = _prepare_forest_inputs(X_df, categorical_cols=cat_cols)
rf = _FastRandomForest(n_trees=14, max_depth=4, min_samples_leaf=5, categorical_indices=cat_idxs, seed=seed)
rf.fit(X_mat, y)
mdi = rf.mdi_importances_
mdi_dict = {cols[j]: float(mdi[j]) for j in range(len(cols))}
oof_df = oof_permutation_importance(
X_df,
y,
categorical_cols=cat_cols,
n_splits=4,
n_repeats=3,
n_trees=10,
seed=seed,
)
oof_dict = {str(r["feature"]): float(r["oof_perm_mean"]) for _, r in oof_df.iterrows()}
return {
"n_samples": int(n_samples),
"mdi_importances": mdi_dict,
"oof_perm_importances": oof_dict,
"mdi_noise_k200_exceeds_signal": mdi_dict[f"noise_cat_K{cardinalities[-1]}"] > mdi_dict["true_binary_signal"],
"oof_signal_exceeds_k200": oof_dict["true_binary_signal"] > oof_dict[f"noise_cat_K{cardinalities[-1]}"],
}
def _make_group_or_kfold(n: int, n_splits: int, groups: np.ndarray | None, seed: int) -> np.ndarray:
rng = np.random.default_rng(np.random.SeedSequence(seed))
if groups is None:
perm = rng.permutation(n)
folds = np.empty(n, dtype=np.int64)
folds[perm] = np.arange(n) % n_splits
return folds
uniq_g, inv = np.unique(groups, return_inverse=True)
perm_g = rng.permutation(uniq_g.size)
g_fold = np.empty(uniq_g.size, dtype=np.int64)
g_fold[perm_g] = np.arange(uniq_g.size) % n_splits
return g_fold[inv]
def oof_permutation_importance(
X_df: pd.DataFrame,
y: np.ndarray | pd.Series,
categorical_cols: list[str] | None = None,
groups: np.ndarray | pd.Series | None = None,
n_splits: int = 5,
n_repeats: int = 4,
n_trees: int = 12,
seed: int = 42,
) -> pd.DataFrame:
"""Compute held-out OOF permutation MSE increase for every feature."""
X_mat, cols, cat_idxs = _prepare_forest_inputs(X_df, categorical_cols)
y_arr = np.asarray(y, dtype=np.float64)
grp_arr = np.asarray(groups, dtype=str) if groups is not None else None
folds = _make_group_or_kfold(X_mat.shape[0], n_splits, grp_arr, seed)
rng = np.random.default_rng(np.random.SeedSequence(seed + 101))
deltas = np.zeros((n_splits, len(cols)), dtype=np.float64)
for f in range(n_splits):
val_mask = folds == f
tr_mask = ~val_mask
rf = _FastRandomForest(n_trees=n_trees, max_depth=5, min_samples_leaf=5, categorical_indices=cat_idxs, seed=seed + f)
rf.fit(X_mat[tr_mask], y_arr[tr_mask])
X_val = X_mat[val_mask].copy()
y_val = y_arr[val_mask]
base_mse = float(np.mean((y_val - rf.predict(X_val)) ** 2))
for j in range(len(cols)):
orig_col = X_val[:, j].copy()
rep_losses = []
for _ in range(n_repeats):
X_val[:, j] = orig_col[rng.permutation(orig_col.size)]
mse_perm = float(np.mean((y_val - rf.predict(X_val)) ** 2))
rep_losses.append(mse_perm - base_mse)
X_val[:, j] = orig_col
deltas[f, j] = float(np.mean(rep_losses))
rows = []
for j, col in enumerate(cols):
rows.append(
{
"feature": col,
"oof_perm_mean": float(np.mean(deltas[:, j])),
"oof_perm_std": float(np.std(deltas[:, j])),
}
)
return pd.DataFrame(rows).sort_values("oof_perm_mean", ascending=False).reset_index(drop=True)
def collinearity_cluster_permutation(
X_df: pd.DataFrame,
y: np.ndarray | pd.Series,
corr_threshold: float = 0.80,
n_splits: int = 4,
n_repeats: int = 3,
seed: int = 42,
) -> dict[str, Any]:
"""Cluster collinear features via Spearman |rho| >= threshold and run joint cluster OOF permutation."""
cols = [str(c) for c in X_df.columns]
p = len(cols)
X_mat = X_df.to_numpy(dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
# Spearman correlation matrix
ranks = np.column_stack([_average_ranks(X_mat[:, j]) for j in range(p)])
ranks_c = ranks - np.mean(ranks, axis=0)
norms = np.sqrt(np.sum(ranks_c * ranks_c, axis=0))
norms = np.where(norms < 1e-12, 1.0, norms)
corr_mat = (ranks_c.T @ ranks_c) / np.outer(norms, norms)
# Connected components under |rho_S| >= corr_threshold
visited = [False] * p
clusters: list[list[int]] = []
for i in range(p):
if visited[i]:
continue
stack = [i]
visited[i] = True
comp: list[int] = []
while stack:
u = stack.pop()
comp.append(u)
for v in range(p):
if not visited[v] and abs(float(corr_mat[u, v])) >= corr_threshold:
visited[v] = True
stack.append(v)
clusters.append(sorted(comp))
single_df = oof_permutation_importance(X_df, y_arr, n_splits=n_splits, n_repeats=n_repeats, n_trees=10, seed=seed)
single_map = {str(r["feature"]): float(r["oof_perm_mean"]) for _, r in single_df.iterrows()}
folds = _make_group_or_kfold(X_mat.shape[0], n_splits, None, seed)
rng = np.random.default_rng(np.random.SeedSequence(seed + 202))
cluster_rows = []
for cid, idxs in enumerate(clusters):
fold_deltas = []
for f in range(n_splits):
val_mask = folds == f
tr_mask = ~val_mask
rf = _FastRandomForest(n_trees=10, max_depth=5, min_samples_leaf=5, seed=seed + f)
rf.fit(X_mat[tr_mask], y_arr[tr_mask])
X_val = X_mat[val_mask].copy()
y_val = y_arr[val_mask]
base_mse = float(np.mean((y_val - rf.predict(X_val)) ** 2))
orig_block = X_val[:, idxs].copy()
rep = []
for _ in range(n_repeats):
perm = rng.permutation(X_val.shape[0])
X_val[:, idxs] = orig_block[perm]
rep.append(float(np.mean((y_val - rf.predict(X_val)) ** 2)) - base_mse)
X_val[:, idxs] = orig_block
fold_deltas.append(float(np.mean(rep)))
feat_names = [cols[j] for j in idxs]
cluster_rows.append(
{
"cluster_id": cid,
"features": feat_names,
"cluster_oof_perm": float(np.mean(fold_deltas)),
"max_single_oof_perm": max(single_map[fn] for fn in feat_names),
}
)
return {
"corr_threshold": float(corr_threshold),
"single_importances": single_map,
"clusters": cluster_rows,
}
def null_importance_pimp(
X_df: pd.DataFrame,
y: np.ndarray | pd.Series,
categorical_cols: list[str] | None = None,
n_permutations: int = 24,
q_fdr: float = 0.05,
n_trees: int = 10,
seed: int = 42,
) -> pd.DataFrame:
"""Altmann et al. (2010) Null-Importance (PIMP) permutation test with Phipson-Smyth p-values and BH-FDR."""
X_mat, cols, cat_idxs = _prepare_forest_inputs(X_df, categorical_cols)
y_arr = np.asarray(y, dtype=np.float64)
rf_obs = _FastRandomForest(n_trees=n_trees, max_depth=4, min_samples_leaf=5, categorical_indices=cat_idxs, seed=seed)
rf_obs.fit(X_mat, y_arr)
obs_imp = rf_obs.mdi_importances_.copy()
rng = np.random.default_rng(np.random.SeedSequence(seed + 303))
null_mat = np.empty((n_permutations, len(cols)), dtype=np.float64)
for b in range(n_permutations):
y_perm = y_arr[rng.permutation(y_arr.size)]
rf_null = _FastRandomForest(n_trees=n_trees, max_depth=4, min_samples_leaf=5, categorical_indices=cat_idxs, seed=seed + 1000 + b)
rf_null.fit(X_mat, y_perm)
null_mat[b, :] = rf_null.mdi_importances_
p_vals = np.empty(len(cols), dtype=np.float64)
z_scores = np.empty(len(cols), dtype=np.float64)
null_means = np.mean(null_mat, axis=0)
null_stds = np.std(null_mat, axis=0)
for j in range(len(cols)):
ge_count = int(np.sum(null_mat[:, j] >= obs_imp[j]))
p_vals[j] = (1.0 + ge_count) / float(n_permutations + 1)
z_scores[j] = (obs_imp[j] - null_means[j]) / max(1e-9, float(null_stds[j]))
bh = benjamini_hochberg(p_vals, q=q_fdr)
rows = []
for j, col in enumerate(cols):
rows.append(
{
"feature": col,
"observed_mdi": float(obs_imp[j]),
"null_mean": float(null_means[j]),
"pimp_z": float(z_scores[j]),
"p_value": float(p_vals[j]),
"bh_q_value": float(bh["adjusted_q"][j]),
"selected_fdr": bool(bh["rejected"][j]),
}
)
return pd.DataFrame(rows).sort_values("pimp_z", ascending=False).reset_index(drop=True)
def boruta_shadow_selection(
X_df: pd.DataFrame,
y: np.ndarray | pd.Series,
n_runs: int = 24,
alpha: float = 0.05,
n_trees: int = 12,
seed: int = 42,
) -> pd.DataFrame:
"""Kursa & Rudnicki (2010) Boruta all-relevant shadow-feature selection with OOB Z-scores and binomial tests."""
X_mat, cols, cat_idxs = _prepare_forest_inputs(X_df)
y_arr = np.asarray(y, dtype=np.float64)
n, p = X_mat.shape
n_shadows = max(5, p)
rng = np.random.default_rng(np.random.SeedSequence(seed + 404))
hits = np.zeros(p, dtype=np.int64)
mean_z = np.zeros(p, dtype=np.float64)
mzsa_history: list[float] = []
for r in range(n_runs):
shadow_cols = [X_mat[rng.permutation(n), j % p] for j in range(n_shadows)]
shadow = np.column_stack(shadow_cols)
aug = np.hstack([X_mat, shadow])
aug_cat = set(cat_idxs) | {p + s_idx for s_idx in range(n_shadows) if (s_idx % p) in cat_idxs}
total_p = p + n_shadows
max_feat = max(1, math.ceil(0.75 * total_p))
oob_deltas = np.zeros((n_trees, total_p), dtype=np.float64)
for t in range(n_trees):
boot = rng.integers(0, n, size=n)
oob_mask = np.ones(n, dtype=bool)
oob_mask[boot] = False
if np.sum(oob_mask) < 10:
oob_mask = np.ones(n, dtype=bool)
tree = _FastCARTRegressor(
max_depth=5,
min_samples_leaf=5,
max_features=max_feat,
categorical_indices=aug_cat,
seed=int(rng.integers(0, 2**31 - 1)),
)
tree.fit(aug[boot], y_arr[boot])
X_oob = aug[oob_mask].copy()
y_oob = y_arr[oob_mask]
base_mse = float(np.mean((y_oob - tree.predict(X_oob)) ** 2))
for j in range(total_p):
orig = X_oob[:, j].copy()
X_oob[:, j] = orig[rng.permutation(orig.size)]
oob_deltas[t, j] = float(np.mean((y_oob - tree.predict(X_oob)) ** 2)) - base_mse
X_oob[:, j] = orig
mu = np.mean(oob_deltas, axis=0)
sd = np.std(oob_deltas, axis=0)
z_scores = np.where(sd > 1e-12, mu / sd, 0.0)
real_z = z_scores[:p]
shadow_z = z_scores[p:]
mzsa = float(np.max(shadow_z))
mzsa_history.append(mzsa)
hits += (real_z > mzsa).astype(np.int64)
mean_z += real_z
alpha_adj = alpha / float(max(1, p))
rows = []
for j, col in enumerate(cols):
h_j = int(hits[j])
p_up = binomial_upper_tail(h_j, n_runs, 0.5)
p_dn = binomial_lower_tail(h_j, n_runs, 0.5)
if p_up < alpha_adj:
decision = "CONFIRMED"
elif p_dn < alpha_adj:
decision = "REJECTED"
else:
decision = "TENTATIVE"
rows.append(
{
"feature": col,
"hits": h_j,
"n_runs": n_runs,
"mean_z": float(mean_z[j] / float(n_runs)),
"avg_mzsa": float(np.mean(mzsa_history)),
"p_confirm": p_up,
"p_reject": p_dn,
"decision": decision,
}
)
return pd.DataFrame(rows).sort_values("hits", ascending=False).reset_index(drop=True)
def verify_llm_candidate_features_gate(
X_base: pd.DataFrame,
candidates: pd.DataFrame,
y: np.ndarray | pd.Series,
n_outer: int = 4,
n_perm: int = 89,
q_fdr: float = 0.05,
seed: int = 42,
) -> dict[str, Any]:
"""4-Stage Anti-Overfit Verification Gate filtering LLM-proposed features via Nested OOF CV + PIMP BH-FDR."""
y_arr = np.asarray(y, dtype=np.float64)
cand_cols = [str(c) for c in candidates.columns]
combined = pd.concat([X_base.reset_index(drop=True), candidates.reset_index(drop=True)], axis=1)
pimp_df = null_importance_pimp(combined, y_arr, n_permutations=n_perm, q_fdr=q_fdr, seed=seed)
pimp_map = {str(r["feature"]): r.to_dict() for _, r in pimp_df.iterrows()}
cand_pvals = [float(pimp_map[c]["p_value"]) for c in cand_cols]
cand_bh = benjamini_hochberg(cand_pvals, q=q_fdr)
cand_q_map = {c: (float(cand_bh["adjusted_q"][i]), bool(cand_bh["rejected"][i])) for i, c in enumerate(cand_cols)}
# Outer CV verification of each candidate vs base-only MSE
folds = _make_group_or_kfold(len(combined), n_outer, None, seed)
X_base_mat = X_base.to_numpy(dtype=np.float64)
base_mses = []
for f in range(n_outer):
val = folds == f
tr = ~val
rf = _FastRandomForest(n_trees=10, max_depth=4, min_samples_leaf=6, seed=seed + f)
rf.fit(X_base_mat[tr], y_arr[tr])
base_mses.append(float(np.mean((y_arr[val] - rf.predict(X_base_mat[val])) ** 2)))
accepted: list[str] = []
rejected: list[str] = []
reports: list[dict[str, Any]] = []
for cname in cand_cols:
X_aug = np.column_stack([X_base_mat, candidates[cname].to_numpy(dtype=np.float64)])
fold_gains = []
for f in range(n_outer):
val = folds == f
tr = ~val
rf = _FastRandomForest(n_trees=10, max_depth=4, min_samples_leaf=6, seed=seed + f)
rf.fit(X_aug[tr], y_arr[tr])
mse_aug = float(np.mean((y_arr[val] - rf.predict(X_aug[val])) ** 2))
fold_gains.append(base_mses[f] - mse_aug)
mean_gain = float(np.mean(fold_gains))
se_gain = float(np.std(fold_gains, ddof=1) / math.sqrt(max(1, n_outer))) if n_outer > 1 else 0.0
p_info = pimp_map[cname]
cand_q, cand_sel = cand_q_map[cname]
passes = bool(cand_sel and mean_gain > se_gain and mean_gain > 0.0)
if passes:
accepted.append(cname)
else:
rejected.append(cname)
reports.append(
{
"candidate": cname,
"mean_oof_mse_gain": mean_gain,
"se_oof_mse_gain": se_gain,
"pimp_p_value": float(p_info["p_value"]),
"bh_q_value": cand_q,
"accepted": passes,
}
)
return {"accepted": accepted, "rejected": rejected, "reports": reports}
"""Composable ColumnTransformerDAG, FeaturePipeline, HMAC-SHA256 Signed JSON State-Dict, and Full Lab 08 Benchmarks."""
from __future__ import annotations
import hashlib
import hmac
import json
import math
import time
from pathlib import Path
from typing import Any, Literal
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from feature_eng_lab.selection_and_metrics import (
boruta_shadow_selection,
chi2_independence_and_cramers_v,
collinearity_cluster_permutation,
compute_discrete_mi,
compute_ksg_mi,
compute_tree_mdi_bias_demo,
null_importance_pimp,
pearson_and_spearman,
verify_llm_candidate_features_gate,
)
from feature_eng_lab.transforms_and_woe import (
BoxCoxTransformer,
CausalRollingFeatureBuilder,
CyclicalTimeEncoder,
FoldPCAExtractor,
MissingnessAndMadClipper,
MonotonicWoEEncoder,
OnlineSlidingWindowState,
OOFJamesSteinEncoder,
PeriodicPLREncoder,
RankGaussTransformer,
ScaleLevel,
SignedFeatureHasher,
YeoJohnsonTransformer,
audit_stevens_scale_violations,
sample_skewness,
)
TransformKind = Literal[
"mad_clip_scale",
"boxcox_scale",
"yeojohnson_scale",
"rankgauss",
"onehot",
"signed_hash",
"oof_target",
"monotonic_woe",
"cyclical",
"plr",
"pca",
]
class ColumnBranchSpec(BaseModel):
"""Strict typed contract binding column subset, Stevens scale, and transform operator."""
model_config = ConfigDict(frozen=True, extra="forbid")
name: str = Field(min_length=1)
columns: tuple[str, ...] = Field(min_length=1)
scale: ScaleLevel
transform_kind: TransformKind
params: dict[str, Any] = Field(default_factory=dict)
class PipelineConfig(BaseModel):
"""Frozen configuration schema for a composable leakage-free FeaturePipeline."""
model_config = ConfigDict(frozen=True, extra="forbid")
name: str = Field(default="ch08_feature_pipeline", min_length=1)
branches: tuple[ColumnBranchSpec, ...] = Field(min_length=1)
l2_alpha: float = Field(default=1.0, ge=0.0)
schema_version: str = Field(default="1.0.0")
class SignedStateEnvelope(BaseModel):
"""Tamper-evident JSON State-Dict envelope replacing unsafe pickle artifacts (CWE-502)."""
model_config = ConfigDict(frozen=True, extra="forbid")
schema_version: str
feature_names_in: tuple[str, ...]
state_payload: dict[str, Any]
payload_sha256: str
hmac_sha256: str
def roc_auc_binary(y_true: np.ndarray, y_score: np.ndarray) -> float:
"""Compute exact Mann-Whitney ROC-AUC in O(n log n) without sklearn."""
y = np.asarray(y_true, dtype=np.int64)
s = np.asarray(y_score, dtype=np.float64)
pos = y == 1
neg = y == 0
n_pos = int(np.sum(pos))
n_neg = int(np.sum(neg))
if n_pos == 0 or n_neg == 0:
return 0.5
order = np.argsort(s, kind="mergesort")
sorted_s = s[order]
n = s.size
ranks = np.empty(n, dtype=np.float64)
i = 0
while i < n:
j = i + 1
while j < n and sorted_s[j] == sorted_s[i]:
j += 1
avg_r = 0.5 * (i + 1 + j)
ranks[order[i:j]] = avg_r
i = j
rank_sum_pos = float(np.sum(ranks[pos]))
u_stat = rank_sum_pos - (n_pos * (n_pos + 1)) / 2.0
return float(u_stat / float(n_pos * n_neg))
def _stable_sigmoid(z: np.ndarray | float) -> np.ndarray | float:
if np.isscalar(z):
val = float(z)
if val >= 0.0:
ez = math.exp(-min(val, 60.0))
return 1.0 / (1.0 + ez)
ez = math.exp(max(val, -60.0))
return ez / (1.0 + ez)
arr = np.asarray(z, dtype=np.float64)
out = np.empty_like(arr, dtype=np.float64)
pos = arr >= 0.0
out[pos] = 1.0 / (1.0 + np.exp(-np.clip(arr[pos], 0.0, 60.0)))
ez_neg = np.exp(np.clip(arr[~pos], -60.0, 0.0))
out[~pos] = ez_neg / (1.0 + ez_neg)
return out
def _fit_l2_logistic_irls(X: np.ndarray, y: np.ndarray, l2_alpha: float = 1.0, max_iter: int = 25) -> tuple[float, np.ndarray]:
"""Fit L2-penalized logistic regression via damped IRLS without penalizing the intercept."""
n, d = X.shape
X_aug = np.hstack([np.ones((n, 1), dtype=np.float64), X])
beta = np.zeros(d + 1, dtype=np.float64)
reg = np.zeros(d + 1, dtype=np.float64)
reg[1:] = float(l2_alpha)
reg_mat = np.diag(reg)
y_arr = np.asarray(y, dtype=np.float64)
for _ in range(max_iter):
eta = X_aug @ beta
p = np.asarray(_stable_sigmoid(eta), dtype=np.float64)
w = np.maximum(p * (1.0 - p), 1e-8)
grad = X_aug.T @ (p - y_arr) + reg * beta
hess = (X_aug * w[:, None]).T @ X_aug + reg_mat + 1e-8 * np.eye(d + 1)
step = np.linalg.solve(hess, grad)
beta -= step
if float(np.linalg.norm(step, ord=2)) < 1e-7:
break
return float(beta[0]), beta[1:].copy()
def _canonical_json_bytes(obj: Any) -> bytes:
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")
class ColumnTransformerDAG:
"""Name-indexed composable feature transformer with strict train-fit isolation and <1e-12 batch/row parity."""
def __init__(self, branches: tuple[ColumnBranchSpec, ...] | list[ColumnBranchSpec]) -> None:
self.branches: tuple[ColumnBranchSpec, ...] = tuple(branches)
if not self.branches:
raise ValueError("ColumnTransformerDAG requires at least one branch.")
self._branch_states: dict[str, dict[str, Any]] = {}
self.feature_names_in_: list[str] = []
self.feature_names_out_: list[str] = []
self._fitted = False
@staticmethod
def _validate_stevens_compatibility(spec: ColumnBranchSpec) -> None:
forbidden = {
(ScaleLevel.NOMINAL, "boxcox_scale"),
(ScaleLevel.NOMINAL, "yeojohnson_scale"),
(ScaleLevel.NOMINAL, "mad_clip_scale"),
(ScaleLevel.INTERVAL, "boxcox_scale"),
}
if (spec.scale, spec.transform_kind) in forbidden:
raise ValueError(
f"Stevens Scale Contract Violation on branch '{spec.name}': "
f"{spec.transform_kind} is forbidden for {spec.scale.value} scale."
)
def _fit_one_branch(
self,
spec: ColumnBranchSpec,
df: pd.DataFrame,
y: np.ndarray | None,
groups: np.ndarray | None,
for_fit_transform: bool,
) -> tuple[dict[str, Any], np.ndarray | None]:
self._validate_stevens_compatibility(spec)
cols = list(spec.columns)
sub_df = df[cols]
kind = spec.transform_kind
params = spec.params
if kind == "mad_clip_scale":
clipper = MissingnessAndMadClipper(
clip_z=float(params.get("clip_z", 3.5)),
add_missing_flags=bool(params.get("add_missing_flags", True)),
)
clipped = clipper.fit_transform(sub_df, cols)
n_num = len(cols)
means = np.mean(clipped[:, :n_num], axis=0)
stds = np.std(clipped[:, :n_num], axis=0)
stds = np.where(stds < 1e-12, 1.0, stds)
state = {
"kind": kind,
"columns": cols,
"clipper": clipper.to_state_dict(),
"means": [float(v) for v in means],
"stds": [float(v) for v in stds],
"out_names": clipper.get_feature_names_out(),
}
if for_fit_transform:
clipped[:, :n_num] = (clipped[:, :n_num] - means) / stds
return state, clipped
return state, None
if kind == "boxcox_scale":
bc = BoxCoxTransformer(use_jacobian=True, standardize=True)
out = bc.fit_transform(sub_df, cols)
state = {
"kind": kind,
"columns": cols,
"transformer": bc.to_state_dict(),
"out_names": [f"{c}_boxcox" for c in cols],
}
return state, (out if for_fit_transform else None)
if kind == "yeojohnson_scale":
yj = YeoJohnsonTransformer(standardize=True)
out = yj.fit_transform(sub_df, cols)
state = {
"kind": kind,
"columns": cols,
"transformer": yj.to_state_dict(),
"out_names": [f"{c}_yj" for c in cols],
}
return state, (out if for_fit_transform else None)
if kind == "rankgauss":
rg = RankGaussTransformer(n_quantiles=int(params.get("n_quantiles", 256)))
out = rg.fit_transform(sub_df, cols)
state = {
"kind": kind,
"columns": cols,
"transformer": rg.to_state_dict(),
"out_names": [f"{c}_rg" for c in cols],
}
return state, (out if for_fit_transform else None)
if kind == "onehot":
min_freq = int(params.get("min_freq", 1))
vocab: dict[str, list[str]] = {}
out_names: list[str] = []
blocks: list[np.ndarray] = []
for c in cols:
s = sub_df[c].astype(str)
vc = s.value_counts()
cats = sorted(str(k) for k, cnt in vc.items() if int(cnt) >= min_freq)
vocab[c] = cats
out_names.extend(f"{c}=={cat}" for cat in cats)
if for_fit_transform:
arr = s.to_numpy()
blk = np.zeros((len(s), len(cats)), dtype=np.float64)
for idx_cat, cat in enumerate(cats):
blk[:, idx_cat] = (arr == cat).astype(np.float64)
blocks.append(blk)
state = {"kind": kind, "columns": cols, "vocab": vocab, "out_names": out_names}
mat = np.hstack(blocks) if (for_fit_transform and blocks) else None
return state, mat
if kind == "signed_hash":
n_buckets = int(params.get("n_buckets", 32))
signed = bool(params.get("signed", True))
seed = int(params.get("seed", 42))
hasher = SignedFeatureHasher(n_buckets=n_buckets, signed=signed, seed=seed)
out_names = [f"{spec.name}_h{b}" for b in range(n_buckets)]
state = {
"kind": kind,
"columns": cols,
"hasher": hasher.to_state_dict(),
"out_names": out_names,
}
if for_fit_transform:
mat = np.zeros((len(sub_df), n_buckets), dtype=np.float64)
for c in cols:
mat += hasher.transform_tokens(sub_df[c], prefix=c)
return state, mat
return state, None
if kind == "oof_target":
if y is None:
raise ValueError("oof_target branch requires target y during fit.")
smooth_m = params.get("smoothing_m", None)
n_splits = int(params.get("n_splits", 5))
seed = int(params.get("seed", 42))
encoders: dict[str, dict[str, Any]] = {}
blocks = []
for c in cols:
enc = OOFJamesSteinEncoder(smoothing_m=smooth_m, n_splits=n_splits, seed=seed)
if for_fit_transform:
blk = enc.fit_transform(sub_df[c], y, groups=groups)[:, None]
blocks.append(blk)
else:
enc.fit(sub_df[c], y)
encoders[c] = enc.to_state_dict()
state = {
"kind": kind,
"columns": cols,
"encoders": encoders,
"out_names": [f"{c}_oof_te" for c in cols],
}
mat = np.hstack(blocks) if (for_fit_transform and blocks) else None
return state, mat
if kind == "monotonic_woe":
if y is None:
raise ValueError("monotonic_woe branch requires binary target y during fit.")
n_bins = int(params.get("n_bins", 8))
lap_alpha = float(params.get("laplace_alpha", 0.5))
encoders = {}
blocks = []
for c in cols:
woe = MonotonicWoEEncoder(n_bins=n_bins, laplace_alpha=lap_alpha, enforce_monotonic=True)
woe.fit(sub_df[c], y)
encoders[c] = woe.to_state_dict()
if for_fit_transform:
blocks.append(woe.transform(sub_df[c])[:, None])
state = {
"kind": kind,
"columns": cols,
"encoders": encoders,
"out_names": [f"{c}_woe" for c in cols],
}
mat = np.hstack(blocks) if (for_fit_transform and blocks) else None
return state, mat
if kind == "cyclical":
period = float(params.get("period", 24.0))
cyc = CyclicalTimeEncoder(period=period)
out_names = []
blocks = []
for c in cols:
out_names.extend([f"{c}_sin", f"{c}_cos"])
if for_fit_transform:
blocks.append(cyc.transform(sub_df[c]))
state = {"kind": kind, "columns": cols, "period": period, "out_names": out_names}
mat = np.hstack(blocks) if (for_fit_transform and blocks) else None
return state, mat
if kind == "plr":
plr = PeriodicPLREncoder(
n_frequencies=int(params.get("n_frequencies", 8)),
freq_std=float(params.get("freq_std", 1.5)),
embed_dim=int(params.get("embed_dim", 8)),
seed=int(params.get("seed", 42)),
)
out = plr.fit_transform(sub_df, cols) if for_fit_transform else None
if not for_fit_transform:
plr.fit(sub_df, cols)
out_names = [f"{c}_plr_{i}" for c in cols for i in range(plr.embed_dim)]
state = {"kind": kind, "columns": cols, "transformer": plr.to_state_dict(), "out_names": out_names}
return state, out
if kind == "pca":
pca = FoldPCAExtractor(n_components=int(params.get("n_components", 2)), standardize=True)
out = pca.fit_transform(sub_df, cols) if for_fit_transform else None
if not for_fit_transform:
pca.fit(sub_df, cols)
k_out = len(pca.components_)
out_names = [f"{spec.name}_pc{i}" for i in range(k_out)]
state = {"kind": kind, "columns": cols, "transformer": pca.to_state_dict(), "out_names": out_names}
return state, out
raise ValueError(f"Unsupported transform_kind: {kind}")
def _transform_branch_df(self, state: dict[str, Any], df: pd.DataFrame) -> np.ndarray:
cols = state["columns"]
kind = state["kind"]
sub_df = df[cols]
if kind == "mad_clip_scale":
clipper = MissingnessAndMadClipper.from_state_dict(state["clipper"])
clipped = clipper.transform(sub_df)
n_num = len(cols)
means = np.asarray(state["means"], dtype=np.float64)
stds = np.asarray(state["stds"], dtype=np.float64)
clipped[:, :n_num] = (clipped[:, :n_num] - means) / stds
return clipped
if kind == "boxcox_scale":
return BoxCoxTransformer.from_state_dict(state["transformer"]).transform(sub_df)
if kind == "yeojohnson_scale":
return YeoJohnsonTransformer.from_state_dict(state["transformer"]).transform(sub_df)
if kind == "rankgauss":
return RankGaussTransformer.from_state_dict(state["transformer"]).transform(sub_df)
if kind == "onehot":
vocab = state["vocab"]
blocks = []
for c in cols:
cats = vocab[c]
arr = sub_df[c].astype(str).to_numpy()
blk = np.zeros((len(arr), len(cats)), dtype=np.float64)
for idx_cat, cat in enumerate(cats):
blk[:, idx_cat] = (arr == cat).astype(np.float64)
blocks.append(blk)
return np.hstack(blocks) if blocks else np.empty((len(df), 0), dtype=np.float64)
if kind == "signed_hash":
hasher = SignedFeatureHasher.from_state_dict(state["hasher"])
mat = np.zeros((len(df), hasher.n_buckets), dtype=np.float64)
for c in cols:
mat += hasher.transform_tokens(sub_df[c], prefix=c)
return mat
if kind == "oof_target":
blocks = []
for c in cols:
enc = OOFJamesSteinEncoder.from_state_dict(state["encoders"][c])
blocks.append(enc.transform(sub_df[c])[:, None])
return np.hstack(blocks)
if kind == "monotonic_woe":
blocks = []
for c in cols:
woe = MonotonicWoEEncoder.from_state_dict(state["encoders"][c])
blocks.append(woe.transform(sub_df[c])[:, None])
return np.hstack(blocks)
if kind == "cyclical":
cyc = CyclicalTimeEncoder(period=float(state["period"]))
blocks = [cyc.transform(sub_df[c]) for c in cols]
return np.hstack(blocks)
if kind == "plr":
return PeriodicPLREncoder.from_state_dict(state["transformer"]).transform(sub_df)
if kind == "pca":
return FoldPCAExtractor.from_state_dict(state["transformer"]).transform(sub_df)
raise ValueError(f"Unknown branch state kind: {kind}")
def _transform_branch_row(self, state: dict[str, Any], row: dict[str, Any]) -> list[float]:
"""Scalar-path single-row execution guaranteeing <1e-12 parity with batch DataFrame transform."""
cols = state["columns"]
kind = state["kind"]
if kind == "mad_clip_scale":
clip = state["clipper"]
vals: list[float] = []
flags: list[float] = []
for j, c in enumerate(cols):
raw = row.get(c, float("nan"))
v = float(raw) if raw is not None else float("nan")
is_miss = not math.isfinite(v)
if is_miss:
v = float(clip["medians"][j])
v = max(float(clip["lower"][j]), min(float(clip["upper"][j]), v))
vals.append((v - float(state["means"][j])) / float(state["stds"][j]))
if clip["add_missing_flags"]:
flags.append(1.0 if is_miss else 0.0)
return vals + flags
if kind == "boxcox_scale":
st = state["transformer"]
out: list[float] = []
for j, c in enumerate(cols):
v = float(row[c])
if v <= 0.0:
raise ValueError("BoxCoxTransformer received non-positive value at row transform.")
lam = float(st["lambdas"][j])
z = math.log(v) if abs(lam) < 1e-8 else (math.pow(v, lam) - 1.0) / lam
if st["standardize"]:
z = (z - float(st["means"][j])) / float(st["stds"][j])
out.append(z)
return out
if kind == "yeojohnson_scale":
st = state["transformer"]
out = []
for j, c in enumerate(cols):
v = float(row[c])
lam = float(st["lambdas"][j])
if v >= 0.0:
z = math.log1p(v) if abs(lam) < 1e-8 else (math.pow(1.0 + v, lam) - 1.0) / lam
else:
z = -math.log1p(-v) if abs(lam - 2.0) < 1e-8 else -(math.pow(1.0 - v, 2.0 - lam) - 1.0) / (2.0 - lam)
if st["standardize"]:
z = (z - float(st["means"][j])) / float(st["stds"][j])
out.append(z)
return out
if kind == "rankgauss":
st = state["transformer"]
out = []
for j, c in enumerate(cols):
raw = row.get(c, float("nan"))
v = float(raw) if raw is not None else float("nan")
qx = st["quantiles_x"][j]
zy = st["normal_y"][j]
if not math.isfinite(v):
v = float(qx[len(qx) // 2])
out.append(float(np.interp(v, qx, zy)))
return out
if kind == "onehot":
vocab = state["vocab"]
out = []
for c in cols:
val = str(row[c])
for cat in vocab[c]:
out.append(1.0 if val == cat else 0.0)
return out
if kind == "signed_hash":
hasher = SignedFeatureHasher.from_state_dict(state["hasher"])
vec = [0.0] * hasher.n_buckets
for c in cols:
b, s = hasher._hash_token(f"{c}={row[c]!s}")
vec[b] += s
return vec
if kind == "oof_target":
out = []
for c in cols:
enc = state["encoders"][c]
out.append(float(enc["mapping"].get(str(row[c]), enc["global_prior"])))
return out
if kind == "monotonic_woe":
out = []
for c in cols:
woe = MonotonicWoEEncoder.from_state_dict(state["encoders"][c])
raw = row.get(c, float("nan"))
v = float(raw) if raw is not None else float("nan")
lbl = woe._assign_bin(v)
out.append(float(woe.woe_map_[lbl]))
return out
if kind == "cyclical":
period = float(state["period"])
out = []
for c in cols:
th = (2.0 * math.pi * float(row[c])) / period
out.extend([math.sin(th), math.cos(th)])
return out
if kind == "plr":
st = state["transformer"]
out = []
for j, c in enumerate(cols):
z = (float(row[c]) - float(st["means"][j])) / float(st["stds"][j])
freqs = st["freqs"][j]
phase = [2.0 * math.pi * z * float(fr) for fr in freqs]
v_j = [math.sin(ph) for ph in phase] + [math.cos(ph) for ph in phase]
W_j = st["weights"][j]
b_j = st["biases"][j]
for out_k in range(len(b_j)):
acc = float(b_j[out_k])
for in_i, v_val in enumerate(v_j):
acc += v_val * float(W_j[in_i][out_k])
out.append(max(0.0, acc))
return out
if kind == "pca":
st = state["transformer"]
z = [(float(row[c]) - float(st["means"][j])) / float(st["stds"][j]) for j, c in enumerate(cols)]
out = []
for comp in st["components"]:
out.append(sum(z_val * float(w_val) for z_val, w_val in zip(z, comp)))
return out
raise ValueError(f"Unknown row branch kind: {kind}")
def fit(
self,
df: pd.DataFrame,
y: np.ndarray | pd.Series | None = None,
groups: np.ndarray | pd.Series | None = None,
) -> ColumnTransformerDAG:
y_arr = np.asarray(y, dtype=np.float64) if y is not None else None
g_arr = np.asarray(groups, dtype=str) if groups is not None else None
seen_cols: list[str] = []
self._branch_states.clear()
self.feature_names_out_.clear()
for spec in self.branches:
for col in spec.columns:
if col not in df.columns:
raise KeyError(f"Missing required column '{col}' for branch '{spec.name}'.")
if col not in seen_cols:
seen_cols.append(col)
state, _ = self._fit_one_branch(spec, df, y_arr, g_arr, for_fit_transform=False)
self._branch_states[spec.name] = state
self.feature_names_out_.extend(state["out_names"])
self.feature_names_in_ = seen_cols
self._fitted = True
return self
def fit_transform(
self,
df: pd.DataFrame,
y: np.ndarray | pd.Series | None = None,
groups: np.ndarray | pd.Series | None = None,
) -> np.ndarray:
y_arr = np.asarray(y, dtype=np.float64) if y is not None else None
g_arr = np.asarray(groups, dtype=str) if groups is not None else None
seen_cols: list[str] = []
self._branch_states.clear()
self.feature_names_out_.clear()
blocks: list[np.ndarray] = []
for spec in self.branches:
for col in spec.columns:
if col not in df.columns:
raise KeyError(f"Missing required column '{col}' for branch '{spec.name}'.")
if col not in seen_cols:
seen_cols.append(col)
state, mat = self._fit_one_branch(spec, df, y_arr, g_arr, for_fit_transform=True)
assert mat is not None
self._branch_states[spec.name] = state
self.feature_names_out_.extend(state["out_names"])
blocks.append(mat)
self.feature_names_in_ = seen_cols
self._fitted = True
return np.hstack(blocks) if blocks else np.empty((len(df), 0), dtype=np.float64)
def transform(self, df: pd.DataFrame) -> np.ndarray:
if not self._fitted:
raise RuntimeError("ColumnTransformerDAG must be fitted before transform.")
blocks = [self._transform_branch_df(self._branch_states[spec.name], df) for spec in self.branches]
return np.hstack(blocks) if blocks else np.empty((len(df), 0), dtype=np.float64)
def transform_row(self, row: dict[str, Any]) -> np.ndarray:
if not self._fitted:
raise RuntimeError("ColumnTransformerDAG must be fitted before transform_row.")
vec: list[float] = []
for spec in self.branches:
vec.extend(self._transform_branch_row(self._branch_states[spec.name], row))
return np.asarray(vec, dtype=np.float64)
def to_state_dict(self) -> dict[str, Any]:
return {
"branches": [b.model_dump(mode="json") for b in self.branches],
"branch_states": self._branch_states,
"feature_names_in": self.feature_names_in_,
"feature_names_out": self.feature_names_out_,
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> ColumnTransformerDAG:
branches = tuple(ColumnBranchSpec(**b) for b in state["branches"])
obj = cls(branches=branches)
obj._branch_states = dict(state["branch_states"])
obj.feature_names_in_ = list(state["feature_names_in"])
obj.feature_names_out_ = list(state["feature_names_out"])
obj._fitted = True
return obj
class FeaturePipeline:
"""Composable leakage-free FeaturePipeline chaining ColumnTransformerDAG with L2 Logistic Estimator."""
def __init__(self, config: PipelineConfig) -> None:
self.config = config
self.transformer = ColumnTransformerDAG(config.branches)
self.intercept_: float = 0.0
self.coef_: np.ndarray = np.array([], dtype=np.float64)
self._fitted = False
def fit(
self,
df: pd.DataFrame,
y: np.ndarray | pd.Series,
groups: np.ndarray | pd.Series | None = None,
) -> FeaturePipeline:
y_arr = np.asarray(y, dtype=np.float64)
X_mat = self.transformer.fit_transform(df, y_arr, groups=groups)
self.intercept_, coef = _fit_l2_logistic_irls(X_mat, y_arr, l2_alpha=self.config.l2_alpha)
coef.setflags(write=False)
self.coef_ = coef
self._fitted = True
return self
def transform(self, df: pd.DataFrame) -> np.ndarray:
return self.transformer.transform(df)
def predict_proba(self, df: pd.DataFrame) -> np.ndarray:
if not self._fitted:
raise RuntimeError("FeaturePipeline must be fitted before predict_proba.")
X_mat = self.transformer.transform(df)
logits = self.intercept_ + X_mat @ self.coef_
return np.asarray(_stable_sigmoid(logits), dtype=np.float64)
def predict_proba_row(self, row: dict[str, Any]) -> float:
if not self._fitted:
raise RuntimeError("FeaturePipeline must be fitted before predict_proba_row.")
vec = self.transformer.transform_row(row)
logit = self.intercept_ + float(np.dot(vec, self.coef_))
return float(_stable_sigmoid(logit))
def to_state_dict(self) -> dict[str, Any]:
return {
"config": self.config.model_dump(mode="json"),
"transformer": self.transformer.to_state_dict(),
"intercept": self.intercept_,
"coef": [float(v) for v in self.coef_],
}
@classmethod
def from_state_dict(cls, state: dict[str, Any]) -> FeaturePipeline:
cfg = PipelineConfig(**state["config"])
obj = cls(config=cfg)
obj.transformer = ColumnTransformerDAG.from_state_dict(state["transformer"])
obj.intercept_ = float(state["intercept"])
coef = np.asarray(state["coef"], dtype=np.float64)
coef.setflags(write=False)
obj.coef_ = coef
obj._fitted = True
return obj
def save_signed_state(self, path: str | Path, secret_key: str) -> SignedStateEnvelope:
"""Serialize pipeline purely as JSON state-dict signed with SHA-256 and HMAC-SHA256."""
if not self._fitted:
raise RuntimeError("Cannot serialize unfitted FeaturePipeline.")
payload = self.to_state_dict()
canon = _canonical_json_bytes(payload)
p_sha = hashlib.sha256(canon).hexdigest()
mac = hmac.new(secret_key.encode("utf-8"), canon, hashlib.sha256).hexdigest()
envelope = SignedStateEnvelope(
schema_version=self.config.schema_version,
feature_names_in=tuple(self.transformer.feature_names_in_),
state_payload=payload,
payload_sha256=p_sha,
hmac_sha256=mac,
)
out_path = Path(path)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(json.dumps(envelope.model_dump(mode="json"), indent=2).encode("utf-8"))
return envelope
@classmethod
def load_signed_state(cls, path: str | Path, secret_key: str) -> FeaturePipeline:
"""Verify SHA-256 and HMAC-SHA256 before restoring FeaturePipeline (rejects tampered files)."""
raw_data = json.loads(Path(path).read_text(encoding="utf-8"))
envelope = SignedStateEnvelope(**raw_data)
canon = _canonical_json_bytes(envelope.state_payload)
expected_sha = hashlib.sha256(canon).hexdigest()
if not hmac.compare_digest(expected_sha, envelope.payload_sha256):
raise ValueError("SignedStateEnvelope SHA-256 integrity mismatch (payload corrupted or tampered).")
expected_mac = hmac.new(secret_key.encode("utf-8"), canon, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected_mac, envelope.hmac_sha256):
raise ValueError("SignedStateEnvelope HMAC-SHA256 verification failed (unauthorized tampering).")
return cls.from_state_dict(envelope.state_payload)
def audit_presplit_vs_infold_leakage(
n_samples: int = 120,
d_noise: int = 1200,
top_k: int = 15,
n_splits: int = 5,
seed: int = 42,
) -> dict[str, Any]:
"""Reproduce ESL 7.10.2 pre-split filter screening hallucination on pure Gaussian white noise vs inside-fold CV."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
X = rng.normal(0.0, 1.0, size=(n_samples, d_noise))
y = np.array([0] * (n_samples // 2) + [1] * (n_samples - n_samples // 2), dtype=np.int64)
rng.shuffle(y)
# Pre-split leaky top-k selection on full dataset
y_c = y - float(np.mean(y))
X_c = X - np.mean(X, axis=0)
corrs_all = np.abs((X_c.T @ y_c) / np.sqrt(np.sum(X_c**2, axis=0) * float(np.sum(y_c**2)) + 1e-18))
leaky_idx = np.argsort(corrs_all)[-top_k:]
perm = rng.permutation(n_samples)
folds = np.empty(n_samples, dtype=np.int64)
folds[perm] = np.arange(n_samples) % n_splits
oof_leaky = np.empty(n_samples, dtype=np.float64)
oof_clean = np.empty(n_samples, dtype=np.float64)
for f in range(n_splits):
val = folds == f
tr = ~val
# Leaky CV: features already selected using validation labels!
b0_l, w_l = _fit_l2_logistic_irls(X[tr][:, leaky_idx], y[tr], l2_alpha=2.0)
oof_leaky[val] = np.asarray(_stable_sigmoid(b0_l + X[val][:, leaky_idx] @ w_l), dtype=np.float64)
# Leakage-free CV: feature screening strictly inside training fold
y_tr_c = y[tr] - float(np.mean(y[tr]))
X_tr_c = X[tr] - np.mean(X[tr], axis=0)
corrs_tr = np.abs((X_tr_c.T @ y_tr_c) / np.sqrt(np.sum(X_tr_c**2, axis=0) * float(np.sum(y_tr_c**2)) + 1e-18))
clean_idx = np.argsort(corrs_tr)[-top_k:]
b0_c, w_c = _fit_l2_logistic_irls(X[tr][:, clean_idx], y[tr], l2_alpha=2.0)
oof_clean[val] = np.asarray(_stable_sigmoid(b0_c + X[val][:, clean_idx] @ w_c), dtype=np.float64)
return {
"n_samples": int(n_samples),
"d_noise": int(d_noise),
"top_k": int(top_k),
"presplit_leaky_cv_auc": roc_auc_binary(y, oof_leaky),
"infold_clean_cv_auc": roc_auc_binary(y, oof_clean),
"max_global_spurious_corr": float(np.max(corrs_all)),
}
def run_full_ch08_benchmarks(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Execute complete reproducible Stage 5B benchmark suite for Unit T1-P2-U03."""
rng = np.random.default_rng(np.random.SeedSequence(seed))
# 1. Stevens Scales + Box-Cox (Jacobian vs Naive) + Yeo-Johnson + RankGauss
stevens_res = audit_stevens_scale_violations()
n_pow = 400 if quick else 1000
x_pos = np.exp(rng.normal(1.2, 0.95, size=n_pow)) # log-normal (true Box-Cox lambda = 0.0)
bc_jac = BoxCoxTransformer(use_jacobian=True, standardize=True).fit(x_pos)
bc_naive = BoxCoxTransformer(use_jacobian=False, standardize=True).fit(x_pos)
z_bc = bc_jac.transform(x_pos)[:, 0]
x_signed = np.concatenate([rng.normal(-2.5, 1.5, size=n_pow // 4), np.exp(rng.normal(0.8, 1.0, size=(3 * n_pow) // 4))])
yj = YeoJohnsonTransformer(standardize=True).fit(x_signed)
z_yj = yj.transform(x_signed)[:, 0]
rg = RankGaussTransformer(n_quantiles=128).fit(x_pos)
z_rg = rg.transform(x_pos)[:, 0]
power_block = {
"stevens": stevens_res,
"boxcox_skew_raw": sample_skewness(x_pos),
"boxcox_skew_transformed": sample_skewness(z_bc),
"boxcox_lambda_mle": float(bc_jac.lambdas_[0]),
"boxcox_lambda_no_jacobian": float(bc_naive.lambdas_[0]),
"yeojohnson_skew_raw": sample_skewness(x_signed),
"yeojohnson_skew_transformed": sample_skewness(z_yj),
"yeojohnson_lambda_mle": float(yj.lambdas_[0]),
"rankgauss_mean": float(np.mean(z_rg)),
"rankgauss_std": float(np.std(z_rg)),
"rankgauss_skew": sample_skewness(z_rg),
}
# 2. Statistical Selection: Filter Blind Spots (Y=X^2, XOR), Miller-Madow, Chi2/Bergsma V, MDI Trap, PIMP, Cluster, Boruta
n_sel = 420 if quick else 800
x_u = rng.uniform(-2.0, 2.0, size=n_sel)
y_u = x_u**2 + rng.normal(0.0, 0.15, size=n_sel)
corr_u = pearson_and_spearman(x_u, y_u)
ksg_u = compute_ksg_mi(x_u, y_u, k=3, unit="nats")
# Discrete independent high-cardinality (K=30) Miller-Madow check
cat_a = rng.integers(0, 25, size=300)
cat_b = rng.integers(0, 25, size=300)
disc_mi_noise = compute_discrete_mi(cat_a, cat_b, unit="nats")
chi2_noise = chi2_independence_and_cramers_v(cat_a, cat_b)
# Pure XOR check
x_xor1 = rng.choice([-1, 1], size=400)
x_xor2 = rng.choice([-1, 1], size=400)
y_xor = x_xor1 * x_xor2
corr_xor = pearson_and_spearman(x_xor1, y_xor)
# CART MDI high-cardinality noise trap vs OOF Permutation vs Null-Importance PIMP
mdi_demo = compute_tree_mdi_bias_demo(n_samples=600 if quick else 1000, cardinalities=(2, 20, 200), seed=seed)
# Multi-feature benchmark for PIMP, Cluster Permutation & Boruta
n_fs = 360 if quick else 600
f_sig1 = rng.normal(0.0, 1.0, size=n_fs)
f_twin1 = 0.96 * f_sig1 + rng.normal(0.0, 0.25, size=n_fs)
f_sig2 = rng.normal(0.0, 1.0, size=n_fs)
f_noise1 = rng.normal(0.0, 1.0, size=n_fs)
f_noise_cat = rng.integers(0, 150, size=n_fs)
y_fs = 1.8 * f_sig1 + 2.2 * np.sin(1.8 * f_sig2) + rng.normal(0.0, 0.45, size=n_fs)
fs_df = pd.DataFrame(
{
"sig_linear": f_sig1,
"sig_twin": f_twin1,
"sig_nonlinear": f_sig2,
"noise_gaussian": f_noise1,
"noise_cat_150": f_noise_cat,
}
)
pimp_df = null_importance_pimp(
fs_df, y_fs, categorical_cols=["noise_cat_150"], n_permutations=59 if quick else 89, q_fdr=0.05, seed=seed
)
cluster_res = collinearity_cluster_permutation(
fs_df.drop(columns=["noise_cat_150"]), y_fs, corr_threshold=0.80, n_splits=4, seed=seed
)
boruta_df = boruta_shadow_selection(
fs_df.drop(columns=["noise_cat_150"]), y_fs, n_runs=24 if quick else 32, alpha=0.05, seed=seed
)
selection_block = {
"u_shape_pearson_r": corr_u["pearson_r"],
"u_shape_spearman_rho": corr_u["spearman_rho"],
"u_shape_ksg_mi_nats": ksg_u,
"xor_pearson_r": corr_xor["pearson_r"],
"discrete_noise_mi_plugin_nats": disc_mi_noise["mi_plugin"],
"discrete_noise_mi_mm_nats": disc_mi_noise["mi_miller_madow"],
"chi2_noise_cramers_v": chi2_noise["cramers_v"],
"chi2_noise_cramers_v_corrected": chi2_noise["cramers_v_corrected"],
"mdi_bias_demo": mdi_demo,
"pimp_table": pimp_df.to_dict(orient="records"),
"cluster_perm": cluster_res,
"boruta_table": boruta_df.to_dict(orient="records"),
}
# 3. Banking Monotonic WoE / IV + Leakage Canary + CSI Drift
n_bank = 1200 if quick else 3000
util_valid = np.clip(rng.beta(1.5, 3.2, size=n_bank), 0.0, 1.0)
is_miss_b = rng.random(n_bank) < 0.06
util = np.where(is_miss_b, np.nan, util_valid)
logit_pd = -3.5 + 1.55 * np.nan_to_num(util, nan=0.72)
prob_pd = 1.0 / (1.0 + np.exp(-logit_pd))
y_pd = (rng.random(n_bank) < prob_pd).astype(np.int64)
woe_enc = MonotonicWoEEncoder(n_bins=8, laplace_alpha=0.5, enforce_monotonic=True).fit(util, y_pd)
# Leakage variable (post-default proxy)
leak_proxy = y_pd * 10.0 + rng.normal(0.0, 0.3, size=n_bank)
woe_leak = MonotonicWoEEncoder(n_bins=6, laplace_alpha=0.5).fit(leak_proxy, y_pd)
util_oot_shift = np.where(rng.random(500) < 0.08, np.nan, np.clip(rng.beta(2.6, 2.2, size=500), 0.0, 1.0))
csi_oot = woe_enc.compute_csi(util_oot_shift)
woe_block = {
"iv_monotonic": float(woe_enc.iv_),
"is_monotonic": bool(woe_enc.is_monotonic_),
"n_final_bins": len(woe_enc.bin_table_),
"bin_table": woe_enc.bin_table_,
"leak_proxy_iv": float(woe_leak.iv_),
"leak_canary_triggered": bool(woe_leak.is_leakage_canary_),
"csi_shifted_oot": float(csi_oot),
}
# 4. Causal PIT Rolling Windows vs Leaky Global Groupby + O(1) Online Parity
n_ent = 40 if quick else 80
rows_ev: list[dict[str, Any]] = []
tx_counter = 0
for u in range(n_ent):
t_cur = 1000.0
n_tx = 18
for k_step in range(n_tx):
t_cur += float(rng.uniform(180.0, 1100.0))
if u % 5 == 0 and k_step in (7, 8):
# Subtle causal pre-fraud velocity uptick before fraud event at step 9
base_amt = float(rng.uniform(40.0, 68.0))
elif u % 5 == 0 and k_step >= 10:
# Massive post-fraud chargeback/burst spike strictly AFTER t_obs
base_amt = float(rng.uniform(250.0, 520.0))
else:
base_amt = float(rng.uniform(15.0, 52.0))
rows_ev.append(
{
"entity_id": f"u_{u:03d}",
"event_ts": t_cur,
"avail_ts": t_cur,
"tx_id": tx_counter,
"amount": base_amt,
"is_fraud": 1 if (k_step == 9 and u % 5 == 0) else 0,
}
)
tx_counter += 1
ev_df = pd.DataFrame(rows_ev)
split_t = float(ev_df["event_ts"].quantile(0.65))
tr_ev = ev_df[ev_df["event_ts"] <= split_t].copy()
oot_ev = ev_df[ev_df["event_ts"] > split_t].copy()
pit_builder = CausalRollingFeatureBuilder(window_seconds=7200.0, lag_seconds=0.0, ewma_half_life=3600.0)
tr_causal = pit_builder.transform_batch(tr_ev)
oot_causal = pit_builder.transform_batch(oot_ev)
tr_leaky = pit_builder.transform_leaky_naive(tr_ev)
# In live scoring, future rows do not exist -> naive single-tx score drops to current amount
auc_leaky_train_illusion = roc_auc_binary(tr_leaky["is_fraud"].to_numpy(), tr_leaky["leaky_entity_mean"].to_numpy())
auc_causal_honest = roc_auc_binary(tr_causal["is_fraud"].to_numpy(), tr_causal["pit_tx_mean"].to_numpy())
# Online O(1) sliding window parity check & latency
online = OnlineSlidingWindowState(window_seconds=7200.0, lag_seconds=0.0, ewma_half_life=3600.0)
ev_sorted = ev_df.sort_values(["entity_id", "event_ts", "tx_id"], kind="mergesort").reset_index(drop=True)
batch_all = pit_builder.transform_batch(ev_sorted)
online_means = np.empty(len(ev_sorted), dtype=np.float64)
t_lat: list[float] = []
for idx_r, row in ev_sorted.iterrows():
t0 = time.perf_counter()
st_feats = online.score_before_ingest(row["entity_id"], float(row["event_ts"]))
online_means[idx_r] = st_feats["pit_tx_mean"]
online.ingest(row["entity_id"], float(row["event_ts"]), float(row["avail_ts"]), float(row["amount"]))
t_lat.append((time.perf_counter() - t0) * 1000.0)
online_batch_diff = float(np.max(np.abs(online_means - batch_all["pit_tx_mean"].to_numpy())))
online_p99_ms = float(np.percentile(t_lat, 99))
# Future perturbation invariance test
ev_pert = ev_sorted.copy()
cut_ts = float(ev_pert["event_ts"].median())
ev_pert.loc[ev_pert["event_ts"] > cut_ts, "amount"] *= 50.0
batch_pert = pit_builder.transform_batch(ev_pert)
past_mask = ev_sorted["event_ts"].to_numpy() <= cut_ts
future_pert_diff = float(np.max(np.abs(batch_all.loc[past_mask, "pit_tx_mean"].to_numpy() - batch_pert.loc[past_mask, "pit_tx_mean"].to_numpy())))
pit_block = {
"leaky_offline_auc_illusion": auc_leaky_train_illusion,
"causal_pit_honest_auc": auc_causal_honest,
"oot_causal_rows": len(oot_causal),
"online_vs_batch_max_diff": online_batch_diff,
"online_single_row_p99_ms": online_p99_ms,
"future_perturbation_max_diff": future_pert_diff,
}
# 5. Extraction (OOF James-Stein vs In-Sample TE, Signed Hashing vs Unsigned) + PLR + LLM Gate
n_card = 560 if quick else 900
n_cats = 55
cats = np.array([f"merch_{int(c):03d}" for c in rng.integers(0, n_cats, size=n_card)])
groups_te = np.array([f"acct_{i // 3:03d}" for i in range(n_card)])
true_risk = {f"merch_{c:03d}": (1.15 if c % 4 == 0 else -0.85) for c in range(n_cats)}
y_te_prob = np.array([1.0 / (1.0 + math.exp(-(true_risk[c] - 0.6))) for c in cats])
y_te = (rng.random(n_card) < y_te_prob).astype(np.int64)
split_te = int(0.65 * n_card)
# Naive in-sample target encoding vs OOF James-Stein respecting groups
tr_cats, tr_y, tr_grp = cats[:split_te], y_te[:split_te], groups_te[:split_te]
te_cats, te_y = cats[split_te:], y_te[split_te:]
raw_means = pd.Series(tr_y).groupby(tr_cats).mean().to_dict()
global_p = float(np.mean(tr_y))
in_sample_tr = np.asarray([raw_means[c] for c in tr_cats])
in_sample_te = np.asarray([raw_means.get(c, global_p) for c in te_cats])
oof_js = OOFJamesSteinEncoder(smoothing_m=None, n_splits=5, seed=seed)
oof_tr = oof_js.fit_transform(tr_cats, tr_y, groups=tr_grp)
oof_te = oof_js.transform(te_cats)
# Signed vs Unsigned Hashing inner product bias
n_pairs = 80 if quick else 160
vocab_dim = 600
recs_a = [{f"t{idx}": 1.0 for idx in rng.choice(vocab_dim, size=12, replace=False)} for _ in range(n_pairs)]
recs_b = [{f"t{idx}": 1.0 for idx in rng.choice(vocab_dim, size=12, replace=False)} for _ in range(n_pairs)]
exact_dots = np.array([sum(ra.get(k, 0.0) * v for k, v in rb.items()) for ra, rb in zip(recs_a, recs_b)])
h_signed = SignedFeatureHasher(n_buckets=128, signed=True, seed=seed)
h_unsigned = SignedFeatureHasher(n_buckets=128, signed=False, seed=seed)
dots_signed = np.sum(h_signed.transform_dicts(recs_a) * h_signed.transform_dicts(recs_b), axis=1)
dots_unsigned = np.sum(h_unsigned.transform_dicts(recs_a) * h_unsigned.transform_dicts(recs_b), axis=1)
# PLR Periodic Embeddings vs Raw Linear on Sharp Discontinuous Threshold Boundary
n_plr = 450 if quick else 800
x_plr = rng.uniform(-2.0, 2.0, size=(n_plr, 1))
# Sharp symmetric non-monotone interval cliffs (impossible for raw 1D linear logistic regression!)
y_plr = ((np.abs(x_plr[:, 0]) < 0.42) | ((np.abs(x_plr[:, 0]) > 1.15) & (np.abs(x_plr[:, 0]) < 1.60))).astype(np.int64)
sp_p = int(0.65 * n_plr)
b0_r, w_r = _fit_l2_logistic_irls(x_plr[:sp_p], y_plr[:sp_p], l2_alpha=0.5)
auc_raw_lin = roc_auc_binary(y_plr[sp_p:], np.asarray(_stable_sigmoid(b0_r + x_plr[sp_p:] @ w_r)))
plr_enc = PeriodicPLREncoder(n_frequencies=16, freq_std=2.0, embed_dim=16, seed=seed)
Z_plr_tr = plr_enc.fit_transform(x_plr[:sp_p])
Z_plr_te = plr_enc.transform(x_plr[sp_p:])
b0_p, w_p = _fit_l2_logistic_irls(Z_plr_tr, y_plr[:sp_p], l2_alpha=1.0)
auc_plr = roc_auc_binary(y_plr[sp_p:], np.asarray(_stable_sigmoid(b0_p + Z_plr_te @ w_p)))
# LLM Feature Verification Gate
n_llm = 320
b1 = rng.uniform(10.0, 100.0, size=n_llm)
b2 = rng.uniform(1.0, 10.0, size=n_llm)
y_llm = 2.5 * (b1 / b2) + rng.normal(0.0, 1.5, size=n_llm)
X_base_llm = pd.DataFrame({"income": b1, "debt": b2})
cands_llm = pd.DataFrame(
{
"llm_true_dti_ratio": b1 / b2,
"llm_spurious_1": rng.normal(0.0, 1.0, size=n_llm),
"llm_spurious_2": rng.normal(0.0, 1.0, size=n_llm),
"llm_spurious_3": rng.normal(0.0, 1.0, size=n_llm),
"llm_spurious_4": rng.normal(0.0, 1.0, size=n_llm),
}
)
llm_gate = verify_llm_candidate_features_gate(X_base_llm, cands_llm, y_llm, n_outer=4, n_perm=99, q_fdr=0.05, seed=seed)
extraction_plr_block = {
"in_sample_te_train_auc": roc_auc_binary(tr_y, in_sample_tr),
"in_sample_te_test_auc": roc_auc_binary(te_y, in_sample_te),
"oof_james_stein_train_auc": roc_auc_binary(tr_y, oof_tr),
"oof_james_stein_test_auc": roc_auc_binary(te_y, oof_te),
"oof_learned_m": float(oof_js.learned_m_),
"signed_hash_inner_bias": float(np.mean(dots_signed - exact_dots)),
"unsigned_hash_inner_bias": float(np.mean(dots_unsigned - exact_dots)),
"raw_linear_cliff_auc": auc_raw_lin,
"plr_embedding_cliff_auc": auc_plr,
"llm_gate_accepted": llm_gate["accepted"],
"llm_gate_rejected_count": len(llm_gate["rejected"]),
}
# 6. Pre-Split Leakage Audit + End-to-End Pipeline DAG Batch/Row Parity & Signed JSON
leak_audit = audit_presplit_vs_infold_leakage(n_samples=110, d_noise=1000, top_k=15, n_splits=5, seed=seed)
n_pipe = 300
pipe_df = pd.DataFrame(
{
"amount": np.where(rng.random(n_pipe) < 0.05, np.nan, np.exp(rng.normal(2.5, 0.8, size=n_pipe))),
"net_balance": rng.normal(10.0, 35.0, size=n_pipe),
"hour": rng.integers(0, 24, size=n_pipe).astype(np.float64),
"region": rng.choice(["US", "EU", "APAC", "LATAM"], size=n_pipe),
"merchant_id": rng.choice([f"M{i:03d}" for i in range(40)], size=n_pipe),
}
)
y_pipe = (rng.random(n_pipe) < (1.0 / (1.0 + np.exp(-(-0.8 + 0.02 * pipe_df["net_balance"].to_numpy()))))).astype(np.int64)
cfg = PipelineConfig(
name="prod_churn_risk_dag",
branches=(
ColumnBranchSpec(name="num_mad", columns=("amount",), scale=ScaleLevel.RATIO, transform_kind="mad_clip_scale"),
ColumnBranchSpec(name="num_yj", columns=("net_balance",), scale=ScaleLevel.RATIO, transform_kind="yeojohnson_scale"),
ColumnBranchSpec(name="cyc_hour", columns=("hour",), scale=ScaleLevel.INTERVAL, transform_kind="cyclical", params={"period": 24.0}),
ColumnBranchSpec(name="cat_ohe", columns=("region",), scale=ScaleLevel.NOMINAL, transform_kind="onehot"),
ColumnBranchSpec(name="cat_hash", columns=("merchant_id",), scale=ScaleLevel.NOMINAL, transform_kind="signed_hash", params={"n_buckets": 16, "signed": True}),
),
l2_alpha=1.0,
)
pipe = FeaturePipeline(cfg).fit(pipe_df.iloc[:220], y_pipe[:220])
val_df = pipe_df.iloc[220:].reset_index(drop=True)
batch_probs = pipe.predict_proba(val_df)
shuffled_probs = pipe.predict_proba(val_df[list(reversed(val_df.columns))])
row_probs = np.empty(len(val_df), dtype=np.float64)
row_lats: list[float] = []
val_records = val_df.to_dict(orient="records")
for idx_r, rec in enumerate(val_records):
t0 = time.perf_counter()
row_probs[idx_r] = pipe.predict_proba_row(rec)
row_lats.append((time.perf_counter() - t0) * 1000.0)
state_json = pipe.to_state_dict()
restored = FeaturePipeline.from_state_dict(state_json)
restored_probs = restored.predict_proba(val_df)
pipeline_block = {
"leakage_audit": leak_audit,
"batch_vs_row_max_diff": float(np.max(np.abs(batch_probs - row_probs))),
"shuffled_columns_max_diff": float(np.max(np.abs(batch_probs - shuffled_probs))),
"json_roundtrip_max_diff": float(np.max(np.abs(batch_probs - restored_probs))),
"single_row_p99_ms": float(np.percentile(row_lats, 99)),
"n_out_features": len(pipe.transformer.feature_names_out_),
}
return {
"seed": int(seed),
"quick": bool(quick),
"power_and_stevens": power_block,
"selection_and_metrics": selection_block,
"banking_woe": woe_block,
"causal_pit": pit_block,
"extraction_and_plr": extraction_plr_block,
"pipeline_dag": pipeline_block,
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 08 (feature_eng_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 feature_eng_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 feature_eng_lab.pipeline_dag import run_full_ch08_benchmarks
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy scalars/arrays and non-finite floats into strict JSON-safe primitives."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar(val: float, floor: float = 0.001) -> float:
"""Ensure strictly positive finite bar widths for HTML dashboard rendering."""
if not math.isfinite(val):
return floor
return float(max(floor, abs(val)))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Feature Engineering & Automated Pipelines Workbench."""
parser = argparse.ArgumentParser(
description="Run Lab 08: Measurement Scales, Big-5 Feature Engineering, MI/PIMP/Boruta, Banking WoE & Pipeline DAG."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true", help="Run fast CI/demo sample budgets.")
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Output JSON path (e.g., artifacts/ch08_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
ps = bench["power_and_stevens"]
sel = bench["selection_and_metrics"]
woe = bench["banking_woe"]
pit = bench["causal_pit"]
ext = bench["extraction_and_plr"]
dag = bench["pipeline_dag"]
mdi = sel["mdi_bias_demo"]
mdi_imps = mdi["mdi_importances"]
oof_imps = mdi["oof_perm_importances"]
pimp_map = {r["feature"]: r for r in sel["pimp_table"]}
boruta_map = {r["feature"]: r for r in sel["boruta_table"]}
leak = dag["leakage_audit"]
kpis = [
{
"id": "kpi_boxcox_jacobian_and_skew",
"label": "Box-Cox Skew & Jacobian MLE",
"value": f"{ps['boxcox_skew_raw']:.2f} -> {ps['boxcox_skew_transformed']:.3f}",
"unit": f"lam={ps['boxcox_lambda_mle']:.2f}",
"status": "ok",
"detail": (
f"Without Jacobian collapses lam={ps['boxcox_lambda_no_jacobian']:.2f}; "
f"Yeo-Johnson cuts signed skew {ps['yeojohnson_skew_raw']:.2f} -> {ps['yeojohnson_skew_transformed']:.3f}."
),
},
{
"id": "kpi_mi_ksg_vs_pearson_u_shape",
"label": "U-Shape (Y=X^2): Pearson vs KSG-1",
"value": f"|r|={abs(sel['u_shape_pearson_r']):.3f} | KSG={sel['u_shape_ksg_mi_nats']:.3f}",
"unit": "nats",
"status": "ok",
"detail": (
f"Spearman rho={sel['u_shape_spearman_rho']:.3f} also blind to Y=X^2; "
f"Miller-Madow trims K=25 noise MI {sel['discrete_noise_mi_plugin_nats']:.3f} -> {sel['discrete_noise_mi_mm_nats']:.3f}."
),
},
{
"id": "kpi_mdi_trap_vs_pimp_fdr",
"label": "MDI K=200 Trap vs PIMP BH-FDR",
"value": f"MDI {mdi_imps['noise_cat_K200']:.3f} vs {mdi_imps['true_binary_signal']:.3f}",
"unit": "Trap Fixed",
"status": "warn",
"detail": (
f"CART MDI ranks K=200 noise > true signal, while OOF Perm ({oof_imps['true_binary_signal']:.3f} vs {oof_imps['noise_cat_K200']:.3f}) "
f"and PIMP (p={pimp_map['noise_cat_150']['p_value']:.3f}) reject noise."
),
},
{
"id": "kpi_woe_iv_and_leak_canary",
"label": "Monotonic Banking WoE / IV",
"value": f"IV {woe['iv_monotonic']:.3f} | Leak {woe['leak_proxy_iv']:.2f}",
"unit": f"{woe['n_final_bins']} bins",
"status": "ok",
"detail": (
f"PAVA monotonic={woe['is_monotonic']}, canary_flagged={woe['leak_canary_triggered']} (>0.50); "
f"shifted OOT CSI={woe['csi_shifted_oot']:.3f}."
),
},
{
"id": "kpi_pit_causal_vs_leaky_auc",
"label": "Causal PIT vs Leaky Groupby Bleed",
"value": f"Leak {pit['leaky_offline_auc_illusion']:.3f} -> PIT {pit['causal_pit_honest_auc']:.3f}",
"unit": f"{pit['online_single_row_p99_ms']:.3f} ms",
"status": "critical",
"detail": (
f"Future perturbation diff={pit['future_perturbation_max_diff']:.1e}; "
f"O(1) online deque parity diff={pit['online_vs_batch_max_diff']:.1e}."
),
},
{
"id": "kpi_signed_hash_and_pipeline_parity",
"label": "PLR Cliff & Pipeline DAG Parity",
"value": f"PLR {ext['plr_embedding_cliff_auc']:.3f} vs {ext['raw_linear_cliff_auc']:.3f}",
"unit": f"{dag['single_row_p99_ms']:.3f} ms",
"status": "ok",
"detail": (
f"Signed Hash bias={ext['signed_hash_inner_bias']:.2f} vs Unsigned=+{ext['unsigned_hash_inner_bias']:.2f}; "
f"Batch/Row diff={dag['batch_vs_row_max_diff']:.1e} (HMAC JSON)."
),
},
]
bars = [
{
"id": "bar_filter_metrics_on_nonlinear_signals",
"title": "Non-Linear Detection (Y=X^2) & Noise Bias Removal (MI Miller-Madow / KSG-1)",
"metric_label": "Score",
"items": [
{"label": "u_shape_pearson_abs_r", "value": _pos_bar(sel["u_shape_pearson_r"]), "display": f"{abs(sel['u_shape_pearson_r']):.3f} (Blind)", "css_class": "is-slow"},
{"label": "u_shape_spearman_abs_rho", "value": _pos_bar(sel["u_shape_spearman_rho"]), "display": f"{abs(sel['u_shape_spearman_rho']):.3f} (Blind)", "css_class": "is-slow"},
{"label": "u_shape_ksg1_mi_nats", "value": _pos_bar(sel["u_shape_ksg_mi_nats"]), "display": f"{sel['u_shape_ksg_mi_nats']:.3f} nats", "css_class": "is-fast"},
{"label": "noise_mi_plugin_vs_mm", "value": _pos_bar(sel["discrete_noise_mi_plugin_nats"]), "display": f"{sel['discrete_noise_mi_plugin_nats']:.3f} -> {sel['discrete_noise_mi_mm_nats']:.3f}", "css_class": "is-mid"},
],
},
{
"id": "bar_selection_mdi_vs_pimp_boruta",
"title": "High-Cardinality Impurity Trap (CART MDI K=200 Noise vs OOF Permutation)",
"metric_label": "Importance",
"items": [
{"label": "mdi_noise_cat_K200", "value": _pos_bar(mdi_imps["noise_cat_K200"]), "display": f"{mdi_imps['noise_cat_K200']:.3f} (Trap!)", "css_class": "is-slow"},
{"label": "mdi_true_binary_signal", "value": _pos_bar(mdi_imps["true_binary_signal"]), "display": f"{mdi_imps['true_binary_signal']:.3f}", "css_class": "is-mid"},
{"label": "oof_perm_true_signal", "value": _pos_bar(oof_imps["true_binary_signal"]), "display": f"{oof_imps['true_binary_signal']:.3f} (Clean)", "css_class": "is-fast"},
{"label": "oof_perm_noise_K200", "value": _pos_bar(oof_imps["noise_cat_K200"]), "display": f"{oof_imps['noise_cat_K200']:.3f} (Exposed)", "css_class": "is-fast"},
],
},
{
"id": "bar_hashing_and_oof_te_errors",
"title": "Representation & Extraction: PLR Pricing Cliff & OOF James-Stein Generalization",
"metric_label": "ROC-AUC",
"items": [
{"label": "raw_linear_cliff_auc", "value": _pos_bar(ext["raw_linear_cliff_auc"]), "display": f"{ext['raw_linear_cliff_auc']:.3f}", "css_class": "is-slow"},
{"label": "plr_periodic_cliff_auc", "value": _pos_bar(ext["plr_embedding_cliff_auc"]), "display": f"{ext['plr_embedding_cliff_auc']:.3f}", "css_class": "is-fast"},
{"label": "insample_te_train_overfit", "value": _pos_bar(ext["in_sample_te_train_auc"]), "display": f"Tr {ext['in_sample_te_train_auc']:.3f} -> Te {ext['in_sample_te_test_auc']:.3f}", "css_class": "is-slow"},
{"label": "oof_james_stein_test_auc", "value": _pos_bar(ext["oof_james_stein_test_auc"]), "display": f"Te {ext['oof_james_stein_test_auc']:.3f} (m={ext['oof_learned_m']:.1f})", "css_class": "is-fast"},
],
},
{
"id": "bar_pipeline_leakage_and_latency",
"title": "Pre-Split Screening Hallucination (White Noise) vs Inside-Fold Pipeline CV",
"metric_label": "CV AUC",
"items": [
{"label": "presplit_leaky_cv_auc", "value": _pos_bar(leak["presplit_leaky_cv_auc"]), "display": f"{leak['presplit_leaky_cv_auc']:.3f} (Fake!)", "css_class": "is-slow"},
{"label": "infold_clean_cv_auc", "value": _pos_bar(leak["infold_clean_cv_auc"]), "display": f"{leak['infold_clean_cv_auc']:.3f} (Honest)", "css_class": "is-fast"},
{"label": "unsigned_hash_bias", "value": _pos_bar(ext["unsigned_hash_inner_bias"]), "display": f"+{ext['unsigned_hash_inner_bias']:.2f}", "css_class": "is-slow"},
{"label": "signed_hash_bias", "value": _pos_bar(ext["signed_hash_inner_bias"]), "display": f"{ext['signed_hash_inner_bias']:+.2f}", "css_class": "is-fast"},
],
},
]
woe_rows = [
[
r["bin"],
int(r["count"]),
f"{r['bad_rate'] * 100:.2f}%",
f"{r['woe']:+.4f}",
f"{r['iv_contrib']:.4f}",
]
for r in woe["bin_table"]
]
sel_rows = []
for fname in ("sig_linear", "sig_twin", "sig_nonlinear", "noise_gaussian", "noise_cat_150"):
pr = pimp_map[fname]
b_dec = boruta_map[fname]["decision"] if fname in boruta_map else "EXCLUDED_CAT"
sel_rows.append(
[
fname,
f"{pr['observed_mdi']:.4f}",
f"{pr['pimp_z']:+.2f}",
f"{pr['bh_q_value']:.4f}",
f"{'ACCEPT' if pr['selected_fdr'] else 'REJECT'} / {b_dec}",
]
)
tables = [
{
"id": "table_stevens_and_power_transforms",
"title": "Stevens Scale Violations & Power/Quantile Conditioning Benchmarks",
"columns": ["benchmark", "raw_or_naive", "remediated_or_invariant", "secondary_check", "verdict"],
"rows": [
[
"ordinal_likert_reversal",
f"mean_diff={ps['stevens']['ordinal_likert']['mean_diff_linear_codes']:+.2f} -> {ps['stevens']['ordinal_likert']['mean_diff_monotone_stretched']:+.2f}",
f"median_preserved={ps['stevens']['ordinal_likert']['median_order_preserved']}",
"G_ord invariant",
"USE_MEDIAN_OR_RANK",
],
[
"nominal_integer_coding",
f"R2(123)={ps['stevens']['nominal_integer_coding']['r2_alpha_123']:.2f} vs R2(132)={ps['stevens']['nominal_integer_coding']['r2_permuted_132']:.2f}",
f"OneHot R2={ps['stevens']['nominal_integer_coding']['r2_onehot']:.2f}",
"G_nom invariant",
"NEVER_INT_ENCODE",
],
[
"box_cox_lognormal",
f"skew={ps['boxcox_skew_raw']:.2f} (no-Jac lam={ps['boxcox_lambda_no_jacobian']:.2f})",
f"skew={ps['boxcox_skew_transformed']:.3f} (MLE lam={ps['boxcox_lambda_mle']:.3f})",
"x > 0 required",
"JACOBIAN_MANDATORY",
],
[
"yeo_johnson_signed",
f"skew={ps['yeojohnson_skew_raw']:.2f}",
f"skew={ps['yeojohnson_skew_transformed']:.3f} (lam={ps['yeojohnson_lambda_mle']:.3f})",
f"RankGauss skew={ps['rankgauss_skew']:.3f}",
"SIGNED_SAFE",
],
],
},
{
"id": "table_woe_monotonic_scorecard",
"title": f"Banking Monotonic PAVA WoE Scorecard (Total IV = {woe['iv_monotonic']:.4f}, Leak Proxy IV = {woe['leak_proxy_iv']:.2f})",
"columns": ["bin", "count", "bad_rate", "woe_laplace", "iv_contrib"],
"rows": woe_rows,
},
{
"id": "table_feature_selection_audit",
"title": "Feature Selection Audit: PIMP Null-Importance (BH-FDR) & Boruta Shadow Decisions",
"columns": ["feature", "observed_mdi", "pimp_z", "bh_q_value", "pimp_and_boruta_verdict"],
"rows": sel_rows,
},
{
"id": "table_pipeline_parity_and_security",
"title": "Pipeline DAG Train-Serving Parity, Causal PIT Windows & Signed JSON Security",
"columns": ["gate_check", "measured_value", "threshold_or_baseline", "latency_or_count", "status"],
"rows": [
[
"batch_vs_single_row_parity",
f"{dag['batch_vs_row_max_diff']:.2e}",
"< 1e-12",
f"p99={dag['single_row_p99_ms']:.3f} ms (<1 ms)",
"PARITY_VERIFIED",
],
[
"shuffled_column_invariance",
f"{dag['shuffled_columns_max_diff']:.2e}",
"== 0.0",
f"d_out={dag['n_out_features']}",
"NAME_INDEXED_SAFE",
],
[
"hmac_json_roundtrip_parity",
f"{dag['json_roundtrip_max_diff']:.2e}",
"< 1e-12 (0 pickle)",
"HMAC-SHA256 verified",
"CWE_502_IMMUNE",
],
[
"causal_pit_online_parity",
f"{pit['online_vs_batch_max_diff']:.2e}",
f"future_pert={pit['future_perturbation_max_diff']:.1e}",
f"p99={pit['online_single_row_p99_ms']:.3f} ms",
"ZERO_FUTURE_BLEED",
],
[
"llm_candidate_4stage_gate",
f"kept={ext['llm_gate_accepted']}",
f"rejected={ext['llm_gate_rejected_count']}/5",
"Nested OOF + BH-FDR",
"OVERFIT_BLOCKED",
],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
bench = run_full_ch08_benchmarks(seed=args.seed, quick=args.quick)
panels = _build_workbench_panels(bench)
payload = _sanitize_json_value({**bench, "workbench_panels": panels})
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8"))
print("=== Lab 08 Workbench (feature_eng_lab, T1-P2-U03) ===")
for kpi in panels["kpis"]:
print(f" [{kpi['status'].upper()}] {kpi['label']}: {kpi['value']} ({kpi['unit']})")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14-test contract verification suite for Lab 08 (feature_eng_lab, Unit T1-P2-U03)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
import time
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from pydantic import ValidationError
from feature_eng_lab import (
MAD_CONSISTENCY,
BoxCoxTransformer,
CausalRollingFeatureBuilder,
ColumnBranchSpec,
ColumnTransformerDAG,
CyclicalTimeEncoder,
FeaturePipeline,
FoldPCAExtractor,
MissingnessAndMadClipper,
MonotonicWoEEncoder,
OnlineSlidingWindowState,
OOFJamesSteinEncoder,
PeriodicPLREncoder,
PipelineConfig,
RankGaussTransformer,
ScaleLevel,
SignedFeatureHasher,
YeoJohnsonTransformer,
audit_presplit_vs_infold_leakage,
audit_stevens_scale_violations,
boruta_shadow_selection,
chi2_independence_and_cramers_v,
chi2_sf,
collinearity_cluster_permutation,
compute_discrete_mi,
compute_ksg_mi,
compute_tree_mdi_bias_demo,
digamma,
norm_ppf,
null_importance_pimp,
pearson_and_spearman,
roc_auc_binary,
sample_skewness,
verify_llm_candidate_features_gate,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
def test_01_stevens_measurement_scale_invariance_failures() -> None:
res = audit_stevens_scale_violations()
assert res["ordinal_likert"]["mean_diff_linear_codes"] > 0.0
assert res["ordinal_likert"]["mean_diff_monotone_stretched"] < 0.0
assert res["ordinal_likert"]["sign_reversed"] is True
assert res["ordinal_likert"]["median_order_preserved"] is True
assert res["nominal_integer_coding"]["r2_alpha_123"] == pytest.approx(0.0, abs=1e-10)
assert res["nominal_integer_coding"]["r2_permuted_132"] == pytest.approx(0.75, abs=1e-10)
assert res["nominal_integer_coding"]["r2_onehot"] == pytest.approx(1.0, abs=1e-10)
assert res["interval_pct_change"]["pct_celsius"] == pytest.approx(1.0, abs=1e-12)
assert res["interval_pct_change"]["pct_fahrenheit"] == pytest.approx(0.36, abs=1e-12)
assert res["interval_pct_change"]["pct_kelvin"] < 0.05
with pytest.raises(ValueError, match="Stevens Scale Contract Violation"):
ColumnTransformerDAG(
[ColumnBranchSpec(name="bad", columns=("region",), scale=ScaleLevel.NOMINAL, transform_kind="boxcox_scale")]
).fit(pd.DataFrame({"region": [1.0, 2.0, 3.0]}))
def test_02_box_cox_profile_ll_jacobian_vs_naive_and_yeo_johnson() -> None:
rng = np.random.default_rng(42)
x_pos = np.exp(rng.normal(1.5, 0.9, size=500)) # true Box-Cox lambda = 0.0
bc = BoxCoxTransformer(use_jacobian=True, standardize=True).fit(x_pos)
z_bc = bc.transform(x_pos)[:, 0]
assert abs(bc.lambdas_[0]) < 0.25
assert bc.naive_no_jacobian_lambdas_[0] < -1.5
assert abs(sample_skewness(z_bc)) < 0.20 * abs(sample_skewness(x_pos))
with pytest.raises(ValueError, match="strictly positive"):
BoxCoxTransformer().fit(np.array([-1.0, 0.0, 2.0, 5.0]))
x_signed = np.concatenate([rng.normal(-3.0, 1.5, size=120), np.exp(rng.normal(1.0, 0.95, size=360))])
yj = YeoJohnsonTransformer(standardize=True).fit(x_signed)
z_yj = yj.transform(x_signed)[:, 0]
assert np.all(np.isfinite(z_yj))
assert abs(sample_skewness(z_yj)) < 0.35 * abs(sample_skewness(x_signed))
def test_03_rankgauss_and_missingness_mad_clipping() -> None:
assert abs(1.0 / float(norm_ppf(0.75)) - MAD_CONSISTENCY) < 1e-8
rng = np.random.default_rng(42)
x = np.exp(rng.normal(0.5, 1.1, size=600))
rg = RankGaussTransformer(n_quantiles=128).fit(x[:450])
z_te = rg.transform(x[450:])[:, 0]
assert abs(float(np.mean(z_te))) < 0.20
assert 0.75 < float(np.std(z_te)) < 1.25
assert abs(sample_skewness(z_te)) < 0.35
# Missingness + MAD clipping + MAD==0 MeanAD fallback
df_m = pd.DataFrame(
{
"a": [1.0, 2.0, 3.0, 2.5, np.nan, 1000.0, 1.5, 2.2],
"zero_inf": [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 50.0],
}
)
clipper = MissingnessAndMadClipper(clip_z=3.0, add_missing_flags=True).fit(df_m)
assert clipper.used_meanad_fallback_ == [False, True]
out = clipper.transform(df_m)
assert out.shape == (8, 4)
assert out[4, 2] == 1.0 # a_is_missing flag
assert out[5, 0] < 50.0 # 1000.0 clipped cleanly
def test_04_cyclical_encoding_and_causal_pit_window_vs_online_parity() -> None:
cyc = CyclicalTimeEncoder(period=24.0)
pts = cyc.transform(np.array([0.0, 1.0, 23.0]))
dist_23_0 = float(np.linalg.norm(pts[2] - pts[0]))
dist_0_1 = float(np.linalg.norm(pts[0] - pts[1]))
assert dist_23_0 == pytest.approx(dist_0_1, rel=1e-12)
rng = np.random.default_rng(7)
rows = []
tx_id = 0
for u in range(20):
t = 1000.0
for step in range(12):
t += float(rng.uniform(100.0, 900.0))
amt = float(250.0 if (step >= 7 and u % 4 == 0) else rng.uniform(10.0, 50.0))
rows.append({"entity_id": f"u{u}", "event_ts": t, "avail_ts": t, "tx_id": tx_id, "amount": amt})
tx_id += 1
df_ev = pd.DataFrame(rows).sort_values(["entity_id", "event_ts", "tx_id"]).reset_index(drop=True)
builder = CausalRollingFeatureBuilder(window_seconds=3600.0, lag_seconds=0.0, ewma_half_life=1800.0)
batch = builder.transform_batch(df_ev)
# Future perturbation invariance test
cut = float(df_ev["event_ts"].median())
df_pert = df_ev.copy()
df_pert.loc[df_pert["event_ts"] > cut, "amount"] *= 100.0
batch_pert = builder.transform_batch(df_pert)
past = df_ev["event_ts"].to_numpy() <= cut
assert np.max(np.abs(batch.loc[past, "pit_tx_mean"].to_numpy() - batch_pert.loc[past, "pit_tx_mean"].to_numpy())) == 0.0
# O(1) Online Sliding Window State Parity & Latency
online = OnlineSlidingWindowState(window_seconds=3600.0, lag_seconds=0.0, ewma_half_life=1800.0)
online_vals = []
lats_ms = []
for _, r in df_ev.iterrows():
t0 = time.perf_counter()
feats = online.score_before_ingest(r["entity_id"], float(r["event_ts"]))
online_vals.append(feats["pit_tx_mean"])
online.ingest(r["entity_id"], float(r["event_ts"]), float(r["avail_ts"]), float(r["amount"]))
lats_ms.append((time.perf_counter() - t0) * 1000.0)
assert np.max(np.abs(np.asarray(online_vals) - batch["pit_tx_mean"].to_numpy())) < 1e-12
assert float(np.percentile(lats_ms, 99)) < 2.0
def test_05_monotonic_woe_iv_laplace_smoothing_and_leak_canary() -> None:
rng = np.random.default_rng(42)
n = 1200
x = np.where(rng.random(n) < 0.08, np.nan, np.clip(rng.beta(1.6, 3.0, size=n), 0.0, 1.0))
prob = 1.0 / (1.0 + np.exp(-(-3.6 + 2.2 * np.nan_to_num(x, nan=0.82))))
y = (rng.random(n) < prob).astype(np.int64)
woe = MonotonicWoEEncoder(n_bins=8, laplace_alpha=0.5, enforce_monotonic=True).fit(x, y)
assert woe.is_monotonic_ is True
assert 0.05 < woe.iv_ < 0.50
assert woe.is_leakage_canary_ is False
assert any(r["bin"] == "MISSING" for r in woe.bin_table_)
transformed = woe.transform(x)
assert np.all(np.isfinite(transformed))
# Zero-event bin smoothness & >0.50 leakage canary
leak_col = y * 5.0 + rng.normal(0.0, 0.2, size=n)
woe_leak = MonotonicWoEEncoder(n_bins=6, laplace_alpha=0.5).fit(leak_col, y)
assert np.all(np.isfinite([r["woe"] for r in woe_leak.bin_table_]))
assert woe_leak.iv_ > 0.50
assert woe_leak.is_leakage_canary_ is True
# CSI drift check
x_shift = np.clip(rng.beta(3.0, 1.5, size=400), 0.0, 1.0)
assert woe.compute_csi(x_shift) > 0.25
def test_06_mi_miller_madow_and_ksg_vs_pearson_spearman_blind_spots() -> None:
assert digamma(1.0) == pytest.approx(-0.5772156649015329, abs=1e-12)
assert digamma(2.0) == pytest.approx(0.4227843350984671, abs=1e-12)
rng = np.random.default_rng(11)
# Discrete independent K=25 noise -> Miller-Madow slashes plug-in upward bias
ca = rng.integers(0, 25, size=300)
cb = rng.integers(0, 25, size=300)
mi_nats = compute_discrete_mi(ca, cb, unit="nats")
mi_bits = compute_discrete_mi(ca, cb, unit="bits")
assert mi_nats["mi_miller_madow"] < mi_nats["mi_plugin"]
assert mi_bits["mi_plugin"] == pytest.approx(mi_nats["mi_plugin"] / math.log(2.0), rel=1e-12)
# Symmetric U-shape Y = X^2: Pearson & Spearman ~ 0, KSG-1 detects strongly
x_u = rng.uniform(-2.0, 2.0, size=500)
y_u = x_u**2 + rng.normal(0.0, 0.1, size=500)
corrs = pearson_and_spearman(x_u, y_u)
assert abs(corrs["pearson_r"]) < 0.12
assert abs(corrs["spearman_rho"]) < 0.12
assert compute_ksg_mi(x_u, y_u, k=3, unit="nats") > 0.80
# Pure XOR: Pearson blind
x1 = rng.choice([-1, 1], size=400)
x2 = rng.choice([-1, 1], size=400)
assert abs(pearson_and_spearman(x1, x1 * x2)["pearson_r"]) < 0.12
def test_07_chi2_independence_and_bergsma_corrected_cramers_v() -> None:
assert chi2_sf(3.841458820694124, 1) == pytest.approx(0.05, abs=1e-5)
rng = np.random.default_rng(21)
a_ind = rng.integers(0, 25, size=300)
b_ind = rng.integers(0, 25, size=300)
res_ind = chi2_independence_and_cramers_v(a_ind, b_ind)
assert res_ind["cramers_v_corrected"] < res_ind["cramers_v"]
a_dep = rng.integers(0, 4, size=300)
b_dep = (a_dep + (rng.random(300) < 0.10).astype(int)) % 4
res_dep = chi2_independence_and_cramers_v(a_dep, b_dep)
assert res_dep["p_value"] < 1e-12
assert res_dep["cramers_v_corrected"] > 0.70
def test_08_tree_mdi_cardinality_trap_and_null_importance_pimp() -> None:
demo = compute_tree_mdi_bias_demo(n_samples=650, cardinalities=(2, 20, 200), seed=42)
assert demo["mdi_noise_k200_exceeds_signal"] is True
assert demo["oof_signal_exceeds_k200"] is True
rng = np.random.default_rng(42)
n = 350
sig = rng.normal(0.0, 1.0, size=n)
noise_cat = rng.integers(0, 150, size=n)
y = 2.2 * sig + rng.normal(0.0, 0.5, size=n)
df = pd.DataFrame({"true_sig": sig, "noise_cat_150": noise_cat})
pimp = null_importance_pimp(df, y, categorical_cols=["noise_cat_150"], n_permutations=49, q_fdr=0.05, seed=42)
pmap = {r["feature"]: r for _, r in pimp.iterrows()}
assert pmap["true_sig"]["selected_fdr"] is True
assert pmap["noise_cat_150"]["selected_fdr"] is False
def test_09_collinearity_cluster_permutation_and_boruta_binomial() -> None:
rng = np.random.default_rng(13)
n = 360
x1 = rng.normal(0.0, 1.0, size=n)
x2 = 0.97 * x1 + rng.normal(0.0, 0.15, size=n)
noise = rng.normal(0.0, 1.0, size=n)
y = 2.4 * x1 + rng.normal(0.0, 0.4, size=n)
df = pd.DataFrame({"x1": x1, "x2_twin": x2, "noise": noise})
c_res = collinearity_cluster_permutation(df, y, corr_threshold=0.80, n_splits=4, seed=13)
twin_cluster = next(c for c in c_res["clusters"] if "x1" in c["features"])
assert "x2_twin" in twin_cluster["features"]
assert twin_cluster["cluster_oof_perm"] > twin_cluster["max_single_oof_perm"]
boruta_df = boruta_shadow_selection(df, y, n_runs=24, alpha=0.05, seed=13)
bmap = {r["feature"]: r["decision"] for _, r in boruta_df.iterrows()}
assert bmap["x1"] == "CONFIRMED"
assert bmap["noise"] == "REJECTED"
def test_10_oof_james_stein_respecting_groups_vs_in_sample_overfit() -> None:
rng = np.random.default_rng(42)
n = 450
cats = np.array([f"c_{int(v):03d}" for v in rng.integers(0, 140, size=n)])
groups = np.array([f"grp_{i // 3:03d}" for i in range(n)])
y = (rng.random(n) < 0.30).astype(np.float64)
# Naive in-sample memorization vs group-isolated OOF James-Stein
raw_means = pd.Series(y).groupby(cats).mean().to_dict()
in_sample = np.asarray([raw_means[c] for c in cats])
auc_in_sample = roc_auc_binary(y.astype(int), in_sample)
oof_enc = OOFJamesSteinEncoder(smoothing_m=None, n_splits=5, seed=42)
oof_vals = oof_enc.fit_transform(cats, y, groups=groups)
auc_oof = roc_auc_binary(y.astype(int), oof_vals)
assert auc_in_sample > 0.78
assert auc_oof < auc_in_sample - 0.15
# Unseen category falls back smoothly to global prior
unseen = oof_enc.transform(np.array(["brand_new_merchant"]))
assert unseen[0] == pytest.approx(oof_enc.global_prior_, abs=1e-12)
def test_11_signed_feature_hashing_unbiasedness_and_plr_spectral_gap() -> None:
rng = np.random.default_rng(99)
n_pairs = 120
recs_a = [{f"tok_{i}": 1.0 for i in rng.choice(500, size=10, replace=False)} for _ in range(n_pairs)]
recs_b = [{f"tok_{i}": 1.0 for i in rng.choice(500, size=10, replace=False)} for _ in range(n_pairs)]
exact = np.array([sum(ra.get(k, 0.0) * v for k, v in rb.items()) for ra, rb in zip(recs_a, recs_b)])
hs_small = SignedFeatureHasher(n_buckets=64, signed=True, seed=99)
hs_large = SignedFeatureHasher(n_buckets=512, signed=True, seed=99)
hu_small = SignedFeatureHasher(n_buckets=64, signed=False, seed=99)
err_s_small = np.sum(hs_small.transform_dicts(recs_a) * hs_small.transform_dicts(recs_b), axis=1) - exact
err_s_large = np.sum(hs_large.transform_dicts(recs_a) * hs_large.transform_dicts(recs_b), axis=1) - exact
err_u_small = np.sum(hu_small.transform_dicts(recs_a) * hu_small.transform_dicts(recs_b), axis=1) - exact
assert float(np.mean(err_u_small)) > 0.80 # systematic positive collision bias
assert abs(float(np.mean(err_s_small))) < 0.35
assert float(np.var(err_s_large)) < float(np.var(err_s_small))
# Periodic PLR closes symmetric non-monotone sharp pricing cliff where raw linear fails
x_c = rng.uniform(-2.0, 2.0, size=(420, 1))
y_c = ((np.abs(x_c[:, 0]) < 0.42) | ((np.abs(x_c[:, 0]) > 1.15) & (np.abs(x_c[:, 0]) < 1.60))).astype(np.int64)
plr = PeriodicPLREncoder(n_frequencies=16, freq_std=2.0, embed_dim=16, seed=42)
Z_tr = plr.fit_transform(x_c[:280])
Z_te = plr.transform(x_c[280:])
w_plr, *_ = np.linalg.lstsq(np.hstack([np.ones((280, 1)), Z_tr]), y_c[:280], rcond=None)
w_raw, *_ = np.linalg.lstsq(np.hstack([np.ones((280, 1)), x_c[:280]]), y_c[:280], rcond=None)
auc_plr = roc_auc_binary(y_c[280:], np.hstack([np.ones((140, 1)), Z_te]) @ w_plr)
auc_raw = roc_auc_binary(y_c[280:], np.hstack([np.ones((140, 1)), x_c[280:]]) @ w_raw)
assert auc_raw < 0.65
assert auc_plr > 0.85
# Fold PCA leakage-safe check
pca = FoldPCAExtractor(n_components=1).fit(Z_tr)
assert pca.transform(Z_te).shape == (140, 1)
def test_12_llm_feature_verification_gate_and_presplit_leakage_audit() -> None:
rng = np.random.default_rng(42)
n = 320
inc = rng.uniform(10.0, 100.0, size=n)
debt = rng.uniform(1.0, 10.0, size=n)
y = 2.5 * (inc / debt) + rng.normal(0.0, 1.5, size=n)
X_base = pd.DataFrame({"income": inc, "debt": debt})
cands = pd.DataFrame(
{
"llm_true_dti": inc / debt,
"llm_noise_1": rng.normal(0.0, 1.0, size=n),
"llm_noise_2": rng.normal(0.0, 1.0, size=n),
"llm_noise_3": rng.normal(0.0, 1.0, size=n),
}
)
gate = verify_llm_candidate_features_gate(X_base, cands, y, n_outer=4, n_perm=89, q_fdr=0.05, seed=42)
assert "llm_true_dti" in gate["accepted"]
assert len(gate["rejected"]) >= 3
audit = audit_presplit_vs_infold_leakage(n_samples=110, d_noise=1000, top_k=15, n_splits=5, seed=42)
assert audit["presplit_leaky_cv_auc"] > 0.78
assert 0.35 <= audit["infold_clean_cv_auc"] <= 0.65
def test_13_column_transformer_dag_parity_shuffled_cols_and_signed_json(tmp_path: Path) -> None:
with pytest.raises(ValidationError):
PipelineConfig(
branches=(ColumnBranchSpec(name="b", columns=("x",), scale=ScaleLevel.RATIO, transform_kind="rankgauss"),),
unexpected_field=True, # type: ignore[call-arg]
)
rng = np.random.default_rng(42)
n = 200
df = pd.DataFrame(
{
"amount": np.where(rng.random(n) < 0.05, np.nan, np.exp(rng.normal(2.0, 0.7, size=n))),
"net_bal": rng.normal(5.0, 20.0, size=n),
"hour": rng.integers(0, 24, size=n).astype(float),
"region": rng.choice(["US", "EU", "APAC"], size=n),
"merch": rng.choice([f"M{i}" for i in range(25)], size=n),
}
)
y = (rng.random(n) < 0.35).astype(int)
cfg = PipelineConfig(
branches=(
ColumnBranchSpec(name="mad", columns=("amount",), scale=ScaleLevel.RATIO, transform_kind="mad_clip_scale"),
ColumnBranchSpec(name="yj", columns=("net_bal",), scale=ScaleLevel.RATIO, transform_kind="yeojohnson_scale"),
ColumnBranchSpec(name="cyc", columns=("hour",), scale=ScaleLevel.INTERVAL, transform_kind="cyclical", params={"period": 24.0}),
ColumnBranchSpec(name="ohe", columns=("region",), scale=ScaleLevel.NOMINAL, transform_kind="onehot"),
ColumnBranchSpec(name="hash", columns=("merch",), scale=ScaleLevel.NOMINAL, transform_kind="signed_hash", params={"n_buckets": 12}),
),
l2_alpha=1.0,
)
pipe = FeaturePipeline(cfg).fit(df.iloc[:150], y[:150])
assert pipe.coef_.flags.writeable is False
val = df.iloc[150:].reset_index(drop=True)
probs_batch = pipe.predict_proba(val)
probs_shuf = pipe.predict_proba(val[list(reversed(val.columns))])
assert np.max(np.abs(probs_batch - probs_shuf)) == 0.0
probs_rows = np.array([pipe.predict_proba_row(r) for r in val.to_dict(orient="records")])
assert np.max(np.abs(probs_batch - probs_rows)) < 1e-12
artifact = tmp_path / "signed_pipeline.json"
pipe.save_signed_state(artifact, secret_key="unit-test-hmac-secret")
restored = FeaturePipeline.load_signed_state(artifact, secret_key="unit-test-hmac-secret")
assert np.max(np.abs(probs_batch - restored.predict_proba(val))) < 1e-12
# Tamper detection test
data_obj = json.loads(artifact.read_text(encoding="utf-8"))
data_obj["state_payload"]["intercept"] += 0.25
artifact.write_text(json.dumps(data_obj), encoding="utf-8")
with pytest.raises(ValueError, match="SHA-256"):
FeaturePipeline.load_signed_state(artifact, secret_key="unit-test-hmac-secret")
def test_14_cli_demo_script_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch08_workbench_results.json"
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--seed", "42", "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed: {proc.stderr}"
assert out_json.is_file()
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
# Security-Only AST deserialization scan across all lab python files
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py")) + list((LAB_ROOT / "tests").rglob("*.py"))
violations: list[tuple[str, str]] = []
for pf in py_files:
tree = ast.parse(pf.read_text(encoding="utf-8"), filename=str(pf))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append((pf.name, root_mod))
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".")[0]
if root_mod in FORBIDDEN_UNSAFE_IMPORTS:
violations.append((pf.name, root_mod))
assert violations == [], f"Unsafe deserialization imports detected: {violations}"
Nominal, Ordinal, Interval, Ratio). Phát biểu toán học nào ĐÚNG khi giải thích vì sao việc lấy trung bình điểm Likert thứ bậc hoặc mã hóa danh định bằng số nguyên gây sụp đổ mô hình?log và Box–Cox đều đòi hỏi điểm 0 thật của thang Ratio (\(x > 0\)); biến đổi Ratio -> Interval thông qua logarithm bảo toàn tính đẳng phương nhân.
Box–Cox bằng cách cực tiểu hóa phương sai phần dư \(\hat{\sigma}^2(\lambda)\) mà bỏ qua số hạng Jacobian \((\lambda - 1)\sum_{i=1}^n \ln x_i\) lại thất bại, và trong lab feature_eng_lab kết quả thực nghiệm cho thấy gì?MAD dùng hằng số nhất quán Chuẩn \(1/\Phi^{-1}(0.75) \approx 1.4826\) (với dự phòng MeanAD khi MAD == 0), còn Yeo–Johnson mở rộng \(C^2(\mathbb{R})\) sang cả miền âm và 0.
WoE/IV Đơn điệu PAVA, Làm mượt Laplace & Cờ Cảnh báo Rò rỉ
Credit Scorecard) tuân thủ SR 11-7 & EU AI Act, quy trình phân khoảng WoE/IV nào giải quyết đồng thời bẫy đường cong rủi ro răng cưa, lỗi chia 0 ở ô không có vỡ nợ, và phát hiện biến rò rỉ hậu quả?PAVA triệt tiêu tình trạng đường cong hình chữ U lẫn ngoại lệ inf khi \(B_b = 0\), đồng thời ngưỡng IV > 0.50 bắt ngay biến rò rỉ sau khởi tạo khoản vay.
Pearson/Spearman vs. Miller–Madow & KSG-1 Mutual Information
XOR \(Y = X_1 X_2\), và hai biến danh mục độc lập có số lượng mức danh mục K = 25 (n = 300), kết quả đo kiểm thông tin nào ĐÚNG?Spearman). KSG-1 dùng chuẩn \(L_\infty\) để triệt tiêu hệ số thể tích không gian cục bộ trong công thức 3H, còn Miller–Madow trừ đúng thiên lệch bậc nhất \(\frac{(|\mathcal{X}_+|-1)(|\mathcal{Y}_+|-1)}{2n}\).
Tree-Gain (MDI) \(\mathcal{O}(K/n)\), OOF Permutation, Cluster & Null-Importance (PIMP) / Boruta
MDI) trên dữ liệu chứa biến phân loại nhiễu nhiều mức (high-cardinality, K = 200 / K = 150) cùng hai biến tín hiệu tương quan chặt (sig_linear & sig_twin, \(\rho = 0.96\)), kết luận nào phản ánh ĐÚNG cơ chế chọn lọc SOTA?PIMP (Altmann 2010) chuẩn hóa theo phân phối vô hiệu riêng từng cột, Boruta (Kursa & Rudnicki 2010) kiểm định nhị thức hai phía trước ngưỡng MZSA, và Cluster Permutation chống pha loãng đa cộng tuyến.
OOF James–Stein Tôn trọng Nhóm vs. Signed Feature Hashing (Weinberger ±1)
OOF James–Stein tôn trọng nhóm thực thể (groups), và Signed Feature Hashing (Weinberger ±1) trên biến phân loại ID nhiều mức (high-cardinality):OOF) tôn trọng nhóm là đường cơ sở tối ưu cho biến phân loại nhiều mức (high-cardinality).
PLR, TabM) & Cổng Kiểm chứng Sinh đặc trưng bằng LLM
PLR (Gorishniy et al., NeurIPS 2022) giúp mạng nơ-ron bảng vượt qua nút thắt trơn phổ (spectral bias) trên các ngưỡng phi tuyến sắc nét, và cơ chế nào ngăn chặn LLM AutoFE (CAAFE/OCTree) quá khớp vào tập thẩm định?TabM) chứng minh kết hợp chiếu tuần hoàn đa tần số (PLR) với Linear -> ReLU khắc phục độ trơn của mạng nơ-ron bảng. Với LLM AutoFE, thử nghiệm hàng chục ứng viên lặp lại trên cùng một tập thẩm định chắc chắn tạo dương tính giả nếu thiếu kiểm soát Nested CV và BH-FDR.
ColumnTransformerDAG), Nhân quả PIT & Tuần tự hóa HMAC-SHA256 Không-pickle
< 1 ms và miễn nhiễm lỗ hổng CWE-502, sự kết hợp nào giữa lọc tiền tách tập, cửa sổ cuộn PIT và tuần tự hóa đường ống được chứng minh trong workbench feature_eng_lab?Pipeline chỉ .fit() trên nếp huấn luyện. Phục vụ thời gian thực chuẩn hóa qua Signed JSON State-Dict (HMAC-SHA256) và định tuyến theo tên cột xóa bỏ triệt để rủi ro CWE-502, hoán vị cột và lệch huấn luyện–phục vụ.
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 Nhóm Bất biến Stevens (1946) & Sửa lỗi Phản ví dụ Thang đo 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết tập tự đẳng cấu cho 4 thang đo \(G_{\text{rat}} \subsetneq G_{\text{int}} \subsetneq G_{\text{ord}} \subsetneq G_{\text{nom}}\). Với Likert (c1, c4, c4, c4) vs (c2, c2, c2, c5), tính trung bình và trung vị dưới hai ánh xạ [1,2,3,4,5] và [1,2,3,4,10].
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi audit_stevens_scale_violations() và kiểm nghiệm hàm kiểm tra tương thích trong ColumnTransformerDAG khi gán nhầm boxcox_scale lên cột NOMINAL.
Tiêu chí Đáp án & Số đối chứng
Ánh xạ [1..5] cho hiệu trung bình +0.50 nhưng [1,2,3,4,10] lật thành -0.75 trong khi trung vị luôn giữ c4 > c2. Mã nguyên danh định kéo R^2 dao động giả từ 0.00 -> 0.75 (OneHot = 1.00), còn % thay đổi nhảy 100% -> 36% -> 3.53% giữa °C/°F/K. ColumnTransformerDAG chặn lỗi này bằng ValueError hợp đồng thang đo.
Bài tập 2 — Dẫn xuất Profile Log-Likelihood Box–Cox (Jacobian), Yeo–Johnson, MAD & RankGauss
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng công thức đổi biến mật độ \(f_X(x) = f_Y(y^{(\lambda)}) |dy^{(\lambda)}/dx|\) để thu được số hạng \((\lambda - 1)\sum \ln x_i\); chứng minh trường hợp x > 1 đẩy \(\hat{\sigma}^2(\lambda) \to 0\) khi bỏ Jacobian. Dẫn xuất hằng số \(1/\Phi^{-1}(0.75) \approx 1.4826\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực nghiệm với BoxCoxTransformer(use_jacobian=True/False), YeoJohnsonTransformer, RankGaussTransformer (norm_ppf Acklam) và MissingnessAndMadClipper (bao gồm cột toàn 0 kích hoạt nhánh MeanAD).
Tiêu chí Đáp án & Số đối chứng
BoxCoxTransformer với Jacobian tìm ra lam = -0.045 giảm skew từ 4.00 -> 0.001, trong khi bỏ Jacobian sụp về lam = -1.279. YeoJohnsonTransformer xử lý an toàn số âm/0 (skew 1.90 -> 0.308), RankGauss giữ skew = 0.065, và MissingnessAndMadClipper tự động kích hoạt MeanAD khi MAD == 0.
Bài tập 3 — Mã hóa Chu kỳ sin/cos, Cửa sổ Nhân quả PIT & Banking WoE/IV Đơn điệu PAVA
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh khoảng cách dây cung trên \(S^1\) tỷ lệ đơn điệu với \(\sin(\pi d_{S^1}/T)\). Viết định nghĩa lọc nhân quả nửa mở \([t_{\text{obs}} - W, t_{\text{obs}})\) kèm \(t_{\text{avail}} \le t_{\text{obs}} - \delta_{\text{lag}}\) và công thức \(\operatorname{WoE}_b = \ln(g_b/b_b)\) làm mượt Laplace.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu CausalRollingFeatureBuilder với OnlineSlidingWindowState (future_perturbation_max_diff) và chạy MonotonicWoEEncoder(laplace_alpha=0.5) trên dữ liệu rủi ro vỡ nợ có missing MNAR + biến rò rỉ.
Tiêu chí Đáp án & Số đối chứng
Cửa sổ nhân quả đạt sai khác nhiễu tương lai 0.0, lệch lô/đơn 5.68e-14 (p99 = 0.074 ms), hạ ảo giác Leaky AUC 0.857 về PIT AUC 0.788 trung thực. MonotonicWoEEncoder ghép 4 khoảng đơn điệu tuyệt đối (IV = 0.4039, MISSING WoE = -0.7264), phát hiện canary rò rỉ IV = 3.94 > 0.50 và CSI = 1.002 khi trôi.
Bài tập 4 — Điểm mù Pearson/Spearman vs. Miller–Madow & KSG-1 MI, và Bergsma Cramér's V
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\operatorname{Cov}(X, X^2) = 0\) trên phân phối đối xứng và \(\operatorname{Cov}(X_1, X_1 X_2) = 0\) trên XOR. Suy diễn thiên lệch dương bậc hai của MI plug-in dẫn tới công thức trừ Miller–Madow, cùng phép triệt tiêu thể tích \(L_\infty\) của KSG-1.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi pearson_and_spearman, compute_discrete_mi(..., unit='nats'/'bits'), compute_ksg_mi(..., k=3), và chi2_independence_and_cramers_v trên các tập đối chứng.
Tiêu chí Đáp án & Số đối chứng
Trên \(Y = X^2\), |Pearson r| = 0.077 và Spearman rho = 0.043 đều bất lực trong khi KSG-1 đạt 1.792 nats. Trên 2 biến K = 25 độc lập (n = 300), Miller–Madow cắt sạch nhiễu 0.926 -> 0.000 nats và Bergsma Cramér's V sửa 0.279 -> 0.000.
Bài tập 5 — Vạch trần Bẫy MDI \(\mathcal{O}(K/n)\) Bằng OOF Permutation, Cluster, PIMP & Boruta
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích cơ chế tìm điểm chia tối ưu trên \(K\) mức của Fisher (1958) tạo độ giảm tạp chất giả tiệm cận \(\approx \frac{2}{\pi}\frac{K-1}{n}\sigma^2\) trên nhiễu rời rạc nhiều mức K (1 << K << n), và viết công thức kiểm định nhị thức hai phía của Boruta quanh MZSA.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy compute_tree_mdi_bias_demo, null_importance_pimp (q_fdr = 0.05), collinearity_cluster_permutation và boruta_shadow_selection trên bộ 5 đặc trưng gồm biến sinh đôi cộng tuyến \(\rho = 0.96\) và biến nhiễu K = 150.
Tiêu chí Đáp án & Số đối chứng
CART MDI xếp noise_cat_K200 (0.622) cao gấp 4x tín hiệu thật (0.154), trong khi OOF Perm trả lại công bằng (+0.302 vs -0.151). PIMP loại sạch noise_cat_150 (pimp_z = -7.91, q = 1.0), Cluster Perm cứu cụm cộng tuyến (6.881 vs sig_twin 0.416), và Boruta chốt CONFIRMED cả sig_linear, sig_twin (23/24), sig_nonlinear.
Bài tập 6 — OOF James–Stein, Signed Hashing ±1, PLR, Cổng LLM & ColumnTransformerDAG Ký HMAC-SHA256
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\mathbb{E}[\langle \phi(x), \phi(x') \rangle] = \langle x, x' \rangle\) khi có hàm dấu \(\xi(i) \in \{\pm 1\}\) và lý giải cơ chế RFF trong PLR. Thiết lập chuỗi xác thực Pipeline từ lọc trong nếp đến lưu trạng thái JSON ký HMAC.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng OOFJamesSteinEncoder(groups=...), SignedFeatureHasher, PeriodicPLREncoder, verify_llm_candidate_features_gate, audit_presplit_vs_infold_leakage, và FeaturePipeline.save_signed_state / load_signed_state (gồm thử nghiệm giả mạo intercept).
Tiêu chí Đáp án & Số đối chứng
OOF James–Stein triệt tiêu quá khớp nội mẫu (0.836 -> 0.692 train, 0.702 test), Signed Hashing đạt độ chệch -0.20 (vs +1.10 Unsigned), PLR giải quyết ngưỡng bậc thang 0.491 -> 0.977, cổng 4 tầng loại 4/5 ứng viên nhiễu, In-Fold CV phá ảo ảnh tiền tách tập 0.878 -> 0.387, và ColumnTransformerDAG đạt lệch lô/đơn 1.11e-16 (0.044 ms) cùng bảo vệ HMAC-SHA256 trước 14/14 pytest.