Chương 05 — Suy luận Nhân quả, Học máy Khử chệch Kép (DML) & Mô hình Hóa Uplift Cho Tác động Kinh doanh Gia tăng
Từ Pearl SCMs, d-Separation, Berkson Collider (-0.500), Backdoor/Frontdoor/do-Calculus, Rubin Potential Outcomes, Doubly Robust AIPW & Overlap Weighting (ATO) đến 5-Fold Cross-Fitted DML2 (90% vs 0% Coverage), S/T/X/R/DR-Learner, Honest Causal Tree, Qini/AUUC, DoWhy Refutation/E-Value & Chuyên đề #3 Churn vs Incremental Uplift (+$118,500 Swing).
Unit ID:
T1-P1-U05
Track & Part: Track 1 (DSAI) — Part 1: Mathematical Foundations, Statistical Inference & Causal Decision Science (part-01-math-stats-and-causal)
Truy xuất Giáo trình Gốc (R27,R28,E27:E28& Chuyên đề#3): Hoàn thiện mảnh ghép cuối của Lesson 3R28(Causal analysis, nối tiếp trực tiếp từ Đại số Nghịch lý Simpson và Đóng khung Giai đoạn 1 ởch-04-ml-lifecycle-reproducible-oop-and-eda.md), phủ trọn vẹn đề án hợp nhấtE27:E28(Implement an end2end data science project from EDA to causal analysis to understand business impacts), và tích hợp toàn văn Bài viết Chuyên sâu#3(From Churn Prediction to Incremental Impact).
Bài thực hành Song hành (Lab 02):labs/lab-02-eda-to-causal-uplift-pipeline/(causal_uplift_lab)
Tình huống Mở đầu: Vì sao Mô hình Dự báo Tốt Nhất (AUC = 0.84) Vẫn Làm Phá sản Chiến dịch Giữ chân Khách hàng?#
Ở Chương 04, chúng ta đã dựng hàng rào Split-First, kiểm toán rò rỉ tiền tách tập, và giải mã Nghịch lý Simpson ở tầng EDA. Nhưng ngay cả khi bảng dữ liệu Point-in-Time đã sạch 100% rò rỉ và mô hình dự báo đạt độ chính xác cao, việc dùng học máy dự báo (\(\mathbb{E}[Y \mid X=x]\)) để ra quyết định can thiệp (\(\mathbb{E}[Y(1) - Y(0) \mid X=x]\)) vẫn gây ra bốn thảm họa kinh tế và thống kê trong sản xuất:
- Thảm họa $118,500 từ Nhắm Mục tiêu theo Rủi ro Rời bỏ (Article
#3): Một công ty viễn thông/SaaS huấn luyệnXGBoostdự báo xác suất rời bỏ \(\hat{p}_{\text{churn}}(x)\) rồi gửi cuộc gọi giữ chân ($5chi phí liên hệ) kèm phiếu giảm giá$25(nếu gia hạn, trên giá trị vòng đờiV = $200) cho Top-30% khách hàng rủi ro cao nhất (3,000trên10,000thuê bao). Kết quả kiểm toán thực tế cho thấy nhóm Top-30% này toàn là Lost Causes (khách hàng đã chuyển sang đối thủ, tỷ lệ ở lại chỉ nhích từ10% -> 11%), khiến chiến dịch lỗ ròng-$17,250(ROI = -0.742)! Còn gửi đại trà cho cả10,000người (Treat-All) kích hoạt nhóm Sleeping Dogs (thuê bao tự gia hạn âm thầm bị nhắc nhớ nên hủy ngay, tỷ lệ ở lại tụt75% -> 55%), gây lỗ thảm khốc-$69,750. Ngược lại, nhắm Top-30% theo tác động gia tăngCATEthu về+$101,250(ROI = +1.588) — cú lội ngược dòng+$118,500trên cùng một tập khách hàng! - Ảo ảnh Thiên lệch Chọn lọc & Lệch Collider (
Berkson r = -0.500): Khi dữ liệu quan sát được chọn lọc bởi một biến hậu quả chung \(C\) (ví dụ: chỉ khảo sát khách hàng mở phiếu hỗ trợ hoặc tuyển dụng qua 2 tiêu chí độc lập), phép điều kiện hóa vô tình tạo ra tương quan âm giả-0.500giữa hai biến hoàn toàn độc lập; tương tự, đưa biến trung gian hoặc biến sau quyết định vào tập điều chỉnhXGBoostxóa sổ hoặc đảo ngược hoàn toàn hiệu ứng nhân quả thật. - Sụp đổ Hỗ trợ Chung (
Positivity Collapse) & Thiên lệch Điều chuẩnML(0%Độ phủ): Trong dữ liệu tín dụng/y tế quan sát (Case 5), khi điểm xu hướng \(e(x)\) tiến sát0hoặc1(max_wt = 1,091.4x), ước lượng ngây thơ báo hiệu ứng giả+0.4969(+49.7 ppkhi hiệu ứng thật bằng0.0000!) vàIPWkhông cắt ngưỡng bị sập cỡ mẫu hiệu dụngESS. Song song đó, dùng thẳng mô hình ML điều chuẩnL1/L2/cây quyết định để khử nhiễu đa chiều (d = 350) theo kiểu plug-in làm độ phủ khoảng tin cậy95%rơi thẳng về0%do thiên lệch co rútO(n^{-1/4}). - Sụp đổ Khi Nối Nhầm Mô hình Nhân quả Không Trung thực (
In-Sample / Non-Honest Overfit): Khớp các hàm nhiễu ML trên cùng tập mẫu dùng để tính phần dư (In-Sample DML, không dùngCross-Fitting) phá vỡ tính trực giao Neyman và làm độ phủ95%tụt xuống55%, trong khi cây nhân quả không trung thực khuếch đại nhiễu cực trị ở các lá.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn học phần T1-P1-U05 (ch-05 và causal_uplift_lab), học viên có đủ năng lực để:
- Làm chủ Hình thức luận Nhân quả Pearl (
SCMs,DAGs,do-Calculus): Phân biệt rạch ròi điều kiện hóa quan sát \(P(Y \mid W, X)\) và can thiệp \(P(Y \mid do(W=w), X)\); thành thạo các quy tắc \(d\)-separation cho Chuỗi (Chain), Chẽ ba (Fork), Hội tụ (Collider) và Bẫy chữ M (M-Bias); chứng minh định lượng thiên lệch chọn lọc Collider/Berkson (\(\rho = -0.500\)); chứng minh công thức điều chỉnh Backdoor và Frontdoor từ 3 Quy tắcdo-Calculus; và hiểu tính đầy đủ của thuật toánID. - Thiết lập Định danh Neyman–Rubin & Ước lượng Bán tham số Bền vững Kép (
IPW,ATO,AIPW): Nắm vững \(Y(1), Y(0)\),ATE/ATT/ATC/ATO/CATE, 3 giả địnhSUTVA,Conditional Ignorability,Positivity; chứng minh Định lý Điểm xu hướng Rosenbaum–Rubin; chứng minh vì saoHT-IPWnổ phương sai và vượt biên[0, 1]cònHájekbất biến dịch chuyển; chứng minh đại số tính Bền vững KépAIPW(nhất quán khi chỉ cần \(\hat{\mu}_w\) hoặc \(\hat{e}\) đúng); và giải quyết sụp đổ positivity bằng Trọng số Chồng lấn (Overlap Weighting ATO) cùngESSKish. - Chứng minh & Triển khai
Double/Debiased ML(DML): Chứng minh thiên lệch điều chuẩn làmNaive Plug-in MLphân kỳ \(\Theta(n^{1/2-\varphi_g})\); chứng minh tính Trực giao Neyman của hàm điểm Robinson (\(\partial_r \mathbb{E}[\psi]|_{r=0} = 0\)) và cận tích sai số bậc hai \(o(n^{-1/2})\) cho phép học máy hội tụ tốc độ \(n^{-1/4}\); cài đặt \(K\)-Fold Cross-Fitting (DML2) và ước lượng phương sai sandwich bất phương sai. - Xây dựng, Đánh giá & Phản bác Hệ thống
Uplift Modeling(CATE& Article#3): Giải phẫu 5 Meta-Learners (S,T,X,R,DR-Learner), Cây & Rừng Nhân quả Trung thực (\(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\), tiêu chuẩnEMSE,GRF,IJ/BLB); đánh giá không phản thực quaUplift@k,AUUC,Qini, chứng minh tính bất thiên vị và bẫy phương sai của \(Y^*\), và xếp hạng ngoài mẫu quaR-loss/DR-loss; thực thi bộ phản bácDoWhy(Placebo,Random Common Cause,Subset), Cinelli–HazlettOVB(\(RV_q\)),E-valueVanderWeele–Ding, và Cận Rosenbaum \(\Gamma\). - Làm chủ Chuyên đề
#3& Triển khai Workbench Thuần-NumPy (causal_uplift_lab): Định thức hóa 4 góc phần tư khách hàng (Persuadables, Sure Things, Lost Causes, Sleeping Dogs), tối ưu hóa chiến dịch giữ chân bằng quy tắc \(\Pi(x) = \tau(x)V - c_{\text{contact}} - \mu_1(x)d_{\text{incentive}}\) cùng Ba lô 0–1 ROI Biên, vận hành kiến trúc sản xuất< 20 ms p99kèm5%đối chứng khám phá ngẫu nhiên thường trực, và vượt qua toàn bộ15/15ca kiểm thửpytest(lõi tham chiếu thuầnstdlib + numpy + pandas + pydantic, kèm rào chắn AST Chỉ Bảo mật cấm tuyệt đốipickle/joblib/cloudpickle).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P1-U05)#
Nội dung Gốc (R27, R28, E27:E28 & #3) |
Nâng cấp Chuẩn SOTA 2026 (ch-05) |
Mục trong Chương 05 | Mô-đun & Hợp đồng Kiểm thử (causal_uplift_lab) |
|---|---|---|---|
R28 Mục 6: Causal analysis (tiếp nối Đại số Simpson ch-04 §1.4) |
Tương quan vs. do(W=w); Pearl SCM \(M = \langle U, V, F, P(U)\rangle\), Phẫu thuật đồ thị \(G_{\overline{W}}\), Chain/Fork/Collider/M-Bias, \(d\)-separation (Bayes-Ball), chứng minh Schur & Berkson Collider, Backdoor & Frontdoor qua 3 Quy tắc do-Calculus, thuật toán ID |
Trụ cột 1 (§1.1–§1.3) + Mermaid 1 + Widget dag-dsep-collider-explorer |
scm_and_identification.py (CausalDAG, simulate_collider_berkson_bias, simulate_simpson_vs_backdoor), Tests 1, 2, 3 |
Potential Outcomes & Bán tham số (Syllabus ch-05) |
Neyman–Rubin \(Y(1), Y(0)\), ATE/ATT/ATC/ATO/CATE, SUTVA/Ignorability/Positivity, Rosenbaum–Rubin, phê bình PSM King–Nielsen, HT vs. Hájek IPW, Chứng minh Bền vững Kép AIPW, cận hiệu quả Hahn \(V_{\text{eff}}\), Overlap Weighting ATO & Kish ESS |
Trụ cột 1 (§1.4–§1.5) + Trụ cột 3 (Case 5) | estimators_and_dml.py (estimate_ipw, estimate_overlap_ato, estimate_aipw, compute_kish_ess), Tests 4, 5 |
Double/Debiased ML (DML) (Syllabus ch-05) |
PLR & IRM, chứng minh phân kỳ Naive Plug-in \(\Theta(n^{1/2-\varphi_g})\), Robinson residualization, Chứng minh Trực giao Neyman & Cận \(o(n^{-1/2})\), \(K\)-Fold Cross-Fitting (DML1/DML2 & bẫy Donsker In-Sample), phương sai sandwich \(\hat{\sigma}^2\), LinearDML / NonParamDML |
Trụ cột 2 (§2.1) + Mermaid 2 + Widget dml-orthogonality-simulator |
estimators_and_dml.py (estimate_naive_plugin, estimate_dml_plr, simulate_plr_dml_ablation), Test 6 |
Uplift Modeling & Honest Causal Forests (Syllabus ch-05) |
5 Meta-Learners (S, T, X, R, DR-Learner); Honest Causal Trees/GRF (\(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\), EMSE, IJ/BLB); Uplift@k, AUUC, Qini Radcliffe có IPW, chứng minh \(Y^*\) & bẫy phương sai, R-loss / DR-loss; Refutation (DoWhy) & Sensitivity (OVB RV_q, E-value, Rosenbaum \(\Gamma\)); Conformal ITE, PolicyTree, CausalPFN |
Trụ cột 2 (§2.2–§2.5) + Trụ cột 3 | uplift_roi_and_qini.py (SLearner, TLearner, XLearner, RLearner, DRLearner, HonestCausalTree, compute_qini_and_auuc, compute_r_and_dr_loss), scm_and_identification.py (run_refutation_suite, compute_e_value, compute_cinelli_hazlett_rv), Tests 7, 8, 9, 12 |
Bài viết #3 + Lab E27:E28 (From Churn Prediction to Incremental Impact) |
Phá vỡ nhắm Top-\(P(\text{churn})\); 4 Góc phần tư (Persuadables, Sure Things, Lost Causes, Sleeping Dogs); mô hình lợi nhuận \(\Pi(x)\) & Ba lô 0–1 ROI Biên; bài toán 10,000 thuê bao (+$118,500 swing) + thực nghiệm Retention 4,000/2,000; DoWhy/EconML + 5 Case (Criteo, Uber, Booking.com, Telco, FinTech/ICU) + kiến trúc < 20 ms p99 |
Trụ cột 3 (§3.1–§3.4) + Trụ cột 4 + Mermaid 3 + Widget churn-vs-uplift-qini-arena |
uplift_roi_and_qini.py (optimize_knapsack_retention_policy, audit_worked_10k_churn_vs_uplift, run_full_causal_uplift_benchmarks), scripts/run_lab_demo.py, Tests 10, 11, 13, 14 |
Bảng Ký hiệu Toán học, Quy ước Dấu & Khử trùng lặp (Unified Notation & Sign Policy)#
Quy ước Dấu Bất biến Xuyên suốt Chương 05 &
causal_uplift_lab(Article#3):
- Kết cục Chính — Tỷ lệ Giữ chân / Gia hạn (\(Y_i \in \{0, 1\}\)): \(Y_i = 1\) nghĩa là khách hàng ở lại / gia hạn, \(Y_i = 0\) nghĩa là khách hàng rời bỏ (churn). Do đó \(\tau(x) := \mathbb{E}[Y(1) - Y(0) \mid X=x] = \mu_1(x) - \mu_0(x) > 0\) mang nghĩa can thiệp cứu được khách hàng.
- Biểu diễn Đối ngẫu Rủi ro Rời bỏ (\(C_i := 1 - Y_i\)): Rủi ro rời bỏ nền là \(p_{\text{churn}}^{(0)}(x) := 1 - \mu_0(x)\), và thay đổi rủi ro rời bỏ bằng đúng \(-\tau(x)\).
- Phân biệt Ký hiệu Kế thừa từ
ch-03&ch-04:
- \(e(x)\) vs. \(\exp(\cdot)\) vs. \(E_{\text{sens}}\): Ký hiệu \(e(x) := \mathbb{P}(W=1 \mid X=x)\) dành riêng cho điểm xu hướng; viết \(\exp(\cdot)\) cho hàm mũ; viết \(E_{\text{sens}}\) cho
E-valueVanderWeele–Ding (tách khỏie-value tuần tự \(E_t\) củach-03và mã hóa \(\hat{e}_c\) củach-04).- \(\mu_w(x)\) & \(\ell_0(x)\): Luôn gắn chỉ số nhánh \(w \in \{0, 1\}\) cho mặt hồi quy kết cục \(\mu_w(x) := \mathbb{E}[Y \mid X=x, W=w]\), và dùng \(\ell_0(x) := \mathbb{E}[Y \mid X=x]\) trong
DML(tách khỏi tiên nghiệm toàn cục \(\mu_0\) củach-04).- \(W_i\), \(\pi_{\text{trt}}\), \(\omega_i\), \(\pi_{\text{pol}}\): \(W_i \in \{0, 1\}\) là biến can thiệp nhị phân; \(\pi_{\text{trt}} := \mathbb{P}(W=1)\) là tỷ lệ can thiệp; \(\omega_i^{\text{HT}}, \omega_i^{\text{Hájek}}, \omega_i^{\text{OW}}\) là trọng số cân bằng; \(\pi_{\text{pol}} : \mathcal{X} \to \{0, 1\}\) là chính sách quyết định.
- \(\Pi(x)\) vs. \(\mathcal{P}_{\text{tree}}\): Dành \(\Pi(x) := \tau(x)V(x) - c_{\text{contact}} - \mu_1(x)d_{\text{incentive}}\) cho Lợi nhuận Gia tăng Ròng Kỳ vọng, và viết \(\mathcal{P}_{\text{tree}}\) cho phân hoạch cây nhân quả trung thực (
I_split,I_est).- \(\boldsymbol{\phi}(X)\) vs. \(\phi\): Chữ đậm \(\boldsymbol{\phi}(X) \in \mathbb{R}^p\) là không gian đặc trưng phi tuyến; vô hướng \(\phi = k/N \in [0, 1]\) là tỷ lệ bao phủ mục tiêu trên đường cong
Qini.
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-05) |
Ký hiệu Mã nguồn (causal_uplift_lab) |
|---|---|---|---|
| \(N, n_1, n_0\) | \(\mathbb{N}_+\) | Tổng mẫu \(N = n_1 + n_0\); \(n_1 = \sum W_i\), \(n_0 = N - n_1\) | n_samples, n_treated, n_control |
| \(X_i \in \mathbb{R}^d, \boldsymbol{\phi}(X_i)\) | Vector | Hiệp biến tiền can thiệp; ánh xạ cơ sở phi tuyến 16 chiều | X, build_nonlinear_basis(X) |
| \(W_i \in \{0, 1\}, Y_i \in \mathbb{R}\) | Nhị phân, Thực | Can thiệp (1 nhận ưu đãi, 0 đối chứng); kết cục (1=ở lại) |
w, y |
| \(Y_i(1), Y_i(0), \tau_i\) | Thực | Kết quả tiềm năng Rubin; ITE \(\tau_i = Y_i(1) - Y_i(0)\) |
y1, y0, tau_true |
| \(\tau(x), \tau_{\text{ATE}}, \tau_{\text{ATT}}, \tau_{\text{ATO}}\) | \(\mathbb{R}\) | CATE \(\mathbb{E}[Y(1)-Y(0)\mid X=x]\); ATE, ATT, Overlap ATO |
tau_hat, ate, att, ato |
| \(e(x), \hat{e}(x), \eta\) | \((0, 1)\) | Điểm xu hướng \(\mathbb{P}(W=1\mid X=x)\); ngưỡng overlap \(\eta\) | e_hat, propensity_clip |
| \(\mu_w(x), \ell_0(x), m_0(x)\) | \(\mathbb{R}\) | \(\mathbb{E}[Y\mid X=x,W=w]\), \(\mathbb{E}[Y\mid X=x]\), \(\mathbb{E}[W\mid X=x]\) | mu0_hat, mu1_hat, l_hat, m_hat |
| \(\tilde{Y}_i, \tilde{W}_i\) | \(\mathbb{R}\) | Phần dư ngoài nếp DML \(Y_i - \hat{\ell}^{(-k)}(X_i)\), \(W_i - \hat{m}^{(-k)}(X_i)\) |
y_res, w_res |
| \(\hat{\psi}_{\text{AIPW}, i}, \tilde{Y}_{\text{DR}, i}\) | \(\mathbb{R}\) | Hàm điểm & giả kết cục bền vững kép AIPW/DR |
psi_scores, y_dr |
| \(M = \langle U, V, F, P(U)\rangle, G_{\overline{W}}, G_{\underline{W}}\) | SCM / DAG | Mô hình nhân quả cấu trúc; đồ thị cắt mũi tên vào/ra \(W\) | CausalDAG, subgraph_without_outgoing |
| \(\mathcal{I}^{\text{split}}, \mathcal{I}^{\text{est}}, \mathcal{P}_{\text{tree}}\) | Tập, Cây | Tập chia nhánh & ước lượng rời nhau trong Cây Trung thực | HonestCausalTree, honest=True |
| \(Q(\phi), \text{AUUC}, q_{\text{Qini}}\) | \(\mathbb{R}\) | Đường cong Qini, Diện tích dưới đường cong Uplift, Hệ số Qini | qini_excess, auuc_excess, qini_norm |
| \(V, c_{\text{contact}}, d_{\text{incentive}}, \Pi(x)\) | \(\mathbb{R}\) | Giá trị vòng đời LTV, chi phí liên hệ, ưu đãi khi gia hạn, lợi nhuận ròng | ltv_value, contact_cost, incentive_cost |
| \(E_{\text{sens}}, RV_q, \Gamma\) | \(\mathbb{R}_{\ge 1}, [0,1]\) | E-value VanderWeele–Ding, Độ vững Cinelli–Hazlett, Cận Rosenbaum | e_value_point, rv_q |
Trụ cột 1 — Nền tảng Toán học & Lý thuyết Suy luận Nhân quả (First-Principles Mathematical & Theoretical Rigor)#
1.1 Từ Nghịch lý Simpson (ch-04) đến Phẫu thuật Can thiệp do(W=w)#
Ở ch-04 (§1.4), khi đối chiếu hai nhánh giao diện A và B trên hai tầng lưu lượng \(S \in \{1, 2\}\) (Cold Mobile vs. Returning Desktop), ta chứng minh được đẳng thức phân rã:
Nhánh A thắng B đúng +5.0 pp ở cả hai phân khúc (\(20\%\) vs \(15\%\) và \(85\%\) vs \(80\%\)), nhưng lại thua thảm -47.0 pp ở bảng cộng gộp (26.5% vs 73.5%). Phép Chuẩn hóa Trực tiếp (Direct Standardization) dùng tỷ trọng gộp \(P(S=s)\) đã khôi phục kết luận đúng -5.0 pp.
Vì sao cùng một bảng số liệu \(P(W, S, Y)\), có lúc ta BẮT BUỘC phải chuẩn hóa theo \(S\), nhưng có lúc chuẩn hóa theo \(S\) lại PHÁ HỦY kết luận?
Viết biểu thức xác suất biên khi quan sát \(W=w\) ("Seeing"):
so với phân phối khi cưỡng chế can thiệp \(do(W=w)\) lên toàn bộ quần thể ("Doing"):
Nếu \(S\) là biến trung gian hậu can thiệp (\(W \to S \to Y\), ví dụ: thuốc hạ đường huyết \(W\) làm giảm đường huyết \(S\), qua đó giảm biến chứng \(Y\)) hoặc biến hội tụ (Collider) (\(W \to S \leftarrow Y\)), thì cả hai đồ thị hoàn toàn khác nhau vẫn tạo ra cùng một bảng tần suất đồng thời \(P(W, S, Y)\)! Thực nghiệm simulate_simpson_vs_backdoor trong causal_uplift_lab minh họa trực diện hai cực đối nghịch này: khi \(S\) là biến hỗn tạp (confounder), chuẩn hóa cửa sau lật hiệu ứng sai lệch +0.4563 về đúng -0.0593 (sát chân lý -0.0500); ngược lại, khi \(M\) là biến trung gian trên chuỗi \(W \to M \to Y\) với tổng tác động thật +0.4046, việc điều kiện hóa theo \(M\) triệt tiêu toàn bộ tín hiệu xuống còn +0.0001 (overcontrol bias)! Đại số xác suất thuần túy không nhìn thấy chiều mũi tên—ta buộc phải dựng Mô hình Nhân quả Cấu trúc (SCM).
| Chiều so sánh | Điều kiện hóa Quan sát (Seeing: \(P(Y \mid W=w, X=x)\)) | Can thiệp Cấu trúc (Doing: \(P(Y \mid do(W=w), X=x)\)) |
|---|---|---|
| Cơ chế toán học | Lọc tập dữ liệu thụ động về lát cắt nơi các cá thể tình cờ mang \(W=w\) (kế thừa quy tắc chọn lịch sử \(P(W \mid X, U)\)). | Phẫu thuật cơ chế sinh dữ liệu DGP: ghi đè phương trình gán \(W \leftarrow w\), cắt đứt mọi mũi tên đi vào \(W\). |
| Độ bất biến khi đổi chính sách | Sụp đổ ngay khi chính sách phân bổ hành động \(\pi_{\text{new}}(w \mid x) \neq \pi_{\text{obs}}(w \mid x)\) thay đổi trong sản xuất. | Bất biến qua mọi chính sách điều phối \(\pi_{\text{new}}\) chừng nào các cơ chế hậu quả khác còn giữ nguyên (autonomy). |
Lỗi kinh điển của ERM dự báo |
Học các biến proxy nhiễu \(U\), điều chỉnh nhầm đặc trưng hậu can thiệp \(M/C\), hoặc xếp hạng theo rủi ro nền thay vì độ nhạy \(\tau(x)\). | Cô lập trực tiếp tác động cận biên khi đổi hành động \(W=0 \to W=1\) cho cùng một cá thể \(X=x\). |
1.2 Mô hình Nhân quả Cấu trúc Pearl (SCM), \(d\)-Separation & Chứng minh Lệch Collider / Berkson#
Định nghĩa 1.1 (SCM & Phẫu thuật Đồ thị)#
Một Mô hình Nhân quả Cấu trúc (Structural Causal Model, Pearl 2009) là bộ tứ \(M = \langle U, V, F, P(U)\rangle\):
- \(U = \{U_1, \dots, U_m\}\) là tập các biến ngoại sinh (exogenous) có phân phối chung \(P(U)\) (nếu các \(U_j\) độc lập đôi một và mỗi \(U_j\) chỉ xuất hiện trong một phương trình, \(M\) gọi là Markovian; nếu chia sẻ nhiễu ẩn gây tương quan sai số, \(M\) là Semi-Markovian).
- \(V = \{V_1, \dots, V_p\}\) là các biến nội sinh quan sát được, xác định theo thứ tự tô-pô của đồ thị có hướng không chu trình
DAG\(G = (V, E)\) qua hệ phương trình cơ chế bất đối xứng:\[V_j \leftarrow f_j(\operatorname{PA}_j, U_j), \qquad j = 1, \dots, p.\] - Định lý Phân tử hóa Markov Nhân quả: Mọi
SCMMarkovian đều phân tử hóa duy nhất dọc theoDAG\(G\):\[P(v_1, \dots, v_p) = \prod_{j=1}^p P(v_j \mid \operatorname{pa}_j).\](Chứng minh tóm tắt: sắp xếp tô-pô \(V_1, \dots, V_p\); bằng quy nạp mỗi \(V_k\) (\(k<j\)) là hàm của \((U_1, \dots, U_k)\) nên độc lập với \(U_j\), suy ra \(V_j \perp (V_1, \dots, V_{j-1})\setminus \operatorname{PA}_j \mid \operatorname{PA}_j\).) - Phẫu thuật Can thiệp (
Graph Surgery) & Công thức Cắt cụt (Truncated Factorization): Can thiệp \(do(W = w)\) tạo mô hình con \(M_w\) bằng cách xóa toàn bộ mũi tên đi vào \(W\) (đồ thị \(G_{\overline{W}}\)) và khóa \(W \leftarrow w\):\[P_M(v_1, \dots, v_p \mid do(W=w)) = \begin{cases} \displaystyle\prod_{j:\, V_j \neq W} P(v_j \mid \operatorname{pa}_j) = \frac{P(v_1, \dots, v_p)}{P(w \mid \operatorname{pa}_W)}, & \text{nếu } v_W = w \text{ và } P(w \mid \operatorname{pa}_W) > 0, \\ 0, & \text{nếu } v_W \neq w. \end{cases}\]
Ba Cấu trúc Cơ sở, Bẫy M-Bias & Quy tắc \(d\)-Separation (Bayes-Ball)#
Trên một đường đi vô hướng bất kỳ \(p = (v_0 = A, v_1, \dots, v_k = B)\) trong DAG \(G\), một đỉnh nội tiếp \(m\) bị chặn (blocked) bởi tập điều kiện \(\mathbf{S}\) khi và chỉ khi thỏa một trong hai quy tắc:
- Quy tắc Phi-Hội tụ (
Chain\(i \to m \to j\) hoặcFork\(i \leftarrow m \to j\)): đường đi bị chặn khi và chỉ khi \(m \in \mathbf{S}\) (điều kiện hóa vào cầu nối hoặc nguyên nhân chung sẽ đóng luồng thông tin). - Quy tắc Hội tụ (
Collider\(i \to m \leftarrow j\)): đường đi bị chặn khi và chỉ khi không bản thân \(m\) lẫn bất kỳ hậu duệ nào của \(m\) nằm trong \(\mathbf{S}\), tức \(\big(\{m\} \cup \operatorname{DE}(m)\big) \cap \mathbf{S} = \emptyset\). Ngược lại, đưa \(m\) (hoặc hậu duệ \(D \in \operatorname{DE}(m)\)) vào \(\mathbf{S}\) sẽ mở thông luồng tương quan giữa hai nguyên nhân độc lập \(i\) và \(j\)!
| Cấu trúc Cơ sở | Hình thái DAG |
Khi \(\mathbf{S} = \emptyset\) | Khi đưa nút giữa vào \(\mathbf{S}\) | Bẫy Thực nghiệm Nếu Xử lý Sai |
|---|---|---|---|---|
1. Chuỗi (Chain / Mediator) |
\(W \to M \to Y\) | Mở (\(W \not\perp Y\)) | Đóng (\(W \perp Y \mid M\)) | Lệch kiểm soát quá mức (Overcontrol): Đưa biến hậu can thiệp \(M\) vào mô hình xóa mất tổng tác động \(W \to Y\). |
2. Chẽ ba (Fork / Confounder) |
\(W \leftarrow Z \to Y\) | Mở (\(W \not\perp Y\)) | Đóng (\(W \perp Y \mid Z\)) | Lệch hỗn tạp (Confounding): Bỏ sót \(Z\) giữ nguyên đường cửa sau giả (gây Nghịch lý Simpson). |
3. Hội tụ (Collider) |
\(W \to C \leftarrow Y\) | Đóng (\(W \perp Y\)) | Mở (\(W \not\perp Y \mid C\) hoặc \(D \in \operatorname{DE}(C)\)) | Lệch chọn lọc / Berkson: Lọc dữ liệu theo hậu quả chung \(C\) đẻ ra tương quan giả âm/dương. |
4. Bẫy chữ M (M-Bias) |
\(W \leftarrow U_1 \to C \leftarrow U_2 \to Y\) | Đóng sẵn tại \(C\) (\(\mathbf{S}=\emptyset\) không lệch!) | Mở (\(W \not\perp Y \mid C\) qua \(U_1, U_2\) ẩn) | Ngụy biện "gom hết biến tiền can thiệp": Đưa \(C\) vào tập điều chỉnh khi \(U_1, U_2\) ẩn sẽ tự tiêm thiên lệch mới! |
Chứng minh Định lượng Lệch Collider / Chọn lọc Berkson (Schur Complement & Cohort \(N=400\))#
Phần A — Chứng minh Tuyến tính–Gaussian (Kế thừa Bù Schur từ ch-03 §1.2):
Xét hai nguyên nhân độc lập biên tuyệt đối \(X \sim \mathcal{N}(0, \sigma_X^2)\) và \(Y \sim \mathcal{N}(0, \sigma_Y^2)\) (\(X \perp\!\!\!\perp Y\), \(\operatorname{Cov}(X, Y) = 0\)) cùng gây ra biến hội tụ \(C = \alpha X + \beta Y + \varepsilon_C\) với \(\varepsilon_C \sim \mathcal{N}(0, \sigma_\varepsilon^2)\) độc lập \((X, Y)\) và \(\alpha, \beta \neq 0\). Khi đó \(\sigma_C^2 := \operatorname{Var}(C) = \alpha^2\sigma_X^2 + \beta^2\sigma_Y^2 + \sigma_\varepsilon^2\), \(\operatorname{Cov}(X, C) = \alpha\sigma_X^2\), và \(\operatorname{Cov}(Y, C) = \beta\sigma_Y^2\). Áp dụng công thức Bù Schur cho phân phối Chuẩn nhiều chiều \((X, Y, C)^\top \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma})\) khi điều kiện hóa trên \(C = c\):
Từ các phần tử của \(\boldsymbol{\Sigma}_{(X,Y)\mid C}\) suy ra chính xác phương sai, hiệp phương sai và tương quan có điều kiện:
Kiểm tra bằng ma trận chính xác \(\boldsymbol{\Lambda}_{(X,Y)} = \boldsymbol{\Sigma}_{(X,Y)\mid C}^{-1}\) cho phần tử ngoài đường chéo \(\Lambda_{XY} = \frac{\alpha\beta}{\sigma_\varepsilon^2} \neq 0\), chứng tỏ \(X \not\perp\!\!\!\perp Y \mid C\). Với \(\sigma_X = \sigma_Y = \alpha = \beta = \sigma_\varepsilon = 1\): lý thuyết cho \(\operatorname{Cov}(X, Y \mid C) = -1/3\) và \(\operatorname{Corr}(X, Y \mid C) = \mathbf{-0.5000}\) (trong mô phỏng \(N=15{,}000\) của causal_uplift_lab, tương quan biên là +0.0103, tương quan riêng điều kiện hóa trên \(C\) đạt -0.4932 và lát cắt \(|C| \le 0.35\) đạt -0.4924). \(\blacksquare\)
Phần B — Phản ví dụ Rời rạc Berkson (N = 400):
Giả sử \(400\) ứng viên có Kỹ năng Kỹ thuật \(X \in \{0, 1\}\) và Tư duy Sản phẩm \(Y \in \{0, 1\}\) độc lập hoàn toàn với đúng 100 người ở mỗi ô \((1,1), (1,0), (0,1), (0,0)\) (\(\operatorname{Corr}(X, Y) = \mathbf{0.000}\)). Nếu bộ phận tuyển dụng chỉ xét nhóm đạt ít nhất một tiêu chí \(C = \mathbb{I}[X=1 \lor Y=1]\) (\(n=300\), loại bỏ 100 người ô \((0,0)\)), ta thu được:
1.3 Tiêu chuẩn Cửa sau (Backdoor), Cửa trước (Frontdoor) & Ba Quy tắc do-Calculus#
Ba Quy tắc do-Calculus & Thuật toán ID (Pearl 1995; Shpitser & Pearl 2006)#
Ký hiệu \(G_{\overline{X}}\) là đồ thị xóa mũi tên vào \(X\), \(G_{\underline{X}}\) là đồ thị xóa mũi tên ra khỏi \(X\), và \(Z(W)\) là tập các nút trong \(Z\) không phải tổ tiên của \(W\) trong \(G_{\overline{X}}\):
- Quy tắc 1 (Thêm/Bớt Quan sát): \(P(y \mid do(x), z, w) = P(y \mid do(x), w)\) nếu \((Y \perp_d Z \mid X, W)_{G_{\overline{X}}}\).
- Quy tắc 2 (Đổi Can thiệp \(\leftrightarrow\) Quan sát): \(P(y \mid do(x), do(z), w) = P(y \mid do(x), z, w)\) nếu \((Y \perp_d Z \mid X, W)_{G_{\overline{X}\underline{Z}}}\).
- Quy tắc 3 (Thêm/Bớt Can thiệp): \(P(y \mid do(x), do(z), w) = P(y \mid do(x), w)\) nếu \((Y \perp_d Z \mid X, W)_{G_{\overline{X},\overline{Z(W)}}}\).
Huang–Valtorta (2006) và Shpitser–Pearl (2006) chứng minh 3 quy tắc này là đầy đủ (complete): mọi đại lượng \(P(y \mid do(x))\) nhận dạng được phi tham số đều rút gọn được bằng một chuỗi hữu hạn Quy tắc 1–3. Thuật toán ID đa thức phân tách đồ thị thành các thành phần hỗn tạp ẩn (C-components) nối bằng cung hai chiều \(V_i \leftrightarrow V_j\) và chỉ thất bại khi tồn tại cấu trúc hàng rào (hedge).
Định lý Điều chỉnh Cửa sau (Backdoor Criterion)#
Tập biến \(\mathbf{Z}\) thỏa Tiêu chuẩn Cửa sau cho \((W, Y)\) khi: (1) \(\mathbf{Z} \cap \operatorname{DE}(W) = \emptyset\) (không chứa bất kỳ hậu duệ nào của \(W\)); và (2) \((Y \perp_d W \mid \mathbf{Z})_{G_{\underline{W}}}\) (chặn mọi đường đi chứa mũi tên vào \(W\)). Khi đó (với \(P(W=w, \mathbf{Z}=\mathbf{z}) > 0\)):
Chứng minh nhanh bằng do-Calculus: Khai triển \(P(y \mid do(w)) = \sum_{\mathbf{z}} P(y \mid do(w), \mathbf{z}) P(\mathbf{z} \mid do(w))\). Nhờ Điều kiện (2) và Quy tắc 2 trên \(G_{\underline{W}}\), \(P(y \mid do(w), \mathbf{z}) = P(y \mid w, \mathbf{z})\). Nhờ Điều kiện (1), mọi đường từ \(W\) tới \(\mathbf{Z}\) trong \(G_{\overline{W}}\) đều phải đảo chiều qua ít nhất một collider không được điều kiện hóa (do tập điều kiện là \(\emptyset\)), nên \((\mathbf{Z} \perp_d W)_{G_{\overline{W}}}\) và Quy tắc 3 rút gọn \(P(\mathbf{z} \mid do(w)) = P(\mathbf{z})\). \(\blacksquare\)
Định lý Điều chỉnh Cửa trước (Frontdoor Criterion) — Chứng minh Từng bước#
Khi tồn tại biến hỗn tạp không quan sát được \(U\) (\(W \leftarrow U \to Y\)) làm tiêu chuẩn Cửa sau sụp đổ, ta vẫn nhận dạng được tác động nhân quả nếu tồn tại tập biến trung gian quan sát được \(\mathbf{M}\) thỏa 3 điều kiện Cửa trước: (1) \(\mathbf{M}\) chặn tất cả đường đi có hướng từ \(W\) đến \(Y\); (2) không có đường cửa sau hở từ \(W\) đến \(\mathbf{M}\), tức \((W \perp_d \mathbf{M})_{G_{\underline{W}}}\); và (3) \(W\) chặn mọi đường cửa sau từ \(\mathbf{M}\) đến \(Y\), tức \((\mathbf{M} \perp_d Y \mid W)_{G_{\underline{\mathbf{M}}}}\). Khi đó:
Chứng minh 5 bước từ 3 Quy tắc do-Calculus:
- Khai triển theo \(\mathbf{M}\): \(P(y \mid do(w)) = \sum_{\mathbf{m}} P(y \mid do(w), \mathbf{m})\, P(\mathbf{m} \mid do(w))\).
- Dùng Điều kiện (2) \((W \perp_d \mathbf{M})_{G_{\underline{W}}}\) và Quy tắc 2: \(P(\mathbf{m} \mid do(w)) = P(\mathbf{m} \mid w)\).
- Vì \(G_{\overline{W}\underline{\mathbf{M}}}\) là đồ thị con của \(G_{\underline{\mathbf{M}}}\), Điều kiện (3) kéo theo \((Y \perp_d \mathbf{M} \mid W)_{G_{\overline{W}\underline{\mathbf{M}}}}\), nên Quy tắc 2 đổi quan sát \(\mathbf{m}\) thành can thiệp: \(P(y \mid do(w), \mathbf{m}) = P(y \mid do(w), do(\mathbf{m}))\).
- Trong \(G_{\overline{\mathbf{M}}\overline{W}}\), cả \(W\) lẫn \(\mathbf{M}\) đều không có mũi tên đi vào nên \(\mathbf{M}\) không mở bất kỳ collider nào; mọi đường thông từ \(W\) tới \(Y\) phải là đường có hướng né \(\mathbf{M}\), mà Điều kiện (1) cấm điều này! Do vậy \((Y \perp_d W \mid \mathbf{M})_{G_{\overline{\mathbf{M}}\overline{W}}}\), và Quy tắc 3 xóa bỏ \(do(w)\): \(P(y \mid do(w), do(\mathbf{m})) = P(y \mid do(\mathbf{m}))\).
- Khai triển \(P(y \mid do(\mathbf{m})) = \sum_{w'} P(y \mid do(\mathbf{m}), w') P(w' \mid do(\mathbf{m}))\): Quy tắc 2 cùng Điều kiện (3) cho \(P(y \mid do(\mathbf{m}), w') = P(y \mid \mathbf{m}, w')\); đồng thời Điều kiện (2) loại trừ đường có hướng \(\mathbf{M} \to \dots \to W\), nên \((W \perp_d \mathbf{M})_{G_{\overline{\mathbf{M}}}}\) và Quy tắc 3 cho \(P(w' \mid do(\mathbf{m})) = P(w')\). Thế các bước vào (1) hoàn tất chứng minh. \(\blacksquare\)
1.4 Khung Kết quả Tiềm năng Neyman–Rubin, IPW (Horvitz–Thompson vs. Hájek) & Chứng minh AIPW Bền vững Kép#
Kết quả Tiềm năng, Bài toán Cơ bản & Điều kiện Định danh#
Với mỗi đơn vị \(i \in \{1, \dots, N\}\), cặp \((Y_i(1), Y_i(0))\) biểu diễn kết quả tiềm năng dưới can thiệp (\(W_i=1\)) và đối chứng (\(W_i=0\)). Hiệu ứng Cá thể (ITE) \(\tau_i := Y_i(1) - Y_i(0)\) không bao giờ quan sát đồng thời (Fundamental Problem of Causal Inference, Holland 1986) vì ta chỉ thấy \(Y_i = Y_i(W_i)\) còn phản thực \(Y_i(1-W_i)\) bị khuyết vĩnh viễn. Ta nhắm tới bốn đại lượng quần thể liên hệ qua \(\tau_{\text{ATE}} = \pi_{\text{trt}}\tau_{\text{ATT}} + (1 - \pi_{\text{trt}})\tau_{\text{ATC}}\):
Định lý Định danh Phi tham số: Dưới 3 giả định:
SUTVA: (a) Không can nhiễu chéo giữa các cá thể (\(Y_i(\mathbf{W}) = Y_i(W_i)\) — bị vi phạm trong mạng xã hội/sàn giao dịch dùng chung tài xế); (b) Tính nhất quán: \(Y_i = W_i Y_i(1) + (1 - W_i) Y_i(0)\).- Tính Khả bỏ qua Có điều kiện (Conditional Ignorability): \(\big(Y(1), Y(0)\big) \perp\!\!\!\perp W \mid X\) (không có biến hỗn tạp ẩn \(U\)).
- Tính Dương / Hỗ trợ Chung (Positivity / Overlap): \(0 < \eta \le e(x) := \mathbb{P}(W=1 \mid X=x) \le 1 - \eta < 1\).
Khi đó \(\mathbb{E}[Y(w) \mid X=x] \stackrel{\text{Ignorability}}{=} \mathbb{E}[Y(w) \mid X=x, W=w] \stackrel{\text{SUTVA}}{=} \mathbb{E}[Y \mid X=x, W=w] =: \mu_w(x)\), suy ra \(\tau(x) = \mu_1(x) - \mu_0(x)\) và \(\tau_{\text{ATE}} = \mathbb{E}_X[\mu_1(X) - \mu_0(X)]\). \(\blacksquare\)
Định lý Điểm Xu hướng Rosenbaum–Rubin (1983) & Cảnh báo PSM#
Định lý: Nếu \((Y(1), Y(0)) \perp W \mid X\) và \(0 < e(X) < 1\), thì \((Y(1), Y(0)) \perp W \mid e(X)\).
Chứng minh: Do \(W \in \{0, 1\}\), tính độc lập tương đương \(P(W=1 \mid Y(1), Y(0), e(X)) = P(W=1 \mid e(X))\). Dùng Quy tắc Tháp kỳ vọng (LoTE, ch-03) chiếu lên \(X\):
và tương tự \(P(W=1 \mid e(X)) = \mathbb{E}[e(X) \mid e(X)] = e(X)\). Điều này nén chiều điều kiện \(X \in \mathbb{R}^d\) thành vô hướng 1D \(e(X)\). \(\blacksquare\)
(Cảnh báo Nghịch lý King–Nielsen 2019: Không giống ghép cặp Mahalanobis MDM hoặc CEM xấp xỉ thí nghiệm phân khối, Ghép cặp Điểm Xu hướng PSM chỉ xấp xỉ ngẫu nhiên hoàn toàn; sau khi đã cắt lệch thô, siết chặt ngưỡng caliper trên 1D \(e(X)\) lại loại nhầm các cặp có \(X\) khác xa nhau nhưng trùng \(e(X)\), làm tăng mất cân bằng hiệp biến trong không gian con trực giao! Hãy dùng \(\hat{e}(x)\) để đánh trọng số AIPW/ATO/DML thay vì PSM.)
HT-IPW vs. Hájek IPW: Chứng minh Nổ Phương sai, Vượt Biên & Bất biến Dịch chuyển#
Hai biến thể Trọng số Nghịch đảo Xác suất (IPW) dùng \(\omega_{1,i}^{\text{HT}} := \frac{W_i}{\hat{e}(X_i)}\) và \(\omega_{0,i}^{\text{HT}} := \frac{1-W_i}{1-\hat{e}(X_i)}\):
- Nổ phương sai từ kỳ vọng nền \(\mu_w(X)^2\): Với \(e(X)\) đã biết, khai triển \(\operatorname{Var}(\hat{\tau}_{\text{HT}})\) cho:
\[\operatorname{Var}(\hat{\tau}_{\text{HT}}) = \frac{1}{N}\mathbb{E}_X\!\left[\frac{\sigma_1^2(X) + \mu_1(X)^2}{e(X)} + \frac{\sigma_0^2(X) + \mu_0(X)^2}{1 - e(X)} - \tau(X)^2\right] + \frac{1}{N}\operatorname{Var}_X(\tau(X)).\]Ngay cả khi kết cục không nhiễu \(Y(1) \equiv Y(0) \equiv 1{,}000\) (\(\sigma_w^2 = 0, \tau = 0\)), thăng giáng của \(\frac{1}{N}\sum \omega_{w,i}^{\text{HT}} \neq 1\) nhân với hằng số nền \(10^6\) làm phương sai bùng nổ khi \(e(X) \to 0\) hoặc \(1\)!
- Vi phạm biên xác suất & dịch chuyển tịnh tiến: Với \(N=50\), chỉ một mẫu nhận điều trị có \(Y_1=1, \hat{e}(X_1)=0.01\) đã đẩy riêng \(\hat{\mu}_{1,\text{HT}} > \frac{100}{50} = 2.0 > 1.0\) (xác suất \(> 200\%\)), đồng thời \(\hat{\tau}_{\text{HT}}(Y + c) \neq \hat{\tau}_{\text{HT}}(Y)\). Ngược lại, trọng số
Hájekluôn chuẩn hóa tổng bằng1, ép \(\hat{\mu}_{w,\text{Hájek}} \in [\min Y, \max Y]\), giữ nguyên \(\hat{\tau}_{\text{Hájek}}(Y+c) = \hat{\tau}_{\text{Hájek}}(Y)\) và triệt tiêu phần phương sai từ hằng số nền!
Chứng minh Đại số Bền vững Kép AIPW & Cận Hiệu quả Bán tham số Hahn#
Kết hợp hồi quy kết cục \(\hat{\mu}_w(X)\) (G-Computation) và hiệu chỉnh phần dư IPW tạo thành hàm điểm AIPW (Augmented IPW, Robins, Rotnitzky & Zhao 1994):
Định lý Bền vững Kép (Double Robustness): Gọi \((\mu_0^*, \mu_1^*, e^*)\) là giới hạn bất kỳ của bộ ước lượng nhiễu (\(0 < \eta \le e^*(X) \le 1 - \eta < 1\)). Ta chứng minh sai lệch kỳ vọng chính xác của \(\psi_{\text{AIPW}}\):
- Nhánh điều trị \(\psi_1 := \mu_1^*(X) + \frac{W(Y - \mu_1^*(X))}{e^*(X)}\). Vì \(WY = WY(1)\) (
SUTVA), nhóm các số hạng quanh \((\mu_1^*(X) - Y(1))\) rồi dùngLoTEvà Tính Khả bỏ qua \(W \perp\!\!\!\perp Y(1) \mid X\):\[\begin{aligned} \mathbb{E}[\psi_1] - \mathbb{E}[Y(1)] &= \mathbb{E}\!\left[\left(1 - \frac{W}{e^*(X)}\right)\Big(\mu_1^*(X) - Y(1)\Big)\right] \\ &= \mathbb{E}_X\!\left[\,\mathbb{E}\!\left[1 - \frac{W}{e^*(X)} \,\middle|\, X\right]\cdot \mathbb{E}\!\left[\mu_1^*(X) - Y(1) \,\middle|\, X\right]\right] \\ &= \mathbb{E}_X\!\left[\frac{\big(e^*(X) - e(X)\big)\big(\mu_1^*(X) - \mu_1(X)\big)}{e^*(X)}\right]. \end{aligned}\] - Tương tự tuyệt đối cho nhánh đối chứng \(\psi_0 := \mu_0^*(X) + \frac{(1-W)(Y - \mu_0^*(X))}{1-e^*(X)}\):
\[\mathbb{E}[\psi_0] - \mathbb{E}[Y(0)] = -\mathbb{E}_X\!\left[\frac{\big(e^*(X) - e(X)\big)\big(\mu_0^*(X) - \mu_0(X)\big)}{1 - e^*(X)}\right].\]
- Trừ (2) khỏi (1) thu được Đồng nhất thức Sai số Tích:
\[\mathbb{E}\big[\psi_{\text{AIPW}}\big] - \tau_{\text{ATE}} = \mathbb{E}_X\!\left[\frac{\big(e^*(X) - e(X)\big)\big(\mu_1^*(X) - \mu_1(X)\big)}{e^*(X)}\right] + \mathbb{E}_X\!\left[\frac{\big(e^*(X) - e(X)\big)\big(\mu_0^*(X) - \mu_0(X)\big)}{1 - e^*(X)}\right].\]- Nếu chỉ \(\mu_w^* = \mu_w\) (ngay cả khi \(e^*\) sai hoàn toàn!): mọi thừa số \((\mu_w^* - \mu_w) \equiv 0 \implies \text{Bias} = 0\). - Nếu chỉ \(e^* = e\) (ngay cả khi \(\mu_w^*\) sai hoàn toàn!): thừa số \((e^* - e) \equiv 0 \implies \text{Bias} = 0\). - Cận Hiệu quả Hahn (1998): Khi cả hai mô hình hội tụ (tích sai số \(o_p(N^{-1/2})\)), \(\sqrt{N}(\hat{\tau}_{\text{AIPW}} - \tau_{\text{ATE}}) \xrightarrow{d} \mathcal{N}(0, V_{\text{eff}})\) với \(V_{\text{eff}} = \mathbb{E}_X\!\big[\frac{\sigma_1^2(X)}{e(X)} + \frac{\sigma_0^2(X)}{1-e(X)} + (\tau(X) - \tau_{\text{ATE}})^2\big]\)—đây là cận phương sai nhỏ nhất không thể vượt qua của mọi ước lượng bán tham số (tương tự
CRLBởch-03), vì phép trừ \(\mu_w(X)\) đã quét sạch phần phương sai \(\mu_w(X)^2 / e(X)\) củaHT-IPW! \(\blacksquare\)
Sụp đổ Positivity, Cỡ mẫu Hiệu dụng ESS & Trọng số Chồng lấn (Overlap Weighting ATO)#
Khi \(e(x) \to 0\) hoặc \(1\), cần kiểm tra ngay Cỡ mẫu Hiệu dụng Kish (ESS) \(\operatorname{ESS}_w := \frac{(\sum_{i:W_i=w}\omega_i)^2}{\sum_{i:W_i=w}\omega_i^2} \in [1, n_w]\). Thay vì chia \(1/e(x)\), Li, Morgan & Zaslavsky (JASA 2018) nhân với hàm nghiêng \(h(x) = e(x)(1 - e(x))\) tạo trọng số bị chặn tuyệt đối \(\omega_i^{\text{OW}} := W_i(1 - \hat{e}(X_i)) + (1 - W_i)\hat{e}(X_i) \in [0, 1]\):
- Đảm bảo cân bằng hiệp biến chính xác trên mẫu hữu hạn khi khớp điểm xu hướng bằng hồi quy logistic MLE, tối thiểu hóa phương sai tiệm cận, và hội tụ về
ATO(Average Treatment Effect for the Overlap Population): \(\tau_{\text{ATO}} = \frac{\mathbb{E}[e(X)(1-e(X))\tau(X)]}{\mathbb{E}[e(X)(1-e(X))]}\). (Trong Case 5 củacausal_uplift_labvới \(e(x)=\sigma(3.5x), \tau_{\text{true}}=0\), quan sát ngây thơ lệch+0.4969,IPWkhông cắt cómax_wt = 1,091.4xvàESS_ctrl = 363.3, cònATOkhôi phục-0.0000vớimax_wt = 0.999!)
1.5 Ma trận Độ phức tạp Tiệm cận (Asymptotic Complexity Matrix)#
| Thuật toán / Phép toán | Độ phức tạp Thời gian | Độ phức tạp Bộ nhớ | Nút thắt Quy mô Thực tế |
|---|---|---|---|
Kiểm tra \(d\)-Separation (Bayes-Ball) & Backdoor |
\(O(\lvert V \rvert + \lvert E \rvert)\) | \(O(\lvert V \rvert)\) | Duyệt BFS tuyến tính đồ thị (Shachter, 1998); chạy tức thì tới \(10^5\) nút. |
Thuật toán ID (Shpitser–Pearl) |
\(O(\lvert V \rvert^2(\lvert V \rvert + \lvert E \rvert))\) | \(O(\lvert V \rvert + \lvert E \rvert)\) | Kiểm tra tính nhận dạng trên Semi-Markovian DAG qua C-components. |
Ghép cặp (PSM 1D vs. MDM \(d\)-chiều) |
PSM: \(O(N\log N)\); MDM: \(O(N^2 d)\) |
PSM: \(O(N)\); MDM: \(O(N^2)\) |
MDM đụng trần RAM ở \(N \gtrsim 50{,}000\); tránh dùng PSM theo King–Nielsen. |
Cross-Fitted AIPW / DML2 (\(K\) nếp) |
\(O\big(K(\mathcal{C}_{\text{fit},\hat{e}} + 2\mathcal{C}_{\text{fit},\hat{\mu}}) + N\big)\) | \(O(N d + N)\) | Song song hóa hoàn toàn theo \(K\) nếp; sai số chuẩn dùng 1 lượt Welford \(O(N)\). |
Honest Causal Forest (\(B\) cây, mẫu con \(s\)) |
Huấn luyện: \(O(B d s \log s)\); Suy luận: \(O(B \log s)\) | \(O(B s)\) | Phân đôi mẫu \(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\); chi phí chính nằm ở vòng quét BLB/IJ. |
Đường cong Qini / AUUC & Ba lô Knapsack |
\(O(N \log N)\) | \(O(N)\) | Chiếm bởi bước sắp xếp giảm dần theo điểm số \(\hat{\tau}(x)\) hoặc \(\hat{\Pi}(x)/\hat{c}_{\text{exp}}(x)\). |
Trụ cột 2 — Double/Debiased ML (DML), Mô hình Hóa Uplift (CATE), Phản bác & Kiến trúc Sản xuất (Advanced Causal ML, Uplift Modeling & Production Systems Architecture)#
2.1 Học máy Khử chệch Kép (DML — Chernozhukov et al., Econometrica 2018)#
Mô hình Hồi quy Tuyến tính Từng phần (PLR) & Lỗ hổng Thiên lệch Điều chuẩn của Naive Plug-In#
Xét mô hình Partially Linear Regression (PLR — Robinson, 1988) với \(Z_i = (Y_i, W_i, X_i) \sim P\), trong đó \(X_i \in \mathbb{R}^d\) có thể rất nhiều chiều (\(d\) cỡ vài trăm tới hàng nghìn):
với \(\ell_0(X) := \mathbb{E}[Y \mid X] = \theta_0 m_0(X) + g_0(X)\) và điều kiện hỗ trợ chung \(\mathbb{E}[V^2] = \mathbb{E}[\operatorname{Var}(W \mid X)] > 0\).
Định lý Phá sản của Ước lượng Naive ML Plug-In: Giả sử kỹ sư huấn luyện một mô hình ML linh hoạt có điều chuẩn (Lasso, Ridge, GBDT, Random Forest, Neural Net) cho \(\hat{g}(X)\) trên tập phụ độc lập, đạt tốc độ hội tụ phi tham số chậm hơn \(\sqrt{n}\): \(\|\hat{g} - g_0\|_{L_2} = \mathcal{O}_p(n^{-\varphi_g})\) với \(\varphi_g \in (0, \frac{1}{2})\) (thường \(\varphi_g \approx \frac{1}{4}\)), rồi cắm vào hồi quy \(\hat{\theta}_{\text{naive}} := \frac{\sum_{i=1}^n W_i(Y_i - \hat{g}(X_i))}{\sum_{i=1}^n W_i^2}\) mà không trực giao hóa \(W\). Khai triển sai số nhân \(\sqrt{n}\) với \(W_i = m_0(X_i) + V_i\):
Do phạt điều chuẩn (\(L_1\)/\(L_2\)/dừng sớm) co rút \(\hat{g}(X)\) về 0, phần dư \(g_0(X) - \hat{g}(X)\) tương quan trực tiếp với \(m_0(X)\), làm số hạng \(T_2\) bùng nổ theo tốc độ:
Kết quả là khoảng tin cậy \(95\%\) danh nghĩa trượt khỏi chân lý \(\theta_0\) và sụp đổ về 0% độ phủ (naive_plugin trong causal_uplift_lab với \(n=500, d=350\) ghi nhận bias = -0.3636 và độ phủ 0%!). \(\blacksquare\)
Trực giao hóa FWL/Robinson, Chứng minh Tính Trực giao Neyman & Cận Tích Sai số \(n^{-1/4}\)#
Mở rộng Định lý Frisch–Waugh–Lovell (FWL) sang hàm phi tuyến, trừ \(\ell_0(X) = \mathbb{E}[Y \mid X] = \theta_0 m_0(X) + g_0(X)\) khỏi \(Y\) triệt tiêu \(g_0(X)\) hoàn toàn:
Ta định nghĩa Hàm điểm Trực giao Neyman Robinson (Partialling-Out Score) theo bộ nhiễu \(\eta = (\ell, m)\):
Chứng minh Tính Trực giao Neyman (Đạo hàm Gateaux bằng \(0\)):
Xét đường nhiễu \(\eta_r := \eta_0 + r(\eta - \eta_0) = (\ell_0 + r\Delta_\ell,\; m_0 + r\Delta_m)\) với \(\Delta_\ell = \ell - \ell_0\), \(\Delta_m = m - m_0\). Thay vào \(\psi\) tại \(\theta = \theta_0\) và lấy đạo hàm theo \(r\) tại \(r = 0\):
Lấy kỳ vọng qua Quy tắc Tháp, sử dụng \(\mathbb{E}[V \mid X] = 0\) và \(\mathbb{E}[\varepsilon \mid X, W] = 0\):
Hệ quả — Khai triển Sai số Tích Bậc hai & Điều kiện Tốc độ \(o_p(n^{-1/4})\):
Khai triển \(\psi(Z; \theta_0, \hat{\eta})\) dưới hàm nhiễu đã khớp \(\hat{\eta} = (\hat{\ell}, \hat{m})\) (tách mẫu \(\mathcal{D}_{-k}\)) và lấy kỳ vọng có điều kiện: mọi số hạng bậc nhất theo \(\Delta_\ell, \Delta_m\) biến mất hoàn toàn, chỉ còn số hạng bậc hai:
Khi nhân với \(\sqrt{n}\) trong phân tích tiệm cận của \(\sqrt{n}(\hat{\theta}_{\text{DML}} - \theta_0)\): chỉ cần cả hai bộ học máy \(\hat{\ell}\) và \(\hat{m}\) hội tụ ở tốc độ khiêm tốn \(o_p(n^{-1/4})\) (ví dụ \(n^{-0.26}\), điều mà Lasso, Random Forest, GBDT và mạng nơ-ron đều đạt được), thì tích sai số là \(o_p(n^{-1/4}) \cdot o_p(n^{-1/4}) = o_p(n^{-1/2})\), khiến \(\sqrt{n} \cdot o_p(n^{-1/2}) = o_p(1) \to 0\)! \(\blacksquare\)
\(K\)-Fold Cross-Fitting (DML1 vs. DML2), Bẫy Donsker In-Sample & Phương sai Sandwich#
Nếu khớp \(\hat{\ell}, \hat{m}\) ngay trên cùng mẫu (In-Sample DML) mà không chia nếp chéo, các mô hình ML độ phức tạp cao (không thuộc lớp hàm Donsker) sẽ học thuộc nhiễu ngẫu nhiên \(\varepsilon_i\) và \(V_i\), khiến tổng thực nghiệm \(\frac{1}{\sqrt{n}}\sum \hat{V}_i(g_0(X_i) - \hat{g}(X_i))\) không triệt tiêu và làm xẹp sai số chuẩn (trong causal_uplift_lab, insample_dml tụt xuống bias = -0.1018 với độ phủ 55%).
Giải pháp K-Fold Cross-Fitting (DML2 — Chuẩn EconML): Chia ngẫu nhiên mẫu thành \(K\) nếp rời nhau \(I_1, \dots, I_K\) (\(K=5\) hoặc \(10\)); trên mỗi nếp \(k\), chỉ huấn luyện \(\hat{\ell}^{(-k)}, \hat{m}^{(-k)}\) trên phần bù \(I_k^c\), rồi dự báo phần dư nghiêm ngặt ngoài nếp \(\tilde{Y}_i = Y_i - \hat{\ell}^{(-k)}(X_i)\) và \(\tilde{W}_i = W_i - \hat{m}^{(-k)}(X_i)\) cho \(i \in I_k\). Cuối cùng gộp toàn bộ \(n\) phần dư giải DML2 (vượt trội DML1 trung bình từng nếp vì ổn định mẫu số hơn):
cho khoảng tin cậy hợp lệ tiệm cận \((1-\alpha)\) là \(\hat{\theta}_{\text{DML2}} \pm z_{1-\alpha/2}\sqrt{\hat{\sigma}^2 / n}\) (khôi phục bias = +0.0087, độ phủ 90% ở kích thước kiểm thử 20 lần lặp trên d=350, n=500).
(Mở rộng: Với Mô hình Hồi quy Tương tác phi tuyến IRM \(Y = g_0(W, X) + U\), hàm điểm trực giao Neyman cho ATE chính là hàm AIPW Cross-Fitted ở §1.4; còn cho tác động không đồng nhất CATE, LinearDML tham số hóa \(\tau(X) = \langle \theta_0, \boldsymbol{\phi}(X)\rangle\) giải hồi quy \(\tilde{Y}_i\) trên \(\boldsymbol{\phi}(X_i)\tilde{W}_i\), trong khi NonParamDML tối ưu hóa trực tiếp tổn thất R-Learner bên dưới.)
2.2 Mô hình Hóa Uplift: Năm CATE Meta-Learners & Rừng Nhân quả Trung thực (GRF)#
Khi mục tiêu chuyển từ ATE vô hướng sang CATE cá nhân hóa \(\tau(x) = \mathbb{E}[Y(1) - Y(0) \mid X=x]\), năm kiến trúc Meta-Learners đại diện cho năm đánh đổi toán học rõ rệt:
S-Learner(Single Model): Ghép \([X, W]\) vào một mô hình chung \(\hat{\mu}(x, w)\) rồi tính \(\hat{\tau}_S(x) = \hat{\mu}(x, 1) - \hat{\mu}(x, 0)\).
Lỗi chí tử (Regularization Drop-Out): Khi \(\tau(x)\) nhỏ hơn nhiều so với phương sai nền \(\mu_0(x)\) và chiều \(X\) lớn, phạt điều chuẩn (L1/L2) hoặc cây chia nhánh tham lam bỏ qua luôn cột nhị phân \(W\), đẩy \(\hat{\tau}_S(x) \to 0\)! (Trongcausal_uplift_lab,S_Learner_NoInteractbị tụtPEHE = 0.2178và lợi nhuận rớt xuống+$5,100.7, nhưng chỉ cần bổ sung tường minh tương tác \(\boldsymbol{\phi}(X) \cdot W\) vào ma trận thiết kế,PEHEnhảy đẹp xuống0.0583!)T-Learner(Two Separate Models): Huấn luyện độc lập \(\hat{\mu}_1(x)\) trên nhóm \(W=1\) và \(\hat{\mu}_0(x)\) trên nhóm \(W=0\), lấy \(\hat{\tau}_T(x) = \hat{\mu}_1(x) - \hat{\mu}_0(x)\).
Lỗi chí tử (Thiên lệch Điều chuẩn Bất đối xứng & Phồng Phương sai): Nếu một nhánh quá thưa (\(e(x) \ll 0.5\) hoặc \(\gg 0.5\)), hai mô hình chịu độ co rút điều chuẩn khác nhau. Ngay cả khi \(\tau(x) \equiv 0\), hiệu \(\text{bias}(\hat{\mu}_1) - \text{bias}(\hat{\mu}_0) \neq 0\) vẫn bịa đặt ra tính không đồng nhất giả, đồng thời \(\operatorname{Var}(\hat{\tau}_T(x)) \propto \frac{1}{e(x)} + \frac{1}{1-e(x)}\).X-Learner(Künzel et al., PNAS 2019): Chữa bệnh mất cân bằng nhánh qua 3 giai đoạn: (1) Khớp \(\hat{\mu}_0, \hat{\mu}_1, \hat{e}\); (2) Gán hiệu ứng giả phản thực \(\tilde{D}_i^1 = Y_i^1 - \hat{\mu}_0(X_i^1)\) và \(\tilde{D}_i^0 = \hat{\mu}_1(X_i^0) - Y_i^0\), rồi khớp \(\hat{\tau}_1(x), \hat{\tau}_0(x)\); (3) Trộn theo điểm xu hướng:\[\hat{\tau}_X(x) = \hat{e}(x)\,\hat{\tau}_0(x) + \big(1 - \hat{e}(x)\big)\,\hat{\tau}_1(x).\]Tại sao chọn \(g(x) = \hat{e}(x)\) co phương sai? Khi \(W=1\) hiếm (\(e(x) \approx 0.05\)), \(\hat{\mu}_0\) học trên \(95\%\) mẫu nên rất chính xác, biến \(\hat{\tau}_1(x)\) thành ước lượng sạch; ngược lại \(\hat{\mu}_1\) nhiễu nặng làm \(\hat{\tau}_0(x)\) nhiễu theo. Trọng số \(1 - \hat{e}(x) \approx 0.95\) dồn gần hết niềm tin vào nhánh chính xác \(\hat{\tau}_1(x)\)!R-Learner(Nie & Wager, Biometrika 2021): Dùng đồng nhất thức Robinson \(Y - \ell_0(X) = \tau(X)(W - m_0(X)) + \varepsilon\) với hàm nhiễu khớp chéo ngoài nếp \(\hat{\ell}^{(-k)}, \hat{m}^{(-k)}\) để tối thiểu hóa mất mát có trọng số:\[\hat{\tau}_R := \arg\min_{\tau \in \mathcal{T}} \left\{ \frac{1}{n}\sum_{i=1}^n \Big[\big(Y_i - \hat{\ell}^{(-k(i))}(X_i)\big) - \tau(X_i)\big(W_i - \hat{m}^{(-k(i))}(X_i)\big)\Big]^2 + \Lambda_n(\tau) \right\}.\]Viết dưới dạng bình phương tối thiểu có trọng số (WLS): \(\tilde{W}_i^2\big(\frac{\tilde{Y}_i}{\tilde{W}_i} - \tau(X_i)\big)^2\). Vì \(\mathbb{E}[\tilde{W}_i^2 \mid X_i] \approx e(X_i)(1 - e(X_i))\),R-Learnertự động hạ trọng số vùng biên \(e \to 0, 1\) (không bao giờ chia \(1/e\) gây nổ phương sai) và giải trực tiếp không cần phép chia \(\tilde{Y}_i/\tilde{W}_i\) khi tham số hóa tuyến tính trên cơ sở \(\boldsymbol{\phi}(X_i)\tilde{W}_i\)!DR-Learner(Kennedy, JRSS-B 2023): Hồi quy trực tiếp giả kết cục bền vững kép khớp chéo ngoài nếp \(\tilde{Y}_{\text{DR}, i}\) lên \(X_i\):\[\tilde{Y}_{\text{DR}, i} := \hat{\mu}_1^{(-k)}(X_i) - \hat{\mu}_0^{(-k)}(X_i) + \frac{W_i\big(Y_i - \hat{\mu}_1^{(-k)}(X_i)\big)}{\hat{e}^{(-k)}(X_i)} - \frac{(1-W_i)\big(Y_i - \hat{\mu}_0^{(-k)}(X_i)\big)}{1-\hat{e}^{(-k)}(X_i)}.\]Vì \(\mathbb{E}[\tilde{Y}_{\text{DR}} \mid X=x] - \tau(x)\) có sai số tỷ lệ với tích \((\hat{e}-e)(\hat{\mu}_w-\mu_w)\),DR-Learnerđạt tốc độ hội tụoraclekhông trọng số dưới thước đoPEHEbất cứ khi nào tích lỗi nhiễu nhỏ hơn sai số minimax ước lượng \(\tau(x)\) (cần cắt ngưỡng \(\hat{e} \in [\epsilon, 1-\epsilon]\)).
| Meta-Learner | Số Mô hình Nhiễu | Chống Mất cân bằng Nhánh | Chống Nhiễu Hỗn tạp | Hành vi Chiều \(X\) Cao | Đánh đổi Chính |
|---|---|---|---|---|---|
S-Learner |
1 (\(\hat{\mu}(x,w)\)) |
Kém | Kém–Trung bình | Kém nếu thiếu \(X \cdot W\) | Phạt điều chuẩn làm tụt \(\hat{\tau} \to 0\) nếu không mã hóa tương tác tường minh. |
T-Learner |
2 (\(\hat{\mu}_0, \hat{\mu}_1\)) |
Kém (\(\operatorname{Var} \propto \frac{1}{\min(e,1-e)}\)) | Trung bình | Kém khi một nhánh thưa | Thiên lệch điều chuẩn bất đối xứng giữa hai nhánh bịa ra CATE giả. |
X-Learner |
5 (\(\hat{\mu}_0, \hat{\mu}_1, \hat{e}, \hat{\tau}_0, \hat{\tau}_1\)) |
Xuất sắc | Khá–Tốt | Tốt khi \(\tau(x)\) trơn hơn \(\mu_w\) | Tốt khi \(e \ll 0.5\) hoặc \(\gg 0.5\), nhưng Giai đoạn 1 chưa trực giao Neyman. |
R-Learner |
3 (\(\hat{\ell}, \hat{m}\) OOF + \(\hat{\tau}_R\)) |
Tốt (\(\tilde{W}_i^2\) tránh nổ \(1/e\)) | Xuất sắc (Neyman) | Xuất sắc | Nếu \(\mathcal{T}\) thiếu linh hoạt, hội tụ về hình chiếu trọng số chồng lấn \(e(1-e)\). |
DR-Learner |
4 (\(\hat{\mu}_0,\hat{\mu}_1,\hat{e}\) OOF + \(\hat{\tau}_{\text{DR}}\)) |
Nhạy khi \(e \to 0,1\) | Xuất sắc (Bền vững Kép) | Xuất sắc (tốc độ oracle) |
Cần chặn biên \(\hat{e} \in [0.03, 0.97]\) khi chồng lấn yếu. |
Cây & Rừng Nhân quả Trung thực (Honest Causal Trees & GRF — Athey, Imbens & Wager 2016–2019)#
- Nguyên tắc Trung thực (Honesty Principle): Cây tham lam truyền thống dùng cùng một tập mẫu để tìm ngưỡng chia cực đại hóa \(|\hat{\tau}_{\text{left}} - \hat{\tau}_{\text{right}}|\) và tính \(\hat{\tau}(L)\), gây thiên lệch chọn lọc cực đoan ("winner's curse"). Cây Nhân quả Trung thực rút mẫu con kích thước \(s = n^\beta\) không hoàn lại rồi tách đôi rời nhau \(\mathcal{S}_b = \mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\): chỉ dùng \(\mathcal{I}^{\text{split}}\) để dựng cấu trúc cây \(\mathcal{P}_{\text{tree}}\), sau đó thả \(\mathcal{I}^{\text{est}}\) vào các lá đóng băng để ước lượng \(\hat{\tau}(L; \mathcal{I}^{\text{est}})\) hoàn toàn bất thiên vị.
- Tiêu chuẩn Chia nhánh
EMSEHiệu chỉnh (Athey & Imbens, 2016): Cực đại hóa giá trị âm sai số bình phương kỳ vọng của tác động điều trị (\(-\widehat{\text{EMSE}}_\tau(\mathcal{P}_{\text{tree}})\)), trong đó \(n^{\text{split}} := \lvert\mathcal{I}^{\text{split}}\rvert\) và \(n^{\text{est}} := \lvert\mathcal{I}^{\text{est}}\rvert\) là tổng cỡ mẫu của hai nửa tách rời:\[-\widehat{\text{EMSE}}_\tau(\mathcal{P}_{\text{tree}}) := \frac{1}{n^{\text{split}}}\sum_{L \in \mathcal{P}_{\text{tree}}} n_{L}^{\text{split}}\,\hat{\tau}_L^2(\mathcal{I}^{\text{split}}) - \left(\frac{1}{n^{\text{split}}} + \frac{1}{n^{\text{est}}}\right)\sum_{L \in \mathcal{P}_{\text{tree}}}\left(\frac{S^2_{\mathcal{I}^{\text{split}}, 1}(L)}{p_1(L)} + \frac{S^2_{\mathcal{I}^{\text{split}}, 0}(L)}{1 - p_1(L)}\right)\](vừa thưởng độ phân kỳ tác động liên lá \(\hat{\tau}_L^2\), vừa trừ phương sai nội lá gắn trọng số \((1/n^{\text{split}} + 1/n^{\text{est}})\) qua cả tập chia \(\mathcal{I}^{\text{split}}\) lẫn tập ước lượng \(\mathcal{I}^{\text{est}}\) để chống vỡ lá thưa). GRFTrực giao hóa (CausalForestDML) & Phương saiIJ/BLB: Generalized Random Forests trước hết tính phần dư trực giao ngoài nếp \((\tilde{Y}_i, \tilde{W}_i)\), sau đó tại mỗi nút cha \(P\) tính giả-kết cục gradient \(\rho_i\) giải phương trình mô-men cục bộ Robinson, lấy mẫu con không hoàn lại \(s = n^\beta\) để đạt tiệm cận Chuẩn, và tính khoảng tin cậy bằng Infinitesimal Jackknife (IJ) hoặc Bootstrap of Little Bags (BLB) (half-sample bags) trong \(B \approx 500\text{–}2{,}000\) cây.
2.3 Đánh giá Uplift Khi Thiếu Phản thực (Uplift@k, AUUC, Qini, \(Y^*\) & R-loss / DR-loss)#
Vì không bao giờ quan sát được \(\tau_i = Y_i(1) - Y_i(0)\) đồng thời trên một cá thể, mọi chỉ số giám sát thuần túy (ROC-AUC, MSE(Y)) đều vô nghĩa. Sắp xếp các mẫu kiểm thử \(i = 1, \dots, N\) theo thứ tự giảm dần của điểm \(\hat{\tau}(X_i)\). Với lát cắt top-\(k\) (\(\phi = k/N\)), đặt \(N_k^T, N_k^C, Y_k^T, Y_k^C\) là tổng đếm và tổng kết cục của hai nhánh trong top-\(k\) (trên dữ liệu quan sát có thiên lệch chọn lọc, thay bằng tổng có trọng số IPW \(\tilde{N}_k^T = \sum_{i\le k}\frac{W_i}{\hat{e}(X_i)}\) và \(\tilde{Y}_k^T = \sum_{i\le k}\frac{W_i Y_i}{\hat{e}(X_i)}\) để loại bỏ nhiễu xu hướng!):
Uplift@k: \(\operatorname{Uplift@}k := \frac{Y_k^T}{N_k^T} - \frac{Y_k^C}{N_k^C}\).- Đường cong Uplift &
AUUC: \(U(\phi) := \left(\frac{Y_k^T}{N_k^T} - \frac{Y_k^C}{N_k^C}\right)\phi\), với diện tích vượt chuẩn ngẫu nhiên \(\operatorname{AUUC}_{\text{excess}} = \int_0^1 \big(U(\phi) - \phi U(1)\big)\,d\phi\). - Đường cong & Hệ số
Qini(Radcliffe, 2007): Quy đổi kết cục nhánh đối chứng về quy mô nhánh điều trị tại từng ngưỡng \(k\):\[Q(k) := \frac{1}{N}\left(Y_k^T - Y_k^C\,\frac{N_k^T}{N_k^C}\right), \qquad Q_{\text{rand}}(k) = \frac{N_k^T}{N^T}\,Q(N), \qquad q_{\text{Qini}} := \frac{\int_0^1 (Q(\phi) - Q_{\text{rand}}(\phi))\,d\phi}{\int_0^1 (Q_{\text{opt}}(\phi) - Q_{\text{rand}}(\phi))\,d\phi}.\] - Kết cục Biến đổi \(Y^*\) — Chứng minh Bất thiên vị & Bẫy Phương sai: Định nghĩa \(Y^* := Y\,\frac{W - e(X)}{e(X)(1 - e(X))}\). Dưới
SUTVA,IgnorabilityvàPositivity:\[\mathbb{E}[Y^* \mid X=x] = \frac{\mathbb{E}[W \mid x]\,\mathbb{E}[Y(1) \mid x]}{e(x)} - \frac{\mathbb{E}[1-W \mid x]\,\mathbb{E}[Y(0) \mid x]}{1-e(x)} = \mu_1(x) - \mu_0(x) = \tau(x). \qquad \blacksquare\]Bẫy Phương sai: Vì \(Y^*\) không trừ kỳ vọng nền \(\mu_w(x)\), \(\operatorname{Var}(Y^* \mid X)\) nổ lớn khi \(e(X) \to 0, 1\) (trongcausal_uplift_lab, \(\operatorname{std}(Y^*)\) vượt hơn \(5\times\) \(\operatorname{std}(\tau_{\text{true}})\)!), khiến việc dùngMSE(Y^*)chọn mô hình rất nhiễu. - Lựa chọn Mô hình Phản thực Ngoài mẫu (
R-loss&DR-loss): Trên tập thẩm định cách ly \(\mathcal{D}_{\text{val}}\), huấn luyện độc lập \((\hat{\ell}_{\text{val}}, \hat{m}_{\text{val}})\) và \(\tilde{Y}_{\text{DR}}^{\text{val}}\) ngoài nếp để chấm điểm các mô hình ứng viên \(\hat{\tau}^{(m)}\):\[\widehat{R\text{-loss}}\big(\hat{\tau}^{(m)}\big) = \frac{1}{n_{\text{val}}}\sum_{i \in \mathcal{D}_{\text{val}}} \Big((Y_i - \hat{\ell}_{\text{val}}^{(-k)}(X_i)) - \hat{\tau}^{(m)}(X_i)(W_i - \hat{m}_{\text{val}}^{(-k)}(X_i))\Big)^2, \qquad \widehat{\text{DR-loss}}\big(\hat{\tau}^{(m)}\big) = \frac{1}{n_{\text{val}}}\sum_{i \in \mathcal{D}_{\text{val}}} \big(\tilde{Y}_{\text{DR}, i}^{\text{val}} - \hat{\tau}^{(m)}(X_i)\big)^2.\](Chú ý:R-losstheo sátPEHEcó trọng số chồng lấn \(e(1-e)\) cònDR-losstheo sátPEHEkhông trọng số. Thực nghiệm trêncausal_uplift_labcho thấy cả hai đều xếp hạng 5 mô hình khớp 100% vớiPEHEthật mà không hề nhìn thấy \(\tau_{\text{true}}\)!)
2.4 Phản bác Giả thuyết (DoWhy Refuters), Phân tích Độ nhạy & Biên Nghiên cứu 2024–2026#
Vì giả định Không có Biến hỗn tạp Ẩn (Unconfoundedness) không bao giờ kiểm định trực tiếp được từ dữ liệu quan sát, ta bắt buộc phải kiểm tra khả năng bác bỏ và độ nhạy:
- Bộ Kiểm định Phản bác
DoWhy(Refutation Suite):placebo_treatment_refuter: Hoán vị hoặc thay \(W\) bằng nhiễu độc lập; ước lượng bắt buộc phải sập về~ 0(trong lab:base = +0.0430sập về-0.0056). Nếu vẫn khác 0 đáng kể \(\implies\) pipeline bị rò rỉ nhãn hoặc lỗi cài đặt!random_common_cause: Bổ sung biến nhiễu độc lập \(U_{\text{rand}} \sim \mathcal{N}(0, 1)\) vào tập điều chỉnh; ước lượng phải bất biến (trong lab: độ lệch chỉ0.00027).data_subset_refuter: Ước lượng lại trên các tập con ngẫu nhiên80%kiểm chứng tính ổn định (trong lab: độ lệch0.01384).
- Độ nhạy Biến Bỏ sót
Cinelli & Hazlett(OVB, JRSS-B 2020 &DML-OVB2022/2024): Biểu diễn độ chệch do biến ẩn \(U\) theo hai hệ số \(R^2\) riêng bị chặn \(R^2_{Y\sim U\mid W,X}, R^2_{W\sim U\mid X} \in [0, 1)\):\[\big|\widehat{\text{Bias}}\big| = \operatorname{SE}(\hat{\theta})\,\sqrt{\text{df}\cdot\frac{R^2_{Y\sim U\mid W,X}\,R^2_{W\sim U\mid X}}{1 - R^2_{W\sim U\mid X}}}, \qquad RV_q = \frac{1}{2}\left(\sqrt{f_q^4 + 4 f_q^2} - f_q^2\right), \quad f_q := q\frac{|t_{\hat{\theta}}|}{\sqrt{\text{df}}}.\]Giá trị vữngRV_1 = 0.0700(trong lab với \(|t| = 4.58\)) nghĩa là bất kỳ biến ẩn nào giải thích ít hơn7.0%phương sai phần dư của cả \(W\) và \(Y\) đều không thể xóa sạch hiệu ứng xuống0! - Chứng minh
E-Value(VanderWeele & Ding, Annals of Internal Medicine 2017): Với tỷ số nguy cơ quan sát \(\text{RR}_{\text{obs}} > 1\) và cận độ chệch chặt \(\text{BF} = \frac{\text{RR}_{EU}\text{RR}_{UD}}{\text{RR}_{EU}+\text{RR}_{UD}-1} \ge \text{RR}_{\text{obs}}\), đặt độ mạnh tối thiểu cân bằng \(\text{RR}_{EU} = \text{RR}_{UD} = E_{\text{sens}} \ge 1\) cho phương trình bậc hai \(E_{\text{sens}}^2 - 2\,\text{RR}_{\text{obs}}\,E_{\text{sens}} + \text{RR}_{\text{obs}} = 0\), giải ra nghiệm \(E_{\text{sens}} \ge 1\):\[E_{\text{sens}} = \text{RR}_{\text{obs}} + \sqrt{\text{RR}_{\text{obs}}(\text{RR}_{\text{obs}} - 1)}. \qquad \blacksquare\](Ví dụ: với \(\text{RR}_{\text{obs}} = 2.0\), \(E_{\text{sens}} = 2 + \sqrt{2} = \mathbf{3.4142}\); với \(\text{RR} < 1\), thay bằng \(1/\text{RR}\); đối với cận CI cắt qua \(1.0\), \(E_{\text{CI}} = 1.0\).) - Cận Độ nhạy
Rosenbaum\(\Gamma\) (2002): Trên các cặp ghép \(X\) giống nhau, nếu nhiễu ẩn làm tỷ số odds nhận điều trị chênh tối đa \(\Gamma \ge 1\) (\(\frac{1}{\Gamma} \le \frac{\pi_j/(1-\pi_j)}{\pi_k/(1-\pi_k)} \le \Gamma\)), thì xác suất nhận điều trị trong cặp nằm trong \([\frac{1}{1+\Gamma}, \frac{\Gamma}{1+\Gamma}]\), cho phép tính \(\Gamma_{\text{crit}}\) tại điểm \(p_{\max}(\Gamma)\) vượt mức ý nghĩa \(\alpha\). - Biên Nghiên cứu 2024–2026:
DoWhy v0.12–v0.14+&EconML v0.15–v0.16+: Tiêu chuẩn điều chỉnh tổng quát (GAC),DRtích hợp sẵn,dowhy.gcmhỗ trợ dữ liệu khuyết (v0.13), Python3.13 + uv(v0.14), vàLinearDML/CausalForestDML/DRLearner/OrthoForest.Conformal ITE(Lei & Candès JRSS-B 2021,arXiv:2006.06138;wTCP-DR, Wang & QiaoarXiv:2501.14933, 2025): Dự báo Conformal có trọng số xu hướng \(w_1(x) \propto 1/e(x)\) và biến thể bền vững kép tạo dải tin cậy hữu hạn mẫu \([\widehat{\text{ITE}}_L(x), \widehat{\text{ITE}}_U(x)]\), cho phép chỉ can thiệp khi cận dưới \(\widehat{\text{ITE}}_L(x) > c_{\text{cost}}\)!- Học Chính sách Tối ưu (
PolicyTree— Athey & Wager, Econometrica 2021): Học trực tiếp cây quyết định chính sách độ sâu giới hạn \(\hat{\pi}_{\text{pol}} = \arg\max_{\pi \in \Pi_{\text{pol}}} \frac{1}{n}\sum (2\pi(X_i)-1)(\tilde{Y}_{\text{DR}, i} - c(X_i))\), đạt hối tiếc phúc lợi tối ưu minimax \(\mathcal{O}(n^{-1/2})\). - Mô hình Nền tảng Nhân quả & Khám phá Có sự Hỗ trợ của
LLM(CausalPFN2025;TabPFN-CFM2026;CauScientist2026): Biến đổi in-context không cần huấn luyện lại trên hàng triệuSCMtổng hợp để ước lượngCATE/ATEzero-shot kèm bất định Bayes—với cảnh báo bắt buộc lọc bỏ biến trung gian/collider trước khi đưa vàoCausalFMvà kiểm định độc lập có điều kiện thống kê đối với các cạnhDAGdoLLMđề xuất.
2.5 Kiến trúc Hệ thống Nhân quả Sản xuất (Production Causal & Uplift Systems Architecture)#
Một hệ thống suy luận nhân quả & tối ưu hóa uplift chuẩn sản xuất gồm ba mặt phẳng tách biệt nghiêm ngặt:
- Mặt phẳng Dữ liệu (
Data Plane—PIT& Nhật ký Xu hướng Thực tế): Kết nối đặc trưng chuẩnASOF(\(t_{\text{feature}} \le t_{\text{decision}}\) kế thừa từch-04). Quy tắc sống còn: Mọi bản ghi hành động được phát ra từ hệ thống (Kafka\(\to\)Iceberg/Delta Lake) bắt buộc phải ghi lại đúng xác suất xu hướng lúc phục vụ \(e_{\text{log}}(x_i)\) vàpolicy_id! Thiếu \(e_{\text{log}}(x_i)\), dữ liệu tương lai mất hoàn toàn khả năng đánh giá ngoài chính sách (Off-Policy Evaluation). - Mặt phẳng Huấn luyện & Cổng Phản bác Ngoại tuyến (
Offline Training & Refutation Plane): Chạy theo lịch (Airflow/Metaflow): (a) Kiểm tra độ phủ chồng lấn (\(0.03 \le \hat{e}(x) \le 0.97\), Kish \(\operatorname{ESS}/N \ge 0.25\)); (b) Khớp chéoK-fold vớiSeedSequence; (c) Chấm điểmQini&Lợi nhuận Gia tăng; (d) Cổng Phản bác Tự động (Placebo\(\approx 0\),Random Common Cause,Subset,E-value, và thắng mô hình dự báo rủi ro trên kiểm chứng giữ lại). - Mặt phẳng Phục vụ Trực tuyến (
Online Serving Plane,< 20 ms p99SLA & Nhóm Khám phá5%):- Phục vụ Lô Trước (
Batch Pre-Scoring -> Redis / Feast Online Store): Tính trước \(\hat{\tau}(x_i)\) và \(\hat{\mu}_1(x_i)\) hằng ngày/giờ cho10M+thuê bao, tra cứu trực tuyến dưới< 5 ms p99kết hợp biến số giá trị \(V(x_i)\), chiết khấu \(d\), và nhân tử Lagrange ngân sách \(\lambda_t^*\). - Phục vụ Thời gian Thực (
FastAPI+ONNX/ Cây lượng tử hóa): Dành cho tín hiệu phiên tức thời (giỏ hàng, trang bấm hủy): ngân sách<= 8 msđọc đặc trưng +<= 8 mssuy luận +<= 4 mslọc Ba lô (< 20 ms p99), kèm bộ ngắt mạch mặc định Không Gửi cho nhóm nghi Sleeping Dogs. - Hàng rào
5%Khám phá Ngẫu nhiên Thường trực (Permanent 5% Exploration Holdout): Luôn dành cố định5%lưu lượng đủ điều kiện để phân bổ ngẫu nhiên (\(e = 0.50\)), ngăn chặn Sụp đổ Positivity (\(e(x) \in \{0, 1\}\)) và Kiểm duyệt Vòng lặp Phản hồi khi mô hình bước vào chu kỳ tái huấn luyện kế tiếp!
- Phục vụ Lô Trước (
Trụ cột 3 — Chuyên đề Sâu #3 (Từ Dự báo Rời bỏ đến Tác động Gia tăng), 5 Tình huống Công nghiệp & Chuẩn Mã 2026 (Deep-Dive Article #3, Industry Case Studies & Production Tech Stack)#
3.1 Chuyên đề Sâu #3: Từ Dự báo Rời bỏ đến Tác động Gia tăng (From Churn Prediction to Incremental Impact)#
Tích hợp Nguyên khối Chuyên đề Sâu (4 Phần): Giải quyết trọn vẹn Chuyên đề
#3qua bốn thành phần bắt buộc: (1) Thất bại thực tế của phân loại rủi ro; (2) Mô hình hóa 4 góc phần tư & Quy tắc Lợi nhuận Ba lô 0–1; (3) Thí nghiệm đối chứng có kiểm soát (causal_uplift_lab); và (4) Cẩm nang quyết định sản xuất.
1. Trường hợp Thất bại Cụ thể: Vì sao Nhắm Top-\(P(\text{churn})\) Phá hủy ROI Giữ chân#
Trong thực hành doanh nghiệp thông thường, đội khoa học dữ liệu đóng khung bài toán giữ chân thành phân loại nhị phân: huấn luyện XGBoost/LightGBM dự báo xác suất rời bỏ \(\hat{p}_{\text{churn}}(x) = \widehat{\mathbb{P}}(C=1 \mid X=x)\), xếp hạng từ cao xuống thấp, rồi gửi cuộc gọi chăm sóc ($5) kèm ưu đãi giảm giá $25 khi gia hạn cho Top-30% khách hàng có rủi ro rời bỏ cao nhất. Chiến lược này thất bại do ba nghịch lý kinh tế–nhân quả:
- Đốt tiền vào Lost Causes (\(\mu_0 \approx 0.10 \to \mu_1 \approx 0.11\)): Nhóm rủi ro cao nhất gồm các tài khoản đã ký hợp đồng với đối thủ hoặc ngừng sử dụng hoàn toàn; ưu đãi chỉ tăng tỷ lệ ở lại thêm
+1 pp, thu về$2.00LTV kỳ vọng trên$7.75chi phí \(\implies\) lỗ chắc chắn-$5.75/người. - Bỏ rơi Mid-Risk Persuadables (\(\hat{p}_{\text{churn}} \approx 0.45\), \(\tau(x) = +0.20\text{–}+0.35\)): Nhóm nhạy cảm về giá đứng ở vùng giữa bảng xếp hạng rủi ro bị bỏ sót hoàn toàn bởi ngưỡng cắt Top-\(k\) rời bỏ.
- Đánh thức Sleeping Dogs (\(\tau(x) = -0.20\)): Gửi thông điệp "Đừng rời bỏ chúng tôi, nhận ngay ưu đãi!" cho các thuê bao tự động gia hạn thầm lặng lại nhắc họ hủy gói dịch vụ không dùng tới—biến một thuê bao đang trả tiền êm đẹp thành mất khách tức thì (
-$58.75/người).
2. Mô hình Định lượng: 4 Góc phần tư Khách hàng, Lợi nhuận \(\Pi(x)\) & Ba lô 0–1 ROI Biên#
Theo quy ước dấu đã khóa (\(Y \in \{0, 1\}\) là Ở lại/Gia hạn, nên \(\tau(x) = \mu_1(x) - \mu_0(x) > 0\) nghĩa là can thiệp giữ chân thành công, và rủi ro rời bỏ nền là \(1 - \mu_0(x)\)), không gian kết quả tiềm năng \((Y_i(0), Y_i(1)) \in \{0, 1\}^2\) chia quần thể thành 4 Góc phần tư Nhân quả:
| Góc phần tư Khách hàng | \((Y_i(0), Y_i(1))\) | \(\tau_i = Y_i(1)-Y_i(0)\) | Bản chất Hành vi & Ý nghĩa Sản xuất | Quyết định Tối ưu |
|---|---|---|---|---|
| 1. Persuadables (Có thể Thuyết phục) | \((0, 1)\) | +1 |
Sẽ rời bỏ nếu không tác động, ở lại khi nhận ưu đãi | Can thiệp (nếu \(\Pi(x) > 0\)) |
| 2. Sure Things (Chắc chắn Ở lại) | \((1, 1)\) | 0 |
Gia hạn bất kể ưu đãi; giảm giá chỉ tự ăn mòn biên lợi nhuận | Không gửi (tiết kiệm \(c + d\)) |
| 3. Lost Causes (Hết Hy vọng) | \((0, 0)\) | 0 |
Rời bỏ bất kể ưu đãi; đốt chi phí liên hệ vô ích | Không gửi (tiết kiệm \(c\)) |
| 4. Sleeping Dogs (Chó Ngủ Yên) | \((1, 0)\) | -1 |
Sẽ âm thầm gia hạn nếu bỏ yên, hủy ngay khi bị nhắc | Cấm tuyệt đối (tránh lỗ \(-V\)) |
Gọi \(V(x)\) là giá trị vòng đời ròng, \(c_{\text{contact}}\) là chi phí tiếp cận cố định khi \(W=1\), và \(d_{\text{incentive}}\) là khoản chiết khấu chỉ phải trả nếu khách gia hạn khi được mời (\(W=1, Y(1)=1\)). So sánh lợi nhuận kỳ vọng \(\mathbb{E}[\text{Profit}(W=1) \mid x] = \mu_1(x)(V(x)-d_{\text{incentive}}) - c_{\text{contact}}\) với \(\mathbb{E}[\text{Profit}(W=0) \mid x] = \mu_0(x)V(x)\) thu được Lợi nhuận Gia tăng Ròng Kỳ vọng:
- Quy tắc Ngưỡng Không Ràng buộc Ngân sách: Can thiệp khi và chỉ khi \(\Pi(x) > 0 \iff \tau(x) > \frac{c_{\text{contact}} + \mu_1(x)\,d_{\text{incentive}}}{V(x)}\).
- Quy tắc Ba lô 0–1 Dưới Giới hạn Ngân sách \(B\) (Budget-Constrained Knapsack Policy): Loại mọi cá thể \(\hat{\Pi}(x_i) \le 0\), xếp hạng phần còn lại giảm dần theo ROI Biên \(\operatorname{ROI}_{\text{marg}}(x_i) := \frac{\hat{\Pi}(x_i)}{\hat{c}_{\text{exp}}(x_i)}\), và can thiệp tuần tự cho tới khi chạm trần ngân sách \(\sum z_i \hat{c}_{\text{exp}}(x_i) \le B\)!
Kiểm chứng Số Học Kinh điển (\(N = 10{,}000\), \(V = 200\,\text{USD}\), \(c_{\text{contact}} = 5\,\text{USD}\), \(d_{\text{incentive}} = 25\,\text{USD}\)):
| Phân khúc (\(N = 10{,}000\)) | Số lượng | Rủi ro Rời \(1-\mu_0\) | Giữ chân \(\mu_0 \to \mu_1\) | Uplift \(\tau(x)\) | Chi phí \(c_{\text{exp}}\) | Lợi nhuận/Người \(\Pi(x)\) | ROI Biên | Tổng Phân khúc |
|---|---|---|---|---|---|---|---|---|
| B: Rủi ro Cao Lost Causes | 3,000 |
0.90 |
0.10 -> 0.11 |
+0.01 |
$7.75 |
-$5.75 |
-0.742 |
-$17,250 |
| A: Rủi ro Cao Persuadables | 1,500 |
0.80 |
0.20 -> 0.55 |
+0.35 |
$18.75 |
+$51.25 |
+2.733 |
+$76,875 |
| E: Rủi ro Vừa Persuadables | 1,500 |
0.45 |
0.55 -> 0.75 |
+0.20 |
$23.75 |
+$16.25 |
+0.684 |
+$24,375 |
| C: Ngủ Đông Sleeping Dogs | 1,500 |
0.25 |
0.75 -> 0.55 |
-0.20 |
$18.75 |
-$58.75 |
-3.133 |
-$88,125 |
| D: An toàn Sure Things | 2,500 |
0.08 |
0.92 -> 0.93 |
+0.01 |
$28.25 |
-$26.25 |
-0.929 |
-$65,625 |
Đối chiếu 3 chính sách trên đúng cùng 10,000 khách hàng: Treat-All lỗ -$69,750; Top-30% Churn Risk (chọn 3,000 người nhóm B) lỗ -$17,250 (ROI = -0.742); trong khi Top-30% Uplift Knapsack (chọn 1,500 A + 1,500 E) thu về +$101,250 (ROI = +1.588) — tạo cách biệt +$118,500 so với dự báo rủi ro rời bỏ!
3. Thí nghiệm Đối chứng Có Kiểm soát (causal_uplift_lab: 4,000 Train / 2,000 Test, 38.0% Sleeping Dogs)#
Trên SCM giữ chân khách hàng phi tuyến có biến hỗn tạp quan sát (tenure_z, usage_freq_z, support_tickets_z, dormant_autopay_flag, price_sensitivity_z) và tác nhân kích hoạt Sleeping Dogs (True Test ATE = +0.0546, Treat-All Test Profit = -$22,292.8), kết quả chạy thực nghiệm scripts/run_lab_demo.py --seed 42 --quick chứng minh hoàn toàn quy luật:
Chiến lược / Mô hình (Test N = 2,000) |
Sai số ATE |
PEHE |
Oracle AUUC |
Oracle Qini |
IPW Qini Thực nghiệm |
Lợi nhuận Top-30% |
|---|---|---|---|---|---|---|
| Dự báo Rủi ro Rời bỏ (\(\hat{p}_{\text{churn}}\)) | N/A | 0.4215 |
+0.0572 |
+0.0299 |
+0.0310 |
+$4,727.3 |
Quan sát Ngây thơ (Hằng số ATE) |
+0.0761 |
0.2351 |
+0.0292 |
+0.0019 |
+0.0014 |
-$13,093.5 |
S-Learner (Thiếu Tương tác \(X \cdot W\)) |
+0.0106 |
0.2178 |
+0.0422 |
+0.0149 |
+0.0039 |
+$5,100.7 |
Honest Causal Tree (Độ sâu 3, 50/50) |
+0.0029 |
0.1587 |
+0.0692 |
+0.0419 |
+0.0549 |
+$9,941.1 |
DR-Learner (Khớp chéo 5-Nếp) |
-0.0136 |
0.1103 |
+0.0825 |
+0.0552 |
+0.0684 |
+$19,940.3 |
R-Learner (DML Trực giao) |
-0.0012 |
0.0976 |
+0.0841 |
+0.0568 |
+0.0671 |
+$21,553.3 |
X-Learner (Trọng số Xu hướng) |
+0.0045 |
0.1018 |
+0.0838 |
+0.0565 |
+0.0645 |
+$21,304.4 |
S-Learner (+ Tương tác \(\boldsymbol{\phi}(X)\cdot W\)) |
+0.0007 |
0.0583 |
+0.0868 |
+0.0595 |
+0.0665 |
+$22,483.1 |
T-Learner (Cơ sở Logistic Đúng dạng) |
+0.0015 |
0.0617 |
+0.0867 |
+0.0594 |
+0.0660 |
+$22,471.0 |
(Ngoài ra, chính sách ngưỡng không giới hạn \(\hat{\Pi}_{\text{DR}}(x) > 0\) chỉ tác động lên 38.1% tập kiểm tra nhưng mang về +$20,894.9 [ROI = +1.280], đạt 85.4% trần lý tưởng Oracle = +$24,465.1 trên 38.5% tập mẫu!)
4. Cẩm nang Quyết định Sản xuất (When to Use X vs. Y)#
| Chế độ Bài toán & Dữ liệu | Ràng buộc / Rủi ro Chính | Lựa chọn Khuyến nghị | Cấm Dùng Tuyệt đối | Mẫu Phục vụ (Serving) |
|---|---|---|---|---|
| Phân loại Trạng thái Không Can thiệp (Gian lận, định giá rủi ro) | Chỉ cần \(\mathbb{P}(Y \mid X)\); không có nhánh hành động đối lập | Bộ phân loại hiệu chuẩn (LightGBM/CatBoost + Isotonic/Venn-Abers) |
Ép buộc mô hình CATE khi hành động cố định |
Online < 10 ms |
| Quyết định Bật/Tắt Toàn cầu | Quyết định ship toàn bộ, không cá nhân hóa theo người dùng | RCT A/B Test + CUPED/MLRATE (ATE + guardrail) |
Cá nhân hóa sớm khi hiệu ứng tổng chưa dương | Kho thử nghiệm (mSPRT) |
RCT Cân bằng (50/50), Dạng Hàm Tương tác Rõ |
Ít hỗn tạp (\(e(x)=0.5\)); cần xếp hạng độ nhạy nhanh | T-Learner, S-Learner (+ \(X\cdot W\)), hoặc CausalForestDML |
S-Learner tuyến tính/nông thiếu tương tác \(X\cdot W\) |
Lô đêm / Cây nhẹ |
Mất cân bằng Nhánh Nặng (e(x) <= 0.15 hoặc >= 0.85) |
Nhánh nhỏ quá khớp hoặc co rút khác nhánh lớn (T-Learner lệch) |
X-Learner (trộn \(\hat{e}(x)\)) hoặc DR-Learner |
T-Learner không trọng số |
Lô đêm \(\to\) Redis/Feast |
| Nhật ký Quan sát Có Nhiễu Hỗn tạp & Chiều \(X\) Cao | Sai lệch chọn lọc; hàm nhiễu hội tụ chậm hơn \(\sqrt{n}\) | Cross-Fitted R-Learner (DML) hoặc DR-Learner + Phản bác |
Hiệu trung bình thô hoặc Plug-in không trực giao |
DoWhy+EconML + Cổng Refute |
| Ngân sách Hạn chế & Chi phí Chiết khấu Biến thiên | \(V(x)\) và tỷ lệ đổi mã \(\mu_1(x)\) khác nhau giữa các nhóm | Ba lô 0–1 ROI Biên (xếp hạng \(\hat{\Pi}(x)/\hat{c}_{\text{exp}}(x)\), ngưỡng \(\lambda^*\)) | Xếp hạng thuần theo \(\hat{\tau}(x)\) hoặc \(\hat{p}_{\text{churn}}(x)\) | Nhân tử \(\lambda_t^*\) + cache \(\hat{\tau}\) |
3.2 Năm Nghiên cứu Tình huống Công nghiệp Thực tế (5 Named Production Case Studies)#
- Case 1 — Đấu thầu Quảng cáo Gia tăng (
Criteo AI Lab Uplift Benchmark, Diemert et al., AdKDD 2018): Trên13,979,592bản ghi hiển thị quảng cáo (85%điều trị,15%đối chứng ngẫu nhiên, tỷ lệ truy cập4.70%, tỷ lệ chuyển đổi0.292%), thuật toán đấu thầu truyền thống (pCTR/pCVR) dồn ngân sách mua lại đúng những khách hàng trung thành vốn tự gõ URL vào mua (Sure Things), trong khi hiển thị quảng cáo quá dày gây phản cảm làm giảm chuyển đổi (Sleeping Dogs). Dùng đường congQini+ kiểm định đối chứng ngẫu nhiên loại bỏ chi phí quảng cáo thừa. - Case 2 — Tối ưu Khuyến mãi Sàn Hai Chiều (
Uber CausalML, Chen et al., 2020): Áp dụngR-Learner,DR-Learnervà Cây Uplift cho các bậc mã giảm giá (\(W \in \{0, 5, 10, 15\}\,\text{USD}\)) trên tài xế và hành khách. Vì lịch sử phân bổ mã khuyến mãi từng vùng có xác suất xu hướng lệch mạnh (\(e_k(x) \to 0.01\) hoặc \(0.99\)),CausalMLáp dụng kẹp biên điểm xu hướng và trực giao hóaR-Learnernhằm dồn mã giảm giá cho hành khách nhạy cảm giá (Persuadables) thay vì khách đi làm hằng ngày (Sure Things). - Case 3 — Chống Tự Ăn mòn Biên Lợi nhuận (
Booking.com UpliftML, Goldenberg et al., RecSys 2020 & ICDM 2022): Khác gợi ý sản phẩm miễn phí, mỗi voucher/nâng hạng phòng được đổi trừ thẳng vào hoa hồng gộp.Booking.comkết hợp ước lượng hồi cứu hiệu chuẩn đối chứng với bài toán Ba lô Đa lựa chọn Trực tuyến (Online MCKP) chọn tối đa 1 ưu đãi trên mỗi phiên qua nhân tử đối ngẫu \(\lambda^*\) giữ chuẩn ROI toàn sàn, rồi kiểm chứng cuối cùng qua A/B Test đối chiếu chính sách trực tuyến. - Case 4 — Giữ chân Thuê bao Viễn thông/SaaS (Bài học Cốt lõi Article
#3): Chiến dịch tự động gửi thư nhắc + ưu đãi gia hạn tới nhóm dự báo rời bỏ cao từng làm tăng+20 pptỷ lệ hủy gói ở phân khúc thuê bao tự động gia hạn thầm lặng (Sleeping Dogs), đồng thời đốt công suất tổng đài vào nhóm Lost Causes. Chuyển sangDR-Learner+ quy tắc \(\hat{\Pi}(x) > 0\) giúp chặn hoàn toàn Sleeping Dogs và lật ROI chiến dịch từ âm sang dương. - Case 5 — Nhiễu Hỗn tạp Theo Chỉ định & Sụp đổ Hỗ trợ Chung trong Tín dụng/Y tế (
VanderWeele & Ding 2017;Li et al. 2018): Thẩm định nâng hạn mức tín dụng (hoặc phác đồ hồi sức) trên \(N=4{,}000\) hồ sơ quan sát có hiệu ứng thật \(\tau_{\text{true}} = 0.000\), nhưng đội ngũ chỉ cấp cho khách hàng điểm tín dụng rất tốt (\(e(x) = \sigma(3.5 x)\)). Kết quả trongcausal_uplift_lab: so sánh ngây thơ thổi phồng hiệu ứng ảo lên+0.4969(+49.7 pp!),IPWkhông kẹp gánh trọng số lên tới1,091.4xđánh tụtESS_ctrlcòn363.3, kẹp biên thô[0.03, 0.97]vẫn lệch+0.1394, trong khi Overlap Weighting (ATO) khóamax_wt = 0.999(ESS_ctrl = 831.4) và khôi phục-0.0000, kết hợp bộ phản bácDoWhy+E-value(3.4142choRR = 2.0) ngăn chặn triển khai nhầm phác đồ vô tác dụng!
3.3 Sáu Chế độ Lỗi Sản xuất (FM1–FM6) & Checklist Sẵn sàng 5 Điểm#
Chế độ Lỗi (FM) |
Nguyên nhân Gốc | Tín hiệu Phát hiện | Khắc phục Chuẩn mực |
|---|---|---|---|
FM1: Điều chỉnh Nhầm Collider / Mediator |
Đưa biến phát sinh sau \(W\) (discount_redeemed, resolution_time) hoặc cấu trúc M-Bias vào \(\mathbf{X}\) |
Tổng tác động biến mất (+0.405 -> 0.000) hoặc tương quan nghịch lý kiểu Berkson (-0.500) |
Khóa hợp đồng thời gian t_feature < t_decision (PIT) & kiểm tra CausalDAG |
FM2: Sụp đổ Positivity (\(e(x) \to 0, 1\)) |
Chính sách lịch sử quá tất định tạo trọng số \(1/e(x) > 100\times\) | Kish \(\operatorname{ESS}/N \ll 0.25\); một vài mẫu chi phối toàn bộ ATE |
Chuyển ATO (Overlap Weights) hoặc thu hẹp vùng hỗ trợ chung / chạy RCT nhỏ |
FM3: Bỏ rơi W (S-Learner) hoặc Lệch T-Learner |
Phạt điều chuẩn nuốt cột \(W\) hoặc co rút lệch hai nhánh không cân bằng | S-Learner báo \(\hat{\tau}(x) \approx 0\) hoặc T-Learner tạo CATE ảo khi ATE = 0 |
Dùng DR-Learner / R-Learner (DML) hoặc X-Learner (hoặc thêm \(X\cdot W\)) |
FM4: Rò rỉ Khớp Nhiễu Trong Mẫu (In-Sample DML) |
Dùng chính dữ liệu khớp \(\hat{\ell}, \hat{m}\) để tính phần dư DML |
Độ phủ khoảng tin cậy 95% tụt thảm hại (55%) & SE bị nén giả |
Bắt buộc K-Fold Cross-Fitting (K >= 5) tách rời tuyệt đối \(\mathcal{D}_{-k}\) và \(I_k\) |
FM5: Bỏ qua Sleeping Dogs & Ngưỡng Lợi nhuận |
Chỉ nhìn AUUC dương ở Top-10% rồi thả chạy Top-40% không trừ chi phí \(c_{\text{exp}}\) |
Lợi nhuận ròng âm hoặc lỗ vùng đuôi khi mở rộng ngân sách | Khóa điều kiện \(\hat{\Pi}(x) > 0\), tối ưu Ba lô ROI Biên, kiểm tra cắt lát Qini |
FM6: Tự Đầu độc Vòng lặp Chính sách Tất định |
Phục vụ 100% theo ngưỡng \(\hat{\Pi}(x) > 0\) triệt tiêu mẫu đối chứng ở nhóm tích cực |
Kỳ tái huấn luyện sau rơi vào Positivity Collapse (e(x) in {0, 1}) |
Giữ vĩnh viễn 5% Nhóm Đối chứng Khám phá Ngẫu nhiên & ghi nhật ký \(e_{\text{log}}(x)\) |
Checklist 5 Điểm Trước Khi Đưa Mô hình Uplift Lên Sản xuất: (1) DAG & hợp đồng PIT đã khóa không chứa hậu duệ của \(W\); (2) Độ phủ chồng lấn ESS/N >= 0.25 (hoặc báo cáo ATO); (3) Ước lượng CATE qua K-fold cross-fitting dưới quy ước dấu đã khóa; (4) Vượt qua Placebo (\(\approx 0\)), Random Common Cause, Subset, báo cáo E-value/RV_q, và thắng mô hình rủi ro trên Qini & lợi nhuận thực nghiệm; (5) Bật lọc \(\hat{\Pi}(x) > 0\) / Ba lô ngân sách < 20 ms p99 kèm 5% đối chứng khám phá ghi \(e_{\text{log}}(x)\).
3.4 Mã nguồn Tham chiếu Hệ sinh thái 2026 (DoWhy + EconML)#
Ranh giới Môi trường: Đoạn mã dưới đây minh họa chuẩn API sản xuất
DoWhy >= 0.12+EconML >= 0.15trong môi trường Python3.12+(uv). TrongLab 02(causal_uplift_lab), toàn bộ các bộ ước lượng này được xây dựng từ đầu bằng thuần Python + NumPy + Pandas + Pydantic v2 để tránh mọi hộp đen và bẫy ABI ngoài.
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
import pandas as pd
from dowhy import CausalModel
from econml.dml import CausalForestDML
from econml.dr import DRLearner
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor
@dataclass(frozen=True)
class UpliftDecisionConfig:
ltv_value: float = 200.0
contact_cost: float = 5.0
incentive_cost: float = 25.0
propensity_clip: tuple[float, float] = (0.03, 0.97)
random_state: int = 42
def run_dowhy_econml_pipeline(
train_df: pd.DataFrame,
test_df: pd.DataFrame,
feature_cols: list[str],
cfg: UpliftDecisionConfig,
) -> dict[str, object]:
"""2026 Production Reference: DoWhy DAG Identification + Refutation + EconML CATE."""
dot_edges = " ".join(f"{col} -> W; {col} -> Y;" for col in feature_cols)
causal_graph = f"digraph {{ {dot_edges} W -> Y; }}"
causal_model = CausalModel(data=train_df, treatment="W", outcome="Y", graph=causal_graph)
identified_estimand = causal_model.identify_effect(proceed_when_unidentifiable=True)
# 1. Cross-Fitted CausalForestDML for ATE/CATE & Honest Intervals
cf_est = causal_model.estimate_effect(
identified_estimand,
method_name="backdoor.econml.dml.CausalForestDML",
control_value=0,
treatment_value=1,
target_units="ate",
method_params={
"init_params": {
"model_y": GradientBoostingRegressor(random_state=cfg.random_state),
"model_t": GradientBoostingClassifier(random_state=cfg.random_state),
"discrete_treatment": True,
"n_estimators": 200,
"honest": True,
"cv": 5,
"random_state": cfg.random_state,
},
"fit_params": {},
},
)
# 2. Automated Refutation Gate Before Promotion
refute_rcc = causal_model.refute_estimate(
identified_estimand, cf_est, method_name="random_common_cause", random_seed=cfg.random_state
)
refute_placebo = causal_model.refute_estimate(
identified_estimand,
cf_est,
method_name="placebo_treatment_refuter",
placebo_type="permute",
random_seed=cfg.random_state,
)
# 3. Cross-Fitted DRLearner + Variable-Cost Retention Profit Rule
dr = DRLearner(
model_propensity=GradientBoostingClassifier(random_state=cfg.random_state),
model_regression=GradientBoostingRegressor(random_state=cfg.random_state),
model_final=GradientBoostingRegressor(random_state=cfg.random_state),
min_propensity=cfg.propensity_clip[0],
cv=5,
random_state=cfg.random_state,
)
dr.fit(
Y=train_df["Y"].to_numpy(dtype=np.float64),
T=train_df["W"].to_numpy(dtype=np.int64),
X=train_df[feature_cols].to_numpy(dtype=np.float64),
)
tau_hat = dr.effect(test_df[feature_cols].to_numpy(dtype=np.float64))
t1_mask = train_df["W"] == 1
mu1_model = GradientBoostingClassifier(random_state=cfg.random_state).fit(
train_df.loc[t1_mask, feature_cols], train_df.loc[t1_mask, "Y"]
)
mu1_hat = mu1_model.predict_proba(test_df[feature_cols])[:, 1]
exp_cost = cfg.contact_cost + mu1_hat * cfg.incentive_cost
net_profit = tau_hat * cfg.ltv_value - exp_cost
return {
"ate_dml": float(cf_est.value),
"placebo_ate": float(refute_placebo.new_effect),
"rcc_ate": float(refute_rcc.new_effect),
"treat_mask": net_profit > 0.0,
"expected_net_profit": float(np.sum(net_profit[net_profit > 0.0])),
}
Trụ cột 4 — Thực hành Lab 02 (causal_uplift_lab) & Bộ 15 Kiểm thử Tự động (Hands-On Lab & 15-Test Verification Rubric)#
Bài thực hành đồng hành tại labs/lab-02-eda-to-causal-uplift-pipeline/ hiện thực hóa trọn vẹn từ nguyên lý gốc mọi thuật toán đồ thị nhân quả, IPW/ATO/AIPW, Cross-Fitted DML2, 5 Meta-Learners, Honest Causal Tree, Qini/AUUC, Phản bác & Ba lô ROI thành gói cài đặt chuẩn PEP 621 causal_uplift_lab.
4.1 Kiến trúc Gói causal_uplift_lab, Lõi Tham chiếu Sạch & Rào chắn Bảo mật AST#
labs/lab-02-eda-to-causal-uplift-pipeline/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch05_workbench_results.json
├── src/
│ └── causal_uplift_lab/
│ ├── __init__.py
│ ├── scm_and_identification.py
│ ├── estimators_and_dml.py
│ └── uplift_roi_and_qini.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_causal_uplift_lab.py
- Hợp đồng
pyproject.toml(Python >= 3.10): Khai báoname = "causal-uplift-lab",dependencies = ["numpy>=1.26", "pandas>=2.0", "pydantic>=2.0"],[project.optional-dependencies] dev = ["pytest>=8.0", "ruff>=0.4"]. - Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật (
Test 15): Toàn bộ hồi quy logisticIRLS\(L_2\), hồi quy Ridge có trọng số, phân tách Bayes-Ball, cây trung thựcEMSE, tối ưu chính sách và bộ phản bác đều cài đặt từ gốc bằngNumPy/Pandas/Pydantic v2(không lệ thuộcscipy/sklearn/dowhy/econmlở lõi tham chiếu). Bộ kiểm thử thực thi Rào chắn AST Chỉ Bảo mật (Security-Only AST Deserialization Ban) cấm tuyệt đối mọi importpickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshaltrong toàn bộsrc/,scripts/, vàtests/.
4.2 Ba Mô-đun Cốt lõi, Thực thi CLI & Bảng 6 KPI Đối chứng (artifacts/ch05_workbench_results.json)#
src/causal_uplift_lab/scm_and_identification.py:CausalUpliftConfig(ConfigDict(frozen=True, extra="forbid")),ReproducibleCausalRng,CausalDAG(Bayes-Ballis_d_separated,is_valid_backdoor_set,find_minimal_backdoor_sets,verify_frontdoor_set),simulate_collider_berkson_bias,simulate_simpson_vs_backdoor,simulate_churn_retention_dgp,simulate_positivity_collapse_dgp,compute_e_value,compute_cinelli_hazlett_rv, vàrun_refutation_suite.src/causal_uplift_lab/estimators_and_dml.py:build_nonlinear_basis,welford_mean_and_se,fit_ridge,fit_l2_logistic,compute_kish_ess,estimate_ipw(HTvs.Hájek),estimate_overlap_ato,estimate_aipw(khớp chéo \(K\)-nếp có cờ kiểm chứng sai lệch đơn nhánh),estimate_naive_plugin,estimate_dml_plr(DML2), vàsimulate_plr_dml_ablation.src/causal_uplift_lab/uplift_roi_and_qini.py:PredictiveChurnRiskModel,SLearner(include_interactionstoggle),TLearner,XLearner,RLearner,DRLearner,HonestCausalTree(\(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\) + ModifiedEMSE),compute_transformed_outcome,compute_qini_and_auuc,compute_r_and_dr_loss,optimize_knapsack_retention_policy,audit_worked_10k_churn_vs_uplift, vàrun_full_causal_uplift_benchmarks.
Chạy lệnh sau tại labs/lab-02-eda-to-causal-uplift-pipeline/:
python scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch05_workbench_results.json
Chỉ số KPI (artifacts/ch05_workbench_results.json) |
Giá trị Đo kiểm Thực tế (--seed 42 --quick) |
Trạng thái |
|---|---|---|
kpi_collider_and_simpson_bridge (Berkson N=400 / Schur & Simpson \(\to\) Backdoor) |
\(-0.500\) / \(-0.059\) (Schur lý thuyết -0.500, thực nghiệm -0.4932; Backdoor lật +0.456 -> -0.059) |
warn (Cảnh báo bẫy collider) |
kpi_aipw_and_positivity_ato (AIPW Bền vững Kép & Case 5 ATO) |
AIPW +0.0448 / ATO -0.0000 (True = +0.0551; sai một nhánh +0.0551/+0.0416; Case 5 Naive = +0.497) |
ok (Đã xác minh) |
kpi_dml_crossfit_coverage (PLR d=350: 5-Fold DML2 vs. Naive độ phủ 95%) |
90% vs 0% (Naive bias = -0.364; In-Sample DML = 55% (-0.102); DML2 bias = +0.009) |
ok (Đã xác minh) |
kpi_article3_10k_profit_swing (Article #3 10k: Churn Top-30% vs. Uplift Top-30%) |
-$17,250 -> +$101,250 (Treat-All = -$69,750; cách biệt +$118,500, ROI -0.742 -> +1.588) |
critical (Minh chứng ROI) |
kpi_retention_qini_and_pehe (Test N=2,000: Churn Risk vs. DR-Learner Top-30%) |
$4,727 vs $19,940 (DR IPW Qini = +0.0684, PEHE = 0.1103; DR Profit>0 = +$20,895; T-Learner = +$22,471) |
ok (Đã xác minh) |
kpi_refutation_and_sensitivity (Placebo ATE, E-value RR=2.0, OVB RV_1) |
Plc -0.0056 / \(E = 3.414\) (RCC shift = 0.00027, Subset = 0.01384, RV_1 = 0.0700 tại \(\lvert t\rvert = 4.58\)) |
ok (Qua cổng phản bác) |
4.3 Hợp đồng 15 Kiểm thử Tự động pytest (tests/test_causal_uplift_lab.py)#
| # | Tên Hàm Kiểm thử | Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | test_causal_dag_dsep_backdoor_mbias_and_frontdoor_rules |
Kiểm định \(d\)-separation (Chain/Fork/Collider/M-Bias), Backdoor loại M & C, Frontdoor 3 điều kiện. |
| 2 | test_collider_and_berkson_selection_bias_exact_proofs |
Khớp chứng minh Schur \(\operatorname{Corr}(X,Y \mid C) = -0.500\) và Berkson rời rạc \(N=400\) (0.000 -> -0.500). |
| 3 | test_simpson_vs_backdoor_identification_bridge |
Khẳng định chuẩn hóa Cửa sau khôi phục -0.05 từ +0.456, còn điều kiện hóa trung gian triệt tiêu +0.405 -> 0. |
| 4 | test_ipw_hajek_bounds_shift_invariance_and_positivity_overlap_ato |
Chứng minh HT-IPW vượt biên [0,1] & gãy dịch chuyển +500, Hájek bất biến, và Case 5 ATO khôi phục 0.000. |
| 5 | test_aipw_doubly_robust_either_nuisance_consistent |
AIPW giữ \(\lvert\text{bias}\rvert < 0.025\) khi chỉ \(e\) sai (IPW sập) hoặc chỉ \(\mu\) sai (G-comp sập), và chỉ sập khi cả hai sai. |
| 6 | test_dml_plr_eliminates_naive_regularization_bias_and_in_sample_overfit |
Naive phủ <= 20%, In-Sample phủ <= 75%, 5-Fold DML2 đạt >= 80% và \(\lvert\text{bias}\rvert < 0.05\) trên d=350. |
| 7 | test_s_learner_dropout_vs_t_x_r_dr_learners_on_imbalanced_arm |
Trên nhánh mất cân bằng 12% treated, S-Learner thiếu tương tác sập (PEHE > 0.60), X/R/T đạt < 0.25. |
| 8 | test_honest_causal_tree_prevents_adaptive_overfitting |
HonestCausalTree tách đôi \(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\) cho RMSE thấp hơn hẳn cây không trung thực (honest=False). |
| 9 | test_uplift_qini_auuc_and_transformed_outcome_unbiasedness |
Kiểm chứng \(\mathbb{E}[Y^*] \approx \tau\) nhưng \(\operatorname{std}(Y^*) > 5\sigma_\tau\), Qini/AUUC dương, và R/DR-loss chọn đúng mô hình. |
| 10 | test_article3_churn_vs_uplift_10k_and_retention_dgp_roi_reversal |
Xác nhận 10k swing +$118,500 chính xác từng đồng và thắng lợi nhuận thực nghiệm trên Retention DGP. |
| 11 | test_knapsack_budget_policy_respects_budget_and_marginal_roi_order |
Bảo đảm Ba lô ưu tiên ROI Biên khi chi phí chiết khấu biến thiên, không bao giờ chọn \(\Pi(x) \le 0\) và không vượt ngân sách. |
| 12 | test_top_frac_policy_never_targets_sleeping_dogs_negative_profit |
Khẳng định chính sách top_frac lọc cứng profit_hat > 0.0, tuyệt đối không bao giờ chọn Sleeping Dogs có lợi nhuận kỳ vọng âm. |
| 13 | test_refutation_suite_e_value_and_cinelli_hazlett_ovb |
Placebo sập < 0.03, RCC & Subset ổn định, E(2.0) = 3.4142, và đồng nhất thức RV_q^2 / (1-RV_q) = f_q^2. |
| 14 | test_pydantic_config_frozen_and_seed_determinism |
CausalUpliftConfig chặn khóa lạ/đột biến và giữ tái lập bit-for-bit theo seed. |
| 15 | test_cli_demo_workbench_json_and_zero_forbidden_imports |
Chạy CLI xuất đủ 6 KPI, 4 bars, 4 tables và rào chắn AST Chỉ Bảo mật quét 0 import giải tuần tự hóa nguy hiểm trên src/, scripts/, tests/. |
Trụ cột 5 — Danh mục Tài liệu SOTA 2024–2026 & Bài tập Đánh giá Năng lực (Curated Reading List & Mastery Exercises)#
5.1 Danh mục Tài liệu Kinh điển & Mũi nhọn 2024–2026#
- Pearl, J. (2009), Shpitser, I. & Pearl, J. (2006) & Berkson, J. (1946). Causality: Models, Reasoning, and Inference (2nd ed.) và Identification of Joint Interventional Distributions (
IDAlgorithm).
Vì sao quan trọng: Đặt nền tảngSCM, \(d\)-separation, Backdoor/Frontdoor, tính đầy đủ của 3 quy tắcdo-calculus và giải phẫu thiên lệch chọn lọc collider. - Rubin, D. B. (1974), Rosenbaum, P. & Rubin, D. B. (1983), Robins, J. et al. (1994), Hahn, J. (1998), King, G. & Nielsen, R. (2019) & Li, F. et al. (JASA 2018).
Vì sao quan trọng: Thiết lập Potential Outcomes, định lýe(X), cảnh báo nghịch lýPSM, chứng minh Bền vững KépAIPW, cận bán tham số Hahn và Overlap WeightingATOchống sụp đổ positivity. - Chernozhukov, V., Chetverikov, D., Demirer, M., Duflo, E., Hansen, C., Newey, W., & Robins, J. (2018). Double/Debiased Machine Learning for Treatment and Structural Parameters (
arXiv:1608.00060).
Vì sao quan trọng: Chứng minh tính Trực giao Neyman, cận tích sai số \(n^{-1/4}\), và \(K\)-Fold Cross-Fitting loại bỏ hoàn toàn thiên lệch điều chuẩn lẫn quá khớp phi-Donsker. - Künzel, S. et al. (PNAS 2019), Nie, X. & Wager, S. (Biometrika 2021), Kennedy, E. (JRSS-B 2023) & Athey, S., Tibshirani, J., & Wager, S. (PNAS 2016 / JASA 2018 / AoS 2019).
Vì sao quan trọng: Chuẩn hóaS/T/X/R/DR-Learner, Cây Nhân quả Trung thực (EMSE+ tách đôi \(\mathcal{I}^{\text{split}}/\mathcal{I}^{\text{est}}\)), và Rừng Ngẫu nhiên Tổng quátGRF(IJ/BLB). - Radcliffe, N. (2007), Diemert, E. et al. (AdKDD 2018 —
Criteo), Goldenberg, D. & Albert, J. (RecSys 2020 / ICDM 2022 —Booking.com), Chen, H. et al. (2020 —Uber CausalML).
Vì sao quan trọng: Cầu nối trực tiếp tới Article#3, đường congQini, phát hiện Sleeping Dogs ở quy mô hàng chục triệu lượt hiển thị, và tối ưu hóa Ba lô Đa lựa chọnMCKP. - VanderWeele, T. & Ding, P. (2017), Cinelli, C. & Hazlett, C. (JRSS-B 2020 / DML-OVB 2024), Lei, L. & Candès, E. (JRSS-B 2021,
arXiv:2006.06138), Wang, Q. & Qiao, N. (wTCP-DR/ Weighted Doubly Robust Conformal Prediction,arXiv:2501.14933, 2025), Athey, S. & Wager, S. (Econometrica 2021 —PolicyTree), &CausalPFN/TabPFN-CFM/CauScientist(2025–2026).
Vì sao quan trọng: Hoàn thiện bộ giáp phản bác, độ nhạy biến ẩn (E-value, \(RV_q\)), dải tin cậy ConformalITE, học chính sách trực tiếp, và mô hình nền tảng nhân quả thế hệ mới.
5.2 Tám Điểm Kiểm tra Tư duy & Nắm vững Khái niệm (Q1–Q8)#
- Q1 (Nghịch lý Simpson vs. Điều kiện hóa Trung gian): Tại sao Chuẩn hóa Trực tiếp ở Chương 04 khôi phục hiệu ứng thật khi \(S\) là biến hỗn tạp (
+0.456 -> -0.059), nhưng lại phá hủy tác động thật khi \(M\) là biến trung gian (+0.405 -> +0.0001) dù bảng \(P(W, S, Y)\) giống hệt nhau? - Q2 (\(d\)-Separation,
M-Bias& Chứng minh Lệch Collider): Nêu cơ chế bất đối xứng của nút Collider trong \(d\)-separation; giải thích vì sao tập rỗng \(\emptyset\) không chệch trên đồ thịM-Biascòn đưa \(C\) vào tập điều chỉnh lại gây hại; và chứng minh từ Bù Schur vì sao \(\operatorname{Corr}(X, Y \mid C) = -0.500\) khi \(C = X + Y + \varepsilon_C\). - Q3 (Cửa trước
Frontdoor&do-Calculus): Trình bày ý nghĩa 3 Quy tắcdo-calculus và chỉ rõ bước nào trong chứng minh Công thức Cửa trước dùng Quy tắc 2 vs. Quy tắc 3 để vượt qua biến hỗn tạp ẩn \(U\). - Q4 (
HT-IPWvs.Hájek,AIPW&ATO): Giải thích vì saoHT-IPWvượt biên[0, 1]và hỏng bất biến dịch chuyển \(Y + c\); viết ra đồng nhất thức sai số tích củaAIPWchứng minh chỉ cần một trong hai mô hình \(\hat{\mu}_w\) hoặc \(\hat{e}\) đúng; và giải thích khi nào dùng Overlap Weighting (ATO). - Q5 (
DML: Thiên lệch Điều chuẩn, Trực giao Neyman & Cross-Fitting): Chứng minh vì saoNaive ML Plug-Inphân kỳ ở tốc độ \(\Theta(n^{1/2-\varphi_g})\) (0%độ phủ), chứng minh đạo hàm Gateaux của điểm Robinson bằng0, và giải thích vì saoIn-Sample DMLvẫn tụt độ phủ (55%) khi bỏK-Fold Cross-Fitting. - Q6 (5 Meta-Learners & Rừng Trung thực): Phân tích khi nào
S-Learnerrơi vào regularization drop-out, khi nàoT-Learnerbịa raCATEgiả do chênh lệch cỡ mẫu, vì sao trọng số \(g(x) = \hat{e}(x)\) trongX-Learnerthu hẹp phương sai, và vì saoHonestCausalTreebắt buộc tách rời \(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\). - Q7 (
Qini/AUUC/ \(Y^*\) /R-loss& Phản bác): Chứng minh \(\mathbb{E}[Y^* \mid X] = \tau(X)\) và giải thích bẫy phương sai của \(Y^*\) so vớiR-loss/DR-loss; trình bày ý nghĩa củaPlaceborefuter,E-value\(E_{\text{sens}} = \text{RR} + \sqrt{\text{RR}(\text{RR}-1)}\), vàCinelli–Hazlett\(RV_q\). - Q8 (Chuyên đề
#3& Kiến trúc Sản xuất): Dựng 4 góc phần tư khách hàng, giải thích cú lội ngược dòng-$17,250 -> +$101,250trên10,000thuê bao, viết quy tắc Ba lô 0–1 ROI Biên với chi phí chiết khấu có điều kiện \(c_{\text{contact}} + \mu_1(x)d_{\text{incentive}}\), và giải thích vai trò sống còn của5%đối chứng khám phá ngẫu nhiên thường trực + log \(e_{\text{log}}(x)\).
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%— Định danh Đồ thị, Chứng minh Berkson & Cầu nối Simpson): Chứng minh bằng Bù Schur công thức \(\operatorname{Cov}(X, Y \mid C)\) và \(\operatorname{Corr}(X, Y \mid C) = -0.500\); chứng minh công thức Frontdoor bằng 3 quy tắcdo-calculus; kiểm chứng bằngCausalDAG,simulate_collider_berkson_bias, vàsimulate_simpson_vs_backdoor. - Bài tập 2 (
20%— Định lý Rosenbaum–Rubin,HTvs.Hájek,ATO& Chứng minh KépAIPW): Chứng minh đầy đủ \((Y(1),Y(0))\perp W \mid X \implies \perp W \mid e(X)\) và đồng nhất thức sai số tíchAIPW; kiểm chứng thực nghiệm Case 5 sụp đổ positivity (Naive = +0.4969vsATO = -0.0000) và kiểm traestimate_aipwkhi làm hỏng lần lượt \(\hat{e}\) và \(\hat{\mu}_w\). - Bài tập 3 (
20%— Chứng minh Trực giao Neyman & Mô phỏngDML2Đa chiều): Chứng minhNaive Plug-Inphân kỳ \(\Theta(n^{1/2-\varphi_g})\) và cận \(o(n^{-1/2})\) khi \(\hat{\ell}, \hat{m}\) hội tụ ở tốc độ \(n^{-1/4}\); chạysimulate_plr_dml_ablation(n_samples=500, n_dim=350)đối chiếu0%(Naive),55%(In-Sample) và90%(5-Fold DML2). - Bài tập 4 (
15%— Meta-Learners Mất cân bằng & Cây Nhân quả Trung thực): Cài đặt và so sánhS,T,X,R,DR-LearnerkhiP(W=1) ≈ 0.12(chứng minhS-Learnerthiếu tương tác tụtPEHE > 0.60); đối chiếuHonestCausalTree(honest=True)vshonest=Falsetrên DGP hiệu ứng bằng0. - Bài tập 5 (
15%— Đánh giá Phản thựcQini/R-loss/DR-loss& Bộ Phản bác + Độ nhạy): Chứng minh \(\mathbb{E}[Y^*\mid X] = \tau(X)\) và giải thích sự bùng nổ phương sai; xếp hạng mô hình bằngcompute_r_and_dr_losstrêncausal_uplift_lab; chạyrun_refutation_suite,compute_e_value(2.0, 1.45), và kiểm tra đồng nhất thứcRV_q^2 / (1-RV_q) = f_q^2. - Bài tập 6 (
15%— Chuyên đề#3: Tối ưu Ba lô ROI Giữ chân & Bài toán10,000Thuê bao): Tự tay giải bài toán10,000khách hàng chứng minh chênh lệch+$118,500; chạyoptimize_knapsack_retention_policydưới ngân sách hữu hạn và biến thiên chi phí \(c_{\text{exp}}(x)\); thiết kế đặc tả kiến trúc serving< 20 ms p99có nhóm giữ lại khám phá5%và log \(e_{\text{log}}(x)\).
5.4 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh toán học không nhảy bước (Schur Collider -0.500, Frontdoor, HT vs Hájek, Đồng nhất thức sai số tích AIPW, Phân kỳ Naive & Trực giao Neyman DML, E-value); gói causal_uplift_lab vượt qua 15/15 pytest với 0 import giải tuần tự hóa nguy hiểm ở rào chắn AST Test 15; giải chuẩn xác cú lội ngược dòng +$118,500 (Article #3), xử lý Positivity ATO, và thiết kế được 5% exploration holdout ngăn tự đầu độc. |
| Senior Standard | 75–89% | Cài đặt đúng thuần NumPy/Pandas/Pydantic qua 15/15 pytest, nhưng còn thiếu chi tiết chứng minh Frontdoor qua do-calculus, bỏ sót biến chi phí chiết khấu có điều kiện \(\mu_1(x) d_{\text{incentive}}\) trong Ba lô ROI, hoặc chưa phân biệt rạch ròi R-loss (overlap-weighted) với DR-loss (unweighted). |
| Needs Remediation | < 75% | Nhầm lẫn dự báo \(\hat{p}_{\text{churn}}(x)\) với uplift \(\tau(x)\); đưa biến hậu can thiệp (mediator/collider) vào mô hình; dùng PSM bất chấp nghịch lý King–Nielsen hoặc IPW không kiểm tra ESS khi \(e(x) \to 0,1\); hoặc khớp nhiễu DML trong mẫu mà không dùng Cross-Fitting. |
PLR High-Dim DML: 95% CI Empirical Coverage (%) Across Regimes
Case 5 Positivity Collapse & AIPW Double Robustness |ATE Error|
Article #3 Retention Test: Oracle Qini Coefficient Across Targeting Policies
Article #3 Retention Test: Realized Net Incremental Profit ($) by Policy
SCM DAG Identification, Collider / Berkson Selection Bias & Simpson -> Backdoor Bridge
| check_or_scenario | theoretical_or_rule | empirical_observed | status |
|---|---|---|---|
| backdoor_confounder_Z | Valid (blocks W <- Z -> Y) | True | IDENTIFIED |
| backdoor_with_mediator_M | Reject (descendant of W) | True | REJECTED_OVERCONTROL |
| backdoor_with_collider_C | Reject (descendant & collider) | True | REJECTED_COLLIDER |
| mbias_empty_conditioning | Blocked at collider C | True | UNBIASED_EMPTY_SET |
| linear_gauss_collider_c | rho = -0.5000 | partial=-0.4932, slice=-0.4924 | BIAS_CONFIRMED |
| berkson_400_cohort | 0.000 -> -0.500 | 0.000 -> -0.500 | BIAS_CONFIRMED |
| simpson_2x2_vs_backdoor | true=-0.050 | naive=+0.456 -> backdoor=-0.059 | REVERSAL_SOLVED |
Positivity Collapse (ATO), AIPW Double Robustness & Cross-Fitted PLR DML Ablation
| estimator_or_regime | target_truth | estimate_or_mean | diagnostic_metric | verdict |
|---|---|---|---|---|
| case5_naive_diff | 0.0000 | +0.4969 | severe confounding | BIASED_FAIL |
| case5_ipw_unclipped | 0.0000 | +0.0140 | max_wt=1091.4, ESS_ctrl=363.3 | POS_COLLAPSE |
| case5_overlap_ato | 0.0000 | -0.0000 | max_wt=0.999, ESS_ctrl=831.4 | EXACT_RECOVERY |
| aipw_both_consistent | +0.0551 | +0.0448 | SE=0.0181 | UNBIASED_DR |
| aipw_bad_propensity_only | +0.0551 | +0.0551 | IPW fails at +0.1307 | RESCUED_BY_MU |
| aipw_bad_outcome_only | +0.0551 | +0.0416 | G-comp fails at +0.0000 | RESCUED_BY_E |
| plr_naive_plugin | 1.000 | 0.6364 | 95% cov=0% | REG_BIAS_FAIL |
| plr_insample_dml | 1.000 | 0.8982 | 95% cov=55% | OVERFIT_UNDERCOV |
| plr_5fold_crossfit_dml2 | 1.000 | 1.0087 | 95% cov=90% | ORTHOGONAL_PASS |
Article #3 Retention DGP Held-Out Ablation (PEHE, AUUC, Qini & Top-30% Net Profit)
| model | ate_bias | pehe | oracle_auuc | oracle_qini | factual_ipw_qini | top30_net_profit |
|---|---|---|---|---|---|---|
| Predictive_Churn_Risk | N/A | 0.4215 | 0.0572 | 0.0299 | 0.031 | 4727.3 |
| Naive_Obs_Constant | 0.0761 | 0.2351 | 0.0292 | 0.0019 | 0.0014 | -13093.5 |
| S_Learner_NoInteract | 0.0106 | 0.2178 | 0.0422 | 0.0149 | 0.0039 | 5100.7 |
| Honest_Causal_Tree | 0.0029 | 0.1587 | 0.0692 | 0.0419 | 0.0549 | 9941.1 |
| DR_Learner_CrossFit | -0.0136 | 0.1103 | 0.0825 | 0.0552 | 0.0684 | 19940.3 |
| R_Learner_DML | -0.0012 | 0.0976 | 0.0841 | 0.0568 | 0.0671 | 21553.3 |
| X_Learner | 0.0045 | 0.1018 | 0.0838 | 0.0565 | 0.0645 | 21304.4 |
| S_Learner_Interact | 0.0007 | 0.0583 | 0.0868 | 0.0595 | 0.0665 | 22483.1 |
| T_Learner | 0.0015 | 0.0617 | 0.0867 | 0.0594 | 0.066 | 22471.0 |
Article #3 10k Policy Audit, DoWhy Refutation Suite & Sensitivity Bounds
| audit_item | metric | value | reference_or_note |
|---|---|---|---|
| 10k_treat_all | net_profit ($) | -69750.0 | Sleeping Dogs + Sure Things burn margin |
| 10k_top30_churn_risk | net_profit ($) | -17250.0 | ROI=-0.742 (Lost Causes) |
| 10k_top30_uplift_knapsack | net_profit ($) | 101250.0 | ROI=+1.588 (Persuadables) |
| refute_placebo_treatment | placebo_ate | -0.00563 | passed=True (base=+0.0430) |
| refute_random_common_cause | rcc_shift | 0.00027 | rcc_ate=+0.0428 |
| refute_data_subset_80pct | subset_shift | 0.013837 | subset_ate=+0.0569 |
| vanderweele_ding_evalue | E_sens (RR=2.0) | 3.4142 | E_CI(1.45)=2.2578 |
| cinelli_hazlett_ovb | RV_1 (q=1.0) | 0.07 | DML |t|=4.58 |
02-track-1-data-science-and-ai/part-01-math-stats-and-causal/labs/lab-02-eda-to-causal-uplift-pipeline
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "causal-uplift-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for Pearl SCMs, Potential Outcomes, Cross-Fitted DML, Uplift Meta-Learners, Honest Causal Trees, Refutation & Retention ROI Optimization (T1-P1-U05)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.4",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
[tool.ruff]
line-length = 100
target-version = "py310"
"""Public package exports for Lab 02: Causal Inference, Cross-Fitted DML & Uplift ROI (`causal_uplift_lab`)."""
from __future__ import annotations
from causal_uplift_lab.estimators_and_dml import (
build_nonlinear_basis,
compute_kish_ess,
estimate_aipw,
estimate_dml_plr,
estimate_ipw,
estimate_naive_plugin,
estimate_overlap_ato,
fit_l2_logistic,
fit_ridge,
make_random_folds,
make_stratified_folds,
predict_proba_logistic,
predict_ridge,
sigmoid_stable,
simulate_plr_dml_ablation,
welford_mean_and_se,
)
from causal_uplift_lab.scm_and_identification import (
CausalDAG,
CausalUpliftConfig,
ReproducibleCausalRng,
compute_cinelli_hazlett_rv,
compute_e_value,
run_refutation_suite,
simulate_churn_retention_dgp,
simulate_collider_berkson_bias,
simulate_positivity_collapse_dgp,
simulate_simpson_vs_backdoor,
)
from causal_uplift_lab.uplift_roi_and_qini import (
DRLearner,
HonestCausalTree,
PredictiveChurnRiskModel,
RLearner,
SLearner,
TLearner,
XLearner,
audit_worked_10k_churn_vs_uplift,
compute_qini_and_auuc,
compute_r_and_dr_loss,
compute_transformed_outcome,
optimize_knapsack_retention_policy,
run_full_causal_uplift_benchmarks,
)
__all__ = [
"CausalDAG",
"CausalUpliftConfig",
"DRLearner",
"HonestCausalTree",
"PredictiveChurnRiskModel",
"RLearner",
"ReproducibleCausalRng",
"SLearner",
"TLearner",
"XLearner",
"audit_worked_10k_churn_vs_uplift",
"build_nonlinear_basis",
"compute_cinelli_hazlett_rv",
"compute_e_value",
"compute_kish_ess",
"compute_qini_and_auuc",
"compute_r_and_dr_loss",
"compute_transformed_outcome",
"estimate_aipw",
"estimate_dml_plr",
"estimate_ipw",
"estimate_naive_plugin",
"estimate_overlap_ato",
"fit_l2_logistic",
"fit_ridge",
"make_random_folds",
"make_stratified_folds",
"optimize_knapsack_retention_policy",
"predict_proba_logistic",
"predict_ridge",
"run_full_causal_uplift_benchmarks",
"run_refutation_suite",
"sigmoid_stable",
"simulate_churn_retention_dgp",
"simulate_collider_berkson_bias",
"simulate_plr_dml_ablation",
"simulate_positivity_collapse_dgp",
"simulate_simpson_vs_backdoor",
"welford_mean_and_se",
]
"""Structural Causal Models (DAG d-separation, Backdoor/Frontdoor), Synthetic DGPs, Refutation & Sensitivity Analysis."""
from __future__ import annotations
import math
from collections import deque
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from typing import Any
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field, model_validator
class CausalUpliftConfig(BaseModel):
"""Frozen Pydantic v2 configuration contract for causal uplift experiments."""
model_config = ConfigDict(frozen=True, extra="forbid")
seed: int = Field(default=42, ge=0)
n_train: int = Field(default=4000, ge=200)
n_test: int = Field(default=2000, ge=200)
n_folds: int = Field(default=5, ge=2, le=20)
propensity_clip: tuple[float, float] = Field(default=(0.03, 0.97))
ltv_value: float = Field(default=200.0, gt=0.0)
contact_cost: float = Field(default=5.0, ge=0.0)
incentive_cost: float = Field(default=25.0, ge=0.0)
ridge_alpha: float = Field(default=1.0, gt=0.0)
logistic_l2: float = Field(default=1.0, gt=0.0)
@model_validator(mode="after")
def _check_clip_bounds(self) -> CausalUpliftConfig:
lo, hi = self.propensity_clip
if not (0.0 < lo < hi < 1.0):
raise ValueError(f"propensity_clip must satisfy 0 < lo < hi < 1, got {self.propensity_clip}")
return self
@dataclass(frozen=True, slots=True)
class ReproducibleCausalRng:
"""Isolated PCG64 substreams spawned via SeedSequence."""
master_seed: int
dgp_rng: np.random.Generator
split_rng: np.random.Generator
refute_rng: np.random.Generator
tree_rng: np.random.Generator
@classmethod
def from_seed(cls, seed: int) -> ReproducibleCausalRng:
s_dgp, s_spl, s_ref, s_tree = np.random.SeedSequence(seed).spawn(4)
return cls(
master_seed=seed,
dgp_rng=np.random.default_rng(s_dgp),
split_rng=np.random.default_rng(s_spl),
refute_rng=np.random.default_rng(s_ref),
tree_rng=np.random.default_rng(s_tree),
)
class CausalDAG:
"""Exact Directed Acyclic Graph supporting Bayes-Ball d-separation, Backdoor & Frontdoor checks."""
def __init__(self, nodes: Iterable[str], edges: Iterable[tuple[str, str]]) -> None:
self.nodes: tuple[str, ...] = tuple(dict.fromkeys(nodes))
node_set = set(self.nodes)
self.parents: dict[str, set[str]] = {n: set() for n in self.nodes}
self.children: dict[str, set[str]] = {n: set() for n in self.nodes}
self.edges: list[tuple[str, str]] = []
for u, v in edges:
if u not in node_set or v not in node_set:
raise ValueError(f"Edge ({u}, {v}) references unknown node.")
if u == v:
raise ValueError(f"Self-loop ({u}, {v}) violates DAG acyclicity.")
if v not in self.children[u]:
self.children[u].add(v)
self.parents[v].add(u)
self.edges.append((u, v))
self._verify_acyclic()
def _verify_acyclic(self) -> None:
indeg = {n: len(self.parents[n]) for n in self.nodes}
q = deque([n for n, d in indeg.items() if d == 0])
visited = 0
while q:
u = q.popleft()
visited += 1
for v in self.children[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
if visited != len(self.nodes):
raise ValueError("Graph contains a directed cycle; CausalDAG requires acyclicity.")
def subgraph_without_outgoing(self, cut_nodes: Iterable[str]) -> CausalDAG:
cut = set(cut_nodes)
return CausalDAG(self.nodes, [(u, v) for u, v in self.edges if u not in cut])
def subgraph_without_incoming(self, cut_nodes: Iterable[str]) -> CausalDAG:
cut = set(cut_nodes)
return CausalDAG(self.nodes, [(u, v) for u, v in self.edges if v not in cut])
def descendants(self, start: str | Iterable[str]) -> set[str]:
seeds = [start] if isinstance(start, str) else list(start)
seen: set[str] = set()
q = deque(seeds)
while q:
u = q.popleft()
for v in self.children[u]:
if v not in seen:
seen.add(v)
q.append(v)
return seen
def ancestors(self, start: str | Iterable[str]) -> set[str]:
seeds = [start] if isinstance(start, str) else list(start)
seen: set[str] = set()
q = deque(seeds)
while q:
u = q.popleft()
for p in self.parents[u]:
if p not in seen:
seen.add(p)
q.append(p)
return seen
def has_directed_path(self, source: str, target: str, blocked: Iterable[str] = ()) -> bool:
"""Return True if a directed path source -> ... -> target exists avoiding blocked interior nodes."""
blk = set(blocked)
if source in blk or target in blk:
return False
seen = {source}
q = deque([source])
while q:
u = q.popleft()
for v in self.children[u]:
if v == target:
return True
if v not in blk and v not in seen:
seen.add(v)
q.append(v)
return False
def reachable_d_connected(self, source: str | Iterable[str], conditioned: Iterable[str] = ()) -> set[str]:
"""Koller-Friedman Bayes-Ball algorithm returning all nodes d-connected to source given conditioned."""
src = [source] if isinstance(source, str) else list(source)
z_set = set(conditioned)
anc_z = z_set | self.ancestors(z_set)
visited_states: set[tuple[str, str]] = set()
q: deque[tuple[str, str]] = deque((s, "up") for s in src)
reachable: set[str] = set()
while q:
node, direction = q.popleft()
if (node, direction) in visited_states:
continue
visited_states.add((node, direction))
if node not in z_set:
reachable.add(node)
if direction == "up" and node not in z_set:
for p in self.parents[node]:
q.append((p, "up"))
for c in self.children[node]:
q.append((c, "down"))
elif direction == "down":
if node not in z_set:
for c in self.children[node]:
q.append((c, "down"))
if node in anc_z:
for p in self.parents[node]:
q.append((p, "up"))
return reachable
def is_d_separated(
self,
source: str | Iterable[str],
target: str | Iterable[str],
conditioned: Iterable[str] = (),
) -> bool:
tgt = {target} if isinstance(target, str) else set(target)
reach = self.reachable_d_connected(source, conditioned)
return len(reach & tgt) == 0
def is_valid_backdoor_set(
self,
treatment: str,
outcome: str,
z_set: Iterable[str],
) -> dict[str, Any]:
"""Check Pearl's two exact Backdoor Criterion conditions relative to (treatment, outcome)."""
z = set(z_set)
if treatment in z or outcome in z:
return {"valid": False, "reason": "Adjustment set cannot contain treatment or outcome."}
desc_w = self.descendants(treatment)
desc_overlap = sorted(z & desc_w)
if desc_overlap:
return {
"valid": False,
"reason": f"Condition 1 failed: contains descendant(s) of {treatment}: {desc_overlap}.",
}
g_under_w = self.subgraph_without_outgoing([treatment])
if not g_under_w.is_d_separated(treatment, outcome, z):
return {
"valid": False,
"reason": "Condition 2 failed: unblocked backdoor path remains in G_underline_W.",
}
return {"valid": True, "adjustment_set": sorted(z), "reason": "Satisfies Pearl Backdoor Criterion."}
def find_minimal_backdoor_sets(
self,
treatment: str,
outcome: str,
observable_nodes: Iterable[str] | None = None,
) -> list[tuple[str, ...]]:
"""Exhaustive minimal valid backdoor sets over observable pre-treatment candidates (for small DAGs)."""
obs = set(self.nodes) if observable_nodes is None else set(observable_nodes)
desc_w = self.descendants(treatment)
candidates = sorted((obs - {treatment, outcome}) - desc_w)
if len(candidates) > 16:
raise ValueError("Candidate count > 16; restrict observable_nodes for exhaustive search.")
valid_sets: list[set[str]] = []
n_cand = len(candidates)
for mask in range(1 << n_cand):
sub = {candidates[i] for i in range(n_cand) if (mask >> i) & 1}
if any(prev.issubset(sub) for prev in valid_sets):
continue
if self.is_valid_backdoor_set(treatment, outcome, sub)["valid"]:
valid_sets.append(sub)
return sorted((tuple(sorted(s)) for s in valid_sets), key=lambda t: (len(t), t))
def verify_frontdoor_set(
self,
treatment: str,
outcome: str,
m_set: Iterable[str],
) -> dict[str, Any]:
"""Verify Pearl's three exact Frontdoor Criterion conditions relative to (treatment, outcome)."""
m = set(m_set)
if not m or treatment in m or outcome in m:
return {"valid": False, "reason": "Mediator set M must be non-empty and disjoint from (W, Y)."}
cond1 = not self.has_directed_path(treatment, outcome, blocked=m)
if not cond1:
return {"valid": False, "reason": "Condition 1 failed: M does not intercept all directed W -> Y paths."}
g_under_w = self.subgraph_without_outgoing([treatment])
cond2 = all(g_under_w.is_d_separated(treatment, mi, ()) for mi in m)
if not cond2:
return {"valid": False, "reason": "Condition 2 failed: unblocked backdoor path from W to M."}
g_under_m = self.subgraph_without_outgoing(m)
cond3 = all(g_under_m.is_d_separated(mi, outcome, {treatment}) for mi in m)
if not cond3:
return {"valid": False, "reason": "Condition 3 failed: W does not block all backdoor paths M -> Y."}
return {"valid": True, "mediator_set": sorted(m), "reason": "Satisfies Pearl Frontdoor Criterion."}
def simulate_collider_berkson_bias(
n_samples: int = 20000,
alpha: float = 1.0,
beta: float = 1.0,
noise_std: float = 1.0,
seed: int = 42,
) -> dict[str, Any]:
"""Reproduce Linear-Gaussian Schur Collider Bias & discrete N=400 Berkson Selection Bias."""
rng = np.random.default_rng(seed)
x = rng.normal(0.0, 1.0, size=n_samples)
y = rng.normal(0.0, 1.0, size=n_samples)
eps = rng.normal(0.0, noise_std, size=n_samples)
c = alpha * x + beta * y + eps
uncond_corr = float(np.corrcoef(x, y)[0, 1])
# Condition on |C| <= 0.35 slice (empirical conditioning on C ≈ 0)
slice_mask = np.abs(c) <= 0.35
cond_slice_corr = float(np.corrcoef(x[slice_mask], y[slice_mask])[0, 1])
# Partial correlation controlling linearly for C matches exact Schur complement
rx = x - (np.cov(x, c, ddof=0)[0, 1] / np.var(c)) * c
ry = y - (np.cov(y, c, ddof=0)[0, 1] / np.var(c)) * c
emp_partial_corr = float(np.corrcoef(rx, ry)[0, 1])
theo_cov = -(alpha * beta) / (alpha**2 + beta**2 + noise_std**2)
theo_corr = -(alpha * beta) / math.sqrt((beta**2 + noise_std**2) * (alpha**2 + noise_std**2))
# Crisp Discrete N=400 Berkson Cohort: (1,1):100, (1,0):100, (0,1):100, (0,0):100
xb = np.array([1] * 200 + [0] * 200, dtype=np.float64)
yb = np.array([1] * 100 + [0] * 100 + [1] * 100 + [0] * 100, dtype=np.float64)
cb = (xb + yb) >= 1.0
berkson_full_corr = float(np.corrcoef(xb, yb)[0, 1])
berkson_sel_corr = float(np.corrcoef(xb[cb], yb[cb])[0, 1])
return {
"n_samples": int(n_samples),
"unconditional_corr": uncond_corr,
"empirical_partial_corr_given_c": emp_partial_corr,
"empirical_slice_corr_given_c0": cond_slice_corr,
"theoretical_cov_given_c": float(theo_cov),
"theoretical_corr_given_c": float(theo_corr),
"berkson_400_full_corr": berkson_full_corr,
"berkson_400_selected_corr": berkson_sel_corr,
}
def simulate_simpson_vs_backdoor(n_samples: int = 2000, seed: int = 42) -> dict[str, Any]:
"""Bridge Ch 04 Simpson 2x2 reversal directly to Pearl Backdoor Adjustment (confounder vs mediator)."""
rng = np.random.default_rng(seed)
# Exact Ch 04 counts scaled or deterministic strata (N=2000: 1000 Stratum 1, 1000 Stratum 2)
n_half = n_samples // 2
s = np.concatenate([np.zeros(n_half, dtype=np.int64), np.ones(n_samples - n_half, dtype=np.int64)])
# In S=0, 90% get W=0 (A) and 10% get W=1 (B); in S=1, 10% get W=0 (A) and 90% get W=1 (B)
p_w = np.where(s == 0, 0.10, 0.90)
w = (rng.random(n_samples) < p_w).astype(np.int64)
# True within-stratum effect of B vs A is -0.05 (A beats B by +5.0 pp in both strata)
p_y = np.where(s == 0, np.where(w == 0, 0.20, 0.15), np.where(w == 0, 0.85, 0.80))
y = (rng.random(n_samples) < p_y).astype(np.float64)
naive_diff = float(np.mean(y[w == 1]) - np.mean(y[w == 0]))
backdoor_std = 0.0
for sv in (0, 1):
ps = float(np.mean(s == sv))
diff_s = float(np.mean(y[(s == sv) & (w == 1)]) - np.mean(y[(s == sv) & (w == 0)]))
backdoor_std += ps * diff_s
# Contrast with a Mediator chain W -> M -> Y where conditioning on M destroys total effect (+0.40)
w_med = (rng.random(n_samples) < 0.5).astype(np.int64)
m_med = (rng.random(n_samples) < np.where(w_med == 1, 0.80, 0.20)).astype(np.int64)
y_med = 0.65 * m_med + rng.normal(0.0, 0.1, size=n_samples)
mediator_total = float(np.mean(y_med[w_med == 1]) - np.mean(y_med[w_med == 0]))
mediator_cond = 0.0
for mv in (0, 1):
pm = float(np.mean(m_med == mv))
mediator_cond += pm * float(np.mean(y_med[(m_med == mv) & (w_med == 1)]) - np.mean(y_med[(m_med == mv) & (w_med == 0)]))
return {
"naive_marginal_diff_confounded": naive_diff,
"backdoor_adjusted_ate": float(backdoor_std),
"true_ate": -0.05,
"simpson_reversal_detected": bool(naive_diff > 0.0 and backdoor_std < 0.0),
"mediator_true_total_effect": mediator_total,
"mediator_overcontrol_biased_effect": float(mediator_cond),
}
def _sigmoid(z: np.ndarray) -> np.ndarray:
zc = np.clip(z, -35.0, 35.0)
return 1.0 / (1.0 + np.exp(-zc))
def simulate_churn_retention_dgp(
n_samples: int = 4000,
seed: int = 42,
) -> dict[str, Any]:
"""Generate confounded Telco/SaaS Retention SCM with Persuadables, Sure Things, Lost Causes & Sleeping Dogs.
Outcome convention (Locked): Y=1 means RETAINED / RENEWED, Y=0 means CHURNED.
Positive tau(x) = mu1(x) - mu0(x) > 0 means retention outreach SAVES the customer.
"""
rng = np.random.default_rng(seed)
x0 = rng.normal(0.0, 1.0, size=n_samples) # tenure_z
x1 = rng.normal(0.0, 1.0, size=n_samples) # usage_freq_z
x2 = rng.normal(0.0, 1.0, size=n_samples) # support_tickets_z
x3 = (rng.random(n_samples) < 0.22).astype(np.float64) # dormant_autopay_flag (Sleeping Dog trigger)
x4 = rng.normal(0.0, 1.0, size=n_samples) # price_sensitivity_z
X = np.column_stack([x0, x1, x2, x3, x4])
e_true = _sigmoid(-0.3 + 0.9 * x0 + 0.7 * x1 + 0.8 * x2 - 0.5 * x3)
w = (rng.random(n_samples) < e_true).astype(np.int64)
eta0 = 0.6 + 0.8 * x0 + 1.1 * x1 - 1.2 * x2 + 1.3 * x3 - 0.3 * x4
delta_eta = 0.95 + 0.85 * x4 + 0.55 * np.tanh(x2) - 0.45 * np.maximum(x0, 0.0) - 2.35 * x3
mu0_true = _sigmoid(eta0)
mu1_true = _sigmoid(eta0 + delta_eta)
tau_true = mu1_true - mu0_true
y0 = (rng.random(n_samples) < mu0_true).astype(np.float64)
y1 = (rng.random(n_samples) < mu1_true).astype(np.float64)
y = np.where(w == 1, y1, y0)
feature_names = ("tenure_z", "usage_freq_z", "support_tickets_z", "dormant_autopay_flag", "price_sensitivity_z")
df = pd.DataFrame(X, columns=list(feature_names))
df["w"] = w
df["y"] = y
df["tau_true"] = tau_true
return {
"X": X,
"w": w,
"y": y,
"y0": y0,
"y1": y1,
"mu0_true": mu0_true,
"mu1_true": mu1_true,
"tau_true": tau_true,
"e_true": e_true,
"feature_names": feature_names,
"sleeping_dog_share": float(np.mean(tau_true < 0.0)),
"df": df,
}
def simulate_positivity_collapse_dgp(n_samples: int = 4000, seed: int = 7) -> dict[str, Any]:
"""Generate Case 5 FinTech/Healthcare zero-effect confounding-by-indication with extreme propensity tails."""
rng = np.random.default_rng(seed)
x = rng.normal(0.0, 1.0, size=n_samples)
z_noise = rng.normal(0.0, 1.0, size=n_samples)
X = np.column_stack([x, z_noise])
e_true = _sigmoid(3.5 * x)
w = (rng.random(n_samples) < e_true).astype(np.int64)
# True treatment effect is EXACTLY 0; outcome driven purely by x
mu_base = _sigmoid(2.2 * x)
y = (rng.random(n_samples) < mu_base).astype(np.float64)
return {
"X": X,
"w": w,
"y": y,
"e_true": e_true,
"true_ate": 0.0,
}
def compute_e_value(risk_ratio: float, ci_bound: float | None = None) -> dict[str, float]:
"""Compute VanderWeele & Ding (2017) E-value for point estimate and optional CI limit."""
if risk_ratio <= 0.0:
raise ValueError("risk_ratio must be strictly positive.")
def _ev(rr: float) -> float:
r = rr if rr >= 1.0 else (1.0 / rr)
return float(r + math.sqrt(r * (r - 1.0)))
e_point = _ev(risk_ratio)
out = {"risk_ratio": float(risk_ratio), "e_value_point": e_point}
if ci_bound is not None:
if ci_bound <= 0.0:
raise ValueError("ci_bound must be strictly positive.")
if (risk_ratio >= 1.0 and ci_bound <= 1.0) or (risk_ratio < 1.0 and ci_bound >= 1.0):
out["e_value_ci"] = 1.0
else:
out["e_value_ci"] = _ev(ci_bound)
return out
def compute_cinelli_hazlett_rv(t_stat: float, df: int, q: float = 1.0) -> dict[str, float]:
"""Compute Cinelli & Hazlett (2020) Robustness Value RV_q for omitted variable bias."""
if df <= 0 or not (0.0 < q <= 1.0):
raise ValueError("df must be > 0 and q must lie in (0, 1].")
fq = q * abs(float(t_stat)) / math.sqrt(float(df))
rv_q = 0.5 * (math.sqrt(fq**4 + 4.0 * fq**2) - fq**2)
return {"f_q": float(fq), "rv_q": float(rv_q)}
def run_refutation_suite(
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
estimator_fn: Callable[[np.ndarray, np.ndarray, np.ndarray, int], float],
seed: int = 42,
subset_frac: float = 0.80,
) -> dict[str, Any]:
"""Execute DoWhy-style falsification suite: Placebo Treatment, Random Common Cause, and Data Subset."""
rng = np.random.default_rng(seed)
base_est = float(estimator_fn(X, w, y, seed))
# 1. Placebo Treatment: permute treatment assignment destroying W -> Y
w_perm = rng.permutation(w)
placebo_est = float(estimator_fn(X, w_perm, y, seed + 1))
# 2. Random Common Cause: append independent N(0, 1) noise covariate keeping fold seed constant
u_rand = rng.normal(0.0, 1.0, size=(X.shape[0], 1))
X_rcc = np.column_stack([X, u_rand])
rcc_est = float(estimator_fn(X_rcc, w, y, seed))
# 3. Data Subset (80%)
n_sub = max(50, round(subset_frac * X.shape[0]))
idx_sub = np.sort(rng.choice(X.shape[0], size=n_sub, replace=False))
subset_est = float(estimator_fn(X[idx_sub], w[idx_sub], y[idx_sub], seed + 3))
return {
"baseline_ate": base_est,
"placebo_ate": placebo_est,
"random_common_cause_ate": rcc_est,
"data_subset_ate": subset_est,
"placebo_passed": bool(abs(placebo_est) < max(0.025, 0.5 * abs(base_est))),
"rcc_shift": float(abs(rcc_est - base_est)),
"subset_shift": float(abs(subset_est - base_est)),
}
"""Pure-NumPy Nuisance Learners, Propensity/IPW/Overlap/AIPW Estimators, and Cross-Fitted Double ML (DML)."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
def sigmoid_stable(z: np.ndarray) -> np.ndarray:
"""Numerically stable logistic sigmoid avoiding exp overflow."""
zc = np.clip(z, -35.0, 35.0)
return 1.0 / (1.0 + np.exp(-zc))
def build_nonlinear_basis(X: np.ndarray) -> np.ndarray:
"""Construct rich 16-feature nonlinear basis from first 5 covariates, preserving extra columns."""
arr = np.asarray(X, dtype=np.float64)
if arr.shape[1] >= 5:
x0, x1, x2, x3, x4 = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3], arr[:, 4]
base = [
x0,
x1,
x2,
x3,
x4,
np.tanh(x2),
np.maximum(x0, 0.0),
x0 * x0,
x1 * x1,
x2 * x2,
x4 * x4,
x0 * x3,
x1 * x3,
x2 * x3,
x4 * x3,
x2 * x4,
]
if arr.shape[1] > 5:
return np.column_stack(base + [arr[:, 5:]])
return np.column_stack(base)
# Generic quadratic expansion for arbitrary dimension d < 5
return np.column_stack([arr, arr * arr, np.tanh(arr)])
def welford_mean_and_se(values: np.ndarray) -> tuple[float, float]:
"""Single-pass Welford mean and standard error avoiding catastrophic cancellation."""
arr = np.asarray(values, dtype=np.float64)
n = int(arr.size)
if n == 0:
raise ValueError("Cannot compute Welford mean/SE of empty array.")
mean = 0.0
m2 = 0.0
for idx, val in enumerate(arr, start=1):
delta = float(val) - mean
mean += delta / idx
delta2 = float(val) - mean
m2 += delta * delta2
if n == 1:
return mean, 0.0
var = m2 / float(n - 1)
return float(mean), float(math.sqrt(max(0.0, var) / float(n)))
def fit_ridge(
X: np.ndarray,
y: np.ndarray,
alpha: float = 1.0,
sample_weights: np.ndarray | None = None,
) -> tuple[np.ndarray, float]:
"""Closed-form Ridge Regression (unpenalized intercept) with optional observation weights."""
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = x_arr.shape
Xb = np.column_stack([x_arr, np.ones(n, dtype=np.float64)])
reg = np.eye(d + 1, dtype=np.float64) * float(alpha)
reg[-1, -1] = 1e-10 # Keep intercept unpenalized (tiny numerical stabilizer)
if sample_weights is not None:
sw = np.asarray(sample_weights, dtype=np.float64)
Xw = Xb * sw[:, None]
xtx = Xw.T @ Xb + reg
xty = Xw.T @ y_arr
else:
xtx = Xb.T @ Xb + reg
xty = Xb.T @ y_arr
coef = np.linalg.solve(xtx, xty)
return coef[:-1], float(coef[-1])
def predict_ridge(X: np.ndarray, w_coef: np.ndarray, intercept: float) -> np.ndarray:
"""Predict with fitted Ridge linear coefficients."""
return np.asarray(X, dtype=np.float64) @ w_coef + float(intercept)
def fit_l2_logistic(
X: np.ndarray,
y: np.ndarray,
l2_reg: float = 1.0,
max_iter: int = 35,
) -> tuple[np.ndarray, float]:
"""Damped Newton-Raphson IRLS for L2-regularized Logistic Regression (pure NumPy)."""
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = x_arr.shape
Xb = np.column_stack([x_arr, np.ones(n, dtype=np.float64)])
reg = np.eye(d + 1, dtype=np.float64) * float(l2_reg)
reg[-1, -1] = 0.0
theta = np.zeros(d + 1, dtype=np.float64)
for _ in range(max_iter):
p = sigmoid_stable(Xb @ theta)
grad = Xb.T @ (p - y_arr) + reg @ theta
w_diag = np.maximum(p * (1.0 - p), 1e-8)
hess = (Xb.T * w_diag) @ Xb + reg + 1e-8 * np.eye(d + 1, dtype=np.float64)
step = np.linalg.solve(hess, grad)
theta -= step
if float(np.max(np.abs(step))) < 1e-7:
break
return theta[:-1], float(theta[-1])
def predict_proba_logistic(X: np.ndarray, w_coef: np.ndarray, intercept: float) -> np.ndarray:
"""Predict positive-class probabilities from fitted logistic weights."""
return sigmoid_stable(np.asarray(X, dtype=np.float64) @ w_coef + float(intercept))
def make_stratified_folds(w: np.ndarray, n_folds: int = 5, seed: int = 42) -> np.ndarray:
"""Deterministic stratified K-fold split preserving treatment prevalence across folds."""
w_arr = np.asarray(w, dtype=np.int64)
rng = np.random.default_rng(seed)
fold_ids = np.empty(w_arr.size, dtype=np.int64)
for cls_val in (0, 1):
idx = np.flatnonzero(w_arr == cls_val)
rng.shuffle(idx)
for pos, i in enumerate(idx):
fold_ids[i] = pos % n_folds
return fold_ids
def make_random_folds(n_samples: int, n_folds: int = 5, seed: int = 42) -> np.ndarray:
"""Deterministic K-fold partition for continuous or binary treatment."""
rng = np.random.default_rng(seed)
perm = rng.permutation(n_samples)
fold_ids = np.empty(n_samples, dtype=np.int64)
for pos, i in enumerate(perm):
fold_ids[i] = pos % n_folds
return fold_ids
def compute_kish_ess(weights: np.ndarray) -> float:
"""Compute Kish Effective Sample Size ESS = (sum w)^2 / sum(w^2)."""
arr = np.asarray(weights, dtype=np.float64)
if arr.size == 0:
return 0.0
s1 = float(np.sum(arr))
s2 = float(np.sum(arr * arr))
if s2 <= 1e-18:
return 0.0
return float((s1 * s1) / s2)
def estimate_ipw(
y: np.ndarray,
w: np.ndarray,
e_hat: np.ndarray,
clip: tuple[float, float] | None = None,
) -> dict[str, float]:
"""Compare unnormalized Horvitz-Thompson IPW vs. normalized Hajek IPW and Kish ESS."""
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
e_arr = np.asarray(e_hat, dtype=np.float64)
if clip is not None:
e_used = np.clip(e_arr, float(clip[0]), float(clip[1]))
else:
e_used = np.clip(e_arr, 1e-12, 1.0 - 1e-12)
t_mask = w_arr == 1.0
c_mask = w_arr == 0.0
w1_ht = np.where(t_mask, 1.0 / e_used, 0.0)
w0_ht = np.where(c_mask, 1.0 / (1.0 - e_used), 0.0)
n = float(y_arr.size)
ht_mu1 = float(np.sum(w1_ht * y_arr) / n)
ht_mu0 = float(np.sum(w0_ht * y_arr) / n)
ht_ate = float(ht_mu1 - ht_mu0)
hajek_mu1 = float(np.sum(w1_ht * y_arr) / np.sum(w1_ht))
hajek_mu0 = float(np.sum(w0_ht * y_arr) / np.sum(w0_ht))
hajek_ate = float(hajek_mu1 - hajek_mu0)
ess_t = compute_kish_ess(w1_ht[t_mask])
ess_c = compute_kish_ess(w0_ht[c_mask])
max_weight = float(max(np.max(w1_ht[t_mask]), np.max(w0_ht[c_mask])))
return {
"ht_mu1": ht_mu1,
"ht_mu0": ht_mu0,
"ht_ate": ht_ate,
"hajek_mu1": hajek_mu1,
"hajek_mu0": hajek_mu0,
"hajek_ate": hajek_ate,
"ess_treated": ess_t,
"ess_control": ess_c,
"max_weight": max_weight,
"min_propensity": float(np.min(e_arr)),
"max_propensity": float(np.max(e_arr)),
}
def estimate_overlap_ato(
y: np.ndarray,
w: np.ndarray,
e_hat: np.ndarray,
X: np.ndarray | None = None,
) -> dict[str, float]:
"""Li, Morgan & Zaslavsky (2018) Overlap Weighting (ATO) on clinical/business equipoise."""
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
e_arr = np.clip(np.asarray(e_hat, dtype=np.float64), 1e-12, 1.0 - 1e-12)
t_mask = w_arr == 1.0
c_mask = w_arr == 0.0
ow_t = 1.0 - e_arr[t_mask]
ow_c = e_arr[c_mask]
mu1_ow = float(np.sum(ow_t * y_arr[t_mask]) / np.sum(ow_t))
mu0_ow = float(np.sum(ow_c * y_arr[c_mask]) / np.sum(ow_c))
out: dict[str, float] = {
"ato_ate": float(mu1_ow - mu0_ow),
"ess_treated": compute_kish_ess(ow_t),
"ess_control": compute_kish_ess(ow_c),
"max_weight": float(max(np.max(ow_t), np.max(ow_c))),
}
if X is not None:
x_arr = np.asarray(X, dtype=np.float64)
mean_t = (ow_t[:, None] * x_arr[t_mask]).sum(axis=0) / np.sum(ow_t)
mean_c = (ow_c[:, None] * x_arr[c_mask]).sum(axis=0) / np.sum(ow_c)
out["max_weighted_balance_diff"] = float(np.max(np.abs(mean_t - mean_c)))
return out
def estimate_aipw(
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
n_folds: int = 5,
clip: tuple[float, float] = (0.05, 0.95),
l2_reg: float = 1.0,
seed: int = 42,
use_basis: bool = True,
misspecify_propensity: bool = False,
misspecify_outcome: bool = False,
) -> dict[str, Any]:
"""K-fold cross-fitted Doubly Robust AIPW ATE estimator with Welford standard error."""
x_raw = np.asarray(X, dtype=np.float64)
x_feat = build_nonlinear_basis(x_raw) if use_basis else x_raw
w_arr = np.asarray(w, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
n = y_arr.size
is_binary_y = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
fold_ids = make_stratified_folds(w_arr, n_folds=n_folds, seed=seed)
mu0_oof = np.empty(n, dtype=np.float64)
mu1_oof = np.empty(n, dtype=np.float64)
e_oof = np.empty(n, dtype=np.float64)
for k in range(n_folds):
val_m = fold_ids == k
tr_m = ~val_m
if misspecify_propensity:
# Deliberately misspecified propensity (constant wrong rate 0.25)
e_oof[val_m] = 0.25
else:
ew, eb = fit_l2_logistic(x_feat[tr_m], w_arr[tr_m].astype(np.float64), l2_reg=l2_reg)
e_oof[val_m] = predict_proba_logistic(x_feat[val_m], ew, eb)
if misspecify_outcome:
# Deliberately misspecified outcome regression (inverted constant surface)
mu0_oof[val_m] = 0.15
mu1_oof[val_m] = 0.15
else:
t_tr = tr_m & (w_arr == 1)
c_tr = tr_m & (w_arr == 0)
if is_binary_y:
w1_c, b1_c = fit_l2_logistic(x_feat[t_tr], y_arr[t_tr], l2_reg=l2_reg)
w0_c, b0_c = fit_l2_logistic(x_feat[c_tr], y_arr[c_tr], l2_reg=l2_reg)
mu1_oof[val_m] = predict_proba_logistic(x_feat[val_m], w1_c, b1_c)
mu0_oof[val_m] = predict_proba_logistic(x_feat[val_m], w0_c, b0_c)
else:
w1_c, b1_c = fit_ridge(x_feat[t_tr], y_arr[t_tr], alpha=l2_reg)
w0_c, b0_c = fit_ridge(x_feat[c_tr], y_arr[c_tr], alpha=l2_reg)
mu1_oof[val_m] = predict_ridge(x_feat[val_m], w1_c, b1_c)
mu0_oof[val_m] = predict_ridge(x_feat[val_m], w0_c, b0_c)
e_clip = np.clip(e_oof, float(clip[0]), float(clip[1]))
w_flt = w_arr.astype(np.float64)
psi_aipw = (
(mu1_oof - mu0_oof)
+ w_flt * (y_arr - mu1_oof) / e_clip
- (1.0 - w_flt) * (y_arr - mu0_oof) / (1.0 - e_clip)
)
ate, se = welford_mean_and_se(psi_aipw)
ipw_res = estimate_ipw(y_arr, w_arr, e_clip, clip=clip)
return {
"ate": ate,
"se": se,
"ci_low": float(ate - 1.96 * se),
"ci_high": float(ate + 1.96 * se),
"gcomp_ate": float(np.mean(mu1_oof - mu0_oof)),
"ipw_hajek_ate": float(ipw_res["hajek_ate"]),
"psi_scores": psi_aipw,
"mu0_oof": mu0_oof,
"mu1_oof": mu1_oof,
"e_oof": e_clip,
}
def estimate_naive_plugin(
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
ridge_alpha: float = 25.0,
) -> dict[str, float]:
"""Naive single-split or residual-unorthogonalized ML plug-in estimator suffering regularization bias."""
x_arr = np.asarray(X, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n = y_arr.size
# Auxiliary half estimates g_hat(X) directly with strong shrinkage, then regresses (Y - g_hat(X)) on W
half = n // 2
# Fit regularized outcome-only nuisance on aux half (biased when X confounds W)
gw, gb = fit_ridge(x_arr[:half], y_arr[:half], alpha=ridge_alpha)
y_minus_g = y_arr[half:] - predict_ridge(x_arr[half:], gw, gb)
w_eval = w_arr[half:]
denom = float(np.sum(w_eval * w_eval))
theta_hat = float(np.sum(w_eval * y_minus_g) / max(denom, 1e-12))
resid = y_minus_g - theta_hat * w_eval
# Naive OLS SE ignoring nuisance regularization bias
se_naive = float(math.sqrt(np.mean(resid * resid) / max(denom, 1e-12)))
return {
"theta_hat": theta_hat,
"se": se_naive,
"ci_low": float(theta_hat - 1.96 * se_naive),
"ci_high": float(theta_hat + 1.96 * se_naive),
}
def estimate_dml_plr(
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
n_folds: int = 5,
ridge_alpha: float = 5.0,
seed: int = 42,
in_sample: bool = False,
) -> dict[str, Any]:
"""Robinson Partially Linear Regression DML2 (cross-fitted by default; in_sample=True for ablation)."""
x_arr = np.asarray(X, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n = y_arr.size
l_hat = np.empty(n, dtype=np.float64)
m_hat = np.empty(n, dtype=np.float64)
if in_sample:
lw, lb = fit_ridge(x_arr, y_arr, alpha=ridge_alpha)
mw, mb = fit_ridge(x_arr, w_arr, alpha=ridge_alpha)
l_hat[:] = predict_ridge(x_arr, lw, lb)
m_hat[:] = predict_ridge(x_arr, mw, mb)
else:
fold_ids = make_random_folds(n, n_folds=n_folds, seed=seed)
for k in range(n_folds):
val_m = fold_ids == k
tr_m = ~val_m
lw, lb = fit_ridge(x_arr[tr_m], y_arr[tr_m], alpha=ridge_alpha)
mw, mb = fit_ridge(x_arr[tr_m], w_arr[tr_m], alpha=ridge_alpha)
l_hat[val_m] = predict_ridge(x_arr[val_m], lw, lb)
m_hat[val_m] = predict_ridge(x_arr[val_m], mw, mb)
y_res = y_arr - l_hat
w_res = w_arr - m_hat
w_res_sq_mean = float(np.mean(w_res * w_res))
theta_hat = float(np.mean(w_res * y_res) / max(w_res_sq_mean, 1e-12))
# Heteroscedasticity-robust Chernozhukov et al. (2018) sandwich variance
psi = (y_res - theta_hat * w_res) * w_res
j0 = -w_res_sq_mean
sigma2 = float(np.mean(psi * psi)) / max(j0 * j0, 1e-18)
se = float(math.sqrt(sigma2 / float(n)))
return {
"theta_hat": theta_hat,
"se": se,
"ci_low": float(theta_hat - 1.96 * se),
"ci_high": float(theta_hat + 1.96 * se),
"y_res": y_res,
"w_res": w_res,
}
def _fit_adaptive_screen_ridge(
X: np.ndarray,
y: np.ndarray,
use_val: bool = True,
max_k: int = 240,
overfit_alpha: float = 0.15,
) -> tuple[np.ndarray, np.ndarray, float]:
"""Adaptive high-dimensional feature screening + Ridge (illustrates in-sample overfit vs OOF generalization)."""
n = y.size
if not use_val:
yc = y - float(np.mean(y))
xc = X - np.mean(X, axis=0)
denom = np.linalg.norm(xc, axis=0) * max(float(np.linalg.norm(yc)), 1e-12) + 1e-12
corr = np.abs(xc.T @ yc) / denom
k_cap = min(int(max_k), X.shape[1])
idx = np.argsort(-corr)[:k_cap]
w_coef, bias = fit_ridge(X[:, idx], y, alpha=overfit_alpha)
return idx, w_coef, bias
sp = int(0.75 * n)
X_tr, y_tr, X_va, y_va = X[:sp], y[:sp], X[sp:], y[sp:]
yc = y_tr - float(np.mean(y_tr))
xc = X_tr - np.mean(X_tr, axis=0)
denom = np.linalg.norm(xc, axis=0) * max(float(np.linalg.norm(yc)), 1e-12) + 1e-12
order = np.argsort(-(np.abs(xc.T @ yc) / denom))
best_mse = 1e18
best_cfg = (min(15, X.shape[1]), 5.0)
for k in (10, 25, 100, min(int(max_k), X.shape[1])):
idx = order[:k]
for a in (0.2, 5.0, 15.0):
wc, bc = fit_ridge(X_tr[:, idx], y_tr, alpha=a)
pred = predict_ridge(X_va[:, idx], wc, bc)
mse = float(np.mean((y_va - pred) ** 2))
if mse < best_mse:
best_mse = mse
best_cfg = (k, a)
k_opt, a_opt = best_cfg
yc_f = y - float(np.mean(y))
xc_f = X - np.mean(X, axis=0)
denom_f = np.linalg.norm(xc_f, axis=0) * max(float(np.linalg.norm(yc_f)), 1e-12) + 1e-12
idx_f = np.argsort(-(np.abs(xc_f.T @ yc_f) / denom_f))[:k_opt]
wf, bf = fit_ridge(X[:, idx_f], y, alpha=a_opt)
return idx_f, wf, bf
def _predict_adaptive_screen_ridge(X: np.ndarray, model: tuple[np.ndarray, np.ndarray, float]) -> np.ndarray:
idx, wc, bc = model
return predict_ridge(X[:, idx], wc, bc)
def simulate_plr_dml_ablation(
n_samples: int = 500,
n_dim: int = 350,
n_trials: int = 25,
n_folds: int = 5,
theta_true: float = 1.0,
seed: int = 42,
) -> dict[str, Any]:
"""Monte Carlo ablation comparing Naive ML Plug-in, In-Sample Overfit DML, and K-Fold Cross-Fitted DML2."""
rng = np.random.default_rng(seed)
naive_ests, insamp_ests, cross_ests = [], [], []
naive_cov, insamp_cov, cross_cov = 0, 0, 0
beta_g = np.zeros(n_dim, dtype=np.float64)
beta_m = np.zeros(n_dim, dtype=np.float64)
beta_g[:6] = np.array([1.2, -1.0, 0.9, -0.8, 0.7, 0.6])
beta_m[:6] = np.array([0.9, -0.8, 0.7, -0.6, 0.5, 0.4])
for trial in range(n_trials):
X = rng.normal(0.0, 1.0, size=(n_samples, n_dim))
m_x = X @ beta_m + 0.40 * np.tanh(X[:, 0])
g_x = X @ beta_g + 0.50 * np.sin(X[:, 1])
w = m_x + rng.normal(0.0, 0.7, size=n_samples)
y = theta_true * w + g_x + rng.normal(0.0, 1.0, size=n_samples)
# 1. Naive Plug-in: heavily regularized single split without residualizing W
half = n_samples // 2
yc = y[:half] - float(np.mean(y[:half]))
xc = X[:half] - np.mean(X[:half], axis=0)
idx_nv = np.argsort(-np.abs(xc.T @ yc))[:25]
wnv, bnv = fit_ridge(X[:half, idx_nv], y[:half], alpha=60.0)
y_minus_g = y[half:] - predict_ridge(X[half:, idx_nv], wnv, bnv)
w_ev = w[half:]
denom = float(np.sum(w_ev * w_ev))
th_nv = float(np.sum(w_ev * y_minus_g) / max(denom, 1e-12))
resid_nv = y_minus_g - th_nv * w_ev
se_nv = float(math.sqrt(np.mean(resid_nv * resid_nv) / max(denom, 1e-12)))
# 2. In-Sample Overfit DML: same high-capacity screening without cross-fitting
ml_in = _fit_adaptive_screen_ridge(X, y, use_val=False, max_k=240, overfit_alpha=0.15)
mm_in = _fit_adaptive_screen_ridge(X, w, use_val=False, max_k=240, overfit_alpha=0.15)
yr_in = y - _predict_adaptive_screen_ridge(X, ml_in)
wr_in = w - _predict_adaptive_screen_ridge(X, mm_in)
w2_in = float(np.mean(wr_in * wr_in))
th_in = float(np.mean(wr_in * yr_in) / max(w2_in, 1e-12))
psi_in = (yr_in - th_in * wr_in) * wr_in
se_in = float(math.sqrt((np.mean(psi_in * psi_in) / max(w2_in * w2_in, 1e-18)) / float(n_samples)))
# 3. K-Fold Cross-Fitted DML2 with validation-selected screening + Ridge
fold_ids = make_random_folds(n_samples, n_folds=n_folds, seed=seed + trial)
l_cf = np.empty(n_samples, dtype=np.float64)
m_cf = np.empty(n_samples, dtype=np.float64)
for k in range(n_folds):
vm = fold_ids == k
tm = ~vm
ml_k = _fit_adaptive_screen_ridge(X[tm], y[tm], use_val=True, max_k=240)
mm_k = _fit_adaptive_screen_ridge(X[tm], w[tm], use_val=True, max_k=240)
l_cf[vm] = _predict_adaptive_screen_ridge(X[vm], ml_k)
m_cf[vm] = _predict_adaptive_screen_ridge(X[vm], mm_k)
yr_cf = y - l_cf
wr_cf = w - m_cf
w2_cf = float(np.mean(wr_cf * wr_cf))
th_cf = float(np.mean(wr_cf * yr_cf) / max(w2_cf, 1e-12))
psi_cf = (yr_cf - th_cf * wr_cf) * wr_cf
se_cf = float(math.sqrt((np.mean(psi_cf * psi_cf) / max(w2_cf * w2_cf, 1e-18)) / float(n_samples)))
naive_ests.append(th_nv)
insamp_ests.append(th_in)
cross_ests.append(th_cf)
if abs(th_nv - theta_true) <= 1.96 * se_nv:
naive_cov += 1
if abs(th_in - theta_true) <= 1.96 * se_in:
insamp_cov += 1
if abs(th_cf - theta_true) <= 1.96 * se_cf:
cross_cov += 1
def _summarize(ests: list[float], hits: int) -> dict[str, float]:
arr = np.asarray(ests, dtype=np.float64)
return {
"mean_estimate": float(np.mean(arr)),
"bias": float(np.mean(arr) - theta_true),
"rmse": float(np.sqrt(np.mean((arr - theta_true) ** 2))),
"coverage_95": float(hits / float(n_trials)),
}
return {
"theta_true": float(theta_true),
"n_samples": int(n_samples),
"n_dim": int(n_dim),
"n_trials": int(n_trials),
"naive_plugin": _summarize(naive_ests, naive_cov),
"insample_dml": _summarize(insamp_ests, insamp_cov),
"crossfit_dml2": _summarize(cross_ests, cross_cov),
}
"""Uplift Meta-Learners (S/T/X/R/DR), Honest Causal Trees, Qini/AUUC Evaluation & Retention Profit Optimization."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import numpy as np
from causal_uplift_lab.estimators_and_dml import (
build_nonlinear_basis,
estimate_aipw,
estimate_dml_plr,
estimate_ipw,
estimate_overlap_ato,
fit_l2_logistic,
fit_ridge,
make_stratified_folds,
predict_proba_logistic,
predict_ridge,
simulate_plr_dml_ablation,
)
from causal_uplift_lab.scm_and_identification import (
CausalDAG,
CausalUpliftConfig,
compute_cinelli_hazlett_rv,
compute_e_value,
run_refutation_suite,
simulate_churn_retention_dgp,
simulate_collider_berkson_bias,
simulate_positivity_collapse_dgp,
simulate_simpson_vs_backdoor,
)
def _fit_outcome_arm(X_feat: np.ndarray, y: np.ndarray, l2_reg: float, is_binary: bool) -> tuple[np.ndarray, float]:
if is_binary:
return fit_l2_logistic(X_feat, y, l2_reg=l2_reg)
return fit_ridge(X_feat, y, alpha=l2_reg)
def _predict_outcome_arm(X_feat: np.ndarray, coef: np.ndarray, bias: float, is_binary: bool) -> np.ndarray:
if is_binary:
return predict_proba_logistic(X_feat, coef, bias)
return predict_ridge(X_feat, coef, bias)
class PredictiveChurnRiskModel:
"""Baseline supervised classifier ranking users by baseline churn risk P(C=1 | X) = 1 - mu_0(X)."""
def __init__(self, l2_reg: float = 1.0) -> None:
self.l2_reg = float(l2_reg)
self._coef: np.ndarray | None = None
self._bias: float = 0.0
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> PredictiveChurnRiskModel:
# Train retention outcome model on baseline/control arm (or pooled without W) to predict churn risk
feat = build_nonlinear_basis(X)
ctrl = np.asarray(w, dtype=np.int64) == 0
self._coef, self._bias = fit_l2_logistic(feat[ctrl], np.asarray(y, dtype=np.float64)[ctrl], l2_reg=self.l2_reg)
return self
def predict_churn_risk(self, X: np.ndarray) -> np.ndarray:
if self._coef is None:
raise RuntimeError("PredictiveChurnRiskModel must be fitted first.")
p_retain = predict_proba_logistic(build_nonlinear_basis(X), self._coef, self._bias)
return 1.0 - p_retain
class SLearner:
"""Single-model S-Learner (supports toggling explicit X*W interactions to expose regularization drop-out)."""
def __init__(self, l2_reg: float = 1.0, include_interactions: bool = True) -> None:
self.l2_reg = float(l2_reg)
self.include_interactions = bool(include_interactions)
self._coef: np.ndarray | None = None
self._bias: float = 0.0
self._is_binary: bool = True
def _design(self, X: np.ndarray, w: np.ndarray) -> np.ndarray:
feat = build_nonlinear_basis(X)
w_col = np.asarray(w, dtype=np.float64)[:, None]
if self.include_interactions:
return np.hstack([feat, w_col, feat * w_col])
return np.hstack([feat, w_col])
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> SLearner:
y_arr = np.asarray(y, dtype=np.float64)
self._is_binary = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
des = self._design(X, w)
self._coef, self._bias = _fit_outcome_arm(des, y_arr, self.l2_reg, self._is_binary)
return self
def predict_mu(self, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
if self._coef is None:
raise RuntimeError("SLearner must be fitted first.")
n = X.shape[0]
mu0 = _predict_outcome_arm(self._design(X, np.zeros(n)), self._coef, self._bias, self._is_binary)
mu1 = _predict_outcome_arm(self._design(X, np.ones(n)), self._coef, self._bias, self._is_binary)
return mu0, mu1
def predict_cate(self, X: np.ndarray) -> np.ndarray:
mu0, mu1 = self.predict_mu(X)
return mu1 - mu0
class TLearner:
"""Two-model T-Learner fitting separate response models per treatment arm."""
def __init__(self, l2_reg: float = 1.0) -> None:
self.l2_reg = float(l2_reg)
self._c0: np.ndarray | None = None
self._b0: float = 0.0
self._c1: np.ndarray | None = None
self._b1: float = 0.0
self._is_binary: bool = True
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> TLearner:
feat = build_nonlinear_basis(X)
w_arr = np.asarray(w, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
self._is_binary = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
self._c0, self._b0 = _fit_outcome_arm(feat[w_arr == 0], y_arr[w_arr == 0], self.l2_reg, self._is_binary)
self._c1, self._b1 = _fit_outcome_arm(feat[w_arr == 1], y_arr[w_arr == 1], self.l2_reg, self._is_binary)
return self
def predict_mu(self, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
if self._c0 is None or self._c1 is None:
raise RuntimeError("TLearner must be fitted first.")
feat = build_nonlinear_basis(X)
mu0 = _predict_outcome_arm(feat, self._c0, self._b0, self._is_binary)
mu1 = _predict_outcome_arm(feat, self._c1, self._b1, self._is_binary)
return mu0, mu1
def predict_cate(self, X: np.ndarray) -> np.ndarray:
mu0, mu1 = self.predict_mu(X)
return mu1 - mu0
class XLearner:
"""Kunzel et al. (2019) 3-stage X-Learner with propensity-weighted blending."""
def __init__(self, l2_reg: float = 1.0, stage2_alpha: float = 5.0) -> None:
self.l2_reg = float(l2_reg)
self.stage2_alpha = float(stage2_alpha)
self._t_base = TLearner(l2_reg=l2_reg)
self._ew: np.ndarray | None = None
self._eb: float = 0.0
self._tau0_w: np.ndarray | None = None
self._tau0_b: float = 0.0
self._tau1_w: np.ndarray | None = None
self._tau1_b: float = 0.0
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> XLearner:
w_arr = np.asarray(w, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
feat = build_nonlinear_basis(X)
self._t_base.fit(X, w_arr, y_arr)
mu0_hat, mu1_hat = self._t_base.predict_mu(X)
self._ew, self._eb = fit_l2_logistic(feat, w_arr.astype(np.float64), l2_reg=self.l2_reg)
t_mask = w_arr == 1
c_mask = w_arr == 0
d1 = y_arr[t_mask] - mu0_hat[t_mask]
d0 = mu1_hat[c_mask] - y_arr[c_mask]
self._tau1_w, self._tau1_b = fit_ridge(feat[t_mask], d1, alpha=self.stage2_alpha)
self._tau0_w, self._tau0_b = fit_ridge(feat[c_mask], d0, alpha=self.stage2_alpha)
return self
def predict_cate(self, X: np.ndarray) -> np.ndarray:
if self._ew is None or self._tau0_w is None or self._tau1_w is None:
raise RuntimeError("XLearner must be fitted first.")
feat = build_nonlinear_basis(X)
g_x = np.clip(predict_proba_logistic(feat, self._ew, self._eb), 0.02, 0.98)
tau0 = predict_ridge(feat, self._tau0_w, self._tau0_b)
tau1 = predict_ridge(feat, self._tau1_w, self._tau1_b)
return g_x * tau0 + (1.0 - g_x) * tau1
def predict_mu1(self, X: np.ndarray) -> np.ndarray:
_, mu1 = self._t_base.predict_mu(X)
return mu1
class RLearner:
"""Nie & Wager (2021) Cross-Fitted Quasi-Oracle R-Learner (Robinson orthogonalized WLS)."""
def __init__(
self,
n_folds: int = 5,
l2_reg: float = 1.0,
stage2_alpha: float = 8.0,
seed: int = 42,
) -> None:
self.n_folds = int(n_folds)
self.l2_reg = float(l2_reg)
self.stage2_alpha = float(stage2_alpha)
self.seed = int(seed)
self._tau_w: np.ndarray | None = None
self._tau_b: float = 0.0
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> RLearner:
feat = build_nonlinear_basis(X)
w_arr = np.asarray(w, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
n = y_arr.size
is_binary = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
fold_ids = make_stratified_folds(w_arr, n_folds=self.n_folds, seed=self.seed)
l_oof = np.empty(n, dtype=np.float64)
m_oof = np.empty(n, dtype=np.float64)
for k in range(self.n_folds):
vm = fold_ids == k
tm = ~vm
if is_binary:
lw, lb = fit_l2_logistic(feat[tm], y_arr[tm], l2_reg=self.l2_reg)
l_oof[vm] = predict_proba_logistic(feat[vm], lw, lb)
else:
lw, lb = fit_ridge(feat[tm], y_arr[tm], alpha=self.l2_reg)
l_oof[vm] = predict_ridge(feat[vm], lw, lb)
mw, mb = fit_l2_logistic(feat[tm], w_arr[tm].astype(np.float64), l2_reg=self.l2_reg)
m_oof[vm] = predict_proba_logistic(feat[vm], mw, mb)
y_res = y_arr - l_oof
w_res = w_arr.astype(np.float64) - m_oof
# Exact R-loss optimization without dividing by w_res:
# minimize || y_res - (w_res * phi_bias) @ theta ||_2^2 + alpha ||theta_no_intercept||_2^2
d = feat.shape[1]
design = np.column_stack([feat, np.ones(n, dtype=np.float64)]) * w_res[:, None]
reg = np.eye(d + 1, dtype=np.float64) * self.stage2_alpha
reg[-1, -1] = 1e-6 # Keep constant CATE intercept minimally regularized
coef = np.linalg.solve(design.T @ design + reg, design.T @ y_res)
self._tau_w = coef[:-1]
self._tau_b = float(coef[-1])
return self
def predict_cate(self, X: np.ndarray) -> np.ndarray:
if self._tau_w is None:
raise RuntimeError("RLearner must be fitted first.")
return predict_ridge(build_nonlinear_basis(X), self._tau_w, self._tau_b)
class DRLearner:
"""Kennedy (2023) Cross-Fitted Doubly Robust Pseudo-Outcome CATE Learner."""
def __init__(
self,
n_folds: int = 5,
clip: tuple[float, float] = (0.05, 0.95),
l2_reg: float = 1.0,
stage2_alpha: float = 10.0,
seed: int = 42,
) -> None:
self.n_folds = int(n_folds)
self.clip = clip
self.l2_reg = float(l2_reg)
self.stage2_alpha = float(stage2_alpha)
self.seed = int(seed)
self._tau_w: np.ndarray | None = None
self._tau_b: float = 0.0
self._mu1_w: np.ndarray | None = None
self._mu1_b: float = 0.0
self._is_binary: bool = True
def fit(self, X: np.ndarray, w: np.ndarray, y: np.ndarray) -> DRLearner:
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.int64)
self._is_binary = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
aipw = estimate_aipw(
X,
w_arr,
y_arr,
n_folds=self.n_folds,
clip=self.clip,
l2_reg=self.l2_reg,
seed=self.seed,
use_basis=True,
)
feat = build_nonlinear_basis(X)
self._tau_w, self._tau_b = fit_ridge(feat, aipw["psi_scores"], alpha=self.stage2_alpha)
# Also fit full-sample mu_1(x) for conditional discount cost estimation
t_mask = w_arr == 1
self._mu1_w, self._mu1_b = _fit_outcome_arm(feat[t_mask], y_arr[t_mask], self.l2_reg, self._is_binary)
return self
def predict_cate(self, X: np.ndarray) -> np.ndarray:
if self._tau_w is None:
raise RuntimeError("DRLearner must be fitted first.")
return predict_ridge(build_nonlinear_basis(X), self._tau_w, self._tau_b)
def predict_mu1(self, X: np.ndarray) -> np.ndarray:
if self._mu1_w is None:
raise RuntimeError("DRLearner must be fitted first.")
return _predict_outcome_arm(build_nonlinear_basis(X), self._mu1_w, self._mu1_b, self._is_binary)
@dataclass
class _CausalTreeNode:
feature_idx: int | None = None
threshold: float | None = None
left: _CausalTreeNode | None = None
right: _CausalTreeNode | None = None
tau_est: float = 0.0
n_split: int = 0
n_est: int = 0
class HonestCausalTree:
"""Athey & Imbens (2016) Honest Causal Tree with disjoint I_split / I_est & Modified EMSE criterion."""
def __init__(
self,
max_depth: int = 3,
min_leaf_arm: int = 15,
honest: bool = True,
n_thresholds: int = 12,
seed: int = 42,
) -> None:
self.max_depth = int(max_depth)
self.min_leaf_arm = int(min_leaf_arm)
self.honest = bool(honest)
self.n_thresholds = int(n_thresholds)
self.seed = int(seed)
self._root: _CausalTreeNode | None = None
def _leaf_emse_score(
self,
y: np.ndarray,
w: np.ndarray,
e_hat: np.ndarray | None,
n_split_total: int,
n_est_total: int,
) -> float:
t_m = w == 1
c_m = w == 0
n1 = int(np.sum(t_m))
n0 = int(np.sum(c_m))
if n1 < self.min_leaf_arm or n0 < self.min_leaf_arm:
return -1e18
if e_hat is not None:
wt1 = 1.0 / np.clip(e_hat[t_m], 0.05, 0.95)
wt0 = 1.0 / np.clip(1.0 - e_hat[c_m], 0.05, 0.95)
mu1 = float(np.sum(wt1 * y[t_m]) / np.sum(wt1))
mu0 = float(np.sum(wt0 * y[c_m]) / np.sum(wt0))
else:
mu1 = float(np.mean(y[t_m]))
mu0 = float(np.mean(y[c_m]))
tau_l = mu1 - mu0
s1_sq = float(np.var(y[t_m], ddof=1)) if n1 > 1 else 0.0
s0_sq = float(np.var(y[c_m], ddof=1)) if n0 > 1 else 0.0
n_l = n1 + n0
p1 = n1 / float(n_l)
var_term = (s1_sq / max(p1, 1e-6) + s0_sq / max(1.0 - p1, 1e-6)) / float(n_l)
# Modified EMSE: reward n_L * tau_L^2, penalize leaf variance across split & est sets
return (n_l / float(n_split_total)) * (tau_l**2) - (1.0 / float(n_split_total) + 1.0 / float(n_est_total)) * n_l * var_term
def _estimate_leaf_tau(self, y: np.ndarray, w: np.ndarray, e_hat: np.ndarray | None, fallback: float) -> float:
t_m = w == 1
c_m = w == 0
if int(np.sum(t_m)) < 2 or int(np.sum(c_m)) < 2:
return fallback
if e_hat is not None:
wt1 = 1.0 / np.clip(e_hat[t_m], 0.05, 0.95)
wt0 = 1.0 / np.clip(1.0 - e_hat[c_m], 0.05, 0.95)
return float(np.sum(wt1 * y[t_m]) / np.sum(wt1) - np.sum(wt0 * y[c_m]) / np.sum(wt0))
return float(np.mean(y[t_m]) - np.mean(y[c_m]))
def _build(
self,
X_sp: np.ndarray,
w_sp: np.ndarray,
y_sp: np.ndarray,
e_sp: np.ndarray | None,
X_es: np.ndarray,
w_es: np.ndarray,
y_es: np.ndarray,
e_es: np.ndarray | None,
depth: int,
n_split_total: int,
n_est_total: int,
parent_tau: float,
) -> _CausalTreeNode:
est_tau = self._estimate_leaf_tau(y_es, w_es, e_es, parent_tau)
node = _CausalTreeNode(tau_est=est_tau, n_split=int(y_sp.size), n_est=int(y_es.size))
if depth >= self.max_depth or y_sp.size < 2 * self.min_leaf_arm:
return node
base_score = self._leaf_emse_score(y_sp, w_sp, e_sp, n_split_total, n_est_total)
best_gain = 1e-9
best_feat: int | None = None
best_thr: float | None = None
qs = np.linspace(0.1, 0.9, self.n_thresholds)
for j in range(X_sp.shape[1]):
vals = X_sp[:, j]
thrs = np.unique(np.quantile(vals, qs))
for thr in thrs:
left_sp = vals <= thr
right_sp = ~left_sp
if int(np.sum(left_sp & (w_sp == 1))) < self.min_leaf_arm or int(np.sum(left_sp & (w_sp == 0))) < self.min_leaf_arm:
continue
if int(np.sum(right_sp & (w_sp == 1))) < self.min_leaf_arm or int(np.sum(right_sp & (w_sp == 0))) < self.min_leaf_arm:
continue
# In honest mode, also ensure estimation sample has >= 3 units per arm in both children
left_es = X_es[:, j] <= thr
right_es = ~left_es
if min(
int(np.sum(left_es & (w_es == 1))),
int(np.sum(left_es & (w_es == 0))),
int(np.sum(right_es & (w_es == 1))),
int(np.sum(right_es & (w_es == 0))),
) < 3:
continue
s_l = self._leaf_emse_score(y_sp[left_sp], w_sp[left_sp], None if e_sp is None else e_sp[left_sp], n_split_total, n_est_total)
s_r = self._leaf_emse_score(y_sp[right_sp], w_sp[right_sp], None if e_sp is None else e_sp[right_sp], n_split_total, n_est_total)
gain = (s_l + s_r) - base_score
if gain > best_gain:
best_gain = gain
best_feat = j
best_thr = float(thr)
if best_feat is None or best_thr is None:
return node
l_sp = X_sp[:, best_feat] <= best_thr
l_es = X_es[:, best_feat] <= best_thr
node.feature_idx = best_feat
node.threshold = best_thr
node.left = self._build(
X_sp[l_sp], w_sp[l_sp], y_sp[l_sp], None if e_sp is None else e_sp[l_sp],
X_es[l_es], w_es[l_es], y_es[l_es], None if e_es is None else e_es[l_es],
depth + 1, n_split_total, n_est_total, est_tau,
)
node.right = self._build(
X_sp[~l_sp], w_sp[~l_sp], y_sp[~l_sp], None if e_sp is None else e_sp[~l_sp],
X_es[~l_es], w_es[~l_es], y_es[~l_es], None if e_es is None else e_es[~l_es],
depth + 1, n_split_total, n_est_total, est_tau,
)
return node
def fit(
self,
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
e_hat: np.ndarray | None = None,
) -> HonestCausalTree:
x_arr = np.asarray(X, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.int64)
y_arr = np.asarray(y, dtype=np.float64)
e_arr = None if e_hat is None else np.asarray(e_hat, dtype=np.float64)
if self.honest:
rng = np.random.default_rng(self.seed)
perm = rng.permutation(x_arr.shape[0])
half = x_arr.shape[0] // 2
sp_idx, es_idx = perm[:half], perm[half:]
else:
all_idx = np.arange(x_arr.shape[0])
sp_idx, es_idx = all_idx, all_idx
global_tau = self._estimate_leaf_tau(y_arr[es_idx], w_arr[es_idx], None if e_arr is None else e_arr[es_idx], 0.0)
self._root = self._build(
x_arr[sp_idx], w_arr[sp_idx], y_arr[sp_idx], None if e_arr is None else e_arr[sp_idx],
x_arr[es_idx], w_arr[es_idx], y_arr[es_idx], None if e_arr is None else e_arr[es_idx],
depth=0,
n_split_total=int(sp_idx.size),
n_est_total=int(es_idx.size),
parent_tau=global_tau,
)
return self
def _predict_row(self, row: np.ndarray, node: _CausalTreeNode) -> float:
if node.feature_idx is None or node.threshold is None or node.left is None or node.right is None:
return node.tau_est
if row[node.feature_idx] <= node.threshold:
return self._predict_row(row, node.left)
return self._predict_row(row, node.right)
def predict_cate(self, X: np.ndarray) -> np.ndarray:
if self._root is None:
raise RuntimeError("HonestCausalTree must be fitted first.")
x_arr = np.asarray(X, dtype=np.float64)
return np.array([self._predict_row(x_arr[i], self._root) for i in range(x_arr.shape[0])], dtype=np.float64)
def compute_transformed_outcome(y: np.ndarray, w: np.ndarray, e_hat: np.ndarray) -> np.ndarray:
"""Compute Horvitz-Thompson Transformed Outcome Y* = Y * (W - e(X)) / (e(X)(1 - e(X)))."""
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
e_arr = np.clip(np.asarray(e_hat, dtype=np.float64), 0.05, 0.95)
return y_arr * (w_arr - e_arr) / (e_arr * (1.0 - e_arr))
def compute_qini_and_auuc(
y: np.ndarray,
w: np.ndarray,
scores: np.ndarray,
top_frac: float = 0.30,
e_hat: np.ndarray | None = None,
tau_true: np.ndarray | None = None,
) -> dict[str, Any]:
"""Compute Uplift@k, AUUC excess, Radcliffe Qini curve (factual & IPW-weighted), and optional Oracle curves."""
y_arr = np.asarray(y, dtype=np.float64)
w_arr = np.asarray(w, dtype=np.float64)
sc = np.asarray(scores, dtype=np.float64)
n = y_arr.size
order = np.argsort(-sc, kind="mergesort")
y_s = y_arr[order]
w_s = w_arr[order]
if e_hat is not None:
e_s = np.clip(np.asarray(e_hat, dtype=np.float64)[order], 0.05, 0.95)
wt_t = w_s / e_s
wt_c = (1.0 - w_s) / (1.0 - e_s)
else:
wt_t = w_s
wt_c = 1.0 - w_s
nt_cum = np.cumsum(wt_t)
nc_cum = np.cumsum(wt_c)
yt_cum = np.cumsum(wt_t * y_s)
yc_cum = np.cumsum(wt_c * y_s)
rate_t = yt_cum / np.maximum(nt_cum, 1e-9)
rate_c = yc_cum / np.maximum(nc_cum, 1e-9)
valid = (nt_cum > 0.0) & (nc_cum > 0.0)
diff = np.where(valid, rate_t - rate_c, 0.0)
k_arr = np.arange(1, n + 1, dtype=np.float64)
fractions = k_arr / float(n)
uplift_curve = diff * fractions
uplift_rand = fractions * uplift_curve[-1]
auuc_excess = float(np.trapezoid(uplift_curve - uplift_rand, fractions))
# Radcliffe Qini curve scaled in treated units (divided by N for scale-free comparison)
qini_raw = np.where(nc_cum > 0.0, yt_cum - yc_cum * (nt_cum / np.maximum(nc_cum, 1e-9)), 0.0) / float(n)
qini_rand = (nt_cum / max(float(nt_cum[-1]), 1e-9)) * qini_raw[-1]
qini_excess = float(np.trapezoid(qini_raw - qini_rand, fractions))
# Theoretical optimal Qini curve on factual labels (responders in W=1 first, non-responders in W=0 last)
opt_score = np.where(w_arr == 1.0, np.where(y_arr > 0.5, 3.0, 1.0), np.where(y_arr < 0.5, 2.0, 0.0))
opt_ord = np.argsort(-opt_score, kind="mergesort")
wt_to = wt_t[order.argsort()][opt_ord] if e_hat is not None else w_arr[opt_ord]
wt_co = wt_c[order.argsort()][opt_ord] if e_hat is not None else (1.0 - w_arr[opt_ord])
yo = y_arr[opt_ord]
nto, nco = np.cumsum(wt_to), np.cumsum(wt_co)
yto, yco = np.cumsum(wt_to * yo), np.cumsum(wt_co * yo)
q_opt = np.where(nco > 0.0, yto - yco * (nto / np.maximum(nco, 1e-9)), 0.0) / float(n)
q_opt_rand = (nto / max(float(nto[-1]), 1e-9)) * q_opt[-1]
q_opt_excess = float(np.trapezoid(q_opt - q_opt_rand, fractions))
qini_norm = float(qini_excess / max(q_opt_excess, 1e-9))
k_top = max(1, min(n, round(top_frac * n))) - 1
uplift_at_k = float(diff[k_top])
out: dict[str, Any] = {
"auuc_excess": auuc_excess,
"qini_excess": qini_excess,
"qini_norm": qini_norm,
"uplift_at_k": uplift_at_k,
"top_frac": float(top_frac),
}
if tau_true is not None:
tau_s = np.asarray(tau_true, dtype=np.float64)[order]
cum_tau = np.cumsum(tau_s) / float(n)
rand_tau = fractions * cum_tau[-1]
out["oracle_auuc"] = float(np.trapezoid(cum_tau, fractions))
out["oracle_qini"] = float(np.trapezoid(cum_tau - rand_tau, fractions))
out["oracle_uplift_at_k"] = float(np.mean(tau_s[: k_top + 1]))
return out
def compute_r_and_dr_loss(
X_val: np.ndarray,
w_val: np.ndarray,
y_val: np.ndarray,
tau_preds_dict: dict[str, np.ndarray],
n_folds: int = 5,
clip: tuple[float, float] = (0.05, 0.95),
l2_reg: float = 1.0,
seed: int = 101,
) -> dict[str, dict[str, float]]:
"""Compute counterfactual model selection metrics (R-loss and DR-loss) strictly on held-out validation data."""
feat = build_nonlinear_basis(X_val)
w_arr = np.asarray(w_val, dtype=np.int64)
y_arr = np.asarray(y_val, dtype=np.float64)
n = y_arr.size
is_binary = bool(np.all((y_arr == 0.0) | (y_arr == 1.0)))
fold_ids = make_stratified_folds(w_arr, n_folds=n_folds, seed=seed)
l_oof = np.empty(n, dtype=np.float64)
m_oof = np.empty(n, dtype=np.float64)
for k in range(n_folds):
vm = fold_ids == k
tm = ~vm
lw, lb = _fit_outcome_arm(feat[tm], y_arr[tm], l2_reg, is_binary)
l_oof[vm] = _predict_outcome_arm(feat[vm], lw, lb, is_binary)
mw, mb = fit_l2_logistic(feat[tm], w_arr[tm].astype(np.float64), l2_reg=l2_reg)
m_oof[vm] = predict_proba_logistic(feat[vm], mw, mb)
aipw_val = estimate_aipw(X_val, w_arr, y_arr, n_folds=n_folds, clip=clip, l2_reg=l2_reg, seed=seed + 7)
y_res = y_arr - l_oof
w_res = w_arr.astype(np.float64) - m_oof
y_dr = aipw_val["psi_scores"]
results: dict[str, dict[str, float]] = {}
for name, tau_hat in tau_preds_dict.items():
t_pred = np.asarray(tau_hat, dtype=np.float64)
r_loss = float(np.mean((y_res - t_pred * w_res) ** 2))
dr_loss = float(np.mean((y_dr - t_pred) ** 2))
results[name] = {"r_loss": r_loss, "dr_loss": dr_loss}
return results
def optimize_knapsack_retention_policy(
tau_hat: np.ndarray,
mu1_hat: np.ndarray,
ltv_value: float = 200.0,
contact_cost: float = 5.0,
incentive_cost: float = 25.0,
budget: float | None = None,
top_frac: float | None = None,
tau_true: np.ndarray | None = None,
mu1_true: np.ndarray | None = None,
) -> dict[str, Any]:
"""Optimize retention campaign via Expected Net Profit Pi(x) = tau*V - c - mu1*d and 0-1 Marginal ROI Knapsack."""
tau_h = np.asarray(tau_hat, dtype=np.float64)
mu1_h = np.clip(np.asarray(mu1_hat, dtype=np.float64), 0.0, 1.0)
n = tau_h.size
exp_cost_hat = float(contact_cost) + mu1_h * float(incentive_cost)
profit_hat = tau_h * float(ltv_value) - exp_cost_hat
marg_roi_hat = profit_hat / np.maximum(exp_cost_hat, 1e-9)
selected = np.zeros(n, dtype=bool)
if top_frac is not None:
k_cap = max(0, min(n, round(top_frac * n)))
# Rank by predicted net profit per unit expected cost and guard against profit_hat <= 0.0 (Sleeping Dogs)
order = np.argsort(-marg_roi_hat, kind="mergesort")
top_idx = order[:k_cap]
selected[top_idx[profit_hat[top_idx] > 0.0]] = True
elif budget is not None:
order = np.argsort(-marg_roi_hat, kind="mergesort")
spent = 0.0
for idx in order:
if profit_hat[idx] <= 0.0:
break
c_i = float(exp_cost_hat[idx])
if spent + c_i <= float(budget):
selected[idx] = True
spent += c_i
else:
selected = profit_hat > 0.0
pred_profit = float(np.sum(profit_hat[selected]))
pred_cost = float(np.sum(exp_cost_hat[selected]))
out: dict[str, Any] = {
"n_targeted": int(np.sum(selected)),
"target_frac": float(np.mean(selected)),
"selected_mask": selected,
"predicted_net_profit": pred_profit,
"predicted_cost": pred_cost,
"predicted_roi": float(pred_profit / max(pred_cost, 1e-9)),
}
if tau_true is not None and mu1_true is not None:
t_true = np.asarray(tau_true, dtype=np.float64)
m1_true = np.asarray(mu1_true, dtype=np.float64)
real_cost = float(contact_cost) + m1_true * float(incentive_cost)
real_profit = t_true * float(ltv_value) - real_cost
out["realized_net_profit"] = float(np.sum(real_profit[selected]))
out["realized_cost"] = float(np.sum(real_cost[selected]))
out["realized_roi"] = float(out["realized_net_profit"] / max(out["realized_cost"], 1e-9))
return out
def audit_worked_10k_churn_vs_uplift(
ltv_value: float = 200.0,
contact_cost: float = 5.0,
incentive_cost: float = 25.0,
) -> dict[str, Any]:
"""Deterministic N=10,000 5-segment worked example proving Top-30% Churn Risk vs Top-30% Uplift swing."""
segments = [
{"name": "B_HighRisk_LostCauses", "count": 3000, "mu0": 0.10, "mu1": 0.11},
{"name": "A_HighRisk_Persuadables", "count": 1500, "mu0": 0.20, "mu1": 0.55},
{"name": "E_MidRisk_Persuadables", "count": 1500, "mu0": 0.55, "mu1": 0.75},
{"name": "C_Dormant_SleepingDogs", "count": 1500, "mu0": 0.75, "mu1": 0.55},
{"name": "D_LowRisk_SureThings", "count": 2500, "mu0": 0.92, "mu1": 0.93},
]
rows = []
tot_treat_all = 0.0
for seg in segments:
tau = seg["mu1"] - seg["mu0"]
c_exp = contact_cost + seg["mu1"] * incentive_cost
pi_user = tau * ltv_value - c_exp
seg_tot = seg["count"] * pi_user
tot_treat_all += seg_tot
rows.append(
{
"segment": seg["name"],
"count": seg["count"],
"churn0": 1.0 - seg["mu0"],
"tau": tau,
"exp_cost": c_exp,
"profit_per_user": pi_user,
"marg_roi": pi_user / c_exp,
"segment_profit": seg_tot,
}
)
# Top-30% (3,000 users) by baseline churn risk (1 - mu0) -> selects 3,000 B_HighRisk_LostCauses
by_churn = sorted(rows, key=lambda r: -r["churn0"])
churn_profit = 0.0
churn_cost = 0.0
rem = 3000
for r in by_churn:
take = min(rem, r["count"])
churn_profit += take * r["profit_per_user"]
churn_cost += take * r["exp_cost"]
rem -= take
# Top-30% (3,000 users) by Uplift / Marginal ROI -> selects 1,500 A + 1,500 E
by_roi = sorted(rows, key=lambda r: -r["marg_roi"])
uplift_profit = 0.0
uplift_cost = 0.0
rem = 3000
for r in by_roi:
if r["profit_per_user"] <= 0.0:
break
take = min(rem, r["count"])
uplift_profit += take * r["profit_per_user"]
uplift_cost += take * r["exp_cost"]
rem -= take
return {
"n_total": 10000,
"segments": rows,
"treat_all_net_profit": float(tot_treat_all),
"top30_churn_net_profit": float(churn_profit),
"top30_churn_roi": float(churn_profit / churn_cost),
"top30_uplift_net_profit": float(uplift_profit),
"top30_uplift_roi": float(uplift_profit / uplift_cost),
"profit_swing_uplift_vs_churn": float(uplift_profit - churn_profit),
}
def _evaluate_retention_learner(
name: str,
tau_hat: np.ndarray,
mu1_hat: np.ndarray,
y_test: np.ndarray,
w_test: np.ndarray,
e_test_hat: np.ndarray,
tau_true_test: np.ndarray,
mu1_true_test: np.ndarray,
cfg: CausalUpliftConfig,
top_frac: float = 0.30,
) -> dict[str, Any]:
true_ate = float(np.mean(tau_true_test))
pred_ate = float(np.mean(tau_hat))
pehe = float(np.sqrt(np.mean((tau_hat - tau_true_test) ** 2)))
q_res = compute_qini_and_auuc(
y_test, w_test, tau_hat, top_frac=top_frac, e_hat=e_test_hat, tau_true=tau_true_test
)
top_pol = optimize_knapsack_retention_policy(
tau_hat,
mu1_hat,
ltv_value=cfg.ltv_value,
contact_cost=cfg.contact_cost,
incentive_cost=cfg.incentive_cost,
top_frac=top_frac,
tau_true=tau_true_test,
mu1_true=mu1_true_test,
)
return {
"model": name,
"ate_hat": pred_ate,
"ate_bias": float(pred_ate - true_ate),
"pehe": pehe,
"oracle_auuc": float(q_res["oracle_auuc"]),
"oracle_qini": float(q_res["oracle_qini"]),
"factual_ipw_qini": float(q_res["qini_excess"]),
"uplift_at_30pct": float(q_res["oracle_uplift_at_k"]),
"top30_net_profit": float(top_pol["realized_net_profit"]),
}
def run_full_causal_uplift_benchmarks(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Execute complete 4-part causal inference & uplift benchmark suite for Lab 02 & Chapter 05."""
cfg = CausalUpliftConfig(
seed=seed,
n_train=4000,
n_test=2000,
propensity_clip=(0.03, 0.97),
)
# 1. SCM / DAG Verification, Collider/Berkson & Simpson -> Backdoor Bridge
mbias_dag = CausalDAG(
nodes=("U1", "U2", "W", "M_node", "Y"),
edges=(("U1", "W"), ("U1", "M_node"), ("U2", "M_node"), ("U2", "Y")),
)
simple_dag = CausalDAG(
nodes=("Z", "W", "M", "Y", "C"),
edges=(("Z", "W"), ("Z", "Y"), ("W", "M"), ("M", "Y"), ("W", "C"), ("Y", "C")),
)
backdoor_z = simple_dag.is_valid_backdoor_set("W", "Y", {"Z"})
backdoor_m = simple_dag.is_valid_backdoor_set("W", "Y", {"Z", "M"})
backdoor_c = simple_dag.is_valid_backdoor_set("W", "Y", {"Z", "C"})
collider_bias = simulate_collider_berkson_bias(n_samples=15000 if quick else 30000, seed=seed)
simpson_bridge = simulate_simpson_vs_backdoor(n_samples=2000, seed=seed)
# 2. Positivity Collapse (Case 5), Double Robustness AIPW & Cross-Fitted DML Ablation
pos_dgp = simulate_positivity_collapse_dgp(n_samples=4000, seed=7 if seed == 42 else seed + 10)
ipw_unclipped = estimate_ipw(pos_dgp["y"], pos_dgp["w"], pos_dgp["e_true"], clip=None)
ipw_clipped = estimate_ipw(pos_dgp["y"], pos_dgp["w"], pos_dgp["e_true"], clip=cfg.propensity_clip)
ato_res = estimate_overlap_ato(pos_dgp["y"], pos_dgp["w"], pos_dgp["e_true"], X=pos_dgp["X"])
naive_pos_diff = float(np.mean(pos_dgp["y"][pos_dgp["w"] == 1]) - np.mean(pos_dgp["y"][pos_dgp["w"] == 0]))
dml_ablation = simulate_plr_dml_ablation(
n_samples=500,
n_dim=350,
n_trials=20 if quick else 30,
n_folds=cfg.n_folds,
theta_true=1.0,
seed=seed,
)
# 3. Article #3 Retention DGP (Train / Test Split-First) + Scalar ATE + Uplift Meta-Learners
tr_dgp = simulate_churn_retention_dgp(n_samples=cfg.n_train, seed=seed)
te_dgp = simulate_churn_retention_dgp(n_samples=cfg.n_test, seed=seed + 999)
X_tr, w_tr, y_tr = tr_dgp["X"], tr_dgp["w"], tr_dgp["y"]
X_te, w_te, y_te = te_dgp["X"], te_dgp["w"], te_dgp["y"]
tau_te, mu1_te = te_dgp["tau_true"], te_dgp["mu1_true"]
true_tr_ate = float(np.mean(tr_dgp["tau_true"]))
true_te_ate = float(np.mean(tau_te))
naive_obs_tr = float(np.mean(y_tr[w_tr == 1]) - np.mean(y_tr[w_tr == 0]))
aipw_tr = estimate_aipw(X_tr, w_tr, y_tr, n_folds=cfg.n_folds, clip=cfg.propensity_clip, seed=seed)
aipw_bad_e = estimate_aipw(
X_tr, w_tr, y_tr, n_folds=cfg.n_folds, clip=cfg.propensity_clip, seed=seed, misspecify_propensity=True
)
aipw_bad_mu = estimate_aipw(
X_tr, w_tr, y_tr, n_folds=cfg.n_folds, clip=cfg.propensity_clip, seed=seed, misspecify_outcome=True
)
# Cross-fitted DML PLR on nonlinear basis for retention ATE
dml_plr_tr = estimate_dml_plr(
build_nonlinear_basis(X_tr), w_tr.astype(np.float64), y_tr, n_folds=cfg.n_folds, ridge_alpha=5.0, seed=seed
)
# Propensity on test for IPW-weighted factual Qini evaluation
ew_tr, eb_tr = fit_l2_logistic(build_nonlinear_basis(X_tr), w_tr.astype(np.float64), l2_reg=cfg.logistic_l2)
e_te_hat = predict_proba_logistic(build_nonlinear_basis(X_te), ew_tr, eb_tr)
churn_clf = PredictiveChurnRiskModel(l2_reg=cfg.logistic_l2).fit(X_tr, w_tr, y_tr)
churn_scores_te = churn_clf.predict_churn_risk(X_te)
s_noint = SLearner(l2_reg=cfg.logistic_l2, include_interactions=False).fit(X_tr, w_tr, y_tr)
s_inter = SLearner(l2_reg=cfg.logistic_l2, include_interactions=True).fit(X_tr, w_tr, y_tr)
t_lrn = TLearner(l2_reg=cfg.logistic_l2).fit(X_tr, w_tr, y_tr)
x_lrn = XLearner(l2_reg=cfg.logistic_l2, stage2_alpha=5.0).fit(X_tr, w_tr, y_tr)
r_lrn = RLearner(n_folds=cfg.n_folds, l2_reg=cfg.logistic_l2, stage2_alpha=8.0, seed=seed).fit(X_tr, w_tr, y_tr)
dr_lrn = DRLearner(
n_folds=cfg.n_folds, clip=cfg.propensity_clip, l2_reg=cfg.logistic_l2, stage2_alpha=10.0, seed=seed
).fit(X_tr, w_tr, y_tr)
htree = HonestCausalTree(max_depth=3, min_leaf_arm=15, honest=True, seed=seed).fit(X_tr, w_tr, y_tr, e_hat=aipw_tr["e_oof"])
mu1_hat_te = dr_lrn.predict_mu1(X_te)
naive_const_tau = np.full(X_te.shape[0], naive_obs_tr, dtype=np.float64)
ablation_rows = [
_evaluate_retention_learner("Predictive_Churn_Risk", churn_scores_te, mu1_hat_te, y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("Naive_Obs_Constant", naive_const_tau, mu1_hat_te, y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("S_Learner_NoInteract", s_noint.predict_cate(X_te), s_noint.predict_mu(X_te)[1], y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("Honest_Causal_Tree", htree.predict_cate(X_te), mu1_hat_te, y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("DR_Learner_CrossFit", dr_lrn.predict_cate(X_te), mu1_hat_te, y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("R_Learner_DML", r_lrn.predict_cate(X_te), mu1_hat_te, y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("X_Learner", x_lrn.predict_cate(X_te), x_lrn.predict_mu1(X_te), y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("S_Learner_Interact", s_inter.predict_cate(X_te), s_inter.predict_mu(X_te)[1], y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
_evaluate_retention_learner("T_Learner", t_lrn.predict_cate(X_te), t_lrn.predict_mu(X_te)[1], y_te, w_te, e_te_hat, tau_te, mu1_te, cfg),
]
# Profit > 0 threshold policies & Treat-All vs Oracle on Test
treat_all_pol = optimize_knapsack_retention_policy(
np.ones(X_te.shape[0]), mu1_hat_te, cfg.ltv_value, cfg.contact_cost, cfg.incentive_cost, top_frac=1.0, tau_true=tau_te, mu1_true=mu1_te
)
oracle_pol = optimize_knapsack_retention_policy(
tau_te, mu1_te, cfg.ltv_value, cfg.contact_cost, cfg.incentive_cost, budget=None, tau_true=tau_te, mu1_true=mu1_te
)
dr_opt_pol = optimize_knapsack_retention_policy(
dr_lrn.predict_cate(X_te), mu1_hat_te, cfg.ltv_value, cfg.contact_cost, cfg.incentive_cost, budget=None, tau_true=tau_te, mu1_true=mu1_te
)
worked_10k = audit_worked_10k_churn_vs_uplift(cfg.ltv_value, cfg.contact_cost, cfg.incentive_cost)
# 4. Counterfactual Validation Selection + Refutation & Sensitivity
val_losses = compute_r_and_dr_loss(
X_te,
w_te,
y_te,
{
"S_Learner_NoInteract": s_noint.predict_cate(X_te),
"Honest_Causal_Tree": htree.predict_cate(X_te),
"DR_Learner": dr_lrn.predict_cate(X_te),
"R_Learner": r_lrn.predict_cate(X_te),
"T_Learner": t_lrn.predict_cate(X_te),
},
n_folds=cfg.n_folds,
clip=cfg.propensity_clip,
seed=seed + 55,
)
refute_res = run_refutation_suite(
X_tr,
w_tr,
y_tr,
lambda xm, wm, ym, sd: estimate_aipw(xm, wm, ym, n_folds=3, clip=cfg.propensity_clip, seed=sd)["ate"],
seed=seed,
)
e_val_rr2 = compute_e_value(risk_ratio=2.0, ci_bound=1.45)
t_stat_dml = float(dml_plr_tr["theta_hat"] / max(dml_plr_tr["se"], 1e-9))
ovb_rv = compute_cinelli_hazlett_rv(t_stat=t_stat_dml, df=cfg.n_train - 17, q=1.0)
return {
"config": cfg.model_dump(),
"scm_and_identification": {
"backdoor_z_valid": backdoor_z["valid"],
"backdoor_m_rejected": not backdoor_m["valid"],
"backdoor_c_rejected": not backdoor_c["valid"],
"minimal_backdoor_sets": [list(s) for s in simple_dag.find_minimal_backdoor_sets("W", "Y")],
"mbias_empty_d_separated": mbias_dag.is_d_separated("W", "Y", ()),
"collider_bias": collider_bias,
"simpson_bridge": simpson_bridge,
},
"positivity_and_dml": {
"case5_positivity": {
"true_ate": 0.0,
"naive_diff": naive_pos_diff,
"ipw_unclipped_hajek_ate": ipw_unclipped["hajek_ate"],
"ipw_unclipped_ess_ctrl": ipw_unclipped["ess_control"],
"ipw_unclipped_max_weight": ipw_unclipped["max_weight"],
"ipw_clipped_hajek_ate": ipw_clipped["hajek_ate"],
"overlap_ato_ate": ato_res["ato_ate"],
"overlap_max_weight": ato_res["max_weight"],
"overlap_ess_ctrl": ato_res["ess_control"],
},
"aipw_double_robustness": {
"true_train_ate": true_tr_ate,
"naive_obs_ate": naive_obs_tr,
"aipw_both_ok": float(aipw_tr["ate"]),
"aipw_se": float(aipw_tr["se"]),
"aipw_bad_propensity_only": float(aipw_bad_e["ate"]),
"aipw_bad_outcome_only": float(aipw_bad_mu["ate"]),
"ipw_under_bad_propensity": float(aipw_bad_e["ipw_hajek_ate"]),
"gcomp_under_bad_outcome": float(aipw_bad_mu["gcomp_ate"]),
"dml_plr_ate": float(dml_plr_tr["theta_hat"]),
"dml_plr_se": float(dml_plr_tr["se"]),
},
"dml_plr_ablation": dml_ablation,
},
"uplift_and_article3": {
"true_test_ate": true_te_ate,
"sleeping_dog_share_test": float(te_dgp["sleeping_dog_share"]),
"worked_10k": worked_10k,
"ablation_table": ablation_rows,
"treat_all_test_profit": float(treat_all_pol["realized_net_profit"]),
"dr_optimal_profit_gt0": {
"net_profit": float(dr_opt_pol["realized_net_profit"]),
"target_frac": float(dr_opt_pol["target_frac"]),
"roi": float(dr_opt_pol["realized_roi"]),
},
"oracle_profit_gt0": {
"net_profit": float(oracle_pol["realized_net_profit"]),
"target_frac": float(oracle_pol["target_frac"]),
"roi": float(oracle_pol["realized_roi"]),
},
"counterfactual_val_losses": val_losses,
},
"refutation_and_sensitivity": {
"dowhy_refuters": refute_res,
"e_value_rr2": e_val_rr2,
"cinelli_hazlett_ovb": ovb_rv,
"dml_t_stat": t_stat_dml,
},
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 02 (causal_uplift_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 causal_uplift_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 causal_uplift_lab.uplift_roi_and_qini import run_full_causal_uplift_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 not math.isfinite(fval):
return "inf" if fval > 0 else ("-inf" if fval < 0 else "nan")
return fval
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar_val(val: float, floor: float = 0.001) -> float:
if not math.isfinite(val):
return floor
return float(max(floor, abs(val)))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run Lab 02: Pearl SCMs, Cross-Fitted DML, Uplift Meta-Learners, Refutation & Retention ROI."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--quick",
action="store_true",
help="Run compact sample sizes and Monte Carlo replications for fast CI execution.",
)
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Optional output JSON path (e.g., artifacts/ch05_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
scm = bench["scm_and_identification"]
col = scm["collider_bias"]
simp = scm["simpson_bridge"]
pos_dml = bench["positivity_and_dml"]
c5 = pos_dml["case5_positivity"]
dr = pos_dml["aipw_double_robustness"]
dml = pos_dml["dml_plr_ablation"]
up = bench["uplift_and_article3"]
w10k = up["worked_10k"]
abl_by_name = {r["model"]: r for r in up["ablation_table"]}
churn_row = abl_by_name["Predictive_Churn_Risk"]
dr_row = abl_by_name["DR_Learner_CrossFit"]
r_row = abl_by_name["R_Learner_DML"]
t_row = abl_by_name["T_Learner"]
s_no_row = abl_by_name["S_Learner_NoInteract"]
ht_row = abl_by_name["Honest_Causal_Tree"]
ref = bench["refutation_and_sensitivity"]
dw = ref["dowhy_refuters"]
ev = ref["e_value_rr2"]
rv = ref["cinelli_hazlett_ovb"]
kpis = [
{
"id": "kpi_collider_and_simpson_bridge",
"label": "Berkson Collider & Simpson Backdoor",
"value": f"{col['berkson_400_selected_corr']:.3f} | {simp['backdoor_adjusted_ate']:+.3f}",
"unit": "Corr | ATE",
"status": "warn",
"detail": (
f"Independent N=400 Berkson conditioning induces r={col['berkson_400_selected_corr']:.3f} "
f"(Gauss Schur={col['empirical_partial_corr_given_c']:.3f}); Backdoor flips naive {simp['naive_marginal_diff_confounded']:+.3f} to {simp['backdoor_adjusted_ate']:+.3f}."
),
},
{
"id": "kpi_aipw_and_positivity_ato",
"label": "Doubly Robust AIPW & Overlap ATO",
"value": f"AIPW {dr['aipw_both_ok']:+.4f} | ATO {c5['overlap_ato_ate']:+.4f}",
"unit": "ATE",
"status": "ok",
"detail": (
f"True train ATE={dr['true_train_ate']:+.4f} vs naive {dr['naive_obs_ate']:+.4f}; "
f"AIPW holds {dr['aipw_bad_propensity_only']:+.4f}/{dr['aipw_bad_outcome_only']:+.4f} under single misspecification; "
f"Case 5 ATO recovers 0 vs naive {c5['naive_diff']:+.3f}."
),
},
{
"id": "kpi_dml_crossfit_coverage",
"label": "DML2 Cross-Fit vs Naive Plug-In (95% CI)",
"value": f"{dml['crossfit_dml2']['coverage_95']*100:.0f}% vs {dml['naive_plugin']['coverage_95']*100:.0f}%",
"unit": "Coverage",
"status": "ok",
"detail": (
f"High-dim PLR (d={dml['n_dim']}): Naive bias={dml['naive_plugin']['bias']:+.3f}, "
f"In-Sample DML={dml['insample_dml']['coverage_95']*100:.0f}%, "
f"5-Fold DML2 bias={dml['crossfit_dml2']['bias']:+.3f}."
),
},
{
"id": "kpi_article3_10k_profit_swing",
"label": "Article #3 10k Churn vs Uplift Top-30%",
"value": f"-${abs(w10k['top30_churn_net_profit']):,.0f} -> +${w10k['top30_uplift_net_profit']:,.0f}",
"unit": "Net Profit",
"status": "critical",
"detail": (
f"Treat-All=-${abs(w10k['treat_all_net_profit']):,.0f}; Top-30% Churn ROI={w10k['top30_churn_roi']:+.3f}; "
f"Top-30% Uplift ROI={w10k['top30_uplift_roi']:+.3f} (+${w10k['profit_swing_uplift_vs_churn']:,.0f} swing)."
),
},
{
"id": "kpi_retention_qini_and_pehe",
"label": "Held-Out Retention Uplift vs Churn Top-30%",
"value": f"${churn_row['top30_net_profit']:,.0f} vs ${dr_row['top30_net_profit']:,.0f}",
"unit": "Test Profit",
"status": "ok",
"detail": (
f"DR-Learner Qini={dr_row['factual_ipw_qini']:+.4f} (PEHE={dr_row['pehe']:.4f}) & "
f"T-Learner=${t_row['top30_net_profit']:,.0f} beat Churn Risk Qini={churn_row['factual_ipw_qini']:+.4f}; "
f"DR Profit>0 achieves ${up['dr_optimal_profit_gt0']['net_profit']:,.0f}."
),
},
{
"id": "kpi_refutation_and_sensitivity",
"label": "Refutation Placebo & Sensitivity Bounds",
"value": f"Plc {dw['placebo_ate']:+.4f} | E {ev['e_value_point']:.3f}",
"unit": "Gate",
"status": "ok",
"detail": (
f"Random Common Cause shift={dw['rcc_shift']:.5f}, Subset={dw['subset_shift']:.5f}; "
f"Cinelli-Hazlett OVB RV_1={rv['rv_q']:.4f} (|t|={abs(ref['dml_t_stat']):.2f})."
),
},
]
bars = [
{
"id": "bar_dml_coverage_and_bias",
"title": "PLR High-Dim DML: 95% CI Empirical Coverage (%) Across Regimes",
"metric_label": "95% CI Coverage (%)",
"items": [
{
"label": "naive_plugin_bias",
"value": _pos_bar_val(dml["naive_plugin"]["coverage_95"] * 100.0, floor=1.0),
"display": f"{dml['naive_plugin']['coverage_95']*100:.0f}% (bias {dml['naive_plugin']['bias']:+.3f})",
"css_class": "is-slow",
},
{
"label": "insample_dml_overfit",
"value": _pos_bar_val(dml["insample_dml"]["coverage_95"] * 100.0, floor=1.0),
"display": f"{dml['insample_dml']['coverage_95']*100:.0f}% (bias {dml['insample_dml']['bias']:+.3f})",
"css_class": "is-mid",
},
{
"label": "crossfit_dml2_clean",
"value": _pos_bar_val(dml["crossfit_dml2"]["coverage_95"] * 100.0, floor=1.0),
"display": f"{dml['crossfit_dml2']['coverage_95']*100:.0f}% (bias {dml['crossfit_dml2']['bias']:+.3f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_positivity_and_aipw_recovery",
"title": "Case 5 Positivity Collapse & AIPW Double Robustness |ATE Error|",
"metric_label": "|ATE Error|",
"items": [
{
"label": "case5_naive_diff",
"value": _pos_bar_val(c5["naive_diff"]),
"display": f"{c5['naive_diff']:+.3f} (spurious)",
"css_class": "is-slow",
},
{
"label": "case5_ipw_unclipped",
"value": _pos_bar_val(c5["ipw_unclipped_hajek_ate"]),
"display": f"{c5['ipw_unclipped_hajek_ate']:+.3f} (ESS {c5['overlap_ess_ctrl']:.0f}->{c5['ipw_unclipped_ess_ctrl']:.0f})",
"css_class": "is-mid",
},
{
"label": "case5_overlap_ato",
"value": _pos_bar_val(c5["overlap_ato_ate"]),
"display": f"{c5['overlap_ato_ate']:+.4f} (exact 0)",
"css_class": "is-fast",
},
{
"label": "aipw_bad_propensity",
"value": _pos_bar_val(dr["aipw_bad_propensity_only"] - dr["true_train_ate"]),
"display": f"{dr['aipw_bad_propensity_only']:+.4f} (err {dr['aipw_bad_propensity_only']-dr['true_train_ate']:+.4f})",
"css_class": "is-fast",
},
{
"label": "aipw_bad_outcome",
"value": _pos_bar_val(dr["aipw_bad_outcome_only"] - dr["true_train_ate"]),
"display": f"{dr['aipw_bad_outcome_only']:+.4f} (err {dr['aipw_bad_outcome_only']-dr['true_train_ate']:+.4f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_uplift_qini_comparison",
"title": "Article #3 Retention Test: Oracle Qini Coefficient Across Targeting Policies",
"metric_label": "Oracle Qini",
"items": [
{
"label": "predictive_churn_risk",
"value": _pos_bar_val(churn_row["oracle_qini"]),
"display": f"{churn_row['oracle_qini']:+.4f} (IPW {churn_row['factual_ipw_qini']:+.4f})",
"css_class": "is-slow",
},
{
"label": "s_learner_no_interact",
"value": _pos_bar_val(s_no_row["oracle_qini"]),
"display": f"{s_no_row['oracle_qini']:+.4f} (PEHE {s_no_row['pehe']:.3f})",
"css_class": "is-slow",
},
{
"label": "honest_causal_tree",
"value": _pos_bar_val(ht_row["oracle_qini"]),
"display": f"{ht_row['oracle_qini']:+.4f} (honest)",
"css_class": "is-mid",
},
{
"label": "dr_learner_crossfit",
"value": _pos_bar_val(dr_row["oracle_qini"]),
"display": f"{dr_row['oracle_qini']:+.4f} (IPW {dr_row['factual_ipw_qini']:+.4f})",
"css_class": "is-fast",
},
{
"label": "r_learner_dml",
"value": _pos_bar_val(r_row["oracle_qini"]),
"display": f"{r_row['oracle_qini']:+.4f} (PEHE {r_row['pehe']:.3f})",
"css_class": "is-fast",
},
{
"label": "t_learner_basis",
"value": _pos_bar_val(t_row["oracle_qini"]),
"display": f"{t_row['oracle_qini']:+.4f} (PEHE {t_row['pehe']:.3f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_retention_net_profit",
"title": "Article #3 Retention Test: Realized Net Incremental Profit ($) by Policy",
"metric_label": "|Profit ($)|",
"items": [
{
"label": "treat_all_blanket",
"value": _pos_bar_val(up["treat_all_test_profit"]),
"display": f"-${abs(up['treat_all_test_profit']):,.0f} (loss!)",
"css_class": "is-slow",
},
{
"label": "predictive_churn_top30",
"value": _pos_bar_val(churn_row["top30_net_profit"]),
"display": f"+${churn_row['top30_net_profit']:,.0f}",
"css_class": "is-mid",
},
{
"label": "dr_learner_top30",
"value": _pos_bar_val(dr_row["top30_net_profit"]),
"display": f"+${dr_row['top30_net_profit']:,.0f}",
"css_class": "is-fast",
},
{
"label": "dr_optimal_profit_gt0",
"value": _pos_bar_val(up["dr_optimal_profit_gt0"]["net_profit"]),
"display": f"+${up['dr_optimal_profit_gt0']['net_profit']:,.0f}",
"css_class": "is-fast",
},
{
"label": "oracle_profit_gt0",
"value": _pos_bar_val(up["oracle_profit_gt0"]["net_profit"]),
"display": f"+${up['oracle_profit_gt0']['net_profit']:,.0f}",
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "table_dag_collider_and_simpson",
"title": "SCM DAG Identification, Collider / Berkson Selection Bias & Simpson -> Backdoor Bridge",
"columns": ["check_or_scenario", "theoretical_or_rule", "empirical_observed", "status"],
"rows": [
["backdoor_confounder_Z", "Valid (blocks W <- Z -> Y)", str(scm["backdoor_z_valid"]), "IDENTIFIED"],
["backdoor_with_mediator_M", "Reject (descendant of W)", str(scm["backdoor_m_rejected"]), "REJECTED_OVERCONTROL"],
["backdoor_with_collider_C", "Reject (descendant & collider)", str(scm["backdoor_c_rejected"]), "REJECTED_COLLIDER"],
["mbias_empty_conditioning", "Blocked at collider C", str(scm["mbias_empty_d_separated"]), "UNBIASED_EMPTY_SET"],
[
"linear_gauss_collider_c",
f"rho = {col['theoretical_corr_given_c']:.4f}",
f"partial={col['empirical_partial_corr_given_c']:.4f}, slice={col['empirical_slice_corr_given_c0']:.4f}",
"BIAS_CONFIRMED",
],
[
"berkson_400_cohort",
"0.000 -> -0.500",
f"{col['berkson_400_full_corr']:.3f} -> {col['berkson_400_selected_corr']:.3f}",
"BIAS_CONFIRMED",
],
[
"simpson_2x2_vs_backdoor",
f"true={simp['true_ate']:+.3f}",
f"naive={simp['naive_marginal_diff_confounded']:+.3f} -> backdoor={simp['backdoor_adjusted_ate']:+.3f}",
"REVERSAL_SOLVED",
],
],
},
{
"id": "table_ipw_aipw_and_dml_ablation",
"title": "Positivity Collapse (ATO), AIPW Double Robustness & Cross-Fitted PLR DML Ablation",
"columns": ["estimator_or_regime", "target_truth", "estimate_or_mean", "diagnostic_metric", "verdict"],
"rows": [
[
"case5_naive_diff",
"0.0000",
f"{c5['naive_diff']:+.4f}",
"severe confounding",
"BIASED_FAIL",
],
[
"case5_ipw_unclipped",
"0.0000",
f"{c5['ipw_unclipped_hajek_ate']:+.4f}",
f"max_wt={c5['ipw_unclipped_max_weight']:.1f}, ESS_ctrl={c5['ipw_unclipped_ess_ctrl']:.1f}",
"POS_COLLAPSE",
],
[
"case5_overlap_ato",
"0.0000",
f"{c5['overlap_ato_ate']:+.4f}",
f"max_wt={c5['overlap_max_weight']:.3f}, ESS_ctrl={c5['overlap_ess_ctrl']:.1f}",
"EXACT_RECOVERY",
],
[
"aipw_both_consistent",
f"{dr['true_train_ate']:+.4f}",
f"{dr['aipw_both_ok']:+.4f}",
f"SE={dr['aipw_se']:.4f}",
"UNBIASED_DR",
],
[
"aipw_bad_propensity_only",
f"{dr['true_train_ate']:+.4f}",
f"{dr['aipw_bad_propensity_only']:+.4f}",
f"IPW fails at {dr['ipw_under_bad_propensity']:+.4f}",
"RESCUED_BY_MU",
],
[
"aipw_bad_outcome_only",
f"{dr['true_train_ate']:+.4f}",
f"{dr['aipw_bad_outcome_only']:+.4f}",
f"G-comp fails at {dr['gcomp_under_bad_outcome']:+.4f}",
"RESCUED_BY_E",
],
[
"plr_naive_plugin",
f"{dml['theta_true']:.3f}",
f"{dml['naive_plugin']['mean_estimate']:.4f}",
f"95% cov={dml['naive_plugin']['coverage_95']*100:.0f}%",
"REG_BIAS_FAIL",
],
[
"plr_insample_dml",
f"{dml['theta_true']:.3f}",
f"{dml['insample_dml']['mean_estimate']:.4f}",
f"95% cov={dml['insample_dml']['coverage_95']*100:.0f}%",
"OVERFIT_UNDERCOV",
],
[
"plr_5fold_crossfit_dml2",
f"{dml['theta_true']:.3f}",
f"{dml['crossfit_dml2']['mean_estimate']:.4f}",
f"95% cov={dml['crossfit_dml2']['coverage_95']*100:.0f}%",
"ORTHOGONAL_PASS",
],
],
},
{
"id": "table_uplift_learners_article3",
"title": "Article #3 Retention DGP Held-Out Ablation (PEHE, AUUC, Qini & Top-30% Net Profit)",
"columns": ["model", "ate_bias", "pehe", "oracle_auuc", "oracle_qini", "factual_ipw_qini", "top30_net_profit"],
"rows": [
[
r["model"],
"N/A" if r["model"] == "Predictive_Churn_Risk" else round(r["ate_bias"], 4),
round(r["pehe"], 4),
round(r["oracle_auuc"], 4),
round(r["oracle_qini"], 4),
round(r["factual_ipw_qini"], 4),
round(r["top30_net_profit"], 1),
]
for r in up["ablation_table"]
],
},
{
"id": "table_refutation_and_10k_policy",
"title": "Article #3 10k Policy Audit, DoWhy Refutation Suite & Sensitivity Bounds",
"columns": ["audit_item", "metric", "value", "reference_or_note"],
"rows": [
["10k_treat_all", "net_profit ($)", round(w10k["treat_all_net_profit"], 2), "Sleeping Dogs + Sure Things burn margin"],
["10k_top30_churn_risk", "net_profit ($)", round(w10k["top30_churn_net_profit"], 2), f"ROI={w10k['top30_churn_roi']:+.3f} (Lost Causes)"],
["10k_top30_uplift_knapsack", "net_profit ($)", round(w10k["top30_uplift_net_profit"], 2), f"ROI={w10k['top30_uplift_roi']:+.3f} (Persuadables)"],
["refute_placebo_treatment", "placebo_ate", round(dw["placebo_ate"], 5), f"passed={dw['placebo_passed']} (base={dw['baseline_ate']:+.4f})"],
["refute_random_common_cause", "rcc_shift", round(dw["rcc_shift"], 6), f"rcc_ate={dw['random_common_cause_ate']:+.4f}"],
["refute_data_subset_80pct", "subset_shift", round(dw["subset_shift"], 6), f"subset_ate={dw['data_subset_ate']:+.4f}"],
["vanderweele_ding_evalue", "E_sens (RR=2.0)", round(ev["e_value_point"], 4), f"E_CI(1.45)={ev['e_value_ci']:.4f}"],
["cinelli_hazlett_ovb", "RV_1 (q=1.0)", round(rv["rv_q"], 4), f"DML |t|={abs(ref['dml_t_stat']):.2f}"],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
bench = run_full_causal_uplift_benchmarks(seed=args.seed, quick=args.quick)
panels = _build_workbench_panels(bench)
payload: dict[str, Any] = {
"config": bench["config"],
"workbench_panels": panels,
"scm_and_identification": bench["scm_and_identification"],
"positivity_and_dml": bench["positivity_and_dml"],
"uplift_and_article3": bench["uplift_and_article3"],
"refutation_and_sensitivity": bench["refutation_and_sensitivity"],
}
clean_payload = _sanitize_json_value(payload)
scm = clean_payload["scm_and_identification"]
pos_dml = clean_payload["positivity_and_dml"]
up = clean_payload["uplift_and_article3"]
ref = clean_payload["refutation_and_sensitivity"]
print("=" * 78)
print(f"Lab 02: Causal Inference & Uplift ROI Workbench (seed={args.seed}, quick={args.quick})")
print("=" * 78)
print("\n[1] Pearl SCM DAGs, Berkson Collider Bias & Simpson -> Backdoor Bridge")
print(
f" Backdoor valid(Z)={scm['backdoor_z_valid']} | rejected(M)={scm['backdoor_m_rejected']} | "
f"rejected(C)={scm['backdoor_c_rejected']} | M-Bias empty d-sep={scm['mbias_empty_d_separated']}"
)
print(
f" Linear-Gaussian Collider partial corr={scm['collider_bias']['empirical_partial_corr_given_c']:.4f} "
f"(theo={scm['collider_bias']['theoretical_corr_given_c']:.4f}) | "
f"Berkson N=400: {scm['collider_bias']['berkson_400_full_corr']:.3f} -> {scm['collider_bias']['berkson_400_selected_corr']:.3f}"
)
print(
f" Simpson Naive={scm['simpson_bridge']['naive_marginal_diff_confounded']:+.4f} -> "
f"Backdoor={scm['simpson_bridge']['backdoor_adjusted_ate']:+.4f} (true={scm['simpson_bridge']['true_ate']:+.4f})"
)
print("\n[2] Positivity Collapse (ATO), AIPW Double Robustness & High-Dim PLR DML2")
c5 = pos_dml["case5_positivity"]
dr = pos_dml["aipw_double_robustness"]
dml = pos_dml["dml_plr_ablation"]
print(
f" Case 5 (True=0.0): Naive={c5['naive_diff']:+.4f} | Unclipped IPW={c5['ipw_unclipped_hajek_ate']:+.4f} "
f"(ESS_ctrl={c5['ipw_unclipped_ess_ctrl']:.1f}, max_wt={c5['ipw_unclipped_max_weight']:.1f}) | "
f"Overlap ATO={c5['overlap_ato_ate']:+.4f}"
)
print(
f" AIPW DR (True={dr['true_train_ate']:+.4f}): BothOK={dr['aipw_both_ok']:+.4f} | "
f"BadPropensityOnly={dr['aipw_bad_propensity_only']:+.4f} | BadOutcomeOnly={dr['aipw_bad_outcome_only']:+.4f}"
)
print(
f" PLR DML (theta=1.0, d={dml['n_dim']}): Naive cov={dml['naive_plugin']['coverage_95']*100:.0f}% "
f"(bias={dml['naive_plugin']['bias']:+.3f}) | InSample cov={dml['insample_dml']['coverage_95']*100:.0f}% | "
f"5-Fold DML2 cov={dml['crossfit_dml2']['coverage_95']*100:.0f}% (bias={dml['crossfit_dml2']['bias']:+.3f})"
)
print("\n[3] Article #3: From Churn Prediction to Incremental Uplift & Profit Optimization")
w10k = up["worked_10k"]
fmt_usd = lambda v: f"+${v:,.0f}" if v >= 0 else f"-${abs(v):,.0f}"
print(
f" 10k Segment Benchmark: Treat-All={fmt_usd(w10k['treat_all_net_profit'])} | "
f"Top-30% Churn={fmt_usd(w10k['top30_churn_net_profit'])} | "
f"Top-30% Uplift={fmt_usd(w10k['top30_uplift_net_profit'])} ({fmt_usd(w10k['profit_swing_uplift_vs_churn'])} swing)"
)
print(f" Held-Out Test Retention DGP (True ATE={up['true_test_ate']:+.4f}, Sleeping Dogs={up['sleeping_dog_share_test']*100:.1f}%):")
for row in up["ablation_table"]:
p_str = f"+${row['top30_net_profit']:,.1f}" if row["top30_net_profit"] >= 0 else f"-${abs(row['top30_net_profit']):,.1f}"
print(
f" - {row['model']:22s} | PEHE={row['pehe']:.4f} | OracleQini={row['oracle_qini']:+.4f} | "
f"IPW_Qini={row['factual_ipw_qini']:+.4f} | Top30_Profit={p_str}"
)
print("\n[4] Refutation Suite & Sensitivity Analysis (E-Value, Cinelli-Hazlett OVB)")
dw = ref["dowhy_refuters"]
print(
f" Base ATE={dw['baseline_ate']:+.4f} | Placebo={dw['placebo_ate']:+.4f} (pass={dw['placebo_passed']}) | "
f"RCC shift={dw['rcc_shift']:.5f} | Subset shift={dw['subset_shift']:.5f}"
)
print(
f" VanderWeele-Ding E-Value (RR=2.0)={ref['e_value_rr2']['e_value_point']:.4f} | "
f"Cinelli-Hazlett RV_1={ref['cinelli_hazlett_ovb']['rv_q']:.4f}"
)
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(
json.dumps(clean_payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
encoding="utf-8",
newline="\n",
)
print(f"\nExported JSON results to {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Verification contract & Security-Only AST Deserialization Ban suite for Lab 02 (causal_uplift_lab)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
from causal_uplift_lab import (
CausalDAG,
CausalUpliftConfig,
DRLearner,
HonestCausalTree,
RLearner,
SLearner,
TLearner,
XLearner,
audit_worked_10k_churn_vs_uplift,
compute_cinelli_hazlett_rv,
compute_e_value,
compute_qini_and_auuc,
compute_r_and_dr_loss,
compute_transformed_outcome,
estimate_aipw,
estimate_ipw,
estimate_overlap_ato,
optimize_knapsack_retention_policy,
run_full_causal_uplift_benchmarks,
run_refutation_suite,
simulate_churn_retention_dgp,
simulate_collider_berkson_bias,
simulate_plr_dml_ablation,
simulate_positivity_collapse_dgp,
simulate_simpson_vs_backdoor,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
# Security-Only AST Deserialization Ban (Reference Core zero-scipy/sklearn/dowhy/econml parity is informational).
FORBIDDEN_UNSAFE_IMPORTS = frozenset(
{
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
)
def test_causal_dag_dsep_backdoor_mbias_and_frontdoor_rules() -> None:
chain = CausalDAG(("W", "M", "Y"), (("W", "M"), ("M", "Y")))
assert not chain.is_d_separated("W", "Y", ())
assert chain.is_d_separated("W", "Y", {"M"})
fork = CausalDAG(("Z", "W", "Y"), (("Z", "W"), ("Z", "Y")))
assert not fork.is_d_separated("W", "Y", ())
assert fork.is_d_separated("W", "Y", {"Z"})
collider = CausalDAG(("W", "Y", "C", "D"), (("W", "C"), ("Y", "C"), ("C", "D")))
assert collider.is_d_separated("W", "Y", ())
assert not collider.is_d_separated("W", "Y", {"C"})
assert not collider.is_d_separated("W", "Y", {"D"})
mbias = CausalDAG(("U1", "U2", "W", "C", "Y"), (("U1", "W"), ("U1", "C"), ("U2", "C"), ("U2", "Y")))
assert mbias.is_d_separated("W", "Y", ())
assert mbias.is_valid_backdoor_set("W", "Y", ())["valid"]
assert not mbias.is_valid_backdoor_set("W", "Y", {"C"})["valid"]
assert mbias.is_valid_backdoor_set("W", "Y", {"C", "U1"})["valid"]
full_dag = CausalDAG(("Z", "W", "M", "Y", "C"), (("Z", "W"), ("Z", "Y"), ("W", "M"), ("M", "Y"), ("W", "C"), ("Y", "C")))
assert full_dag.is_valid_backdoor_set("W", "Y", {"Z"})["valid"]
assert not full_dag.is_valid_backdoor_set("W", "Y", {"Z", "M"})["valid"]
assert not full_dag.is_valid_backdoor_set("W", "Y", {"Z", "C"})["valid"]
assert full_dag.find_minimal_backdoor_sets("W", "Y") == [("Z",)]
fd_dag = CausalDAG(("U", "W", "M", "Y"), (("U", "W"), ("U", "Y"), ("W", "M"), ("M", "Y")))
assert fd_dag.verify_frontdoor_set("W", "Y", {"M"})["valid"]
fd_leak = CausalDAG(("U", "W", "M", "Y"), (("U", "W"), ("U", "Y"), ("W", "M"), ("M", "Y"), ("W", "Y")))
assert not fd_leak.verify_frontdoor_set("W", "Y", {"M"})["valid"]
def test_collider_and_berkson_selection_bias_exact_proofs() -> None:
res = simulate_collider_berkson_bias(n_samples=20000, alpha=1.0, beta=1.0, noise_std=1.0, seed=42)
assert abs(res["unconditional_corr"]) < 0.03
assert math.isclose(res["theoretical_cov_given_c"], -1.0 / 3.0, abs_tol=1e-12)
assert math.isclose(res["theoretical_corr_given_c"], -0.5, abs_tol=1e-12)
assert abs(res["empirical_partial_corr_given_c"] - (-0.5)) < 0.02
assert abs(res["empirical_slice_corr_given_c0"] - (-0.5)) < 0.04
assert math.isclose(res["berkson_400_full_corr"], 0.0, abs_tol=1e-12)
assert math.isclose(res["berkson_400_selected_corr"], -0.5, abs_tol=1e-12)
def test_simpson_vs_backdoor_identification_bridge() -> None:
res = simulate_simpson_vs_backdoor(n_samples=2000, seed=42)
assert res["naive_marginal_diff_confounded"] > 0.35
assert res["backdoor_adjusted_ate"] < -0.02
assert abs(res["backdoor_adjusted_ate"] - (-0.05)) < 0.03
assert res["simpson_reversal_detected"] is True
assert res["mediator_true_total_effect"] > 0.30
assert abs(res["mediator_overcontrol_biased_effect"]) < 0.05
def test_ipw_hajek_bounds_shift_invariance_and_positivity_overlap_ato() -> None:
rng = np.random.default_rng(11)
n = 50
w = np.zeros(n, dtype=np.int64)
w[:15] = 1
e_hat = np.full(n, 0.5, dtype=np.float64)
e_hat[0] = 0.01 # Extreme treated inverse weight 100 / 50 = 2.0 > 1.0
y = rng.integers(0, 2, size=n).astype(np.float64)
y[0] = 1.0
ipw_edge = estimate_ipw(y, w, e_hat, clip=None)
assert ipw_edge["ht_mu1"] > 1.0 # Horvitz-Thompson violates [0, 1] probability bounds
assert 0.0 <= ipw_edge["hajek_mu1"] <= 1.0
shifted = estimate_ipw(y + 500.0, w, e_hat, clip=None)
assert math.isclose(shifted["hajek_ate"], ipw_edge["hajek_ate"], abs_tol=1e-10)
assert abs(shifted["ht_ate"] - ipw_edge["ht_ate"]) > 10.0 # HT violates shift equivariance
pos = simulate_positivity_collapse_dgp(n_samples=4000, seed=7)
naive_diff = float(np.mean(pos["y"][pos["w"] == 1]) - np.mean(pos["y"][pos["w"] == 0]))
assert naive_diff > 0.40
unclip = estimate_ipw(pos["y"], pos["w"], pos["e_true"], clip=None)
assert unclip["ess_control"] < 500.0 and unclip["max_weight"] > 100.0
ato = estimate_overlap_ato(pos["y"], pos["w"], pos["e_true"], X=pos["X"])
assert ato["max_weight"] <= 1.0
assert abs(ato["ato_ate"]) < 0.03
def test_aipw_doubly_robust_either_nuisance_consistent() -> None:
dgp = simulate_churn_retention_dgp(n_samples=4000, seed=42)
true_ate = float(np.mean(dgp["tau_true"]))
both_ok = estimate_aipw(dgp["X"], dgp["w"], dgp["y"], n_folds=5, clip=(0.03, 0.97), seed=42)
bad_e = estimate_aipw(
dgp["X"], dgp["w"], dgp["y"], n_folds=5, clip=(0.03, 0.97), seed=42, misspecify_propensity=True
)
bad_mu = estimate_aipw(
dgp["X"], dgp["w"], dgp["y"], n_folds=5, clip=(0.03, 0.97), seed=42, misspecify_outcome=True
)
both_bad = estimate_aipw(
dgp["X"], dgp["w"], dgp["y"], n_folds=5, clip=(0.03, 0.97), seed=42, misspecify_propensity=True, misspecify_outcome=True
)
assert abs(both_ok["ate"] - true_ate) < 0.025
assert abs(bad_e["ipw_hajek_ate"] - true_ate) > 0.05 # Single IPW fails
assert abs(bad_e["ate"] - true_ate) < 0.025 # AIPW rescued by outcome model
assert abs(bad_mu["gcomp_ate"] - true_ate) > 0.04 # Single G-comp fails
assert abs(bad_mu["ate"] - true_ate) < 0.025 # AIPW rescued by propensity model
assert abs(both_bad["ate"] - true_ate) > 0.25
def test_dml_plr_eliminates_naive_regularization_bias_and_in_sample_overfit() -> None:
abl = simulate_plr_dml_ablation(n_samples=500, n_dim=350, n_trials=20, n_folds=5, theta_true=1.0, seed=42)
assert abl["naive_plugin"]["coverage_95"] <= 0.20
assert abs(abl["naive_plugin"]["bias"]) > 0.20
assert abl["insample_dml"]["coverage_95"] <= 0.75
assert abl["insample_dml"]["rmse"] > abl["crossfit_dml2"]["rmse"]
assert abl["crossfit_dml2"]["coverage_95"] >= 0.80
assert abs(abl["crossfit_dml2"]["bias"]) < 0.05
def test_s_learner_dropout_vs_t_x_r_dr_learners_on_imbalanced_arm() -> None:
rng = np.random.default_rng(77)
def _gen_imbalanced(n: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
X = rng.normal(0.0, 1.0, size=(n, 5))
e = 1.0 / (1.0 + np.exp(-(-2.2 + 0.6 * X[:, 0] + 0.4 * X[:, 1]))) # ~12% treated
w = (rng.random(n) < e).astype(np.int64)
mu0 = 2.0 * X[:, 0] + 1.5 * np.tanh(X[:, 2]) - 1.2 * X[:, 1]
tau = 0.6 + 0.8 * X[:, 3] - 0.5 * X[:, 4]
y = mu0 + w * tau + rng.normal(0.0, 0.5, size=n)
return X, w, y, tau
X_tr, w_tr, y_tr, _ = _gen_imbalanced(3500)
X_te, _, _, tau_te = _gen_imbalanced(1500)
s_drop = SLearner(l2_reg=25.0, include_interactions=False).fit(X_tr, w_tr, y_tr)
x_mod = XLearner(l2_reg=1.0, stage2_alpha=5.0).fit(X_tr, w_tr, y_tr)
r_mod = RLearner(n_folds=5, l2_reg=1.0, stage2_alpha=5.0, seed=77).fit(X_tr, w_tr, y_tr)
t_mod = TLearner(l2_reg=1.0).fit(X_tr, w_tr, y_tr)
pehe_s = float(np.sqrt(np.mean((s_drop.predict_cate(X_te) - tau_te) ** 2)))
pehe_x = float(np.sqrt(np.mean((x_mod.predict_cate(X_te) - tau_te) ** 2)))
pehe_r = float(np.sqrt(np.mean((r_mod.predict_cate(X_te) - tau_te) ** 2)))
pehe_t = float(np.sqrt(np.mean((t_mod.predict_cate(X_te) - tau_te) ** 2)))
assert pehe_s > 0.60 # S-learner without interactions ignores heterogeneous X*W
assert pehe_x < 0.20 and pehe_r < 0.20 and pehe_t < 0.25
def test_honest_causal_tree_prevents_adaptive_overfitting() -> None:
rng = np.random.default_rng(123)
def _gen_null(n: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
X = rng.normal(0.0, 1.0, size=(n, 5))
w = (rng.random(n) < 0.5).astype(np.int64)
y = 1.5 * np.sin(X[:, 0]) + rng.normal(0.0, 1.2, size=n) # True CATE = 0 everywhere
return X, w, y
X_tr, w_tr, y_tr = _gen_null(1200)
X_te, _, _ = _gen_null(800)
honest_tree = HonestCausalTree(max_depth=4, min_leaf_arm=10, honest=True, seed=123).fit(X_tr, w_tr, y_tr)
greedy_tree = HonestCausalTree(max_depth=4, min_leaf_arm=10, honest=False, seed=123).fit(X_tr, w_tr, y_tr)
pred_honest = honest_tree.predict_cate(X_te)
pred_greedy = greedy_tree.predict_cate(X_te)
rmse_honest = float(np.sqrt(np.mean(pred_honest**2)))
rmse_greedy = float(np.sqrt(np.mean(pred_greedy**2)))
assert rmse_honest < rmse_greedy
def test_uplift_qini_auuc_and_transformed_outcome_unbiasedness() -> None:
tr = simulate_churn_retention_dgp(n_samples=3500, seed=42)
te = simulate_churn_retention_dgp(n_samples=2000, seed=99)
y_star = compute_transformed_outcome(te["y"], te["w"], te["e_true"])
assert abs(float(np.mean(y_star)) - float(np.mean(te["tau_true"]))) < 0.06
assert float(np.std(y_star)) > 5.0 * float(np.std(te["tau_true"])) # Variance trap check
s_bad = SLearner(include_interactions=False).fit(tr["X"], tr["w"], tr["y"]).predict_cate(te["X"])
dr_mod = DRLearner(n_folds=5, clip=(0.03, 0.97), seed=42).fit(tr["X"], tr["w"], tr["y"])
dr_pred = dr_mod.predict_cate(te["X"])
r_pred = RLearner(n_folds=5, seed=42).fit(tr["X"], tr["w"], tr["y"]).predict_cate(te["X"])
q_dr = compute_qini_and_auuc(te["y"], te["w"], dr_pred, top_frac=0.30, e_hat=te["e_true"], tau_true=te["tau_true"])
assert q_dr["qini_excess"] > 0.03 and q_dr["auuc_excess"] > 0.015 and q_dr["qini_norm"] > 0.10
losses = compute_r_and_dr_loss(
te["X"], te["w"], te["y"], {"s_bad": s_bad, "dr": dr_pred, "r": r_pred}, n_folds=5, clip=(0.03, 0.97), seed=7
)
assert losses["dr"]["r_loss"] < losses["s_bad"]["r_loss"]
assert losses["r"]["dr_loss"] < losses["s_bad"]["dr_loss"]
def test_article3_churn_vs_uplift_10k_and_retention_dgp_roi_reversal() -> None:
w10k = audit_worked_10k_churn_vs_uplift(ltv_value=200.0, contact_cost=5.0, incentive_cost=25.0)
assert math.isclose(w10k["treat_all_net_profit"], -69750.0, abs_tol=1e-6)
assert math.isclose(w10k["top30_churn_net_profit"], -17250.0, abs_tol=1e-6)
assert math.isclose(w10k["top30_uplift_net_profit"], 101250.0, abs_tol=1e-6)
assert math.isclose(w10k["profit_swing_uplift_vs_churn"], 118500.0, abs_tol=1e-6)
bench = run_full_causal_uplift_benchmarks(seed=42, quick=True)
up = bench["uplift_and_article3"]
rows = {r["model"]: r for r in up["ablation_table"]}
assert up["treat_all_test_profit"] < -10000.0
assert rows["Predictive_Churn_Risk"]["top30_net_profit"] < 0.5 * rows["DR_Learner_CrossFit"]["top30_net_profit"]
assert up["dr_optimal_profit_gt0"]["net_profit"] > 0.75 * up["oracle_profit_gt0"]["net_profit"]
def test_knapsack_budget_policy_respects_budget_and_marginal_roi_order() -> None:
# Two segments tie on tau_hat = +0.25, but segment 0 has mu1=0.2 (cheap conditional discount) vs 0.95 (expensive)
tau_hat = np.array([0.25, 0.25, -0.10, 0.02], dtype=np.float64)
mu1_hat = np.array([0.20, 0.95, 0.50, 0.90], dtype=np.float64)
pol = optimize_knapsack_retention_policy(
tau_hat, mu1_hat, ltv_value=200.0, contact_cost=5.0, incentive_cost=25.0, budget=25.0
)
assert pol["predicted_cost"] <= 25.0 + 1e-9
# Unit 0 costs 10.0 and profit=40.0 (ROI=4.0), Unit 1 costs 28.75 (>25), Unit 2/3 have Pi<=0
assert list(pol["selected_mask"]) == [True, False, False, False]
def test_top_frac_policy_never_targets_sleeping_dogs_negative_profit() -> None:
"""Regression: top_frac policy must enforce profit_hat > 0.0 so Sleeping Dogs are never targeted."""
tau_hat = np.array([0.35, -0.20, 0.02, 0.25], dtype=np.float64)
mu1_hat = np.array([0.50, 0.55, 0.90, 0.40], dtype=np.float64)
# Expected profits (V=200, c=5, d=25):
# [0]: 70 - 17.5 = +52.5 (>0)
# [1]: -40 - 18.75 = -58.75 (Sleeping Dog, <0)
# [2]: 4 - 27.5 = -23.5 (Sure Thing / Lost Cause, <0)
# [3]: 50 - 15.0 = +35.0 (>0)
pol = optimize_knapsack_retention_policy(
tau_hat, mu1_hat, ltv_value=200.0, contact_cost=5.0, incentive_cost=25.0, top_frac=0.75
)
assert list(pol["selected_mask"]) == [True, False, False, True]
assert pol["n_targeted"] == 2
assert pol["predicted_net_profit"] == pytest.approx(52.5 + 35.0)
def test_refutation_suite_e_value_and_cinelli_hazlett_ovb() -> None:
tr = simulate_churn_retention_dgp(n_samples=2500, seed=42)
ref = run_refutation_suite(
tr["X"],
tr["w"],
tr["y"],
lambda xm, wm, ym, sd: estimate_aipw(xm, wm, ym, n_folds=3, clip=(0.03, 0.97), seed=sd)["ate"],
seed=42,
)
assert ref["placebo_passed"] is True
assert abs(ref["placebo_ate"]) < 0.03
assert ref["rcc_shift"] < 0.01
assert ref["subset_shift"] < 0.04
ev = compute_e_value(risk_ratio=2.0, ci_bound=0.90)
assert math.isclose(ev["e_value_point"], 2.0 + math.sqrt(2.0), abs_tol=1e-10)
assert math.isclose(ev["e_value_ci"], 1.0, abs_tol=1e-12)
rv = compute_cinelli_hazlett_rv(t_stat=4.0, df=998, q=1.0)
lhs = (rv["rv_q"] ** 2) / (1.0 - rv["rv_q"])
assert math.isclose(lhs, rv["f_q"] ** 2, abs_tol=1e-12)
def test_pydantic_config_frozen_and_seed_determinism() -> None:
with pytest.raises(ValidationError):
CausalUpliftConfig(unknown_flag=123)
with pytest.raises(ValidationError):
CausalUpliftConfig(propensity_clip=(0.6, 0.4))
cfg = CausalUpliftConfig(seed=42)
with pytest.raises(ValidationError):
cfg.seed = 99 # type: ignore[misc]
b1 = run_full_causal_uplift_benchmarks(seed=42, quick=True)
b2 = run_full_causal_uplift_benchmarks(seed=42, quick=True)
assert b1["positivity_and_dml"]["aipw_double_robustness"] == b2["positivity_and_dml"]["aipw_double_robustness"]
assert b1["uplift_and_article3"]["ablation_table"] == b2["uplift_and_article3"]["ablation_table"]
def test_cli_demo_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch05_workbench_test.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,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, proc.stderr
for marker in ("[1] Pearl SCM DAGs", "[2] Positivity Collapse", "[3] Article #3", "[4] Refutation Suite"):
assert marker in proc.stdout
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 Ban across every .py file in src/, scripts/, and tests/
found_forbidden: list[tuple[str, str]] = []
for folder in ("src", "scripts", "tests"):
for py_file in (LAB_ROOT / folder).rglob("*.py"):
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_pkg = alias.name.split(".", 1)[0]
if root_pkg in FORBIDDEN_UNSAFE_IMPORTS:
found_forbidden.append((py_file.name, root_pkg))
elif isinstance(node, ast.ImportFrom) and node.module:
root_pkg = node.module.split(".", 1)[0]
if root_pkg in FORBIDDEN_UNSAFE_IMPORTS:
found_forbidden.append((py_file.name, root_pkg))
assert found_forbidden == [], f"Forbidden unsafe deserialization imports detected: {found_forbidden}"
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 — Định danh Đồ thị, Chứng minh Berkson & Cầu nối Simpson 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Sử dụng định lý Bù Schur cho phân phối chuẩn nhiều chiều \((W, Y, C)^T\) với \(\Sigma_{WY} = 0\): công thức hiệp phương sai điều kiện là \(\Sigma_{WY \mid C} = \Sigma_{WY} - \Sigma_{W,C}\Sigma_{CC}^{-1}\Sigma_{C,Y}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với Frontdoor \(W \to M \to Y\) kèm nhiễu ẩn \(U \to W, U \to Y\), lần lượt chứng minh \(P(m \mid do(w)) = P(m \mid w)\) (Quy tắc 2) và \(P(y \mid do(m)) = \sum_{w'} P(y \mid m, w')P(w')\) (Quy tắc 2 trên đồ thị cắt mũi tên đi vào M kết hợp Quy tắc 3). Đối chiếu thực nghiệm với CausalDAG, simulate_collider_berkson_bias, và simulate_simpson_vs_backdoor trong causal_uplift_lab.
Tiêu chí Đáp án & Số đối chứng
Thay \(\Sigma_{W,C} = \gamma_W\), \(\Sigma_{Y,C} = \gamma_Y\), \(\Sigma_{CC} = \gamma_W^2 + \gamma_Y^2 + \sigma_C^2\) vào Bù Schur ta thu được \(\operatorname{Corr}(W,Y \mid C) = -\frac{\gamma_W \gamma_Y}{\sqrt{(\gamma_W^2+\sigma_C^2)(\gamma_Y^2+\sigma_C^2)}}\), tại giá trị 1 cho đúng -0.500 (Lab N=15,000 đo được -0.4932; N=400 trên Widget cho -0.493). Với cầu nối Simpson trong run_lab_demo.py, hiệu ứng thô +0.4563 đảo dấu về -0.0593 khi kiểm soát Z (true ATE = -0.05).
Bài tập 2 — Định lý Rosenbaum–Rubin, HT vs. Hájek, ATO & Chứng minh Kép AIPW 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Để chứng minh \(W \perp X \mid e(X)\), tính \(P(W=1 \mid X, e(X)) = P(W=1 \mid X) = e(X)\) và sử dụng định lý kỳ vọng lặp để chứng tỏ nó đúng bằng \(P(W=1 \mid e(X))\). Với đồng nhất thức AIPW, khai triển phần số hạng nhóm điều trị \(\hat{\psi}_1 - \mathbb{E}[Y(1)]\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Viết phần chênh lệch AIPW dưới dạng tổng của kỳ vọng ảnh hưởng cộng hàm tích sai số \((\hat{e}(X) - e(X))(\mu_1(X) - \hat{\mu}_1(X)) / \hat{e}(X)\). Thực nghiệm kiểm chứng bằng estimate_ipw, estimate_overlap_ato, và estimate_aipw(..., misspecify_propensity=True / misspecify_outcome=True) trên Case 5.
Tiêu chí Đáp án & Số đối chứng
Khi tách sai số AIPW nhánh w=1, số hạng sai số thuần túy thu gọn về \(\mathbb{E}\left[\frac{(e(X)-\hat{e}(X))(\mu_1(X)-\hat{\mu}_1(X))}{\hat{e}(X)}\right]\): chỉ cần một trong hai \(\hat{e}=e\) hoặc \(\hat{\mu}_1=\mu_1\) là kỳ vọng sai số bằng đúng 0. Trên Case 5 (Lab 02), naive = +0.4969, clipped IPW lệch về +0.1394, còn estimate_overlap_ato thu hồi chuẩn xác -0.0000 với ESS_ctrl tăng từ 363.3 lên 831.4; trên Retention DGP (true ATE = +0.0551), AIPW giữ +0.0551 (hỏng propensity) và +0.0416 (hỏng outcome).
Bài tập 3 — Chứng minh Trực giao Neyman & Mô phỏng DML2 Đa chiều 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khai triển \(\hat{\theta}_{\text{naive}} - \theta_0\) từ hồi quy \(Y - \hat{g}(X) \sim \theta W\): mẫu số chia theo \(W^2\) để lại số hạng tuyến tính bậc một \(\mathbb{E}[m_0(X)(g_0(X)-\hat{g}(X))] / \mathbb{E}[W^2]\) không triệt tiêu và hội tụ chậm cỡ \(n^{-\varphi_g}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chứng minh đạo hàm Gateaux \(\partial_r \mathbb{E}[\psi(Z; \theta_0, \eta_0 + r(\eta - \eta_0))]|_{r=0} = 0\) cho hàm score Robinson \((Y - \ell(X) - \theta(W - m(X)))(W - m(X))\). Sau đó gọi simulate_plr_dml_ablation(n_samples=500, n_dim=350, n_trials=20, n_folds=5).
Tiêu chí Đáp án & Số đối chứng
Vì \(\mathbb{E}[V \mid X] = 0\) và \(\mathbb{E}[U \mid X, W] = 0\), đạo hàm Gateaux theo cả \(\ell\) và \(m\) đều triệt tiêu đồng thời tại chân trị. Sai số còn lại chỉ là bậc hai \(\|\hat{\ell}-\ell_0\|_{L_2}\|\hat{m}-m_0\|_{L_2} = O_p(n^{-(\varphi_\ell+\varphi_m)}) = o_p(n^{-1/2})\) nếu mỗi learner đạt \(n^{-1/4}\). Thực nghiệm Lab 02 (d=350, N=500) xác nhận: Naive bias = -0.3636 (0% CI coverage), In-Sample DML bias = -0.1018 (55% coverage), 5-Fold DML2 bias = +0.0087 (RMSE = 0.0760, 90% coverage).
Bài tập 4 — Meta-Learners Mất cân bằng & Cây Nhân quả Trung thực 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chú ý khi \(P(W=1) \approx 0.12\), SLearner(include_interactions=False) không cho phép đặc trưng phi tuyến giao với W trong mô hình tuyến tính/Ridge/Logistic, còn HonestCausalTree(honest=False) dùng chung 100% mẫu để vừa chia vừa tính chênh lệch trung bình lá.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Huấn luyện toàn bộ SLearner, TLearner, XLearner, RLearner, DRLearner, và HonestCausalTree trên Retention DGP đã chia Train/Test trước, đồng thời kiểm tra tỷ lệ phát hiện dị chất giả của cây không trung thực trên dữ liệu \(\tau_0(X) \equiv 0\).
Tiêu chí Đáp án & Số đối chứng
Kết quả kiểm chuẩn Lab 02 chứng minh: SLearner thiếu tương tác bị sụp đổ với PEHE > 0.60, trong khi có tương tác đạt 0.1112; DRLearner đạt Qini cao nhất (+0.0684, PEHE = 0.1103) và TLearner đạt lợi nhuận Top-30% thực nghiệm cao ($22,471 vs Churn Risk chỉ $4,727). Trên dữ liệu thuần nhiễu tau = 0, tách mẫu trung thực \(\mathcal{I}^{\text{split}} \sqcup \mathcal{I}^{\text{est}}\) cắt giảm mạnh phương sai dự báo sai lệch so với cây thích nghi.
Bài tập 5 — Đánh giá Phản thực Qini/R-loss/DR-loss & Bộ Phản bác + Độ nhạy 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Với biến đổi kết cục \(Y^* = Y \frac{W - e(X)}{e(X)(1-e(X))}\), áp dụng kỳ vọng lặp điều kiện theo X và W để chứng minh \(\mathbb{E}[Y^* \mid X] = \mu_1(X) - \mu_0(X) = \tau(X)\), sau đó chỉ ra số hạng mẫu số \(e(X)^2(1-e(X))^2\) làm phình phương sai.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng compute_r_and_dr_loss so sánh 5 Meta-Learners với mô hình dự báo churn, chạy run_refutation_suite, compute_e_value(rr_point=2.0, rr_ci_lower=1.45), và xác nhận bằng số đồng nhất thức đại số \(RV_q^2 / (1 - RV_q) = f_q^2\) từ compute_cinelli_hazlett_rv.
Tiêu chí Đáp án & Số đối chứng
Vì có xác suất chia cho e(X) hoặc 1-e(X) gần 0 ngay cả khi Y lớn, \(Y^*\) thiếu cơ chế trừ trung tâm (centering) như trong DR pseudo-outcome nên phương sai cực lớn. Trên ch05_workbench_results.json, run_refutation_suite cho kết quả base ATE = +0.0430, Placebo ATE = -0.00563, Random Common Cause shift = 0.00027, Data Subset shift = 0.01384; compute_e_value(2.0, 1.45) đạt 3.4142 (CI 2.2578) và compute_cinelli_hazlett_rv cho RV_1 = 0.0700 (|t| = 4.58) khớp hoàn hảo đồng nhất thức \(RV_q^2 / (1 - RV_q) = f_q^2\).
Bài tập 6 — Chuyên đề #3: Tối ưu Ba lô ROI Giữ chân & Bài toán 10,000 Thuê bao 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lập bảng 5 phân khúc (Lost Causes 3,000; Persuadables High 1,500; Persuadables Mid 1,500; Sleeping Dogs 1,500; Sure Things 2,500), tính \(c_{\text{exp}} = c + \mu_1 d\) và lợi nhuận đơn vị \(\pi = \tau V - c_{\text{exp}}\) (lấy V=$200, c=$5, d=$25).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Xếp hạng từ cao xuống thấp theo Churn Risk \(1-\mu_0\) vs Marginal ROI \(\pi / c_{\text{exp}}\) (áp dụng điều kiện dừng \(\pi > 0\)), sau đó kiểm tra hàm optimize_knapsack_retention_policy trên tập Test N=2,000 và mô tả kiến trúc serving trực tuyến (latency < 20 ms p99, exploration 5% holdout logging propensity e_log(x)).
Tiêu chí Đáp án & Số đối chứng
Bài toán 10,000 khách hàng: Treat-All lỗ -$69,750; Top-30% Churn Risk dồn hết vào 3,000 Lost Causes (\(\mu_0=0.10, \mu_1=0.11\)) lỗ -$17,250 (ROI -0.742); Top-30% Uplift chọn 1,500 Persuadables High (\(\tau=+0.35\)) + 1,500 Persuadables Mid (\(\tau=+0.20\)) thu lời +$101,250 (ROI +1.588), biên độ tăng thêm +$118,500. Trên tập Test N=2,000 của Lab 02, chiến lược DR-Learner Profit > 0 đạt +$20,895 (tiệm cận Oracle +$24,465), còn kiến trúc serving phải ghi nhận xác suất ngẫu nhiên 5% holdout làm logged propensity để liên tục hiệu chỉnh chính sách mà không bị lệch chọn mẫu.