Chương 12 — Học Không giám sát: Phân cụm (K-Means++, GMM/EM, DBSCAN, HDBSCAN), Giảm chiều & Học Đa tạp (PCA, t-SNE, UMAP, PaCMAP), Ma trận Độ phức tạp ML & Miền Marketing (Lab 04)
Từ Bẫy Tỷ lệ RFM (99.8% Monetary -> ARI 0.208->0.973, OOT 1.000), EM ELBO đơn điệu, Ảo giác Silhouette (0.134 vs 1.000) & HDBSCAN EOM (0.985) đến t-SNE (4.08x->0.98x) vs PaCMAP/PCA (rho=0.892/0.985), Ma trận O(n^2) vs O(nKd) & Marketing Absorbing Markov/Shapley/CUPED (-68.94% Var)/AIPW-DR iROAS.
Unit ID:
T1-P2-U07
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Truy xuất Giáo trình Gốc (R36,R29:R31): Lesson 11 (Clustering & Dimensionality Reduction — 2 buổi, phủ trọn vẹn 100% cả 5 mục trong01-track-dsai-raw-curriculum.md: Soft & hard clustering, K-Means, DBSCAN and hierarchical, Dimensionality reduction: projection & manifold learning, Computational complexity of ML models, Industrial tips) kết hợp trọn vẹn Miền Marketing Analytics (R29:R31): Customer Segmentation, Multi-Touch Attribution & Experimentation (Ranh giới không chồng lấn: tối ưu tuyến tính/logistic & bộ tách thời gian kế thừa từch-06; kiểm toán rò rỉ & hiệu chuẩn xác suất từch-07; thang đo Stevens & chuẩn hóa đặc trưng trong nếp từch-08; máy vector hỗ trợ & nhân từch-09; cây quyết định & GBDT từch-10; suy luận nhân quả AIPW/DML từch-05; tìm kiếm láng giềng gần chính xáckNN/HNSWthuộcch-11và chuỗi thời gian bán lẻ thuộcch-13)
Bài thực hành Song hành (Lab 04):labs/lab-04-marketing-segmentation-attribution-experimentation/(marketing_seg_mta_lab)
Tình huống Mở đầu: Bốn Thảm họa Sản xuất Khi Phân cụm, Chiếu Đa tạp & Đo lường Marketing Không Kiểm soát#
Khác với học có giám sát nơi biến mục tiêu \(Y\) đóng vai trò ngọn hải đăng định hướng sai số, Học Không giám sát (Unsupervised Learning) buộc thuật toán tự định nghĩa cấu trúc từ hình học khoảng cách và mật độ trong \(\mathbb{R}^d\). Chỉ cần sai một giả định về thang đo, độ cong đa tạp, độ phức tạp ma trận \(n \times n\), hoặc thiên lệch chọn lọc hành vi người dùng, toàn bộ hệ thống phân khúc và phân bổ ngân sách Marketing sẽ sụp đổ âm thầm:
- Bẫy Thang đo
RFM— Khi Cột Tiền tệMonetaryNghiền nát Toàn bộ Chân dung Khách hàng (ARI = 0.2082): Một đội ngũ CRM phân khúc khách hàng trên bảngRFM(Recency1–200ngày, Frequency1–35đơn, Monetary$20–$20,000+, Promo Sensitivity0–1) bằngK-Means++trên khoảng cách Euclid thô. Vì phương sai tăng theo bình phương đơn vị đo, riêng cộtMonetarylệch phải nặng chiếm tới99.8147%tổng phương sai Euclid! Hệ quả làK-Means++biến thành phép cắt lát 1 chiều theo hóa đơn USD (Train ARI = 0.2082), gộp nhầm khách hàng săn khuyến mãi mua đều với nhóm khách ngủ đông giá trị vừa. Chỉ khi nén đuôi phải bằnglog1pvà khớpRobustScalerduy nhất trên tậptrain(snapshot_day <= 90),K-Means++mới vọt lênARI = 0.9729(Full-Covariance GMM = 0.9908) và duy trìOOT Stability ARI = 1.0000trên tập tương lai (snapshot_day >= 91). - Ảo giác
Silhouettetrên Hình học Phi lồi & Biến dạng Cụm4.08x -> 0.98xcủat-SNE: Trên tập dữ liệu hai trăng khuyết lồng nhau (Two-Moons) kèm nhiễu biên,K-Means++chẻ đôi hai vầng trăng (ARI = 0.1335) nhưng vẫn được chỉ số nội tạiSilhouettechấm điểm0.4641— cao hơn hẳn lời giải đúng tuyệt đối củaDBSCAN(ARI = 1.0000,Silhouette = 0.3247) vàHDBSCAN(ARI = 0.9875) vìSilhouetteluôn thiên vị các khối lồi Voronoi! Tệ hơn nữa, khi chiếu4cụm dữ liệu12chiều xuống2Dbằngt-SNE(với Cụm 2 có bán kính thực rộng gấp4.084xCụm 0), phép chuẩn hóa mật độ cục bộ và phân kỳ KL bất đối xứng khiếnt-SNEbóp méo tỷ lệ bán kính xuống0.981x(biến cụm thưa to thành khối tròn bằng hệt cụm đặc!) và kéo tụt tương quan khoảng cách toàn cụcSpearmanvề0.6126(sklearn 0.4883) so với0.8918củaPaCMAPvà0.9848củaPCA. ChạyK-Meanstrên tọa độ2D t-SNElà sai lầm nghiêm trọng trong phân tích sản phẩm. - Bức tường Bộ nhớ
O(n^2)(2 TBRAM ởn = 500k) & Cái chết của Thuật toán Thiếu Kiểm toán Độ phức tạp: Đẩy nguyên mô hình phân cấp tích tụWardhoặcKernel SVM RBFlên bảng500,000người dùng buộc hệ thống cấp phát ma trận khoảng cách / Gram \(n \times n\)float64ngốn2.0 TBRAM gây tràn bộ nhớSIGKILLtức thì, trong khiK-Means++(~512 MB) hoặcGBDT Hist uint8(~64 MB) hoàn tất trong vài giây với độ trễ suy luận< 1 ms. - Ảo ảnh
Last-Touch ROAS = 8.15xCướp công Kênh Mở phễu & Lãng phí Ngân sách A/B: Trong quy bổ đa chạm (MTA), khách hàng đã bị tác động bởiDisplay(28%đóng góp cấu trúc thật) vàSocial(26%) thường gõ tên thương hiệu vàoPaid Searchngay trước khi thanh toán. Quy tắcLast-Touchngây thơ gán77.1%công lao choPaid Search(trong khi giá trị gia tăng thật chỉ10.0%, sai sốL1 = 1.3424) và báo cáoROASquan sát8.15x(Naive Diff = 4.17x) so với chân lý nhân quả1.86x. Kết hợp Chuỗi Markov Hấp thụ (L1 = 0.4894), Giá trị Shapley Chính xác (L1 = 0.2854, sai số hiệu quả0.0e+00),CUPEDgiảm-68.94%phương sai thử nghiệm A/B (SE $1.82 -> $1.01), vàCross-Fitted AIPW-DRkhôi phụciROAS_DR = 1.81xđã nângiROASphân bổ ngân sách holdout từ0.68x -> 2.17x.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 12 và gói thực hành marketing_seg_mta_lab (T1-P2-U07), học viên có năng lực:
- Làm chủ Phân cụm Cứng, Phân cụm Mềm (
GMM/EM), Phân cấp & Mật độ (R36.1–R36.2): Phân biệt rạch ròi bài toán tối ưu phân hoạchK-Means/ khởi tạo \(D^2\)K-Means++với cận cạnh tranh \(\mathcal{O}(\log K)\); dẫn xuất trọn vẹn thuật toánEMtừ cận dướiELBO, điều kiện không giảm đơn điệu \(\ell(\theta^{(t+1)}) \ge \ell(\theta^{(t)})\), kỹ thuật log-sum-exp và chính quy chống kỳ dị \(\epsilon_{\text{reg}}\mathbf{I}_d\) choFull-Covariance GMM; phân tích hồi quy Lance–Williams cho phân cấp tích tụ (Single/Complete/Average/Ward); cài đặtDBSCANvàHDBSCAN(Campello et al. 2013; McInnes et al. 2017) từ khoảng cách lõi \(\operatorname{core}_k\), khoảng cách khả đạt tương hỗ \(d_{\text{mreach-}k}\), cây khung cực tiểu Prim MST đến trích xuất Excess-of-Mass (EOM) trên cây nén; và kiểm toán đánh đổi các độ đoSilhouette(cùng bẫy hình học lồi),Davies–Bouldin,Calinski–Harabasz,BIC,ARI, vàNMI. - Thiết kế Giảm chiều Tuyến tính & Học Đa tạp Phi tuyến (
R36.3): Chứng minh ưu thế ổn định số học củathin SVD(Eckart–Young) trongPCAso với bình phương số điều kiện \(\kappa(\mathbf{X})^2\) khi tính ma trận hiệp phương sai; vận dụngTruncatedSVDbảo toàn ma trận thưaCSRvàICA(FastICA) tối đa hóa tính phi chuẩn độc lập; giải phẫu toán học củaLaplacian Eigenmaps(\(\mathbf{L}_{\text{sym}}\)),t-SNE(tìm kiếm nhị phân perplexity, nhân Cauchy Student-\(t\) chống chen chúc, bẫy bất đối xứng KL),UMAP(tập đơn hình mờ & entropy chéo, Parametric UMAP),PaCMAP(cân bằng 3 pha cặpNB/MN/FP) vàLocalMAP(AAAI 2025); đánh giá định lượng quaTrustworthiness@k,Continuity@k, và tương quan hạng khoảng cách toàn cụcSpearman\(\rho_S\). - Định cỡ Hệ thống Theo Ma trận Độ phức tạp Thuật toán ML Cổ điển (
R36.4): Ước lượng chính xác độ phức tạp thời gian huấn luyện, độ trễ suy luận đơn dòng và bộ nhớ RAM của trọn bộ họ thuật toán cổ điển (OLS/Ridge,Logistic/Softmax,Linear vs Kernel SVM,CART/RF,GBDT Hist,Exact kNN vs HNSW/IVF-PQ,K-Means++,GMM EM,Agglomerative,DBSCAN/HDBSCAN,PCA/TruncatedSVD,t-SNE/UMAP/PaCMAP) trước khi cấp phát hạ tầng sản xuất. - Triển khai Chuỗi Phân tích Marketing Chống Rò rỉ (
Lab 04&R36.5): Xây dựng đường ống phân khúcRFMchống rò rỉ thời gian giữOOT Stability ARI >= 0.75; tính Hiệu ứng Loại bỏ Markov Hấp thụ (\(\mathbf{N} = (\mathbf{I}-\mathbf{Q})^{-1}, \mathbf{B} = \mathbf{N}\mathbf{R}\)) và Giá trị Shapley Chính xác thỏa mãn 4 tiên đề; giảm phương sai thử nghiệm A/B>= 25%bằngCUPEDdùng hiệp biến tiền thử nghiệm; ước lượngiROAS_DRbằngCross-Fitted AIPW-DRđánh bại thiên lệch chọn lọcLast-Touch, vượt qua16/16kiểm thửpytestkèm rào chắn AST bảo mật deserialization.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U07, Dòng R36 & Lab 04)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R36 & R29:R31) |
Nâng cấp Chuẩn SOTA 2026 (ch-12) |
Mục trong Chương 12 | Mô-đun & Hợp đồng Kiểm thử (marketing_seg_mta_lab) |
|---|---|---|---|
| R36.1 Soft & Hard Clustering | Phân hoạch cứng \(r_{ik}\) vs hậu nghiệm mềm \(\gamma_{ik}\); Full-Covariance GMM & dẫn xuất EM (ELBO) đơn điệu, log-sum-exp & chính quy \(\epsilon_{\text{reg}}\mathbf{I}_d\) chống kỳ dị |
Trụ cột 1 (§1.1–§1.2) + Mermaid 1 + Widget clustering-geometry-kmeans-gmm-dbscan |
clustering_and_manifolds.py (KMeansPlusPlus, FullCovarianceGMM), Tests 2, 3, 4 |
| R36.2a K-Means++, Hierarchical & Validity | Thuật toán Lloyd, khởi tạo \(D^2\) K-Means++ \(\mathcal{O}(\log K)\); phân cấp Lance–Williams (Single/Complete/Average/Ward); Silhouette (cùng bẫy lồi), DBI, CH, ARI, NMI |
Trụ cột 1 (§1.1, §1.3–§1.4) + Widget 1 | clustering_and_manifolds.py (silhouette_score_ref, davies_bouldin_score_ref, calinski_harabasz_score_ref, adjusted_rand_index_ref, normalized_mutual_info_ref), Tests 3, 5, 6 |
R36.2b DBSCAN & SOTA HDBSCAN |
DBSCAN (\(\varepsilon_{\text{db}}\), min_samples); HDBSCAN (core_k, \(d_{\text{mreach-}k}\), Prim MST, cây nén & EOM Campello 2013 / McInnes 2017, fast_hdbscan / cuML.accel) |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1) + Mermaid 1 | clustering_and_manifolds.py (DBSCANReference, HDBSCANHierarchyReference, sklearn.cluster.HDBSCAN parity), Tests 5, 13 |
| R36.3 Dimensionality Reduction: Projection & Manifold Learning | PCA (thin SVD vs \(\kappa^2\)), TruncatedSVD (thưa CSR), ICA (FastICA); Laplacian Eigenmaps, t-SNE, UMAP (+ Parametric), PaCMAP (3 pha NB/MN/FP) & LocalMAP (AAAI 2025); Trustworthiness@k, Continuity@k & Spearman \(\rho_S\) |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.2) + Mermaid 2 + Widget manifold-pca-tsne-umap-pacmap-explorer |
clustering_and_manifolds.py (PCAReference, LaplacianEigenmapsReference, NeighborEmbeddingReference, trustworthiness_at_k, audit_tsne_clustering_distortion), Tests 7, 8, 13 |
| R36.4 Computational Complexity of ML Models | Ma trận độ phức tạp đầy đủ (Fit Time, Inference Query Time, RAM, Nút thắt) phủ 14 họ thuật toán ML cổ điển từ OLS/GBDT đến HNSW, GMM, Ward, UMAP |
Trụ cột 2 (§2.3) + Widget 2 (Mode B) | Phân tích chi phí RAM/Time \(O(n^2)\) vs \(O(nKd)\) trong Trụ cột 2 & 3 |
R36.5 Industrial Tips & Domain Lab 04 (R29:R31) |
Bẫy tỷ lệ RFM (log1p + RobustScaler trên train + OOT ARI >= 0.75), cấm cluster trên t-SNE, Absorbing Markov MTA (\((\mathbf{I}-\mathbf{Q})^{-1}\mathbf{R}\)), Exact Shapley, CUPED (>= 25% var cut) & AIPW-DR iROAS |
Trụ cột 2 (§2.4) + Trụ cột 3 + Trụ cột 4 + Mermaid 3 + Widget mta-markov-shapley-cuped-arena |
mta_and_experimentation.py (AbsorbingMarkovMTA, ExactShapleyMTA, estimate_cuped_ate, estimate_iroas_aipw_dr, run_full_lab04_benchmarks), Tests 1, 9–12, 14, 15 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-12) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (marketing_seg_mta_lab) |
|---|---|---|---|---|
| \(n, d, r\) | \(\mathbb{N}_+\) | Số quan sát \(n\), số chiều gốc \(d\) (\(\mathbf{x}_i \in \mathbb{R}^d\)), số chiều giảm \(r \ll d\) | Giữ \(r\) cho chiều không gian chiếu (tách khỏi \(k_{\text{nn}}\) và \(K\)) | n_samples, n_features, n_components |
| \(K, C_k, \boldsymbol{\mu}_k\) | \(\mathbb{N}_+, \text{Set}, \mathbb{R}^d\) | Số cụm \(K\), tập chỉ số cụm \(C_k\), tâm cụm / trung bình thành phần \(\boldsymbol{\mu}_k\) | Chữ hoa \(K\) cho số cụm; chữ thường \(k_{\text{nn}}\) cho số láng giềng | n_clusters, centroids_, means_ |
| \(r_{ik}, \gamma_{ik}\) | \(\{0, 1\}, [0, 1]\) | Chỉ báo gán cụm cứng K-Means; xác suất hậu nghiệm mềm GMM \(P(z_i=k\mid\mathbf{x}_i)\) |
Tách khỏi chỉ báo láng giềng và tham số \(\rho_i\) của UMAP |
labels_, responsibilities_ |
| \(\pi_k, \boldsymbol{\Sigma}_k, \epsilon_{\text{reg}}\) | \([0, 1], \mathbb{R}^{d\times d}, \mathbb{R}_{>0}\) | Trọng số hỗn hợp (\(\sum_k \pi_k = 1\)), ma trận hiệp phương sai, chính quy đường chéo | Luôn cộng \(\epsilon_{\text{reg}}\mathbf{I}_d\) chặn suy biến \(\lvert\boldsymbol{\Sigma}_k\rvert \to 0\) | weights_, covariances_, reg_covar |
| \(\mathcal{L}_{\text{ELBO}}(q, \theta), \ell(\theta)\) | \(\mathbb{R}\) | Cận dưới bằng chứng và log-likelihood quan sát \(\sum_i \ln\sum_k \pi_k\mathcal{N}_k\) | Bảo đảm tăng đơn điệu \(\ell(\theta^{(t+1)}) \ge \ell(\theta^{(t)})\) | elbo_history_, log_likelihood_history_ |
| \(\varepsilon_{\text{db}}, m_{\text{pts}}\) | \(\mathbb{R}_{>0}, \mathbb{N}_+\) | Bán kính lân cận DBSCAN \(\varepsilon_{\text{db}}\); kích thước cụm tối thiểu HDBSCAN \(m_{\text{pts}}\) |
Phân biệt rạch ròi \(\varepsilon_{\text{db}}\) với \(\epsilon_{\text{reg}}\) | eps, min_samples, min_cluster_size |
| \(\operatorname{core}_k(\mathbf{x}), d_{\text{mreach-}k}\) | \(\mathbb{R}_{\ge 0}\) | Khoảng cách lõi tới láng giềng thứ \(k\); khoảng cách khả đạt tương hỗ \(\max\{\operatorname{core}_k(a), \operatorname{core}_k(b), d(a,b)\}\) | Nền dựng Prim MST và tính ổn định EOM \(S(C)\) |
core_distances_, mst_edges_ |
| \(\mathbf{L}_{\text{sym}}, p_{ij}, q_{ij}\) | \(\mathbb{R}^{n\times n}, [0, 1]\) | Laplacian đồ thị chuẩn hóa \(\mathbf{I} - \mathbf{D}^{-1/2}\mathbf{W}\mathbf{D}^{-1/2}\); xác suất cặp cao/thấp chiều t-SNE |
Tách biệt hoàn toàn khỏi ma trận chuyển Markov \(\mathbf{P}_{\text{mk}}\) | L_sym, P, Q |
| \(T(k_{\text{nn}}), \rho_S\) | \([0, 1], [-1, 1]\) | Trustworthiness@k (cục bộ) và hệ số tương quan hạng khoảng cách Spearman toàn cục |
Đo lường đánh đổi cục bộ/toàn cục giữa các phép chiếu đa tạp | trustworthiness_k, global_spearman_rho |
| \(\mathbf{P}_{\text{mk}}, \mathbf{Q}_{\text{mk}}, \mathbf{R}_{\text{mk}}, \mathbf{N}_{\text{mk}}\) | Stochastic Matrices | Ma trận chuyển Markov hấp thụ, khối chuyển tiếp \(\mathbf{Q}_{\text{mk}}\), khối hấp thụ \(\mathbf{R}_{\text{mk}}\), ma trận cơ bản \((\mathbf{I}-\mathbf{Q}_{\text{mk}})^{-1}\) | Tổng mọi hàng \(\mathbf{P}_{\text{mk}}\) đúng 1.0; hiệu ứng loại bỏ \(E_c = 1 - P_{\text{conv}}^{(-c)} / P_{\text{conv}}\) |
transition_matrix_, Q_, R_, fundamental_matrix_ |
| \(\phi_c, v(S)\) | \(\mathbb{R}\) | Giá trị phân bổ Shapley cho kênh \(c\); hàm giá trị liên minh \(v(S)\) (\(v(\emptyset)=0\)) | Tiên đề hiệu quả \(\sum_{c \in N} \phi_c = v(N)\) khớp < 1e-12 |
shapley_values_, grand_coalition_value_ |
| \(\hat{\theta}_{\text{cuped}}, \hat{\tau}_{\text{DR}}, \text{iROAS}_{\text{DR}}\) | \(\mathbb{R}\) | Hệ số điều chỉnh CUPED \(\frac{\operatorname{Cov}(Y, X_{\text{pre}})}{\operatorname{Var}(X_{\text{pre}})}\), lift AIPW chéo nếp, ROAS gia tăng nhân quả |
Bắt buộc dùng \(X_{\text{pre}}\) tiền thử nghiệm cho CUPED |
theta_cuped, aipw_dr_ate, iroas_dr |
Trụ cột 1 — Nền tảng Toán học: Phân cụm Cứng/Mềm, GMM/EM, Phân cấp, Mật độ & Chiếu Tuyến tính#
1.1 Phân cụm Cứng vs. Mềm & Thuật toán K-Means / K-Means++ (R36.1–R36.2)#
Cho tập dữ liệu không nhãn \(\{\mathbf{x}_i\}_{i=1}^n \subset \mathbb{R}^d\) và số cụm \(K\):
- Phân cụm Cứng (Hard Clustering): Tìm phân hoạch rời nhau \(\{C_1, \dots, C_K\}\) biểu diễn bởi chỉ báo \(r_{ik} \in \{0, 1\}\) (\(\sum_{k=1}^K r_{ik} = 1\)). Mỗi điểm chỉ thuộc duy nhất một cụm (
K-Means,DBSCAN,Agglomerative). - Phân cụm Mềm (Soft / Probabilistic Clustering): Gán cho mỗi điểm vector xác suất hậu nghiệm \(\gamma_{ik} = P(z_i = k \mid \mathbf{x}_i) \in [0, 1]\) (\(\sum_{k=1}^K \gamma_{ik} = 1\)). Phân cụm mềm giữ nguyên độ bất định ở vùng biên chồng lấn (ví dụ một khách hàng mang
65%đặc tính Promo Hunter và35%Loyal Core), rất quan trọng khi nối sang hàm chi phí Bayes (ch-07).
Thuật toán Lloyd (K-Means) & Giới hạn Cạnh tranh \(\mathcal{O}(\log K)\) của K-Means++#
K-Means cực tiểu hóa tổng bình phương sai số nội cụm (Within-Cluster Sum of Squares — WCSS):
Thuật toán Lloyd lặp xen kẽ hai bước hạ tọa độ (coordinate descent), mỗi bước đều không làm tăng \(\mathcal{J}\) và hội tụ sau hữu hạn bước về cực tiểu địa phương:
- Bước Gán cụm (Assignment): Cố định \(\{\boldsymbol{\mu}_k\}\), chọn cụm có khoảng cách Euclid bình phương nhỏ nhất: \(r_{ik}^{(t)} = \mathbb{I}\!\left(k = \arg\min_j \|\mathbf{x}_i - \boldsymbol{\mu}_j^{(t-1)}\|_2^2\right)\). Hình học phân hoạch tạo thành các ô đa diện lồi Voronoi.
- Bước Cập nhật Tâm (Update): Cố định \(\{r_{ik}\}\), giải \(\nabla_{\boldsymbol{\mu}_k}\mathcal{J} = -2\sum_{i \in C_k}(\mathbf{x}_i - \boldsymbol{\mu}_k) = \mathbf{0}\) thu được trung bình cộng số học \(\boldsymbol{\mu}_k^{(t)} = \frac{1}{|C_k|}\sum_{i \in C_k}\mathbf{x}_i\).
Bẫy Khởi tạo Ngẫu nhiên & Định lý K-Means++ (Arthur & Vassilvitskii, SODA 2007): Khởi tạo đều ngây thơ có thể kẹt vào cực tiểu địa phương tồi tệ tùy ý với tỷ lệ sai số \(\mathcal{J} / \mathcal{J}_{\text{OPT}} = \Omega(n)\) ngay cả khi \(K=2\). K-Means++ chọn tâm đầu \(\boldsymbol{\mu}_1\) ngẫu nhiên đều, rồi lần lượt rút các tâm \(\boldsymbol{\mu}_m\) tiếp theo với xác suất tỷ lệ thuận bình phương khoảng cách tới tâm gần nhất đã có (\(D^2\)-weighting):
Arthur & Vassilvitskii chứng minh trước cả khi chạy vòng lặp Lloyd đầu tiên, nghiệm khởi tạo K-Means++ đã đạt cận kỳ vọng:
Độ phức tạp & Thiên kiến Quy nạp: Thời gian \(\mathcal{O}(n K d T_{\text{iter}})\) + khởi tạo \(\mathcal{O}(n K d)\), bộ nhớ \(\mathcal{O}((n+K)d)\). Giả định ngầm các cụm lồi cầu đẳng hướng (isotropic spherical) cùng phương sai, nhạy cảm cực độ với ngoại lai (do chuẩn \(L_2^2\)) và vỡ trận ngay lập tức nếu các đặc trưng chênh lệch thang đo.
1.2 Mô hình Hỗn hợp Gaussian (GMM), Dẫn xuất EM Qua ELBO & Chống Kỳ dị (R36.1)#
Khắc phục giả định hình cầu đẳng hướng của K-Means, GMM mô hình hóa mật độ dữ liệu như tổ hợp lồi của \(K\) phân phối chuẩn đa biến \(\theta = \{\pi_k, \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k\}_{k=1}^K\) (\(\pi_k \ge 0, \sum_k \pi_k = 1\)):
| Loại Hiệp phương sai | Số tham số / cụm | Hình học cụm | Độ phức tạp EM / vòng lặp | Khi nào dùng? |
|---|---|---|---|---|
full |
\(\frac{d(d+1)}{2}\) | Ellipsoid xoay tùy ý, học tương quan giữa các cột | \(\mathcal{O}(n K d^2 + K d^3)\) | \(d \lesssim 30\), cụm thuôn chéo lệch kích thước |
tied |
\(\frac{d(d+1)}{2}\) dùng chung | Các ellipsoid song song cùng hướng & hình dạng | \(\mathcal{O}(n K d^2 + d^3)\) | Tương quan đồng nhất (tương đương Mahalanobis chung) |
diag |
\(d\) | Ellipsoid song trục tọa độ | \(\mathcal{O}(n K d)\) | \(d\) trung bình/cao hoặc ít mẫu (\(n\) nhỏ) |
spherical |
\(1\) | Hình cầu bán kính riêng \(\sigma_k^2\) | \(\mathcal{O}(n K d)\) | Tiến về K-Means khi \(\sigma_k^2 \to 0^+\) và \(\pi_k\) đều |
Dẫn xuất Thuật toán EM Từ Bất đẳng thức Jensen & Cận dưới ELBO#
Cực đại hóa trực tiếp hợp lý log \(\ell(\theta) = \sum_{i=1}^n \ln \sum_{k=1}^K \pi_k \mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k)\) không có nghiệm đóng vì \(\ln\) bao ngoài phép cộng. Đưa vào phân phối phụ \(q_i(k)\) trên biến ẩn \(z_i \in \{1,\dots,K\}\) (\(\sum_k q_i(k) = 1\)), áp dụng bất đẳng thức Jensen (hàm \(\ln\) lõm chặt):
- Bước E (Expectation — Khít
ELBO): Cố định \(\theta^{(t)}\), khoảng cách \(D_{\mathrm{KL}} \ge 0\) triệt tiêu về đúng0khi và chỉ khi chọn phân phối phụ bằng chính hậu nghiệm thực tế, thực thi trong không gian log-sum-exp (LSE) chống tràn số dưới (underflow):\[\ln \tilde{\gamma}_{ik} = \ln \pi_k^{(t)} + \ln\mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_k^{(t)}, \boldsymbol{\Sigma}_k^{(t)}), \qquad \gamma_{ik}^{(t+1)} = \exp\!\left(\ln\tilde{\gamma}_{ik} - \max_j \ln\tilde{\gamma}_{ij} - \ln \sum_{j=1}^K e^{\ln\tilde{\gamma}_{ij} - \max_l \ln\tilde{\gamma}_{il}}\right).\] - Bước M (Maximization — Tối ưu hóa Khép kín): Cố định \(\gamma_{ik}^{(t+1)}\) (\(N_k := \sum_{i=1}^n \gamma_{ik}\)), lấy đạo hàm \(\mathcal{L}_{\text{ELBO}}\) theo \(\pi_k, \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k\) kèm chính quy \(\epsilon_{\text{reg}}\mathbf{I}_d\) cho nghiệm đóng duy nhất:
\[\pi_k^{(t+1)} = \frac{N_k}{n}, \qquad \boldsymbol{\mu}_k^{(t+1)} = \frac{1}{N_k}\sum_{i=1}^n \gamma_{ik}\mathbf{x}_i, \qquad \boldsymbol{\Sigma}_k^{(t+1)} = \frac{1}{N_k}\sum_{i=1}^n \gamma_{ik}(\mathbf{x}_i - \boldsymbol{\mu}_k^{(t+1)})(\mathbf{x}_i - \boldsymbol{\mu}_k^{(t+1)})^\top + \epsilon_{\text{reg}}\mathbf{I}_d.\]
Định lý 1.1 (Tính Tăng Đơn điệu của EM & Bẫy Kỳ dị Ma trận Hiệp phương sai)#
Ở mọi bước lặp EM, hàm hợp lý log quan sát không bao giờ giảm:
(Lưu ý quan trọng: Nếu bỏ qua số hạng chính quy \(\epsilon_{\text{reg}}\mathbf{I}_d\), chỉ cần một thành phần Gaussian sụp vào đúng một điểm \(\boldsymbol{\mu}_k = \mathbf{x}_i\) với \(\sigma_k^2 \to 0^+\), định thức \(|\boldsymbol{\Sigma}_k|^{-1/2} \to +\infty\) sẽ thổi bùng \(\ell(\theta) \to +\infty\) thành cực đại giả quá khớp! Trong Lab 04 với \(\epsilon_{\text{reg}} = 10^{-5}\), mọi bước tăng ELBO qua 9 vòng lặp đều không âm với min delta_ELBO = 2.80e-07, đạt GMM Train ARI = 0.9908 và OOT ARI = 1.000.)*
1.3 Phân cụm Phân cấp Tích tụ (Agglomerative & Công thức Lance–Williams) (R36.2)#
Khởi đầu bằng \(n\) cụm đơn lẻ rồi gộp dần cặp cụm \((A, B)\) gần nhau nhất để dựng cây phân cấp (dendrogram), phương pháp phân cấp tích tụ thống nhất dưới phương trình cập nhật Lance–Williams cho khoảng cách tới bất kỳ cụm \(C\) còn lại:
Liên kết (Linkage) |
Tham số Lance–Williams (\(\alpha_A, \alpha_B, \beta, \gamma\)) | Ý nghĩa Hình học & Bệnh lý | Độ phức tạp Thời gian / Bộ nhớ |
|---|---|---|---|
Single (Ngắn nhất) |
\(\frac{1}{2}, \frac{1}{2}, 0, -\frac{1}{2}\) | Tương đương Cây khung cực tiểu Kruskal/Prim (MST); bắt được hình cong phi lồi nhưng dính hiệu ứng dây chuyền (chaining) qua cầu nhiễu |
\(\mathcal{O}(n^2)\) (SLINK) / \(\mathcal{O}(n^2)\) RAM |
Complete (Xa nhất) |
\(\frac{1}{2}, \frac{1}{2}, 0, +\frac{1}{2}\) | Cực tiểu hóa đường kính tối đa từng cụm; cụm nén chặt nhưng rất nhạy cảm với ngoại lai | \(\mathcal{O}(n^2)\) (CLINK/NN-Chain) / \(\mathcal{O}(n^2)\) |
Average (UPGMA) |
\(\frac{\lvert A\rvert}{\lvert A\rvert+\lvert B\rvert}, \frac{\lvert B\rvert}{\lvert A\rvert+\lvert B\rvert}, 0, 0\) | Trung bình khoảng cách mọi cặp giữa hai cụm; cân bằng giữa Single và Complete |
\(\mathcal{O}(n^2)\) (NN-Chain) / \(\mathcal{O}(n^2)\) |
Ward (Tối thiểu Phương sai) |
\(\frac{\lvert A\rvert+\lvert C\rvert}{\lvert A\rvert+\lvert B\rvert+\lvert C\rvert}, \frac{\lvert B\rvert+\lvert C\rvert}{\lvert A\rvert+\lvert B\rvert+\lvert C\rvert}, \frac{-\lvert C\rvert}{\lvert A\rvert+\lvert B\rvert+\lvert C\rvert}, 0\) | Gộp cặp có chi phí tăng WCSS \(\frac{\lvert A\rvert\lvert B\rvert}{\lvert A\rvert+\lvert B\rvert}\|\boldsymbol{\mu}_A - \boldsymbol{\mu}_B\|_2^2\) nhỏ nhất; cụm lồi đều kích thước | \(\mathcal{O}(n^2)\) (NN-Chain) hoặc \(\mathcal{O}(n^3)\) ngây thơ / \(\mathcal{O}(n^2)\) RAM |
1.4 Phân cụm Mật độ DBSCAN & Các Độ đo Thẩm định Cụm (Kèm Bẫy Silhouette) (R36.2)#
DBSCAN (Ester et al., KDD 1996) không cần chọn trước \(K\) và tự cách ly nhiễu dựa trên hai tham số \((\varepsilon_{\text{db}}, m_{\text{pts}})\):
- Điểm lõi (Core Point): \(\lvert N_{\varepsilon_{\text{db}}}(\mathbf{x})\rvert \ge m_{\text{pts}}\) với \(N_{\varepsilon_{\text{db}}}(\mathbf{x}) = \{\mathbf{y} : d(\mathbf{x}, \mathbf{y}) \le \varepsilon_{\text{db}}\}\).
- Điểm biên (Border Point): Không phải điểm lõi nhưng nằm trong lân cận \(\varepsilon_{\text{db}}\) của ít nhất một điểm lõi.
- Nhiễu (Noise
-1): Không đạt mật độ lẫn không khả đạt từ bất kỳ điểm lõi nào.
Nhược điểm cố hữu: Dù dùng chỉ mục không gian KD-Tree đạt \(\mathcal{O}(n \log n)\) ở chiều thấp \(d \lesssim 15\), ở \(d\) cao thuật toán thoái hóa về \(\mathcal{O}(n^2)\). Nghiêm trọng hơn, một bán kính \(\varepsilon_{\text{db}}\) cố định sẽ thất bại khi các cụm có mật độ chênh lệch (nếu \(\varepsilon_{\text{db}}\) nhỏ thì cụm thưa bị tan rã thành nhiễu; nếu \(\varepsilon_{\text{db}}\) lớn thì các cụm đặc sát nhau bị dính làm một).
Thẩm định Nội tại vs. Ngoại tại & Bẫy Convexity của Silhouette#
| Nhóm | Độ đo | Công thức & Hướng tối ưu | Bẫy Sản xuất Phải Tránh |
|---|---|---|---|
| Nội tại | Silhouette Score \(s(i) \in [-1, 1]\) | \(\frac{b(i) - a(i)}{\max(a(i), b(i))}\) (Cao hơn tốt hơn) | Thiên vị cụm lồi! Trên Two-Moons (Lab 04), K-Means (ARI=0.1335) nhận Sil=0.4641 cao hơn DBSCAN (ARI=1.0000, Sil=0.3247)! |
| Nội tại | Davies–Bouldin (DBI) |
\(\frac{1}{K}\sum_{i=1}^K \max_{j \neq i}\frac{S_i + S_j}{\|\boldsymbol{\mu}_i - \boldsymbol{\mu}_j\|_2}\) (Thấp hơn tốt hơn) | Đo tỷ lệ phân tán theo tâm cụm, chỉ hợp lệ cho cấu trúc lồi |
| Nội tại | Calinski–Harabasz (CH) |
\(\frac{\operatorname{tr}(\mathbf{B}_K)/(K-1)}{\operatorname{tr}(\mathbf{W}_K)/(n-K)}\) (Cao hơn tốt hơn) | Phạt cụm nhỏ thuôn dài; tăng tự nhiên khi cụm tách cầu |
| Nội tại | GMM BIC |
\(-2\ell(\hat{\theta}) + p_{\text{free}}\ln n\) (Thấp hơn tốt hơn) | Dùng để chọn \(K\) và dạng hiệp phương sai cho GMM |
| Ngoại tại | Adjusted Rand Index (ARI) |
Hiệu chỉnh ngẫu nhiên từ các cặp đồng gán (1.0 hoàn hảo, 0.0 ngẫu nhiên) |
Bất biến hoán vị nhãn; chuẩn đo OOT Cluster Stability |
| Ngoại tại | Normalized Mutual Info (NMI) |
\(\frac{2I(U; V)}{H(U) + H(V)} \in [0, 1]\) (Cao hơn tốt hơn) | Hơi thiên vị khi số cụm dự đoán \(K\) rất lớn nếu không dùng AMI |
1.5 Giảm chiều Tuyến tính: PCA (SVD vs. Hiệp phương sai), TruncatedSVD & ICA (R36.3)#
Cho ma trận đặc trưng đã quy tâm \(\tilde{\mathbf{X}} = \mathbf{X} - \mathbf{1}\bar{\mathbf{x}}^\top \in \mathbb{R}^{n \times d}\), phép chiếu tuyến tính trực giao \(\mathbf{Z} = \tilde{\mathbf{X}}\mathbf{W}_r\) (\(\mathbf{W}_r \in \mathbb{R}^{d \times r}, \mathbf{W}_r^\top\mathbf{W}_r = \mathbf{I}_r\)) có hai cách phát biểu tương đương nhau: (1) Cực đại hóa phương sai phép chiếu \(\operatorname{tr}(\mathbf{W}_r^\top \mathbf{S} \mathbf{W}_r)\), và (2) Cực tiểu hóa sai số tái tạo Frobenius \(\|\tilde{\mathbf{X}} - \tilde{\mathbf{X}}\mathbf{W}_r\mathbf{W}_r^\top\|_F^2\) theo Định lý Eckart–Young–Mirsky.
- Tại sao Thư viện SOTA dùng
thin SVDthay vì Phân rã Trị riêng Ma trận Hiệp phương sai \(\mathbf{S}\)? Vì tạo \(\mathbf{S} = \frac{1}{n-1}\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}}\) làm bình phương số điều kiện \(\kappa(\mathbf{S}) = \kappa(\tilde{\mathbf{X}})^2\), làm mất nửa độ chính xác dấu phẩy động khi các cột tương quan mạnh. Tính trực tiếp \(\tilde{\mathbf{X}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) giữ nguyên độ chính xác máy (float64), tỷ lệ phương sai giải thích tích lũy \(\sum_{j=1}^r \sigma_j^2 / \sum_j \sigma_j^2\) tăng đơn điệu ngặt tới1.0, với độ phức tạp \(\mathcal{O}(\min(n d^2, n^2 d))\) (hoặc \(\mathcal{O}(n d r)\) bằngRandomized SVD— Halko et al., SIAM Review 2011). TruncatedSVD(LSA) cho Ma trận ThưaCSR: Nếu áp dụngPCAchuẩn (có trừ trung bình \(\bar{\mathbf{x}}\)) lên ma trậnTF-IDFhoặc hành vi thưa \(10^6 \times 10^5\), ma trận biến thành đặc sệt và nổ800 GBRAM ngay lập tức!TruncatedSVDphân rã trực tiếp ma trận thưa \(\mathbf{X}\) mà không quy tâm, bảo toànO(nnz)bộ nhớ.ICA(FastICA— Independent Component Analysis):PCAchỉ bảo đảm các trục chiếu không tương quan bậc hai và nhạy nhất với phân phối chuẩn. Ngược lại,ICAlàm trắng (whiten) dữ liệu rồi tìm ma trận khử trộn \(\mathbf{S} = \mathbf{W}\tilde{\mathbf{X}}^\top\) sao cho các thành phần nguồn độc lập thống kê bằng cách tối đa hóa tính phi chuẩn (non-Gaussianity) qua xấp xỉ negentropy \(J(y) \approx [\mathbb{E}\{G(y)\} - \mathbb{E}\{G(\nu)\}]^2\) (logcosh/ kurtosis) hoặc nguyên lý Infomax. Đánh đổi: Các thành phầnICAkhông có thứ tự giảm dần phương sai chuẩn nhưPCA.
Trụ cột 2 — Học Đa tạp SOTA (HDBSCAN, t-SNE, UMAP, PaCMAP), Ma trận Độ phức tạp ML & Kiến trúc Marketing (Lab 04)#
2.1 HDBSCAN — Cây Nén Mật độ Biến thiên & Trích xuất EOM (Campello et al., 2013; McInnes et al., 2017)#
Để loại bỏ tham số \(\varepsilon_{\text{db}}\) cứng nhắc, HDBSCAN biến bài toán phân cụm mật độ thành phân cấp liên kết đơn trên một mê-tríc làm phình khoảng cách ở vùng thưa:
- Khoảng cách lõi (\(\operatorname{core}_k(\mathbf{x})\)): Khoảng cách từ \(\mathbf{x}\) tới láng giềng gần thứ \(k\) (
min_samples) — đại diện cho nghịch đảo mật độ cục bộ. - Khoảng cách Khả đạt Tương hỗ (Mutual Reachability Distance):
\[d_{\text{mreach-}k}(\mathbf{a}, \mathbf{b}) := \max\big\{\operatorname{core}_k(\mathbf{a}),\, \operatorname{core}_k(\mathbf{b}),\, d(\mathbf{a}, \mathbf{b})\big\}.\]Hai điểm trong vùng lõi đặc giữ nguyên khoảng cách gốc, còn các điểm nhiễu thưa có \(\operatorname{core}_k\) lớn bị đẩy ra xa mọi điểm khác!
- Cây Khung Cực tiểu (Prim / Dual-Tree Borůvka MST) & Nén cây (
min_cluster_size\(m_{\text{pts}}\)): Xây dựng MST trên \(d_{\text{mreach-}k}\) tránh lưu toàn bộ ma trận \(n \times n\), sắp xếp cạnh sinh cây dendrogram theo ngưỡng \(\lambda = 1 / d_{\text{mreach-}k}\). Khi duyệt từ gốc xuống lá, bất kỳ phép tách nào tạo ra nhánh con \(< m_{\text{pts}}\) không được coi là cụm mới mà chỉ là các điểm "rơi ra khỏi cụm cha", tạo thành Cây Nén (Condensed Tree) gọn nhẹ. - Trích xuất Ổn định Excess-of-Mass (
EOM): Mỗi cụm ứng viên \(C\) sinh ra ở mức \(\lambda_{\text{birth}}(C)\) có tổng độ bền vững:\[S(C) := \sum_{\mathbf{x} \in C}\Big(\lambda_{\text{death}}(\mathbf{x}, C) - \lambda_{\text{birth}}(C)\Big).\]Quy hoạch động từ lá lên gốc chọn tập cụm rời nhau tối đa hóa \(\sum_C S(C)\): nếu \(S(C_{\text{cha}}) \ge S(C_{\text{trái}}) + S(C_{\text{phải}})\) thì hợp nhất về cha; ngược lại giữ các cụm con! Ở hệ sinh thái 2024–2026,fast_hdbscan(Borůvka song song đa nhân CPU) và NVIDIAcuML.acceltăng tốcHDBSCANgấp10x–60xtrên hàng triệu vector nhúng.
2.2 Học Đa tạp Phi tuyến (Laplacian Eigenmaps, t-SNE, UMAP, PaCMAP, LocalMAP) (R36.3)#
Khi dữ liệu nằm trên đa tạp cong \(r\)-chiều \(\mathcal{M} \subset \mathbb{R}^d\) (như Swiss Roll hoặc dữ liệu hành vi phân nhánh phi tuyến), khoảng cách dây cung Euclid xuyên qua khoảng trống sẽ kéo sai hàng xóm thực sự. Các thuật toán đa tạp thay thế phép chiếu tuyến tính bằng bảo toàn đồ thị láng giềng:
Laplacian Eigenmaps(Belkin & Niyogi, 2003): Dựng đồ thị \(k\)-NN đối xứng trọng số Gaussian \(W_{ij} = \exp(-\|\mathbf{x}_i - \mathbf{x}_j\|_2^2 / (2\sigma^2))\), giải bài toán trị riêng tổng quát trên Laplacian chuẩn hóa \(\mathbf{L}_{\text{sym}} = \mathbf{I} - \mathbf{D}^{-1/2}\mathbf{W}\mathbf{D}^{-1/2}\) để lấy \(r\) vector riêng tương ứng các trị riêng nhỏ nhất khác0. Hạn chế: Tốn \(\mathcal{O}(k n^2)\)–\(\mathcal{O}(n^3)\) và không tự chiếu điểm OOT mới nếu không dùng Nyström.t-SNE(van der Maaten & Hinton, JMLR 2008):- Không gian cao chiều: Tìm kiếm nhị phân độ nhạy \(\sigma_i\) từng điểm sao cho phân phối điều kiện \(p_{j\mid i} \propto \exp(-\|\mathbf{x}_i - \mathbf{x}_j\|_2^2 / (2\sigma_i^2))\) khớp đúng \(\operatorname{Perp}(P_i) = 2^{H(P_i)} = \text{perplexity}\), rồi đối xứng hóa \(p_{ij} = \frac{p_{j\mid i} + p_{i\mid j}}{2n}\).
- Giải quyết Bài toán Chen chúc (Crowding Problem): Thể tích vỏ cầu trong \(\mathbb{R}^d\) tăng theo \(r^{d-1}\) còn trên mặt phẳng
2Dchỉ tăng tuyến tính \(2\pi r\), khiến các láng giềng trung bình ép nghẹt vùng lõi.t-SNEthay phân phối Gaussian ở không gian thấp chiều bằng phân phối Cauchy / Student-\(t\) đuôi nặng (\(\nu = 1\)): \(q_{ij} \propto (1 + \|\mathbf{y}_i - \mathbf{y}_j\|_2^2)^{-1}\). - Bẫy Bất đối xứng KL: Cực tiểu hóa \(\mathrm{KL}(P \| Q) = \sum_{i \neq j} p_{ij}\ln\frac{p_{ij}}{q_{ij}}\) phạt cực nặng khi tách xa hai điểm vốn gần (\(p_{ij}\) lớn, \(q_{ij}\) nhỏ), nhưng phạt gần như bằng
0khi \(p_{ij} \approx 0\)! Hệ quả làt-SNEđạtTrustworthiness@10cực cao (0.9658trongLab 04) nhưng xóa sạch tỷ lệ kích thước thực giữa các cụm (4.084x -> 0.981x) và bóp méo khoảng cách toàn cục (Spearman = 0.6126).
UMAP(McInnes, Healy & Melville, arXiv:1802.03426): Mô hình hóa đa tạp bằng tập đơn hình mờ (fuzzy simplicial sets) với bán kính cục bộ \(\rho_i\) đảm bảo tính liên thông tại láng giềng gần nhất, rồi tối ưu entropy chéo mờ bằng lấy mẫu âm SGD (\(\mathcal{O}(n^{1.14})\) thực nghiệm):\[\mathcal{L}_{\text{UMAP}} = \sum_{e=(i,j)} \left[ w_{ij}\ln\frac{w_{ij}}{q_{ij}} + (1 - w_{ij})\ln\frac{1 - w_{ij}}{1 - q_{ij}} \right], \qquad q_{ij} = \big(1 + a\|\mathbf{y}_i - \mathbf{y}_j\|_2^{2b}\big)^{-1}.\]Số hạng đẩy \((1 - w_{ij})\) cộng khởi tạo phổ giúpUMAPgiữ bố cục toàn cục tốt hơnt-SNE, hỗ trợ.transform(X_new)cho OOT và biến thể mạng nơ-ron Parametric UMAP phục vụ suy luận trực tuyến.PaCMAP(Wang, Huang, Rudin & Shaposhnik, JMLR 2021) &LocalMAP(AAAI 2025): Chứng minh các hàm mất mát giảm chiều thành công đều cân bằng lực hút và lực đẩy qua ba tập cặp: Gần (NB), Trung gian (MN), và Xa (FP) với \(\tilde{d}_{ab} := \|\mathbf{y}_a - \mathbf{y}_b\|_2^2 + 1\):\[\mathcal{L}_{\text{PaCMAP}} = w_{\text{NB}}\sum_{(i,j)\in\text{NB}}\frac{\tilde{d}_{ij}}{10 + \tilde{d}_{ij}} + w_{\text{MN}}\sum_{(i,k)\in\text{MN}}\frac{\tilde{d}_{ik}}{10000 + \tilde{d}_{ik}} + w_{\text{FP}}\sum_{(i,l)\in\text{FP}}\frac{1}{1 + \tilde{d}_{il}}.\]Bằng lịch 3 pha giảm dần \(w_{\text{MN}}\) (Pha 1neo khung toàn cục \(\to\)Pha 2tinh chỉnh cụm \(\to\)Pha 3trau chuốt chi tiết với \(w_{\text{MN}}=0\)),PaCMAPbảo toàn đồng thời láng giềng cục bộ (Trust@10 = 0.9025) lẫn tương quan toàn cục (Spearman = 0.8918, vượt xa0.6126củat-SNE).LocalMAP(AAAI 2025) cải tiến tiếp bằng cách tỉa động các cạnh đồ thị nhiễu liên cụm ở pha cuối để tách sạch các cụm thật kề nhau.
Hai Chỉ số Kiểm toán Đa tạp & Lệnh Cấm Sản xuất#
Trustworthiness@k: Phạt láng giềng giả (điểm đứng cạnh nhau trong2Dnhưng vốn ở rất xa trong \(\mathbb{R}^d\)).Continuity@k: Phạt láng giềng bị xé rách (điểm vốn kề nhau trong \(\mathbb{R}^d\) bị đẩy xa trong2D).- Lệnh Cấm: Không bao giờ chạy
K-Meanshay suy diễn mật độ/kích thước cụm trực tiếp trên tọa độ2D t-SNE; hãy phân cụm trên không gian gốc đã chuẩn hóa hoặc không gianPCAgiữ \(\ge 90\%\) phương sai!
2.3 Ma trận Độ phức tạp Thuật toán Machine Learning Cổ điển (R36.4)#
Đây là bản đồ ra quyết định kiến trúc cốt lõi của Kỹ sư AI/DS cho mọi mô hình đã học xuyên suốt Phần 2 (Ch 06 \(\to\) Ch 12), tính theo số dòng \(n\), số chiều \(d\), số cụm/lớp \(K\), số vòng lặp \(T_{\text{iter}}\), số cây \(B_{\text{ens}}\), độ sâu cây \(D_{\text{tree}}\), số vector hỗ trợ \(n_{\text{SV}}\), chiều chiếu \(r\), và bậc kết nối đồ thị HNSW \(M_{\text{hnsw}}\):
| Họ Mô hình | Độ phức tạp Huấn luyện (Fit Time) |
Độ trễ Suy luận 1 Truy vấn | Bộ nhớ RAM Huấn luyện / Mô hình | Nút thắt Quy mô & Khuyến nghị Hạ tầng |
|---|---|---|---|---|
OLS / Ridge (Cholesky vs CG) |
\(\mathcal{O}(n d^2 + d^3)\) chính xác; \(\mathcal{O}(T_{\text{cg}}\cdot\text{nnz})\) | \(\mathcal{O}(d)\) | \(\mathcal{O}(d^2)\) hoặc \(\mathcal{O}(d)\) | Cholesky vỡ nếu \(d > 20\text{k}\); chuyển sang CG hoặc SGD |
Logistic / Softmax (L-BFGS/SGD) |
\(\mathcal{O}(T_{\text{iter}}\, n d K)\) | \(\mathcal{O}(K d)\) | \(\mathcal{O}(K d)\) | Suy luận CPU < 0.05 ms, nén tốt cho baseline chuẩn hiệu chuẩn |
Linear SVM (Pegasos/LIBLINEAR DCD) |
\(\mathcal{O}(n d / (\lambda\varepsilon_{\text{opt}}))\) hoặc \(\mathcal{O}(\bar{n}_{\text{iter}}\cdot\text{nnz})\) | \(\mathcal{O}(d)\) | \(\mathcal{O}(d)\) | Tuyệt đối tránh ma trận Gram khi \(n\) lớn hoặc văn bản CSR thưa |
Kernel SVM (SMO / RBF) |
\(\mathcal{O}(n^2 d)\) đến \(\mathcal{O}(n^3)\) | \(\mathcal{O}(n_{\text{SV}} d)\) (\(n_{\text{SV}} = \Omega(2R^* n)\)) | \(\mathcal{O}(n^2)\) Gram (2 TB @ 500k) |
Định lý Steinwart làm phình suy luận; thay bằng RFF/Nyström |
CART / Random Forest (presorted) |
\(\mathcal{O}(B_{\text{ens}}\, m_{\text{try}}\, n \log n \cdot D_{\text{tree}})\) | \(\mathcal{O}(B_{\text{ens}}\, D_{\text{tree}})\) | \(\mathcal{O}(B_{\text{ens}} 2^{D_{\text{tree}}})\) | Cây sâu không tỉa phình model > 2 GB; khóa max_depth/CCP 1-SE |
GBDT Hist (XGBoost/LightGBM/CatBoost) |
\(\mathcal{O}(B_{\text{ens}} n d)\) chia thùng + \(\mathcal{O}(B_{\text{ens}} b_{\text{bin}} d 2^{D_{\text{tree}}})\) | \(\mathcal{O}(B_{\text{ens}}\, D_{\text{tree}})\) (Treelite < 1 ms) |
\(\mathcal{O}(n d\text{ bytes})\) (uint8) |
hist tiết kiệm 10x RAM so với exact; Oblivious SIMD tối ưu CPU batch |
Exact kNN (Brute vs KD-Tree) |
\(\mathcal{O}(1)\) brute; \(\mathcal{O}(d n \log n)\) KD | \(\mathcal{O}(n d)\) brute; thoái hóa \(\mathcal{O}(n d)\) khi \(d > 20\) | \(\mathcal{O}(n d)\) | Lời nguyền số chiều đánh sập KD-Tree từ \(d \gtrsim 20\) |
ANN (HNSW / IVF-PQ) |
\(\mathcal{O}(n \log n \cdot M_{\text{hnsw}} d)\) | \(\mathcal{O}(\log n \cdot ef_{\text{search}} M_{\text{hnsw}} d)\) | \(\mathcal{O}(n (d + M_{\text{hnsw}}))\) (PQ giảm 16x–64x) |
RAM đồ thị do vector float32 chi phối; nén PQ/BQ khi \(> 10\text{M}\) vector |
K-Means / K-Means++ |
\(\mathcal{O}(n K d T_{\text{iter}})\) + \(\mathcal{O}(n K d)\) | \(\mathcal{O}(K d)\) | \(\mathcal{O}((n+K)d)\) | Mở rộng dễ tới \(n > 10^7\) qua Mini-Batch; bắt buộc chuẩn hóa trước |
GMM EM (Full vs Diag) |
\(\mathcal{O}(T_{\text{iter}}(n K d^2 + K d^3))\) full; \(\mathcal{O}(T_{\text{iter}} n K d)\) diag | \(\mathcal{O}(K d^2)\) full; \(\mathcal{O}(K d)\) diag | \(\mathcal{O}(n K + K d^2)\) | Full vỡ khi \(d > 200\) (O(d^3)); giảm chiều PCA trước khi chạy |
Agglomerative (Ward/SLINK) |
\(\mathcal{O}(n^2)\) (SLINK/NN-Chain) tới \(\mathcal{O}(n^3)\) |
Không hỗ trợ OOT trực tiếp | \(\mathcal{O}(n^2)\) ma trận khoảng cách | Tường RAM cứng ở \(n \approx 50\text{k}\) (~10–20 GB) |
DBSCAN / HDBSCAN |
\(\mathcal{O}(n^2)\) tổng quát; \(\mathcal{O}(n \log n)\) Borůvka chiều thấp | approximate_predict \(\mathcal{O}(\log n)\) |
\(\mathcal{O}(n d)\) (HDBSCAN MST tránh \(n^2\)) |
Chiều cao cần dựng đồ thị \(k\)-NN qua PCA hoặc ANN |
PCA / TruncatedSVD |
\(\mathcal{O}(\min(n d^2, n^2 d))\) chính xác; \(\mathcal{O}(n d r)\) rSVD |
\(\mathcal{O}(d r)\) | \(\mathcal{O}(d r)\) | Luôn dùng TruncatedSVD trên ma trận CSR thưa |
t-SNE / UMAP / PaCMAP |
\(\mathcal{O}(n^2)\) chính xác; \(\mathcal{O}(n \log n)\) BH-tSNE; \(\mathcal{O}(n^{1.14})\) UMAP/PaCMAP |
Không (t-SNE); \(\mathcal{O}(k d + T r)\) (UMAP); MLP (Parametric) |
\(\mathcal{O}(n k_{\text{nn}})\) đồ thị | Dựng đồ thị \(k\)-NN là nút thắt lớn nhất; dùng cuML GPU khi \(n > 100\text{k}\) |
2.4 Kiến trúc Marketing Analytics (Lab 04): Phân khúc OOT, Quy bổ Markov/Shapley & Thử nghiệm Nhân quả CUPED / iROAS#
Để biến phân cụm và suy luận nhân quả (ch-05) thành động cơ tăng trưởng doanh thu thực chiến trong Lab 04, toàn bộ hệ thống ghép nối qua 4 tầng kiểm soát rò rỉ nghiêm ngặt:
- Tầng 1 — Phân khúc
RFMChống Rò rỉ & Ổn địnhOOT(ARI >= 0.75): Tách cứng cửa sổ lịch sửtrain_df(snapshot_day <= 90) khỏi tập đánh giá tương laioot_df(snapshot_day >= 91). Biến đổilog1p(frequency, monetary)rồi khớpRobustScalerchỉ trêntrain_df, đóng băng tâm cụmK-Means++/ tham sốGMM, và đối chiếu nhãn tương lai bằng ghép cặp Hungarian (linear_sum_assignment) bảo đảmOOT Stability ARI >= 0.75. -
Tầng 2 — Quy bổ Đa chạm (
MTA): Chuỗi Markov Hấp thụ & Giá trị Shapley Chính xác:- Chuỗi Markov Hấp thụ (Anderl et al., IJRM 2016): Coi các kênh (
Paid Search,Social,Display,Email,Organic) cùng nútStartlà tập trạng thái chuyển tiếp \(\mathcal{T}\) và{Conversion, Null}là hai trạng thái hấp thụ \(\mathcal{A}\). Ma trận chuyển chuẩn hóa từng hàng có tổng đúng bằng1.0:\[\mathbf{P}_{\text{mk}} = \begin{pmatrix}\mathbf{Q}_{\text{mk}} & \mathbf{R}_{\text{mk}} \\ \mathbf{0} & \mathbf{I}_2\end{pmatrix}, \qquad \mathbf{N}_{\text{mk}} = (\mathbf{I} - \mathbf{Q}_{\text{mk}})^{-1}, \qquad \mathbf{B}_{\text{mk}} = \mathbf{N}_{\text{mk}}\mathbf{R}_{\text{mk}}.\]Xác suất chuyển đổi nền từStartlà \(P_{\text{conv}} = (\mathbf{B}_{\text{mk}})_{\text{Start}, \text{Conversion}}\). Khi loại bỏ kênh \(c\) (chuyển toàn bộ cạnh đi vào \(c\) và rời khỏi \(c\) thẳng vềNull), ta thu được xác suất mới \(P_{\text{conv}}^{(-c)}\) và Hiệu ứng Loại bỏ (Removal Effect) \(E_c = 1 - \frac{P_{\text{conv}}^{(-c)}}{P_{\text{conv}}}\), chuẩn hóa về tỷ trọng công lao \(w_c = E_c / \sum_j E_j\). - Giá trị Shapley Chính xác (Shapley, 1953; Shao & Li, KDD 2011): Với hàm giá trị liên minh \(v(S)\) đo độ nâng chuyển đổi khi chỉ các kênh trong tập \(S \subseteq N\) hoạt động (\(v(\emptyset) = 0\), \(|N|=M\)):
\[\phi_c(v) = \sum_{S \subseteq N \setminus \{c\}} \frac{|S|!\,(M - |S| - 1)!}{M!}\Big(v(S \cup \{c\}) - v(S)\Big),\]bảo đảm duy nhất cả
4tiên đề: Hiệu quả (\(\sum_{c \in N} \phi_c = v(N)\)), Đối xứng, Kênh giảDummy = 0, và Cộng tính.
- Chuỗi Markov Hấp thụ (Anderl et al., IJRM 2016): Coi các kênh (
-
Tầng 3 — Giảm Phương sai
CUPED(Deng et al., WSDM 2013): Trên thử nghiệm ngẫu nhiên \(W_i \in \{0, 1\}\), sử dụng hiệp biến hoàn toàn tiền thử nghiệm \(X_{\text{pre}, i}\) (ví dụ: chi tiêu 30 ngày trước khi chạy chiến dịch, \(X_{\text{pre}} \perp W\)):\[Y_i^{\text{CUPED}} := Y_i - \hat{\theta}_{\text{cuped}}\big(X_{\text{pre}, i} - \bar{X}_{\text{pre}}\big), \qquad \hat{\theta}_{\text{cuped}} = \frac{\widehat{\operatorname{Cov}}(Y, X_{\text{pre}})}{\widehat{\operatorname{Var}}(X_{\text{pre}})}.\]Vì \(\mathbb{E}[X_{\text{pre}} - \bar{X}_{\text{pre}} \mid W=1] = \mathbb{E}[X_{\text{pre}} - \bar{X}_{\text{pre}} \mid W=0] = 0\), ước lượng
CUPEDkhông chệch tuyệt đối đồng thời nén phương sai theo công thức \(\operatorname{Var}(Y^{\text{CUPED}}) = \operatorname{Var}(Y)(1 - \rho_{Y, X_{\text{pre}}}^2)\) (-68.94%trongLab 04, rút ngắn thời gian chạy A/B test xuống chỉ còn ~31%!). - Tầng 4 — Khử Thiên lệch Chọn lọc Bằng
Cross-Fitted AIPW-DR(iROAS_DR): Với các chiến dịch quan sát nơi người dùng có ý định cao tự nhấp vào quảng cáo thương hiệu (\(W_i = 1\) tương quan mạnh với doanh thu nền \(\mu_0(X_i)\)), ghép chéo5-Foldmô hình kết cục \(\hat{\mu}_w^{(-k)}(X_i)\) và điểm xu hướng bị kẹp ngưỡng \(\hat{e}^{(-k)}(X_i) \in [\eta, 1-\eta]\) cho ước lượng bền vững kép (ch-05):\[\hat{\psi}_i = \big(\hat{\mu}_1^{(-k)}(X_i) - \hat{\mu}_0^{(-k)}(X_i)\big) + \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)}, \qquad \widehat{\text{iROAS}}_{\text{DR}} = \frac{\frac{1}{n}\sum_i \hat{\psi}_i}{\text{AdCost}}.\]
Trụ cột 3 — Công nghiệp Thực chiến (R36.5), Ma trận Phản mẫu & Mã nguồn Hệ sinh thái 2026#
3.1 Năm Quy tắc Vàng Công nghiệp (R36.5 Industrial Tips)#
- Kiểm toán Tỷ lệ & Phân phối Trước Khi Tính Khoảng cách: Mọi cột tiền tệ hoặc tần suất đếm có độ lệch >
1.5phải đi qualog1p+RobustScalerkhớp duy nhất trên tậptraintrước khi tính \(L_2\) trongK-Means/GMM/DBSCAN/UMAP. - Đừng Bao giờ Chọn
KChỉ Bằng Mắt TrênElbow Plot: Hãy ghépBIC(vớiGMM),Davies–Bouldin,Calinski–Harabaszvà Độ ổn định Cụm Theo Thời gian / Bootstrap (OOT ARI >= 0.75); đồng thời đối chiếu tâm cụm qua ghép cặp Hungarian để tránh đảo nhãn ngẫu nhiên khi huấn luyện lại hàng tháng. - Không Dùng
SilhouetteSo sánhK-MeansvsDBSCAN/HDBSCAN:Silhouetteđo độ lồi Voronoi và luôn phạt sai các cụm cong/xoắn; hãy đánh giá phân cụm mật độ bằng độ ổn định mật độ, tỷ lệ nhiễu OOT, và nâng giá trị kinh doanh hậu nghiệm. - Kỷ luật Tham số Đa tạp (
init="pca"& Cấm Clusteringt-SNE): Luôn khởi tạot-SNE/UMAPbằngPCA, quét nhiều mứcperplexity/n_neighbors, dùngPaCMAP/LocalMAPkhi bố cục liên cụm quan trọng, và chỉ dùng2D embeddingđể quan sát — không chạyK-Meanstrên tọa độ2Dđã méo bán kính. - Vòng lặp Hiệu chuẩn Quy bổ Nhân quả: Luôn coi kết quả
MTA(Markov/Shapley) trên dữ liệu quan sát là giả thuyết phân bổ, và hiệu chuẩn định kỳ bằng thử nghiệm ngẫu nhiên (CUPED) hoặc geo-lift (AIPW-DRiROAS).
3.2 Tám Phản mẫu Sản xuất & Hàng rào Kiểm soát (Anti-Patterns Matrix)#
| # | Phản mẫu (Anti-Pattern) |
Hậu quả Sản xuất | Cổng Phát hiện / Kiểm thử | Biện pháp Khắc phục Bắt buộc |
|---|---|---|---|---|
| 1 | Dùng K-Means trên RFM Thô Chưa Scale |
Monetary chiếm 99.8% phương sai; ARI rớt về 0.208 |
Kiểm tra tỷ trọng phương sai từng cột; kiểm thử ngưỡng ARI |
Áp dụng log1p + RobustScaler (khớp chỉ trên train_df) |
| 2 | Khớp Scaler / PCA trên Gộp Train + OOT |
Rò rỉ phân phối tương lai, thổi phồng giả độ ổn định OOT |
Kiểm tra max(train_day) < min(oot_day) và pipeline bất biến |
Khớp Pipeline hoàn toàn trong cửa sổ train quá khứ |
| 3 | Chạy K-Means Trực tiếp Trên Tọa độ 2D t-SNE |
Hư cấu cụm có kích thước & khoảng cách giả (4.08x -> 0.98x) |
Đo global_spearman_rho & biến dạng bán kính cụm |
Dùng t-SNE chỉ để nhìn; phân cụm trong không gian PCA / gốc |
| 4 | Dùng Silhouette Chọn K-Means Thay HDBSCAN |
Chọn nhầm mô hình chẻ đôi hình trăng khuyết (ARI=0.134) |
Kiểm tra hình học phi lồi & độ lệch mật độ giữa các cụm | Dùng HDBSCAN (EOM) khi mật độ lệch hoặc hình thù cong |
| 5 | Chạy PCA (with_mean=True) trên CSR Thưa |
Phá cấu trúc thưa thành ma trận đặc 800 GB \(\to\) OOM |
Kiểm tra scipy.sparse.issparse(X) trước khi chọn phép chiếu |
Chuyển ngay sang TruncatedSVD (hoặc Randomized SVD) |
| 6 | Cấp phát Agglomerative / Kernel SVM ở n > 100k |
Ma trận n x n ngốn 80 GB – 2 TB RAM \(\to\) sập tiến trình |
Tính trần RAM 8 * n^2 trong CI trước khi chạy |
Chuyển sang MiniBatchKMeans, HDBSCAN Borůvka, hoặc HNSW |
| 7 | Tối ưu Ngân sách Theo Last-Touch ROAS |
Đổ tiền vào Brand Search ăn sẵn (8.15x giả vs 1.86x thật) |
Đối chiếu phân bổ kênh MTA với thí nghiệm giữ lại (Holdout) |
Kết hợp Markov / Shapley MTA + hiệu chuẩn AIPW-DR iROAS |
| 8 | Nhét Biến Hậu Can thiệp Vào CUPED |
Biến X bị ảnh hưởng bởi W phá vỡ giả định không chệch |
Kiểm tra dấu thời gian timestamp(X) < start_time(test) |
Chỉ cho phép hiệp biến tiền thử nghiệm \(X_{\text{pre}}\) trong CUPED |
3.3 Mã nguồn Thực thi Hệ sinh thái 2026 (scikit-learn HDBSCAN, TSNE, PCA, TruncatedSVD, FastICA & Lab 04 Pipeline)#
(Mọi khối mã dưới đây đều tự chứa, định kiểu chặt chẽ, cố định hạt giống seed=42, và chạy sạch exit 0 trực tiếp trong môi trường Python 3.12 .venv.)
from __future__ import annotations
import numpy as np
from sklearn.cluster import DBSCAN, HDBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.decomposition import PCA, FastICA, TruncatedSVD
from sklearn.manifold import TSNE, trustworthiness
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import RobustScaler
from scipy.sparse import csr_matrix
def demo_sklearn_clustering_and_manifold_stack(seed: int = 42) -> dict[str, float]:
"""Run Tier-2 scikit-learn clustering (KMeans++, Full-GMM, DBSCAN, HDBSCAN) & manifolds."""
rng = np.random.default_rng(seed)
# 1. Non-convex Two-Moons: K-Means Silhouette trap vs DBSCAN & HDBSCAN
X_moons, y_moons = make_moons(n_samples=300, noise=0.07, random_state=seed)
km_pred = KMeans(n_clusters=2, n_init=10, random_state=seed).fit_predict(X_moons)
db_pred = DBSCAN(eps=0.22, min_samples=5).fit_predict(X_moons)
hdb_pred = HDBSCAN(min_samples=5, min_cluster_size=15, copy=True).fit_predict(X_moons)
# 2. Full-Covariance GMM vs Spherical K-Means on tilted correlated ellipses + OOT split
cov_tilted = np.array([[2.2, 1.8], [1.8, 1.7]])
X_c0 = rng.multivariate_normal([0.0, 0.0], cov_tilted, size=200)
X_c1 = rng.multivariate_normal([1.8, -1.6], cov_tilted, size=200)
X_el, y_el = np.vstack([X_c0, X_c1]), np.array([0] * 200 + [1] * 200)
scaler = RobustScaler().fit(X_el[:300])
X_tr_s, X_te_s = scaler.transform(X_el[:300]), scaler.transform(X_el[300:])
gmm = GaussianMixture(n_components=2, covariance_type="full", reg_covar=1e-5, random_state=seed)
gmm_oot_ari = float(adjusted_rand_score(y_el[300:], gmm.fit(X_tr_s).predict(X_te_s)))
# 3. Linear SVD/Sparse/ICA vs t-SNE Trustworthiness
X_hi = rng.normal(0.0, 1.0, size=(120, 10))
X_hi[:40, :3] += 4.5
X_hi[40:80, 3:6] -= 4.5
pca_2d = PCA(n_components=2, svd_solver="full").fit_transform(X_hi)
ica_2d = FastICA(n_components=2, random_state=seed, max_iter=500).fit_transform(X_hi)
sparse_csr = csr_matrix(np.maximum(X_hi, 0.0))
tsvd_2d = TruncatedSVD(n_components=2, random_state=seed).fit_transform(sparse_csr)
tsne_2d = TSNE(n_components=2, perplexity=20.0, init="pca", random_state=seed).fit_transform(X_hi)
return {
"moons_kmeans_ari": round(float(adjusted_rand_score(y_moons, km_pred)), 4),
"moons_kmeans_sil": round(float(silhouette_score(X_moons, km_pred)), 4),
"moons_dbscan_ari": round(float(adjusted_rand_score(y_moons, db_pred)), 4),
"moons_hdbscan_ari": round(float(adjusted_rand_score(y_moons, hdb_pred)), 4),
"gmm_tilted_oot_ari": round(gmm_oot_ari, 4),
"pca_trust10": round(float(trustworthiness(X_hi, pca_2d, n_neighbors=10)), 4),
"tsne_trust10": round(float(trustworthiness(X_hi, tsne_2d, n_neighbors=10)), 4),
"tsvd_shape_cols": int(tsvd_2d.shape[1]),
"ica_finite": int(np.all(np.isfinite(ica_2d))),
}
if __name__ == "__main__":
print("Tier-2 Sklearn Clustering & Manifolds:", demo_sklearn_clustering_and_manifold_stack())
from __future__ import annotations
import numpy as np
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.model_selection import KFold
def demo_markov_cuped_and_aipw_iroas(seed: int = 42) -> dict[str, float]:
"""Minimal self-contained Absorbing Markov, CUPED & 5-Fold AIPW-DR iROAS verification."""
# 1. Absorbing Markov Chain over [Start, Display, Search, Conv, Null]
P = np.array(
[
[0.0, 0.60, 0.40, 0.00, 0.00], # Start
[0.0, 0.00, 0.70, 0.15, 0.15], # Display
[0.0, 0.00, 0.00, 0.65, 0.35], # Search
[0.0, 0.00, 0.00, 1.00, 0.00], # Conv (Absorbing)
[0.0, 0.00, 0.00, 0.00, 1.00], # Null (Absorbing)
],
dtype=np.float64,
)
assert np.allclose(P.sum(axis=1), 1.0)
Q, R = P[:3, :3], P[:3, 3:]
N = np.linalg.inv(np.eye(3) - Q)
B = N @ R
base_conv = float(B[0, 0]) # P(Start -> Conv)
# Removal effect of Display (state index 1)
P_no_disp = P.copy()
P_no_disp[0, 4] += P_no_disp[0, 1]
P_no_disp[0, 1] = 0.0
P_no_disp[1, :] = [0.0, 0.0, 0.0, 0.0, 1.0]
p_conv_no_disp = float(np.linalg.solve(np.eye(3) - P_no_disp[:3, :3], P_no_disp[:3, 3:])[0, 0])
removal_display = 1.0 - p_conv_no_disp / base_conv
# 2. CUPED Variance Reduction on randomized A/B test
rng = np.random.default_rng(seed)
n = 2000
x_pre = np.exp(rng.normal(4.2, 0.5, size=n))
w_rand = rng.binomial(1, 0.5, size=n)
y_ab = 15.0 + 0.9 * x_pre + 10.0 * w_rand + rng.normal(0.0, 22.0, size=n)
theta = float(np.cov(y_ab, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))
y_cuped = y_ab - theta * (x_pre - float(np.mean(x_pre)))
var_raw = float(np.var(y_ab[w_rand == 1], ddof=1) / np.sum(w_rand == 1) + np.var(y_ab[w_rand == 0], ddof=1) / np.sum(w_rand == 0))
var_cuped = float(np.var(y_cuped[w_rand == 1], ddof=1) / np.sum(w_rand == 1) + np.var(y_cuped[w_rand == 0], ddof=1) / np.sum(w_rand == 0))
cuped_var_cut_pct = 100.0 * (1.0 - var_cuped / var_raw)
# 3. Cross-Fitted AIPW-DR iROAS under selection bias
intent = rng.normal(0.0, 1.0, size=n)
X_cov = np.column_stack([x_pre, intent])
w_obs = rng.binomial(1, 1.0 / (1.0 + np.exp(-1.1 * intent)))
ad_cost = 18.0
y_obs = 50.0 + 0.6 * x_pre + 40.0 * intent + 34.2 * w_obs + rng.normal(0.0, 12.0, size=n)
naive_roas = float((np.mean(y_obs[w_obs == 1]) - np.mean(y_obs[w_obs == 0])) / ad_cost)
mu0, mu1, e_hat = np.zeros(n), np.zeros(n), np.zeros(n)
for tr, va in KFold(n_splits=5, shuffle=True, random_state=seed).split(X_cov):
m0 = Ridge(alpha=1.0).fit(X_cov[tr][w_obs[tr] == 0], y_obs[tr][w_obs[tr] == 0])
m1 = Ridge(alpha=1.0).fit(X_cov[tr][w_obs[tr] == 1], y_obs[tr][w_obs[tr] == 1])
prop = LogisticRegression(max_iter=300, random_state=seed).fit(X_cov[tr], w_obs[tr])
mu0[va], mu1[va] = m0.predict(X_cov[va]), m1.predict(X_cov[va])
e_hat[va] = np.clip(prop.predict_proba(X_cov[va])[:, 1], 0.04, 0.96)
psi = (mu1 - mu0) + w_obs * (y_obs - mu1) / e_hat - (1 - w_obs) * (y_obs - mu0) / (1.0 - e_hat)
iroas_dr = float(np.mean(psi) / ad_cost)
return {
"markov_base_conv": round(base_conv, 4),
"markov_removal_display": round(removal_display, 4),
"cuped_var_cut_pct": round(cuped_var_cut_pct, 2),
"naive_biased_roas": round(naive_roas, 2),
"aipw_iroas_dr": round(iroas_dr, 2),
}
if __name__ == "__main__":
print("Markov / CUPED / AIPW-DR:", demo_markov_cuped_and_aipw_iroas())
Trụ cột 4 — Phòng Thí nghiệm Miền Marketing (Lab 04: marketing_seg_mta_lab)#
4.1 Kiến trúc Hai Tầng (Two-Tier Lab), uv.lock & AST Bảo mật Deserialization#
Gói marketing_seg_mta_lab triển khai song hành Tầng 1 Reference Core (cài đặt từ nguyên lý gốc trên NumPy + SciPy + Pydantic v2) và Tầng 2 SOTA Ecosystem Parity (scikit-learn), khóa môi trường qua uv.lock, và vượt qua kiểm toán AST cấm tuyệt đối giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal):
labs/lab-04-marketing-segmentation-attribution-experimentation/
├── pyproject.toml
├── uv.lock
├── README.md
├── artifacts/
│ └── ch12_lab04_results.json
├── src/
│ └── marketing_seg_mta_lab/
│ ├── __init__.py
│ ├── clustering_and_manifolds.py # Temporal RFM, KMeans++, Full-GMM EM, DBSCAN, HDBSCAN MST+EOM, PCA/Laplacian/t-SNE/PaCMAP
│ └── mta_and_experimentation.py # Absorbing Markov MTA, Exact Shapley, CUPED, 5-Fold AIPW-DR iROAS & Workbench export
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_marketing_seg_mta_lab.py # 16 kiểm thử đơn vị, bất biến toán học & AST bảo mật deserialization
4.2 Kết quả Thực nghiệm CLI (artifacts/ch12_lab04_results.json)#
Chạy một lệnh duy nhất từ thư mục gốc của Lab 04:
python scripts/run_lab_demo.py --seed 42 --output artifacts/ch12_lab04_results.json
Báo cáo artifacts/ch12_lab04_results.json xuất trọn vẹn workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% các chỉ số thực đo sau:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm Chính xác | Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_rfm_scaling_rescue |
0.208 -> 0.973 (Train ARI) |
ok — Phương sai Monetary thô chiếm 99.8147% làm K-Means++ sụp ở 0.2082; đường ống log1p + RobustScaler (chỉ fit trên train) nâng K-Means++ ARI = 0.9729 (khớp Tier 2 sklearn = 0.9758) và GMM ARI = 0.9908 (Sil = 0.6422, DBI = 0.4894, CH = 3991.32). |
kpi_oot_cluster_stability |
ARI 1.000 (Truth 1.000) |
ok — Tách nghiêm ngặt theo thời gian (train_day <= 90 < oot_day >= 91); cả K-Means++ đóng băng lẫn Full-Covariance GMM đạt OOT ARI = 1.000 (BIC = 1385.69, 9 vòng EM tăng đơn điệu min delta_ELBO = 2.80e-07, Tier 2 GMM ARI = 1.000). |
kpi_nonconvex_hdbscan_vs_kmeans |
HDBSCAN 0.988 vs KM 0.134 (ARI) |
ok — Trên Two-Moons, DBSCAN (1.0000) & HDBSCAN (0.9875, khớp sklearn HDBSCAN = 0.9875) giải trọn hình phi lồi nơi K-Means thất bại (0.1335) dù bị Silhouette chấm bẫy 0.4641 > 0.3247; trên 3 mật độ lệch nhau, HDBSCAN EOM đạt 0.9848 vượt xa DBSCAN ngưỡng cứng (0.7404). |
kpi_manifold_local_vs_global |
PaCMAP rho=0.892 | vs tSNE 0.613 |
warn — t-SNE đạt cục bộ Trust@10 = 0.9658 (sklearn 0.9660), nhưng làm méo tỷ lệ bán kính Cụm 2 / Cụm 0 từ 4.084x -> 0.981x (Spearman = 0.6126, Laplacian = 0.6423); PaCMAP bảo toàn đồng thời Trust@10 = 0.9025 và Spearman = 0.8918, còn PCA giữ Spearman = 0.9848 (3.417x). |
kpi_markov_shapley_mta |
L1 Err 1.342 -> 0.489 (Shapley 0.285) |
ok — Trên 4,000 hành trình (base_conv = 0.3715), Last-Touch phóng đại Paid Search lên 77.1% (thực 10.0%, L1 = 1.3424) và dìm Display (3.6% vs 28.0%); Absorbing Markov hạ L1 về 0.4894 (Search = 34.5%), Exact Shapley hạ tiếp còn 0.2854 (Display = 25.6%, Social = 21.5%, Email = 19.8%, Search = 24.3%) với sai số hiệu quả 0.0e+00. |
kpi_cuped_and_iroas_dr |
-68.9% Var | iROAS 1.81x (True 1.86x) |
ok — CUPED (\(\rho = 0.8228\), \(\hat{\theta} = 0.8432\)) cắt giảm -68.94% phương sai (SE $1.82 -> $1.01, ATE = $11.67 vs chân lý $11.50); Cross-Fitted AIPW-DR khử thiên lệch chọn lọc Naive = 4.17x / Last-Touch = 8.15x về iROAS_DR = 1.81x (ATE_DR = $32.59, SE = $0.68, chân lý 1.86x) và nâng holdout policy iROAS 0.68x -> 2.17x. |
4.3 Hợp đồng 16 Kiểm thử Tự động pytest (tests/test_marketing_seg_mta_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_01_pydantic_configs_strict_forbid |
Xác nhận tất cả lớp cấu hình Pydantic v2 (extra="forbid") từ chối tham số lạ hoặc reg_covar <= 0. |
| 2 | test_02_temporal_rfm_zero_leakage_split |
Khẳng định max(train_df["snapshot_day"]) < min(oot_df["snapshot_day"]) và hai tập customer_id rời nhau 100%. |
| 3 | test_03_rfm_scaling_rescue_beats_raw_euclidean |
Chứng minh monetary_raw_variance_share > 0.98, raw_ari < 0.45, còn log1p + RobustScaler vọt > 0.80 và khớp Tier 2 sklearn > 0.90. |
| 4 | test_04_oot_cluster_stability_and_gmm_monotonic_elbo |
Kiểm chứng OOT Stability ARI >= 0.75, GMM OOT ARI >= 0.75, khớp sklearn GMM > 0.85, và mọi bước lặp EM có delta_ELBO >= -1e-9. |
| 5 | test_05_nonconvex_dbscan_and_hdbscan_beat_kmeans_and_silhouette_trap |
Khẳng định DBSCAN/HDBSCAN đạt ARI > 0.85 trên Two-Moons (vs K-Means < 0.40), K-Means Silhouette > DBSCAN Silhouette, và HDBSCAN thắng DBSCAN > +0.15 ARI trên 3 mật độ. |
| 6 | test_06_internal_and_external_validity_metrics_match_sklearn |
Đối chiếu Silhouette, Davies–Bouldin, Calinski–Harabasz, ARI, NMI Tier 1 khớp sklearn.metrics tới < 1e-6. |
| 7 | test_07_pca_svd_variance_monotonicity_and_reconstruction |
Kiểm chứng phương sai tích lũy tăng đơn điệu tới 1.0, khớp sklearn PCA tới < 1e-10, và sai số tái tạo giảm khi tăng \(r\). |
| 8 | test_08_manifold_trustworthiness_and_global_preservation_pacmap_vs_tsne |
Đối chiếu trustworthiness_at_k khớp sklearn tới < 1e-6, PaCMAP Spearman > t-SNE Spearman, và chứng minh t-SNE làm méo tỷ lệ bán kính 4.08x nặng hơn PCA. |
| 9 | test_09_absorbing_markov_row_sums_fundamental_matrix_and_removal_effect |
Khẳng định tổng mỗi hàng \(\mathbf{P}_{\text{mk}}\) đúng 1.0 (< 1e-12), (I-Q)N == I (< 1e-10), và Markov giảm lỗi L1 hơn Last-Touch. |
| 10 | test_10_exact_shapley_efficiency_symmetry_and_dummy_axioms |
Kiểm chứng Efficiency (< 1e-12), Symmetry, Dummy == 0.0, và Exact Shapley thắng Last-Touch về sai số L1. |
| 11 | test_11_cuped_unbiasedness_and_variance_reduction_ge_25pct |
Khẳng định CUPED giảm phương sai >= 25%, cuped_se < raw_se, và không chệch trong vòng 3 * SE. |
| 12 | test_12_aipw_dr_iroas_overcomes_last_touch_selection_bias |
Khẳng định iROAS_DR gần chân lý hơn hẳn Naive & Last-Touch, đồng thời dr_policy_holdout_iroas > lt_policy_holdout_iroas. |
| 13 | test_13_tier2_hdbscan_and_tsne_parity |
Đối chiếu trực tiếp HDBSCANHierarchyReference với sklearn.cluster.HDBSCAN và NeighborEmbeddingReference("tsne") với sklearn.manifold.TSNE. |
| 14 | test_14_cli_demo_execution_and_workbench_json_schema |
Chạy scripts/run_lab_demo.py --quick, xác nhận đủ 6 KPI, 4 biểu đồ cột, 4 bảng, OOT ARI >= 0.75, và CUPED >= 25%. |
| 15 | test_15_security_only_ast_deserialization_guard |
Quét AST toàn bộ src/, scripts/, tests/ khẳng định 0 import giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
| 16 | test_16_multichannel_holdout_iroas_genuine_policy_evaluation |
Xác nhận đánh giá phân bổ ngân sách đa kênh qua thí nghiệm holdout ngẫu nhiên độc lập (dr_policy_holdout_iroas > lt_policy_holdout_iroas + 0.8 và nhạy theo hạt giống mẫu hữu hạn). |
Trụ cột 5 — Tài liệu Đọc SOTA & Bộ Đánh giá Năng lực (SOTA Reading List & Mastery Assessment)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong (Curated Reading List)#
- Arthur, D., & Vassilvitskii, S. (SODA 2007). k-means++: The Advantages of Careful Seeding.
Vì sao quan trọng: Chứng minh phép khởi tạo theo xác suất tỷ lệ \(D(\mathbf{x})^2\) đạt cận cạnh tranh kỳ vọng \(\mathcal{O}(\log K)\) trước cả bước Lloyd đầu tiên. - Campello, R. J. G. B., Moulavi, D., & Sander, J. (PAKDD 2013); McInnes, L., Healy, J., & Astels, S. (JOSS 2017). Density-Based Clustering Based on Hierarchical Density Estimates; hdbscan: Hierarchical density based clustering.
Vì sao quan trọng: Loại bỏ tham số \(\varepsilon\) cứng nhắc củaDBSCANbằng khoảng cách khả đạt tương hỗ, MST và tối ưu hóa ổn địnhEOMtrên cây nén đa mật độ. - van der Maaten, L., & Hinton, G. (JMLR 2008). Visualizing Data using t-SNE.
Vì sao quan trọng: Giải bài toán chen chúc đa tạp bằng nhân Student-\(t\), đồng thời phơi bày bản chất bất đối xứng của \(\mathrm{KL}(P \| Q)\) giải thích vì sao không được diễn giải khoảng cách hay kích thước cụm toàn cục trên đồ thịt-SNE. - McInnes, L., Healy, J., & Melville, J. (arXiv:1802.03426 / JOSS 2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction.
Vì sao quan trọng: Đặt nền tảng topo hình học tập đơn hình mờ, tốc độ thực nghiệm \(\mathcal{O}(n^{1.14})\), giữ cấu trúc toàn cục tốt hơnt-SNEvà mở đường choParametric UMAP. - Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (JMLR 2021, arXiv:2012.04456); Wang, Y., Sun, Y., Huang, H., & Rudin, C. (AAAI 2025). Understanding How Dimension Reduction Tools Work: PaCMAP; LocalMAP.
Vì sao quan trọng: Giải mã toán học lực hút/đẩy qua 3 nhóm cặp (NB/MN/FP), giải quyết tận gốc đánh đổi cục bộ/toàn cục trongPaCMAPvà tinh chỉnh tách cụm cục bộ trongLocalMAP. - Shao, X., & Li, L. (ACM KDD 2011); Anderl, E., Becker, I., von Wangenheim, F., & Schumann, J. H. (IJRM 2016); Deng, A., Xu, Y., Kohavi, R., & Walker, T. (ACM WSDM 2013). Data-driven multi-touch attribution models; Mapping the customer journey; Improving the Sensitivity of Online Controlled Experiments (
CUPED).
Vì sao quan trọng: Định hình bộ chuẩn hiện đại của Khoa học Dữ liệu Marketing: thayLast-Touchbằng đồ thị Markov hấp thụ + Shapley, và giảm phương sai thử nghiệm A/B nhờ hiệp biến tiền thử nghiệmCUPED.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Tại sao biến
Monetarylệch phải lại kéo sậpK-Means++thô xuốngARI = 0.2082trênRFM, và quy trìnhlog1p + RobustScalerkhắc phục chống rò rỉ thời gian như thế nào? - Q2: Chứng minh từng bước qua bất đẳng thức Jensen vì sao thuật toán
EMchoFull-Covariance GMMđảm bảo \(\ell(\theta^{(t+1)}) \ge \ell(\theta^{(t)})\) không giảm, và vì sao thiếu \(\epsilon_{\text{reg}}\mathbf{I}_d\) gây nổ log-likelihood? - Q3: Trên
Two-Moonsvà3cụm mật độ biến thiên, vì saoSilhouettechấm điểm saiK-Meanscao hơnDBSCAN(0.4641 > 0.3247), vàHDBSCANkhắc phục điểm mù đa mật độ củaDBSCAN(0.9848 > 0.7404) bằng cơ chế nào? - Q4: Giải thích vì sao tính
PCAqua ma trận hiệp phương sai \(\mathbf{X}^\top\mathbf{X}\) bình phương số điều kiện \(\kappa(\mathbf{X})^2\) so vớithin SVD, khi nào bắt buộc dùngTruncatedSVDthayPCA, vàICAkhácPCAở giả định thống kê nào? - Q5: So sánh cơ chế giải quyết crowding problem của
t-SNE(Student-\(t\) + KL bất đối xứng) vớiUMAP(entropy chéo mờ) vàPaCMAP(3 pha cặpNB/MN/FP); vì sao cấm chạyK-Meanstrực tiếp trên tọa độ2D t-SNE? - Q6: Trình bày sự phân hóa bộ nhớ RAM, thời gian huấn luyện và độ trễ suy luận ở \(n = 500{,}000, d = 128\) giữa
Kernel SVM RBF/Ward,Full GMM,K-Means++,HDBSCAN/UMAP,GBDT Hist, vàHNSW. - Q7: Chứng minh vai trò của ma trận cơ bản \(\mathbf{N} = (\mathbf{I}-\mathbf{Q})^{-1}\) trong quy bổ
Absorbing Markov, cách tínhRemoval Effect, và vì saoExact Shapleykhử được thiên lệch77.1% Paid SearchcủaLast-Touch? - Q8: Giải thích điều kiện bắt buộc để
CUPEDgiữ tính không chệch khi giảm phương sai (-68.94%), và cáchCross-Fitted AIPW-DRsửa ROAS chọn lọc từ8.15x(Last-Touch/4.17xNaive) về1.81x(tiệm cận chân lý1.86x)?
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%): Phân tích bùng nổ phương sai Euclid củaMonetary(99.81%), chứng minhK-Meanshội tụ đơn điệu về cực tiểu địa phương; chạyaudit_rfm_scaling_and_oot_stabilitychứng minh cứuARItừ0.2082 -> 0.9729và đạtOOT Stability ARI = 1.0000 >= 0.75. - Bài tập 2 (
15%): Dẫn xuất chi tiết bước E/M củaFull-Covariance GMMquaELBOvà thủ thuật log-sum-exp; chạyFullCovarianceGMMxác nhận mọi bước EM códelta_ELBO >= 2.80e-07 >= 0và khớp Tier 2sklearn(ARI = 1.000). - Bài tập 3 (
20%): Cài đặt và đối chiếuDBSCANReferencevsHDBSCANHierarchyReference(khoảng cách lõi, \(d_{\text{mreach-}k}\), Prim MST, cây nénEOM) trên Two-Moons (ARI 1.000 / 0.9875vsK-Means 0.1335) và 3 cụm lệch mật độ (0.9848vs0.7404), kèm bẫySilhouette. - Bài tập 4 (
20%): So sánhPCAReference(thin SVD),LaplacianEigenmapsReference,NeighborEmbeddingReference(t-SNE&PaCMAP) vềTrustworthiness@10(0.9658vs0.9025),Spearmantoàn cục (0.6126vs0.8918), và biến dạng bán kính cụm (4.084x -> 0.981x), đồng thời lập bảng dự toán RAM/Time ML cho500kdòng. - Bài tập 5 (
15%): Kiểm chứng ma trận chuyển \(\mathbf{P}_{\text{mk}}\) hàng tổng1.0, đẳng thức \((\mathbf{I}-\mathbf{Q})\mathbf{N}=\mathbf{I}\),Removal Effect, vàExactShapleyMTA(Efficiency diff = 0.0e+00,Dummy = 0.0, giảmL1từ1.3424 -> 0.2854). - Bài tập 6 (
15%): Dẫn xuất công thức tối ưu \(\hat{\theta}_{\text{cuped}}\) chứng minh mức giảm phương sai \(\rho^2\); chạyestimate_cuped_ate(-68.94%\(\ge 25\%\)) vàestimate_iroas_aipw_dr(iROAS_DR = 1.81xvsLast-Touch 8.15x;Policy 2.17x > 0.68x), vượt trọn vẹn16/16kiểm thửpytestvàruff check.
5.4 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh chặt chẽ không nhảy bước (bước hội tụ EM qua ELBO, định nghĩa HDBSCAN d_mreach-k + EOM, nguyên nhân biến dạng KL của t-SNE vs 3 pha PaCMAP, ma trận cơ bản Markov \((\mathbf{I}-\mathbf{Q})^{-1}\), đẳng thức giảm phương sai CUPED và tính bền vững kép AIPW-DR); marketing_seg_mta_lab vượt trọn vẹn 16/16 pytest với 0 vi phạm AST deserialization (Test 15), OOT ARI = 1.000 >= 0.75, CUPED giảm -68.94% phương sai, và tất cả khối mã Trụ cột 3 chạy sạch exit 0. |
| Senior Standard | 75–89% | Vận hành đúng đường ống log1p + RobustScaler chống rò rỉ OOT, chạy thông 16/16 pytest và run_lab_demo.py, nắm chắc phân biệt K-Means/GMM/HDBSCAN và Markov/Shapley/CUPED, nhưng còn thiếu chiều sâu khi chứng minh biến dạng bán kính của t-SNE hay phân rã ma trận độ phức tạp ML cổ điển. |
| Needs Remediation | < 75% | Chạy K-Means trực tiếp trên Monetary thô (ARI = 0.208); khớp Scaler trên cả tập OOT; dùng Silhouette để loại bỏ DBSCAN/HDBSCAN; chạy K-Means trên tọa độ 2D t-SNE; để tràn RAM O(n^2) ở Ward/Kernel SVM; dùng Last-Touch hoặc biến hậu thử nghiệm trong CUPED; hoặc để lọt pickle/joblib (CWE-502) vào mã nguồn Lab. |
Clustering Recovery (ARI): RFM Scale Trap & Non-Convex Two-Moons
Manifold Global Distance Preservation (Spearman rho_S) vs Local Trust@10
MTA Channel Share Error (L1 vs True Lift) & Paid-Search Over-Credit
Causal Experimentation: Selection-Biased ROAS vs AIPW-DR iROAS (True ~1.86x)
RFM Segmentation: Raw Scale Trap, Full-Covariance GMM EM & OOT Stability
| experiment | raw_or_baseline | remediated_method | diagnostic_detail | status |
|---|---|---|---|---|
| rfm_scale_trap | Raw KM ARI=0.208 | log1p+Robust ARI=0.973 | Monetary var share=99.81% | SCALE_RESCUED |
| oot_cluster_stability | Train max_day=90 | OOT min_day=91 | Frozen vs Refit ARI=1.000 | OOT_STABLE_PASS |
| gmm_em_monotonicity | EM iters=9 | OOT ARI=1.000 | min delta ELBO=2.80e-07 | MONOTONIC_ELBO |
| tier2_sklearn_parity | KM parity ARI=0.976 | GMM parity ARI=1.000 | Sil=0.642, DBI=0.489 | TIER2_PARITY |
Non-Convex / Varying-Density Clustering & Manifold Fidelity Audit
| benchmark | kmeans_or_tsne | dbscan_or_pacmap | hdbscan_or_pca | verdict |
|---|---|---|---|---|
| two_moons_ari | KMeans ARI=0.134 | DBSCAN ARI=1.000 | HDBSCAN ARI=0.988 (sk 0.988) | DENSITY_WINS |
| varying_density_ari | KMeans convex split | DBSCAN fixed-eps=0.740 | HDBSCAN EOM=0.985 | HDBSCAN_ADAPTIVE |
| manifold_trust_k10 | t-SNE=0.966 | PaCMAP=0.902 | PCA=0.928 | HIGH_LOCAL_FIDELITY |
| manifold_global_rho | t-SNE=0.613 | PaCMAP=0.892 | Radius warp t-SNE=0.98x (True 4.08x) | NEVER_CLUSTER_TSNE |
Multi-Touch Attribution: Last-Touch Bias vs Absorbing Markov & Exact Shapley
| channel | true_structural | last_touch | markov_removal | exact_shapley |
|---|---|---|---|---|
| Paid Search | 10.0% | 77.1% | 34.5% | 24.3% |
| Social | 26.0% | 5.5% | 17.9% | 21.5% |
| Display | 28.0% | 3.6% | 16.5% | 25.6% |
| 22.0% | 8.3% | 17.2% | 19.8% | |
| Organic | 14.0% | 5.4% | 13.9% | 8.9% |
Marketing Causal Experimentation: CUPED Variance Reduction & AIPW-DR iROAS
| estimator | estimate_or_ate | uncertainty_or_roas | ground_truth_ref | audit_verdict |
|---|---|---|---|---|
| ab_raw_difference | ATE=$8.47 | SE=$1.82 | True=$11.50 | HIGH_VARIANCE |
| ab_cuped_adjusted | ATE=$11.67 | SE=$1.01 (-68.9% var) | rho=0.823 | CUPED_PASS_GE25 |
| obs_naive_last_touch | Diff=$75.09 | Naive=4.17x | LT=8.15x | True iROAS=1.86x | SELECTION_BIASED |
| obs_aipw_dr_iroas | ATE_DR=$32.59 | iROAS_DR=1.81x (SE=$0.68) | Policy 2.17x > 0.68x | CAUSAL_PARITY_PASS |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/lab-04-marketing-segmentation-attribution-experimentation
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "marketing-seg-mta-lab"
version = "0.1.0"
description = "Lab 04: Marketing Customer Segmentation (K-Means++, Full-Covariance GMM EM, DBSCAN, HDBSCAN), Manifold Learning (PCA, Laplacian, t-SNE/PaCMAP), Multi-Touch Attribution (Markov Removal, Exact Shapley) & Causal Experimentation (CUPED, AIPW-DR iROAS)"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.2",
"pydantic>=2.0",
"scikit-learn>=1.5",
"scipy>=1.13",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.6",
"mypy>=1.11",
]
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-q"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 04 — Marketing Segmentation, Manifold Learning, MTA & Causal Experimentation."""
from __future__ import annotations
from marketing_seg_mta_lab.clustering_and_manifolds import (
DBSCANReference,
DensityClusterConfig,
FullCovarianceGMM,
GMMConfig,
HDBSCANHierarchyReference,
KMeansPlusPlus,
LaplacianEigenmapsReference,
ManifoldConfig,
NeighborEmbeddingReference,
PCAReference,
RFMClusteringConfig,
TemporalRFMCohorts,
adjusted_rand_index_ref,
align_clusters_hungarian,
audit_rfm_scaling_and_oot_stability,
audit_tsne_clustering_distortion,
calinski_harabasz_score_ref,
continuity_at_k,
davies_bouldin_score_ref,
evaluate_manifold_preservation,
generate_nonconvex_two_moons_and_density_cohorts,
generate_temporal_rfm_marketing_cohorts,
normalized_mutual_info_ref,
silhouette_score_ref,
trustworthiness_at_k,
)
from marketing_seg_mta_lab.mta_and_experimentation import (
AbsorbingMarkovMTA,
ExactShapleyMTA,
ExperimentationConfig,
MarkovMTAConfig,
compute_first_touch_attribution,
compute_last_touch_attribution,
estimate_cuped_ate,
estimate_iroas_aipw_dr,
evaluate_multichannel_holdout_iroas,
generate_marketing_ab_experiment,
generate_multi_channel_journeys,
run_full_lab04_benchmarks,
)
__all__ = [
"AbsorbingMarkovMTA",
"DBSCANReference",
"DensityClusterConfig",
"ExactShapleyMTA",
"ExperimentationConfig",
"FullCovarianceGMM",
"GMMConfig",
"HDBSCANHierarchyReference",
"KMeansPlusPlus",
"LaplacianEigenmapsReference",
"ManifoldConfig",
"MarkovMTAConfig",
"NeighborEmbeddingReference",
"PCAReference",
"RFMClusteringConfig",
"TemporalRFMCohorts",
"adjusted_rand_index_ref",
"align_clusters_hungarian",
"audit_rfm_scaling_and_oot_stability",
"audit_tsne_clustering_distortion",
"calinski_harabasz_score_ref",
"compute_first_touch_attribution",
"compute_last_touch_attribution",
"continuity_at_k",
"davies_bouldin_score_ref",
"estimate_cuped_ate",
"estimate_iroas_aipw_dr",
"evaluate_manifold_preservation",
"evaluate_multichannel_holdout_iroas",
"generate_marketing_ab_experiment",
"generate_multi_channel_journeys",
"generate_nonconvex_two_moons_and_density_cohorts",
"generate_temporal_rfm_marketing_cohorts",
"normalized_mutual_info_ref",
"run_full_lab04_benchmarks",
"silhouette_score_ref",
"trustworthiness_at_k",
]
"""Tier 1 & Tier 2 clustering, RFM OOT stability, and manifold learning algorithms."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
from scipy.stats import spearmanr
from sklearn.cluster import DBSCAN, HDBSCAN, KMeans
from sklearn.manifold import TSNE
from sklearn.manifold import trustworthiness as sklearn_trustworthiness
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import RobustScaler
class RFMClusteringConfig(BaseModel):
"""Strict configuration for K-Means++ customer segmentation."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_clusters: int = Field(default=4, ge=2, le=32)
n_init: int = Field(default=10, ge=1, le=50)
max_iter: int = Field(default=100, ge=5, le=1000)
tol: float = Field(default=1e-6, gt=0.0)
seed: int = Field(default=42, ge=0)
class GMMConfig(BaseModel):
"""Strict configuration for Full-Covariance EM Gaussian Mixture Model."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_components: int = Field(default=4, ge=2, le=32)
max_iter: int = Field(default=80, ge=5, le=500)
tol: float = Field(default=1e-6, gt=0.0)
reg_covar: float = Field(default=1e-5, gt=0.0)
seed: int = Field(default=42, ge=0)
class DensityClusterConfig(BaseModel):
"""Strict configuration for DBSCAN and HDBSCAN density clustering."""
model_config = ConfigDict(frozen=True, extra="forbid")
eps: float = Field(default=0.35, gt=0.0)
min_samples: int = Field(default=6, ge=2, le=100)
min_cluster_size: int = Field(default=12, ge=3, le=200)
class ManifoldConfig(BaseModel):
"""Strict configuration for PCA, Laplacian Eigenmaps, t-SNE & PaCMAP."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_components: int = Field(default=2, ge=1, le=64)
perplexity: float = Field(default=25.0, gt=1.0, le=100.0)
n_neighbors: int = Field(default=10, ge=2, le=100)
n_iter: int = Field(default=180, ge=30, le=1000)
learning_rate: float = Field(default=80.0, gt=0.0)
seed: int = Field(default=42, ge=0)
@dataclass(frozen=True)
class TemporalRFMCohorts:
"""Strictly time-split marketing RFM cohorts preventing future scaler leakage."""
train_df: pd.DataFrame
oot_df: pd.DataFrame
feature_names: tuple[str, ...]
persona_names: tuple[str, ...]
def generate_temporal_rfm_marketing_cohorts(
n_train: int = 900,
n_oot: int = 600,
seed: int = 42,
) -> TemporalRFMCohorts:
"""Generate temporal Train (days 1..90) and OOT (days 91..150) RFM cohorts."""
rng = np.random.default_rng(seed)
personas = ("VIP_Champions", "Loyal_Core", "Promo_Hunters", "Hibernating")
weights = np.array([0.22, 0.30, 0.26, 0.22], dtype=np.float64)
def _sample_cohort(n: int, day_low: int, day_high: int, drift: float) -> pd.DataFrame:
labels = rng.choice(4, size=n, p=weights)
recency = np.zeros(n, dtype=np.float64)
freq = np.zeros(n, dtype=np.float64)
monetary = np.zeros(n, dtype=np.float64)
promo = np.zeros(n, dtype=np.float64)
# Persona 0: VIP Champions (low recency, high frequency, very high skewed spend, low-mid promo)
m0 = labels == 0
recency[m0] = np.clip(rng.normal(12.0 + drift, 5.0, size=m0.sum()), 1.0, 40.0)
freq[m0] = np.clip(rng.normal(19.0, 3.0, size=m0.sum()), 10.0, 35.0)
monetary[m0] = np.exp(rng.normal(7.55, 0.55, size=m0.sum())) # ~1900 median, heavy right tail
promo[m0] = np.clip(rng.normal(0.16, 0.05, size=m0.sum()), 0.02, 0.40)
# Persona 1: Loyal Core (low-mid recency, steady frequency, moderate spend, low promo)
m1 = labels == 1
recency[m1] = np.clip(rng.normal(28.0 + drift, 7.0, size=m1.sum()), 5.0, 60.0)
freq[m1] = np.clip(rng.normal(10.0, 2.0, size=m1.sum()), 5.0, 18.0)
monetary[m1] = np.exp(rng.normal(5.85, 0.42, size=m1.sum())) # ~347 median
promo[m1] = np.clip(rng.normal(0.12, 0.04, size=m1.sum()), 0.01, 0.32)
# Persona 2: Promo Hunters (mid recency, moderate freq, small spend, HIGH promo sensitivity)
m2 = labels == 2
recency[m2] = np.clip(rng.normal(45.0 + drift, 9.0, size=m2.sum()), 10.0, 85.0)
freq[m2] = np.clip(rng.normal(7.5, 1.8, size=m2.sum()), 3.0, 14.0)
monetary[m2] = np.exp(rng.normal(4.45, 0.40, size=m2.sum())) # ~85 median
promo[m2] = np.clip(rng.normal(0.82, 0.07, size=m2.sum()), 0.55, 0.99)
# Persona 3: Hibernating (high recency, low frequency, modest noisy spend, mid promo)
m3 = labels == 3
recency[m3] = np.clip(rng.normal(135.0 + drift, 16.0, size=m3.sum()), 85.0, 200.0)
freq[m3] = np.clip(rng.normal(2.0, 0.6, size=m3.sum()), 1.0, 5.0)
monetary[m3] = np.exp(rng.normal(5.30, 0.50, size=m3.sum())) # ~200 median
promo[m3] = np.clip(rng.normal(0.38, 0.08, size=m3.sum()), 0.15, 0.65)
days = np.sort(rng.integers(day_low, day_high + 1, size=n))
return pd.DataFrame(
{
"customer_id": np.arange(n, dtype=np.int64),
"snapshot_day": days,
"recency_days": recency,
"frequency_orders": freq,
"monetary_usd": monetary,
"promo_sensitivity": promo,
"true_persona": labels.astype(np.int64),
}
)
train_df = _sample_cohort(n_train, 1, 90, drift=0.0)
oot_df = _sample_cohort(n_oot, 91, 150, drift=2.0)
oot_df["customer_id"] = oot_df["customer_id"] + n_train
return TemporalRFMCohorts(
train_df=train_df,
oot_df=oot_df,
feature_names=("recency_days", "frequency_orders", "monetary_usd", "promo_sensitivity"),
persona_names=personas,
)
def preprocess_rfm_features(
train_df: pd.DataFrame,
oot_df: pd.DataFrame,
feature_names: tuple[str, ...],
) -> tuple[np.ndarray, np.ndarray, RobustScaler]:
"""Apply log1p on skewed monetary/frequency + train-only RobustScaler."""
def _transform_raw(df: pd.DataFrame) -> np.ndarray:
mat = df.loc[:, list(feature_names)].to_numpy(dtype=np.float64).copy()
for idx, name in enumerate(feature_names):
if name in ("frequency_orders", "monetary_usd"):
mat[:, idx] = np.log1p(np.maximum(mat[:, idx], 0.0))
return mat
X_tr_log = _transform_raw(train_df)
X_oot_log = _transform_raw(oot_df)
scaler = RobustScaler()
X_tr_scaled = scaler.fit_transform(X_tr_log)
X_oot_scaled = scaler.transform(X_oot_log)
return X_tr_scaled, X_oot_scaled, scaler
def generate_nonconvex_two_moons_and_density_cohorts(
n_moons: int = 320,
n_density: int = 300,
seed: int = 42,
) -> dict[str, Any]:
"""Generate Two-Moons + outliers and varying-density 3-cluster cohorts."""
rng = np.random.default_rng(seed)
# 1. Interlocking Two Moons + 8 isolated outliers
n_half = n_moons // 2
t1 = np.linspace(0.0, np.pi, n_half)
t2 = np.linspace(0.0, np.pi, n_moons - n_half)
moon1 = np.column_stack([np.cos(t1), np.sin(t1)]) + rng.normal(0.0, 0.075, size=(n_half, 2))
moon2 = np.column_stack([1.0 - np.cos(t2), 0.5 - np.sin(t2)]) + rng.normal(
0.0, 0.075, size=(n_moons - n_half, 2)
)
outliers_m = np.array([[-1.4, 1.5], [2.4, -1.1], [0.5, 1.85], [2.5, 1.4], [-1.3, -1.0]])
X_moons = np.vstack([moon1, moon2, outliers_m])
y_moons = np.concatenate(
[
np.zeros(n_half, dtype=np.int64),
np.ones(n_moons - n_half, dtype=np.int64),
np.full(len(outliers_m), -1, dtype=np.int64),
]
)
# 2. Varying-Density 3-Blob Cohort (tight dense core, medium cluster, diffuse cluster + noise)
n_c = n_density // 3
c_dense = rng.normal(loc=[-3.0, 0.0], scale=0.18, size=(n_c, 2))
c_mid = rng.normal(loc=[0.2, 0.5], scale=0.45, size=(n_c, 2))
c_sparse = rng.normal(loc=[4.2, -0.3], scale=0.95, size=(n_density - 2 * n_c, 2))
noise_d = np.array([[-5.2, 3.2], [7.8, 3.4], [1.0, -4.1], [5.5, 4.0], [-4.8, -3.5]])
X_density = np.vstack([c_dense, c_mid, c_sparse, noise_d])
y_density = np.concatenate(
[
np.zeros(n_c, dtype=np.int64),
np.ones(n_c, dtype=np.int64),
np.full(n_density - 2 * n_c, 2, dtype=np.int64),
np.full(len(noise_d), -1, dtype=np.int64),
]
)
return {
"X_moons": X_moons,
"y_moons": y_moons,
"X_density": X_density,
"y_density": y_density,
}
class KMeansPlusPlus:
"""Tier 1 Reference K-Means++ (Arthur & Vassilvitskii 2007 D^2 seeding + Lloyd)."""
def __init__(self, config: RFMClusteringConfig | None = None) -> None:
self.config = config or RFMClusteringConfig()
self.centroids_: np.ndarray | None = None
self.labels_: np.ndarray | None = None
self.inertia_: float = float("inf")
self.init_inertia_: float = float("inf")
self.n_iter_: int = 0
@staticmethod
def _init_d2_centers(X: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
n, _ = X.shape
centers = np.empty((k, X.shape[1]), dtype=np.float64)
first_idx = int(rng.integers(0, n))
centers[0] = X[first_idx]
min_sq_dist = np.sum((X - centers[0]) ** 2, axis=1)
for c in range(1, k):
total = float(np.sum(min_sq_dist))
if total <= 1e-15:
probs = np.full(n, 1.0 / n, dtype=np.float64)
else:
probs = min_sq_dist / total
next_idx = int(rng.choice(n, p=probs))
centers[c] = X[next_idx]
d2 = np.sum((X - centers[c]) ** 2, axis=1)
min_sq_dist = np.minimum(min_sq_dist, d2)
return centers
def fit(self, X: np.ndarray) -> KMeansPlusPlus:
X_arr = np.asarray(X, dtype=np.float64)
k = self.config.n_clusters
best_inertia = float("inf")
best_init_inertia = float("inf")
best_centroids: np.ndarray | None = None
best_labels: np.ndarray | None = None
best_n_iter = 0
for run_idx in range(self.config.n_init):
rng = np.random.default_rng(self.config.seed + run_idx)
centers = self._init_d2_centers(X_arr, k, rng)
dists0 = cdist(X_arr, centers, metric="sqeuclidean")
init_inertia = float(np.sum(np.min(dists0, axis=1)))
labels = np.zeros(X_arr.shape[0], dtype=np.int64)
prev_inertia = init_inertia
n_iter = 0
for step in range(1, self.config.max_iter + 1):
sq_dists = cdist(X_arr, centers, metric="sqeuclidean")
labels = np.argmin(sq_dists, axis=1).astype(np.int64)
inertia = float(np.sum(sq_dists[np.arange(X_arr.shape[0]), labels]))
new_centers = centers.copy()
for j in range(k):
mask = labels == j
if np.any(mask):
new_centers[j] = np.mean(X_arr[mask], axis=0)
else:
farthest = int(np.argmax(np.min(sq_dists, axis=1)))
new_centers[j] = X_arr[farthest]
shift = float(np.max(np.linalg.norm(new_centers - centers, axis=1)))
centers = new_centers
n_iter = step
if shift < self.config.tol or abs(prev_inertia - inertia) < self.config.tol:
prev_inertia = inertia
break
prev_inertia = inertia
if prev_inertia < best_inertia:
best_inertia = prev_inertia
best_init_inertia = init_inertia
best_centroids = centers.copy()
best_labels = labels.copy()
best_n_iter = n_iter
self.centroids_ = best_centroids
self.labels_ = best_labels
self.inertia_ = float(best_inertia)
self.init_inertia_ = float(best_init_inertia)
self.n_iter_ = best_n_iter
return self
def predict(self, X: np.ndarray) -> np.ndarray:
if self.centroids_ is None:
raise RuntimeError("KMeansPlusPlus must be fitted before calling predict().")
sq_dists = cdist(np.asarray(X, dtype=np.float64), self.centroids_, metric="sqeuclidean")
return np.argmin(sq_dists, axis=1).astype(np.int64)
def fit_predict(self, X: np.ndarray) -> np.ndarray:
self.fit(X)
assert self.labels_ is not None
return self.labels_.copy()
class FullCovarianceGMM:
"""Tier 1 Reference Full-Covariance GMM fitted by regularized EM with log-sum-exp."""
def __init__(self, config: GMMConfig | None = None) -> None:
self.config = config or GMMConfig()
self.weights_: np.ndarray | None = None
self.means_: np.ndarray | None = None
self.covariances_: np.ndarray | None = None
self.log_likelihood_history_: list[float] = []
self.elbo_history_: list[float] = []
@staticmethod
def _log_gaussian_pdf(X: np.ndarray, mean: np.ndarray, cov: np.ndarray) -> np.ndarray:
d = X.shape[1]
sign, logdet = np.linalg.slogdet(cov)
if sign <= 0:
cov = cov + 1e-4 * np.eye(d)
_, logdet = np.linalg.slogdet(cov)
diff = X - mean
solved = np.linalg.solve(cov, diff.T).T
mahal = np.sum(diff * solved, axis=1)
return -0.5 * (d * np.log(2.0 * np.pi) + logdet + mahal)
def _e_step(
self,
X: np.ndarray,
weights: np.ndarray,
means: np.ndarray,
covs: np.ndarray,
) -> tuple[np.ndarray, float]:
n = X.shape[0]
k = len(weights)
log_weighted = np.empty((n, k), dtype=np.float64)
for j in range(k):
log_weighted[:, j] = np.log(max(weights[j], 1e-15)) + self._log_gaussian_pdf(
X, means[j], covs[j]
)
max_lw = np.max(log_weighted, axis=1, keepdims=True)
lse = max_lw[:, 0] + np.log(np.sum(np.exp(log_weighted - max_lw), axis=1))
log_resp = log_weighted - lse[:, None]
resp = np.exp(log_resp)
total_ll = float(np.sum(lse))
return resp, total_ll
def fit(self, X: np.ndarray) -> FullCovarianceGMM:
X_arr = np.asarray(X, dtype=np.float64)
n, d = X_arr.shape
k = self.config.n_components
km = KMeansPlusPlus(RFMClusteringConfig(n_clusters=k, max_iter=30, seed=self.config.seed)).fit(X_arr)
assert km.centroids_ is not None and km.labels_ is not None
weights = np.full(k, 1.0 / k, dtype=np.float64)
means = km.centroids_.copy()
reg_eye = self.config.reg_covar * np.eye(d, dtype=np.float64)
covs = np.empty((k, d, d), dtype=np.float64)
global_cov = np.cov(X_arr, rowvar=False) + reg_eye
for j in range(k):
mask = km.labels_ == j
if np.sum(mask) > d + 1:
covs[j] = np.cov(X_arr[mask], rowvar=False) + reg_eye
else:
covs[j] = global_cov.copy()
weights[j] = max(float(np.mean(mask)), 1e-3)
weights /= np.sum(weights)
self.log_likelihood_history_ = []
self.elbo_history_ = []
prev_ll = -float("inf")
for _ in range(self.config.max_iter):
resp, ll = self._e_step(X_arr, weights, means, covs)
self.log_likelihood_history_.append(ll)
self.elbo_history_.append(ll) # Exact E-step sets KL(q || p(z|x)) = 0 => ELBO == LL
if ll - prev_ll < self.config.tol and len(self.log_likelihood_history_) > 1:
break
prev_ll = ll
nk = np.maximum(np.sum(resp, axis=0), 1e-10)
weights = nk / n
means = (resp.T @ X_arr) / nk[:, None]
for j in range(k):
diff = X_arr - means[j]
weighted_diff = diff * resp[:, j : j + 1]
covs[j] = (weighted_diff.T @ diff) / nk[j] + reg_eye
self.weights_ = weights
self.means_ = means
self.covariances_ = covs
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
if self.weights_ is None or self.means_ is None or self.covariances_ is None:
raise RuntimeError("FullCovarianceGMM must be fitted first.")
resp, _ = self._e_step(
np.asarray(X, dtype=np.float64),
self.weights_,
self.means_,
self.covariances_,
)
return resp
def predict(self, X: np.ndarray) -> np.ndarray:
return np.argmax(self.predict_proba(X), axis=1).astype(np.int64)
def bic(self, X: np.ndarray) -> float:
if self.weights_ is None or self.means_ is None or self.covariances_ is None:
raise RuntimeError("FullCovarianceGMM must be fitted first.")
X_arr = np.asarray(X, dtype=np.float64)
n, d = X_arr.shape
k = self.config.n_components
_, ll = self._e_step(X_arr, self.weights_, self.means_, self.covariances_)
n_params = (k - 1) + k * d + k * d * (d + 1) // 2
return float(-2.0 * ll + n_params * np.log(max(n, 1)))
class DBSCANReference:
"""Tier 1 Reference DBSCAN over Euclidean eps-neighborhoods."""
def __init__(self, eps: float = 0.25, min_samples: int = 5) -> None:
self.eps = eps
self.min_samples = min_samples
self.labels_: np.ndarray | None = None
self.core_sample_mask_: np.ndarray | None = None
def fit_predict(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
dists = cdist(X_arr, X_arr, metric="euclidean")
adj = dists <= self.eps
core_mask = np.sum(adj, axis=1) >= self.min_samples
labels = np.full(n, -1, dtype=np.int64)
visited = np.zeros(n, dtype=bool)
cluster_id = 0
for idx in range(n):
if visited[idx] or not core_mask[idx]:
continue
queue = [idx]
visited[idx] = True
labels[idx] = cluster_id
while queue:
curr = queue.pop()
if core_mask[curr]:
neighbors = np.flatnonzero(adj[curr])
for nb in neighbors:
if not visited[nb]:
visited[nb] = True
queue.append(int(nb))
if labels[nb] == -1:
labels[nb] = cluster_id
cluster_id += 1
self.labels_ = labels
self.core_sample_mask_ = core_mask
return labels.copy()
class HDBSCANHierarchyReference:
"""Tier 1 Reference HDBSCAN: core distance, mutual reachability, Prim MST & EOM tree."""
def __init__(self, min_samples: int = 6, min_cluster_size: int = 12) -> None:
self.min_samples = min_samples
self.min_cluster_size = min_cluster_size
self.core_distances_: np.ndarray | None = None
self.mst_edges_: list[tuple[int, int, float]] = []
self.labels_: np.ndarray | None = None
self.cluster_stabilities_: dict[int, float] = {}
@staticmethod
def _prim_mst(weight_mat: np.ndarray) -> list[tuple[int, int, float]]:
n = weight_mat.shape[0]
in_tree = np.zeros(n, dtype=bool)
key = np.full(n, float("inf"), dtype=np.float64)
parent = np.full(n, -1, dtype=np.int64)
key[0] = 0.0
edges: list[tuple[int, int, float]] = []
for _ in range(n):
candidates = np.where(~in_tree, key, float("inf"))
u = int(np.argmin(candidates))
in_tree[u] = True
if parent[u] != -1:
edges.append((int(parent[u]), u, float(key[u])))
row = weight_mat[u]
update = (~in_tree) & (row < key)
key[update] = row[update]
parent[update] = u
return edges
def fit_predict(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
dists = cdist(X_arr, X_arr, metric="euclidean")
k_idx = min(self.min_samples - 1, n - 1)
sorted_dists = np.partition(dists, k_idx, axis=1)[:, k_idx]
core_d = sorted_dists.astype(np.float64)
self.core_distances_ = core_d
mreach = np.maximum(dists, np.maximum(core_d[:, None], core_d[None, :]))
np.fill_diagonal(mreach, 0.0)
mst_edges = sorted(self._prim_mst(mreach), key=lambda e: e[2])
self.mst_edges_ = mst_edges
# Build single-linkage dendrogram tree nodes 0..2n-2
uf_parent = list(range(2 * n - 1))
def _find(x: int) -> int:
while uf_parent[x] != x:
uf_parent[x] = uf_parent[uf_parent[x]]
x = uf_parent[x]
return x
children: dict[int, tuple[int, int]] = {}
node_size: dict[int, int] = {i: 1 for i in range(n)}
node_dist: dict[int, float] = {i: 0.0 for i in range(n)}
node_points: dict[int, list[int]] = {i: [i] for i in range(n)}
next_id = n
for u, v, w in mst_edges:
ru, rv = _find(u), _find(v)
if ru == rv:
continue
children[next_id] = (ru, rv)
node_size[next_id] = node_size[ru] + node_size[rv]
node_dist[next_id] = max(float(w), 1e-12)
node_points[next_id] = node_points[ru] + node_points[rv]
uf_parent[ru] = next_id
uf_parent[rv] = next_id
next_id += 1
root = next_id - 1
# Condense tree top-down
condensed_children: dict[int, list[int]] = {}
condensed_birth: dict[int, float] = {0: 0.0}
condensed_events: dict[int, list[tuple[int, float]]] = {0: []}
condensed_points: dict[int, list[int]] = {0: list(node_points[root])}
next_cid = 1
stack: list[tuple[int, int]] = [(root, 0)]
while stack:
tree_node, cid = stack.pop()
if tree_node < n:
lam_end = 1.0 / max(node_dist[tree_node], 1e-12)
condensed_events[cid].append((1, lam_end))
continue
left_n, right_n = children[tree_node]
lam_split = 1.0 / max(node_dist[tree_node], 1e-12)
left_big = node_size[left_n] >= self.min_cluster_size
right_big = node_size[right_n] >= self.min_cluster_size
if left_big and right_big:
c_left = next_cid
c_right = next_cid + 1
next_cid += 2
condensed_children.setdefault(cid, []).extend([c_left, c_right])
condensed_birth[c_left] = lam_split
condensed_birth[c_right] = lam_split
condensed_events[c_left] = []
condensed_events[c_right] = []
condensed_points[c_left] = list(node_points[left_n])
condensed_points[c_right] = list(node_points[right_n])
condensed_events[cid].append((node_size[tree_node], lam_split))
stack.append((left_n, c_left))
stack.append((right_n, c_right))
elif left_big and not right_big:
condensed_events[cid].append((node_size[right_n], lam_split))
stack.append((left_n, cid))
elif right_big and not left_big:
condensed_events[cid].append((node_size[left_n], lam_split))
stack.append((right_n, cid))
else:
condensed_events[cid].append((node_size[tree_node], lam_split))
# Compute EOM stability S(c) = sum_x (lam_death(x) - lam_birth(c))
stabilities: dict[int, float] = {}
for cid in range(next_cid):
birth = condensed_birth[cid]
stab = 0.0
for sz, lam_death in condensed_events[cid]:
stab += sz * max(0.0, lam_death - birth)
stabilities[cid] = stab
self.cluster_stabilities_ = stabilities
# Bottom-up EOM selection (root cid=0 excluded if it splits into valid children)
selected: set[int] = set()
subtree_stab: dict[int, float] = {}
for cid in range(next_cid - 1, -1, -1):
ch_list = condensed_children.get(cid, [])
if not ch_list:
selected.add(cid)
subtree_stab[cid] = stabilities[cid]
else:
child_sum = sum(subtree_stab[c] for c in ch_list)
if cid != 0 and stabilities[cid] >= child_sum:
# Select parent and deselect entire subtree
rem_stack = list(ch_list)
while rem_stack:
rem = rem_stack.pop()
selected.discard(rem)
rem_stack.extend(condensed_children.get(rem, []))
selected.add(cid)
subtree_stab[cid] = stabilities[cid]
else:
subtree_stab[cid] = child_sum
labels = np.full(n, -1, dtype=np.int64)
for out_label, cid in enumerate(sorted(selected)):
if cid == 0 and next_cid > 1:
continue
for pt in condensed_points[cid]:
labels[pt] = out_label
# Re-index densely starting at 0 while keeping -1 as noise
unique_pos = sorted(int(v) for v in np.unique(labels) if v >= 0)
remap = {old: new for new, old in enumerate(unique_pos)}
final_labels = np.array([remap[int(v)] if v >= 0 else -1 for v in labels], dtype=np.int64)
self.labels_ = final_labels
return final_labels.copy()
def align_clusters_hungarian(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
"""Remap predicted cluster IDs onto reference cluster IDs via Hungarian matching."""
y_t = np.asarray(y_true, dtype=np.int64)
y_p = np.asarray(y_pred, dtype=np.int64)
t_vals = sorted(int(v) for v in np.unique(y_t) if v >= 0)
p_vals = sorted(int(v) for v in np.unique(y_p) if v >= 0)
if not t_vals or not p_vals:
return y_p.copy()
cost = np.zeros((len(p_vals), len(t_vals)), dtype=np.int64)
for i, pv in enumerate(p_vals):
for j, tv in enumerate(t_vals):
cost[i, j] = -int(np.sum((y_p == pv) & (y_t == tv)))
row_ind, col_ind = linear_sum_assignment(cost)
mapping = {p_vals[r]: t_vals[c] for r, c in zip(row_ind, col_ind, strict=True)}
next_id = (max(t_vals) + 1) if t_vals else 0
for pv in p_vals:
if pv not in mapping:
mapping[pv] = next_id
next_id += 1
return np.array([mapping[int(v)] if v >= 0 else -1 for v in y_p], dtype=np.int64)
def silhouette_score_ref(X: np.ndarray, labels: np.ndarray) -> float:
"""Tier 1 Reference mean Silhouette coefficient."""
X_arr = np.asarray(X, dtype=np.float64)
lbl = np.asarray(labels, dtype=np.int64)
uniq = np.unique(lbl)
if len(uniq) < 2 or len(uniq) >= len(lbl):
return 0.0
dists = cdist(X_arr, X_arr, metric="euclidean")
s_vals = np.zeros(len(lbl), dtype=np.float64)
for i in range(len(lbl)):
same = (lbl == lbl[i]) & (np.arange(len(lbl)) != i)
a_i = float(np.mean(dists[i, same])) if np.any(same) else 0.0
b_i = float("inf")
for c in uniq:
if c == lbl[i]:
continue
other = lbl == c
b_i = min(b_i, float(np.mean(dists[i, other])))
denom = max(a_i, b_i)
s_vals[i] = 0.0 if denom <= 1e-15 else (b_i - a_i) / denom
return float(np.mean(s_vals))
def davies_bouldin_score_ref(X: np.ndarray, labels: np.ndarray) -> float:
"""Tier 1 Reference Davies-Bouldin Index (lower is better)."""
X_arr = np.asarray(X, dtype=np.float64)
lbl = np.asarray(labels, dtype=np.int64)
uniq = [int(c) for c in np.unique(lbl) if c >= 0]
k = len(uniq)
if k < 2:
return float("inf")
centroids = np.array([np.mean(X_arr[lbl == c], axis=0) for c in uniq])
scatters = np.array(
[float(np.mean(np.linalg.norm(X_arr[lbl == c] - centroids[i], axis=1))) for i, c in enumerate(uniq)]
)
ratios = []
for i in range(k):
max_r = 0.0
for j in range(k):
if i == j:
continue
cdist_ij = float(np.linalg.norm(centroids[i] - centroids[j]))
if cdist_ij > 1e-15:
max_r = max(max_r, (scatters[i] + scatters[j]) / cdist_ij)
ratios.append(max_r)
return float(np.mean(ratios))
def calinski_harabasz_score_ref(X: np.ndarray, labels: np.ndarray) -> float:
"""Tier 1 Reference Calinski-Harabasz Variance Ratio Criterion (higher is better)."""
X_arr = np.asarray(X, dtype=np.float64)
lbl = np.asarray(labels, dtype=np.int64)
uniq = [int(c) for c in np.unique(lbl) if c >= 0]
k = len(uniq)
n = len(lbl)
if k < 2 or n <= k:
return 0.0
grand_mean = np.mean(X_arr, axis=0)
bgss = 0.0
wgss = 0.0
for c in uniq:
pts = X_arr[lbl == c]
c_mean = np.mean(pts, axis=0)
bgss += len(pts) * float(np.sum((c_mean - grand_mean) ** 2))
wgss += float(np.sum((pts - c_mean) ** 2))
if wgss <= 1e-15:
return float("inf")
return float((bgss / (k - 1)) / (wgss / (n - k)))
def adjusted_rand_index_ref(labels_true: np.ndarray, labels_pred: np.ndarray) -> float:
"""Tier 1 Reference Hubert-Arabie Adjusted Rand Index (ARI)."""
u = np.asarray(labels_true, dtype=np.int64)
v = np.asarray(labels_pred, dtype=np.int64)
n = len(u)
if n < 2:
return 1.0
_, u_idx = np.unique(u, return_inverse=True)
_, v_idx = np.unique(v, return_inverse=True)
cont = np.zeros((int(u_idx.max()) + 1, int(v_idx.max()) + 1), dtype=np.float64)
np.add.at(cont, (u_idx, v_idx), 1.0)
sum_comb_c = float(np.sum(cont * (cont - 1.0) / 2.0))
a = np.sum(cont, axis=1)
b = np.sum(cont, axis=0)
sum_comb_a = float(np.sum(a * (a - 1.0) / 2.0))
sum_comb_b = float(np.sum(b * (b - 1.0) / 2.0))
total_comb = n * (n - 1.0) / 2.0
expected = (sum_comb_a * sum_comb_b) / total_comb
max_idx = 0.5 * (sum_comb_a + sum_comb_b)
if abs(max_idx - expected) <= 1e-15:
return 1.0 if sum_comb_c == expected else 0.0
return float((sum_comb_c - expected) / (max_idx - expected))
def normalized_mutual_info_ref(labels_true: np.ndarray, labels_pred: np.ndarray) -> float:
"""Tier 1 Reference Normalized Mutual Information (arithmetic average)."""
u = np.asarray(labels_true, dtype=np.int64)
v = np.asarray(labels_pred, dtype=np.int64)
n = float(len(u))
if n <= 1.0:
return 1.0
_, u_idx = np.unique(u, return_inverse=True)
_, v_idx = np.unique(v, return_inverse=True)
cont = np.zeros((int(u_idx.max()) + 1, int(v_idx.max()) + 1), dtype=np.float64)
np.add.at(cont, (u_idx, v_idx), 1.0)
p_ij = cont / n
p_i = np.sum(p_ij, axis=1)
p_j = np.sum(p_ij, axis=0)
nz = p_ij > 0
mi = float(np.sum(p_ij[nz] * np.log(p_ij[nz] / (p_i[:, None] * p_j[None, :])[nz])))
h_u = -float(np.sum(p_i[p_i > 0] * np.log(p_i[p_i > 0])))
h_v = -float(np.sum(p_j[p_j > 0] * np.log(p_j[p_j > 0])))
if h_u + h_v <= 1e-15:
return 1.0
return float(2.0 * mi / (h_u + h_v))
def audit_rfm_scaling_and_oot_stability(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Audit raw-Euclidean monetary collapse vs log1p+RobustScaler + OOT cluster stability."""
n_tr = 600 if quick else 900
n_oot = 400 if quick else 600
cohorts = generate_temporal_rfm_marketing_cohorts(n_train=n_tr, n_oot=n_oot, seed=seed)
X_raw_tr = cohorts.train_df.loc[:, list(cohorts.feature_names)].to_numpy(dtype=np.float64)
y_tr = cohorts.train_df["true_persona"].to_numpy(dtype=np.int64)
y_oot = cohorts.oot_df["true_persona"].to_numpy(dtype=np.int64)
# 1. Raw Euclidean failure (Monetary USD dominates >99% variance)
km_raw = KMeansPlusPlus(RFMClusteringConfig(n_clusters=4, seed=seed)).fit(X_raw_tr)
raw_pred_tr = km_raw.labels_
assert raw_pred_tr is not None
raw_ari = adjusted_rand_index_ref(y_tr, raw_pred_tr)
raw_nmi = normalized_mutual_info_ref(y_tr, raw_pred_tr)
var_shares = np.var(X_raw_tr, axis=0)
monetary_var_share = float(var_shares[2] / np.sum(var_shares))
# 2. Leakage-proof log1p + train-fitted RobustScaler
X_tr_scaled, X_oot_scaled, _ = preprocess_rfm_features(
cohorts.train_df, cohorts.oot_df, cohorts.feature_names
)
km_scaled = KMeansPlusPlus(RFMClusteringConfig(n_clusters=4, seed=seed)).fit(X_tr_scaled)
scaled_pred_tr = km_scaled.labels_
assert scaled_pred_tr is not None
scaled_ari_tr = adjusted_rand_index_ref(y_tr, scaled_pred_tr)
scaled_nmi_tr = normalized_mutual_info_ref(y_tr, scaled_pred_tr)
# Tier 2 sklearn parity check on scaled train
sk_km = KMeans(n_clusters=4, init="k-means++", n_init=10, random_state=seed).fit(X_tr_scaled)
km_tier_parity_ari = float(adjusted_rand_score(scaled_pred_tr, sk_km.labels_))
# Frozen train centroids predict on OOT vs refit OOT cluster stability
oot_frozen_pred = km_scaled.predict(X_oot_scaled)
km_oot_refit = KMeansPlusPlus(RFMClusteringConfig(n_clusters=4, seed=seed)).fit(X_oot_scaled)
oot_refit_aligned = align_clusters_hungarian(oot_frozen_pred, km_oot_refit.predict(X_oot_scaled))
oot_stability_ari = adjusted_rand_index_ref(oot_frozen_pred, oot_refit_aligned)
oot_truth_ari = adjusted_rand_index_ref(y_oot, oot_frozen_pred)
# Full-Covariance GMM EM (monotonic ELBO check)
gmm = FullCovarianceGMM(GMMConfig(n_components=4, reg_covar=1e-5, seed=seed)).fit(X_tr_scaled)
gmm_pred_tr = gmm.predict(X_tr_scaled)
gmm_pred_oot = gmm.predict(X_oot_scaled)
gmm_ari_tr = adjusted_rand_index_ref(y_tr, gmm_pred_tr)
gmm_ari_oot = adjusted_rand_index_ref(y_oot, gmm_pred_oot)
sk_gmm = GaussianMixture(
n_components=4, covariance_type="full", reg_covar=1e-5, random_state=seed
).fit(X_tr_scaled)
gmm_sk_ari = float(adjusted_rand_score(gmm_pred_tr, sk_gmm.predict(X_tr_scaled)))
elbo_diffs = np.diff(np.array(gmm.elbo_history_, dtype=np.float64))
gmm_min_elbo_step = float(np.min(elbo_diffs)) if len(elbo_diffs) > 0 else 0.0
return {
"train_max_day": int(cohorts.train_df["snapshot_day"].max()),
"oot_min_day": int(cohorts.oot_df["snapshot_day"].min()),
"monetary_raw_variance_share": round(monetary_var_share, 6),
"raw_kmeans_train_ari": round(raw_ari, 4),
"raw_kmeans_train_nmi": round(raw_nmi, 4),
"scaled_kmeans_train_ari": round(scaled_ari_tr, 4),
"scaled_kmeans_train_nmi": round(scaled_nmi_tr, 4),
"kmeans_tier2_sklearn_parity_ari": round(km_tier_parity_ari, 4),
"oot_frozen_vs_refit_stability_ari": round(oot_stability_ari, 4),
"oot_frozen_vs_truth_ari": round(oot_truth_ari, 4),
"gmm_train_ari": round(gmm_ari_tr, 4),
"gmm_oot_ari": round(gmm_ari_oot, 4),
"gmm_tier2_sklearn_ari": round(gmm_sk_ari, 4),
"gmm_em_iters": len(gmm.elbo_history_),
"gmm_min_elbo_delta": float(gmm_min_elbo_step),
"gmm_final_elbo": round(float(gmm.elbo_history_[-1]), 2),
"gmm_bic_train": round(gmm.bic(X_tr_scaled), 2),
"scaled_kmeans_silhouette": round(silhouette_score_ref(X_tr_scaled, scaled_pred_tr), 4),
"scaled_kmeans_dbi": round(davies_bouldin_score_ref(X_tr_scaled, scaled_pred_tr), 4),
"scaled_kmeans_ch": round(calinski_harabasz_score_ref(X_tr_scaled, scaled_pred_tr), 2),
}
class PCAReference:
"""Tier 1 Reference PCA via thin SVD avoiding covariance condition-number squaring."""
def __init__(self, n_components: int = 2) -> None:
self.n_components = n_components
self.mean_: np.ndarray | None = None
self.components_: np.ndarray | None = None
self.explained_variance_ratio_: np.ndarray | None = None
self.cumulative_variance_ratio_: np.ndarray | None = None
def fit(self, X: np.ndarray) -> PCAReference:
X_arr = np.asarray(X, dtype=np.float64)
n, _ = X_arr.shape
self.mean_ = np.mean(X_arr, axis=0)
X_centered = X_arr - self.mean_
_, s_vals, vt = np.linalg.svd(X_centered, full_matrices=False)
ev = (s_vals ** 2) / max(n - 1, 1)
total_var = max(float(np.sum(ev)), 1e-15)
all_ratios = ev / total_var
r = min(self.n_components, vt.shape[0])
self.components_ = vt[:r]
self.explained_variance_ratio_ = all_ratios[:r]
self.cumulative_variance_ratio_ = np.cumsum(all_ratios)
return self
def transform(self, X: np.ndarray) -> np.ndarray:
if self.mean_ is None or self.components_ is None:
raise RuntimeError("PCAReference must be fitted first.")
return (np.asarray(X, dtype=np.float64) - self.mean_) @ self.components_.T
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
def inverse_transform(self, Z: np.ndarray) -> np.ndarray:
if self.mean_ is None or self.components_ is None:
raise RuntimeError("PCAReference must be fitted first.")
return np.asarray(Z, dtype=np.float64) @ self.components_ + self.mean_
class LaplacianEigenmapsReference:
"""Tier 1 Reference Spectral Manifold Embedding via Normalized Graph Laplacian."""
def __init__(self, n_components: int = 2, n_neighbors: int = 10, gamma: float = 0.5) -> None:
self.n_components = n_components
self.n_neighbors = n_neighbors
self.gamma = gamma
self.embedding_: np.ndarray | None = None
def fit_transform(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
sq_d = cdist(X_arr, X_arr, metric="sqeuclidean")
np.fill_diagonal(sq_d, float("inf"))
knn_idx = np.argsort(sq_d, axis=1)[:, : min(self.n_neighbors, n - 1)]
W = np.zeros((n, n), dtype=np.float64)
for i in range(n):
for j in knn_idx[i]:
w_ij = float(np.exp(-self.gamma * sq_d[i, j]))
W[i, j] = w_ij
W[j, i] = w_ij
deg = np.maximum(np.sum(W, axis=1), 1e-12)
d_inv_sqrt = 1.0 / np.sqrt(deg)
L_sym = np.eye(n) - (W * d_inv_sqrt[:, None]) * d_inv_sqrt[None, :]
L_sym = 0.5 * (L_sym + L_sym.T)
_, eigvecs = np.linalg.eigh(L_sym)
# Skip trivial constant eigenvector 0; extract 1..n_components
emb = eigvecs[:, 1 : 1 + self.n_components]
self.embedding_ = emb * d_inv_sqrt[:, None]
return self.embedding_.copy()
class NeighborEmbeddingReference:
"""Tier 1 Reference t-SNE (perplexity + Student-t KL) and PaCMAP (NB/MN/FP 3-phase)."""
def __init__(self, mode: str = "tsne", config: ManifoldConfig | None = None) -> None:
if mode not in ("tsne", "pacmap"):
raise ValueError("mode must be 'tsne' or 'pacmap'.")
self.mode = mode
self.config = config or ManifoldConfig()
self.embedding_: np.ndarray | None = None
@staticmethod
def _compute_perplexity_affinities(sq_d: np.ndarray, target_perp: float) -> np.ndarray:
n = sq_d.shape[0]
P = np.zeros((n, n), dtype=np.float64)
log_u = np.log(target_perp)
for i in range(n):
beta_min, beta_max = -float("inf"), float("inf")
beta = 1.0
d_i = np.delete(sq_d[i], i)
for _ in range(40):
p_i = np.exp(-d_i * beta)
sum_p = float(np.sum(p_i))
if sum_p <= 1e-15:
p_i = np.full_like(d_i, 1.0 / len(d_i))
sum_p = 1.0
else:
p_i = p_i / sum_p
h = -float(np.sum(p_i * np.log(np.maximum(p_i, 1e-15))))
h_diff = h - log_u
if abs(h_diff) < 1e-5:
break
if h_diff > 0:
beta_min = beta
beta = beta * 2.0 if beta_max == float("inf") else 0.5 * (beta + beta_max)
else:
beta_max = beta
beta = beta * 0.5 if beta_min == -float("inf") else 0.5 * (beta + beta_min)
row = np.insert(p_i, i, 0.0)
P[i] = row
P_sym = (P + P.T) / (2.0 * n)
return np.maximum(P_sym, 1e-12)
def fit_transform(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
rng = np.random.default_rng(self.config.seed)
# PCA init stabilizes global orientation for both t-SNE & PaCMAP
Y = PCAReference(n_components=self.config.n_components).fit_transform(X_arr)
std0 = max(float(np.std(Y)), 1e-6)
Y = (Y / std0) * 0.01 if self.mode == "tsne" else (Y / std0) * 1.0
sq_d = cdist(X_arr, X_arr, metric="sqeuclidean")
if self.mode == "tsne":
P = self._compute_perplexity_affinities(sq_d, min(self.config.perplexity, max(5.0, n / 4.0)))
vel = np.zeros_like(Y)
for it in range(self.config.n_iter):
exag = 4.0 if it < min(40, self.config.n_iter // 4) else 1.0
sq_y = cdist(Y, Y, metric="sqeuclidean")
inv_y = 1.0 / (1.0 + sq_y)
np.fill_diagonal(inv_y, 0.0)
Q = np.maximum(inv_y / max(float(np.sum(inv_y)), 1e-12), 1e-12)
pq = (exag * P - Q) * inv_y
grad = np.zeros_like(Y)
for i in range(n):
grad[i] = 4.0 * np.sum(pq[i : i + 1].T * (Y[i] - Y), axis=0)
mom = 0.5 if it < 30 else 0.8
vel = mom * vel - self.config.learning_rate * grad
Y = Y + vel
Y -= np.mean(Y, axis=0)
self.embedding_ = Y
return Y.copy()
# PaCMAP-style 3-regime pair embedding (Near, Mid-Near, Further Pairs)
k_nb = min(self.config.n_neighbors, max(2, n - 2))
order = np.argsort(sq_d, axis=1)
nb_pairs = []
mn_pairs = []
fp_pairs = []
mid_lo = min(n - 2, max(k_nb + 1, n // 6))
mid_hi = min(n - 1, max(mid_lo + 2, n // 2))
for i in range(n):
for j in order[i, 1 : 1 + k_nb]:
nb_pairs.append((i, int(j)))
for j in rng.choice(order[i, mid_lo:mid_hi], size=min(4, max(1, mid_hi - mid_lo)), replace=False):
mn_pairs.append((i, int(j)))
for j in rng.choice(order[i, mid_hi:], size=min(6, max(1, n - mid_hi)), replace=False):
fp_pairs.append((i, int(j)))
nb_arr = np.array(nb_pairs, dtype=np.int64)
mn_arr = np.array(mn_pairs, dtype=np.int64)
fp_arr = np.array(fp_pairs, dtype=np.int64)
n_steps = self.config.n_iter
lr = 0.35
for it in range(n_steps):
frac = it / max(n_steps - 1, 1)
if frac < 0.35:
w_nb, w_mn, w_fp = 2.0, 1000.0 * (1.0 - frac / 0.35) + 3.0, 1.0
elif frac < 0.70:
w_nb, w_mn, w_fp = 3.0, 3.0, 1.0
else:
w_nb, w_mn, w_fp = 1.0, 0.0, 1.0
grad = np.zeros_like(Y)
for pairs, w_p, c_denom, attractive in (
(nb_arr, w_nb, 10.0, True),
(mn_arr, w_mn, 10000.0, True),
(fp_arr, w_fp, 1.0, False),
):
if w_p <= 0.0 or len(pairs) == 0:
continue
diff = Y[pairs[:, 0]] - Y[pairs[:, 1]]
d_tilde = 1.0 + np.sum(diff ** 2, axis=1)
if attractive:
# d/dY [ w * d_tilde / (c + d_tilde) ] = 2 * w * c / (c + d_tilde)^2 * diff
coeff = (2.0 * w_p * c_denom / ((c_denom + d_tilde) ** 2))[:, None]
else:
# d/dY [ w / (1 + d_tilde) ] = -2 * w / (1 + d_tilde)^2 * diff
coeff = (-2.0 * w_p / ((1.0 + d_tilde) ** 2))[:, None]
g_pair = coeff * diff
np.add.at(grad, pairs[:, 0], g_pair)
np.add.at(grad, pairs[:, 1], -g_pair)
Y -= lr * np.clip(grad, -5.0, 5.0)
Y -= np.mean(Y, axis=0)
self.embedding_ = Y
return Y.copy()
def trustworthiness_at_k(X_high: np.ndarray, Y_low: np.ndarray, k: int = 10) -> float:
"""Tier 1 Reference Venna-Kaski Trustworthiness@k (penalizes false 2D neighbors)."""
n = X_high.shape[0]
k_eff = min(k, max(1, (n - 1) // 2 - 1))
d_hi = cdist(X_high, X_high, metric="euclidean")
d_lo = cdist(Y_low, Y_low, metric="euclidean")
np.fill_diagonal(d_hi, float("inf"))
np.fill_diagonal(d_lo, float("inf"))
ranks_hi = np.argsort(np.argsort(d_hi, axis=1), axis=1) + 1
nn_hi = np.argsort(d_hi, axis=1)[:, :k_eff]
nn_lo = np.argsort(d_lo, axis=1)[:, :k_eff]
penalty = 0.0
for i in range(n):
hi_set = set(int(v) for v in nn_hi[i])
for j in nn_lo[i]:
j_int = int(j)
if j_int not in hi_set:
penalty += float(ranks_hi[i, j_int] - k_eff)
denom = n * k_eff * (2.0 * n - 3.0 * k_eff - 1.0)
if denom <= 0.0:
return 1.0
return float(1.0 - (2.0 / denom) * penalty)
def continuity_at_k(X_high: np.ndarray, Y_low: np.ndarray, k: int = 10) -> float:
"""Tier 1 Reference Continuity@k (penalizes torn true high-D neighborhoods)."""
return trustworthiness_at_k(Y_low, X_high, k=k)
def evaluate_manifold_preservation(X_high: np.ndarray, Y_low: np.ndarray, k: int = 10) -> dict[str, float]:
"""Compute Trustworthiness@k, Continuity@k, and Global Spearman Distance Correlation."""
trust = trustworthiness_at_k(X_high, Y_low, k=k)
cont = continuity_at_k(X_high, Y_low, k=k)
d_hi = cdist(X_high, X_high, metric="euclidean")
d_lo = cdist(Y_low, Y_low, metric="euclidean")
tri_idx = np.triu_indices(X_high.shape[0], k=1)
rho_s = float(spearmanr(d_hi[tri_idx], d_lo[tri_idx]).statistic)
return {
"trustworthiness_k": round(trust, 4),
"continuity_k": round(cont, 4),
"global_spearman_rho": round(rho_s, 4),
}
def audit_tsne_clustering_distortion(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Contrast global preservation across PCA, t-SNE & PaCMAP + expose clustering on t-SNE."""
rng = np.random.default_rng(seed)
n_per = 45 if quick else 70
d_hi = 12
# Create 4 separated clusters in R^12 with distinct radii & inter-cluster scales
centers = np.zeros((4, d_hi), dtype=np.float64)
centers[0, :3] = [0.0, 0.0, 0.0]
centers[1, :3] = [2.6, 0.0, 0.0]
centers[2, :3] = [12.0, 12.0, 0.0]
centers[3, :3] = [-11.0, 14.0, 2.0]
scales = [0.35, 0.35, 1.40, 0.50]
X_list, y_list = [], []
for c in range(4):
X_list.append(rng.normal(loc=centers[c], scale=scales[c], size=(n_per, d_hi)))
y_list.append(np.full(n_per, c, dtype=np.int64))
X_hi = np.vstack(X_list)
y_true = np.concatenate(y_list)
Z_pca = PCAReference(n_components=2).fit_transform(X_hi)
Z_lap = LaplacianEigenmapsReference(n_components=2, n_neighbors=10, gamma=0.25).fit_transform(X_hi)
Z_tsne_ref = NeighborEmbeddingReference(
mode="tsne", config=ManifoldConfig(perplexity=20.0, n_iter=180, seed=seed)
).fit_transform(X_hi)
Z_pacmap_ref = NeighborEmbeddingReference(
mode="pacmap", config=ManifoldConfig(n_neighbors=8, n_iter=180, seed=seed)
).fit_transform(X_hi)
Z_tsne_sk = TSNE(
n_components=2, perplexity=20.0, init="pca", learning_rate="auto", random_state=seed
).fit_transform(X_hi)
m_pca = evaluate_manifold_preservation(X_hi, Z_pca, k=10)
m_lap = evaluate_manifold_preservation(X_hi, Z_lap, k=10)
m_tsne_ref = evaluate_manifold_preservation(X_hi, Z_tsne_ref, k=10)
m_pacmap_ref = evaluate_manifold_preservation(X_hi, Z_pacmap_ref, k=10)
m_tsne_sk = evaluate_manifold_preservation(X_hi, Z_tsne_sk, k=10)
sk_trust_tsne = float(sklearn_trustworthiness(X_hi, Z_tsne_sk, n_neighbors=10))
# Measure intra-cluster diameter ratio distortion: Cluster 2 is 4.0x wider than Cluster 0 in R^12!
def _spread_ratio(Z: np.ndarray) -> float:
r0 = float(np.mean(np.linalg.norm(Z[y_true == 0] - np.mean(Z[y_true == 0], axis=0), axis=1)))
r2 = float(np.mean(np.linalg.norm(Z[y_true == 2] - np.mean(Z[y_true == 2], axis=0), axis=1)))
return r2 / max(r0, 1e-12)
true_spread_ratio = _spread_ratio(X_hi)
pca_spread_ratio = _spread_ratio(Z_pca)
tsne_spread_ratio = _spread_ratio(Z_tsne_sk)
# Also compare non-convex Two-Moons + varying density clustering (Tier 1 & Tier 2)
shapes = generate_nonconvex_two_moons_and_density_cohorts(
n_moons=220 if quick else 320,
n_density=210 if quick else 300,
seed=seed,
)
X_moons, y_moons = shapes["X_moons"], shapes["y_moons"]
km_moons = KMeansPlusPlus(RFMClusteringConfig(n_clusters=2, seed=seed)).fit_predict(X_moons)
db_moons = DBSCANReference(eps=0.22, min_samples=5).fit_predict(X_moons)
hdb_ref_moons = HDBSCANHierarchyReference(min_samples=5, min_cluster_size=12).fit_predict(X_moons)
hdb_sk_moons = HDBSCAN(min_samples=5, min_cluster_size=12, copy=True).fit_predict(X_moons)
X_dens, y_dens = shapes["X_density"], shapes["y_density"]
db_dens = DBSCANReference(eps=0.35, min_samples=5).fit_predict(X_dens)
hdb_ref_dens = HDBSCANHierarchyReference(min_samples=5, min_cluster_size=12).fit_predict(X_dens)
hdb_sk_dens = HDBSCAN(min_samples=5, min_cluster_size=12, copy=True).fit_predict(X_dens)
sk_db_moons = DBSCAN(eps=0.22, min_samples=5).fit_predict(X_moons)
db_pos = db_moons >= 0
sil_db = float(silhouette_score(X_moons[db_pos], db_moons[db_pos]))
return {
"pca_metrics": m_pca,
"laplacian_metrics": m_lap,
"tsne_ref_metrics": m_tsne_ref,
"tsne_sklearn_metrics": m_tsne_sk,
"pacmap_ref_metrics": m_pacmap_ref,
"sklearn_trustworthiness_tsne": round(sk_trust_tsne, 4),
"true_cluster2_to_cluster0_radius_ratio": round(true_spread_ratio, 3),
"pca_cluster2_to_cluster0_radius_ratio": round(pca_spread_ratio, 3),
"tsne_cluster2_to_cluster0_radius_ratio": round(tsne_spread_ratio, 3),
"two_moons_kmeans_ari": round(adjusted_rand_index_ref(y_moons, km_moons), 4),
"two_moons_kmeans_silhouette": round(silhouette_score_ref(X_moons, km_moons), 4),
"two_moons_dbscan_ari": round(adjusted_rand_index_ref(y_moons, db_moons), 4),
"two_moons_dbscan_tier2_parity_ari": round(float(adjusted_rand_score(db_moons, sk_db_moons)), 4),
"two_moons_dbscan_silhouette": round(sil_db, 4),
"two_moons_hdbscan_ref_ari": round(adjusted_rand_index_ref(y_moons, hdb_ref_moons), 4),
"two_moons_hdbscan_sk_ari": round(adjusted_rand_index_ref(y_moons, hdb_sk_moons), 4),
"varying_density_dbscan_ari": round(adjusted_rand_index_ref(y_dens, db_dens), 4),
"varying_density_hdbscan_ref_ari": round(adjusted_rand_index_ref(y_dens, hdb_ref_dens), 4),
"varying_density_hdbscan_sk_ari": round(adjusted_rand_index_ref(y_dens, hdb_sk_dens), 4),
}
"""Multi-Touch Attribution (Markov, Exact Shapley), CUPED & AIPW-DR iROAS experimentation."""
from __future__ import annotations
import itertools
import math
from typing import Any
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.model_selection import KFold
from marketing_seg_mta_lab.clustering_and_manifolds import (
audit_rfm_scaling_and_oot_stability,
audit_tsne_clustering_distortion,
)
class MarkovMTAConfig(BaseModel):
"""Strict configuration for Absorbing Markov & Exact Shapley MTA."""
model_config = ConfigDict(frozen=True, extra="forbid")
channels: tuple[str, ...] = ("Paid Search", "Social", "Display", "Email", "Organic")
min_transition_smoothing: float = Field(default=1e-9, ge=0.0)
seed: int = Field(default=42, ge=0)
class ExperimentationConfig(BaseModel):
"""Strict configuration for CUPED and Cross-Fitted AIPW-DR iROAS."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_users: int = Field(default=3200, ge=200, le=200000)
ad_cost_per_treated: float = Field(default=18.0, gt=0.0)
n_folds: int = Field(default=5, ge=2, le=20)
propensity_clip: float = Field(default=0.04, gt=0.0, lt=0.45)
seed: int = Field(default=42, ge=0)
def generate_multi_channel_journeys(
n_journeys: int = 4000,
channels: tuple[str, ...] = ("Paid Search", "Social", "Display", "Email", "Organic"),
seed: int = 42,
) -> tuple[list[dict[str, Any]], dict[str, float]]:
"""Simulate customer touchpoint journeys with brand-search interception & upper-funnel lift."""
rng = np.random.default_rng(seed)
# True incremental structural contributions (Paid Search is largely bottom-funnel capture!)
true_channel_weights = {
"Display": 0.28,
"Social": 0.26,
"Email": 0.22,
"Organic": 0.14,
"Paid Search": 0.10,
}
true_shares = {ch: true_channel_weights[ch] for ch in channels}
journeys: list[dict[str, Any]] = []
for _ in range(n_journeys):
# Upper-funnel discovery channels frequently appear early in path
path: list[str] = []
latent_intent = rng.normal(0.0, 0.5)
has_display = bool(rng.uniform() < 0.36)
has_social = bool(rng.uniform() < 0.38)
has_email = bool(rng.uniform() < 0.34)
has_organic = bool(rng.uniform() < 0.30)
if has_display:
path.append("Display")
latent_intent += 0.95
if has_social:
path.append("Social")
latent_intent += 0.90
if has_organic:
path.append("Organic")
latent_intent += 0.45
if has_email:
path.append("Email")
latent_intent += 0.78
# High-intent users intercept Brand Paid Search at the end of their journey!
p_brand_search = 1.0 / (1.0 + math.exp(-(latent_intent - 0.35)))
has_search = bool(rng.uniform() < p_brand_search)
if has_search:
path.append("Paid Search")
latent_intent += 0.25 # small true incremental lift despite high last-touch frequency!
if not path:
first_ch = str(rng.choice(list(channels), p=[0.20, 0.22, 0.22, 0.18, 0.18]))
path.append(first_ch)
# Synergy boost when upper-funnel + nurturing work together
synergy = 0.45 if (has_display and has_email) or (has_social and has_email) else 0.0
conv_logit = -1.75 + 0.85 * (latent_intent + synergy)
p_conv = 1.0 / (1.0 + math.exp(-conv_logit))
converted = bool(rng.uniform() < p_conv)
journeys.append({"path": path, "converted": converted})
return journeys, true_shares
def compute_last_touch_attribution(
journeys: list[dict[str, Any]],
channels: tuple[str, ...],
) -> dict[str, float]:
"""Compute Last-Touch attribution shares across converting journeys."""
counts = {ch: 0.0 for ch in channels}
for j in journeys:
if j["converted"] and j["path"]:
last_ch = j["path"][-1]
if last_ch in counts:
counts[last_ch] += 1.0
total = max(sum(counts.values()), 1e-12)
return {ch: round(counts[ch] / total, 6) for ch in channels}
def compute_first_touch_attribution(
journeys: list[dict[str, Any]],
channels: tuple[str, ...],
) -> dict[str, float]:
"""Compute First-Touch attribution shares across converting journeys."""
counts = {ch: 0.0 for ch in channels}
for j in journeys:
if j["converted"] and j["path"]:
first_ch = j["path"][0]
if first_ch in counts:
counts[first_ch] += 1.0
total = max(sum(counts.values()), 1e-12)
return {ch: round(counts[ch] / total, 6) for ch in channels}
class AbsorbingMarkovMTA:
"""First-order Absorbing Markov Chain Attribution with Fundamental Matrix N=(I-Q)^(-1)."""
def __init__(self, config: MarkovMTAConfig | None = None) -> None:
self.config = config or MarkovMTAConfig()
self.states: list[str] = ["Start", *self.config.channels, "Conversion", "Null"]
self.state_idx: dict[str, int] = {s: i for i, s in enumerate(self.states)}
self.transition_matrix_: np.ndarray | None = None
self.Q_: np.ndarray | None = None
self.R_: np.ndarray | None = None
self.fundamental_matrix_: np.ndarray | None = None
self.base_conversion_prob_: float = 0.0
self.removal_effects_: dict[str, float] = {}
self.attribution_shares_: dict[str, float] = {}
def fit(self, journeys: list[dict[str, Any]]) -> AbsorbingMarkovMTA:
n_states = len(self.states)
counts = np.zeros((n_states, n_states), dtype=np.float64)
for j in journeys:
seq = ["Start", *j["path"], "Conversion" if j["converted"] else "Null"]
for a, b in zip(seq[:-1], seq[1:], strict=True):
if a in self.state_idx and b in self.state_idx:
counts[self.state_idx[a], self.state_idx[b]] += 1.0
# Absorbing rows stay fixed at identity
conv_i = self.state_idx["Conversion"]
null_i = self.state_idx["Null"]
counts[conv_i, :] = 0.0
counts[conv_i, conv_i] = 1.0
counts[null_i, :] = 0.0
counts[null_i, null_i] = 1.0
P = np.zeros_like(counts)
for i in range(n_states):
row_sum = float(np.sum(counts[i]))
if row_sum <= 0.0:
P[i, null_i] = 1.0
else:
P[i] = counts[i] / row_sum
n_trans = n_states - 2
Q = P[:n_trans, :n_trans]
R = P[:n_trans, n_trans:]
N_mat = np.linalg.inv(np.eye(n_trans) - Q)
B = N_mat @ R
self.transition_matrix_ = P
self.Q_ = Q
self.R_ = R
self.fundamental_matrix_ = N_mat
self.base_conversion_prob_ = float(B[0, 0])
removal: dict[str, float] = {}
for ch in self.config.channels:
c_idx = self.state_idx[ch]
P_rem = P.copy()
# Redirect all incoming transitions to ch directly to Null, and absorb ch -> Null
for row_i in range(n_trans):
if row_i == c_idx:
P_rem[row_i, :] = 0.0
P_rem[row_i, null_i] = 1.0
else:
mass = P_rem[row_i, c_idx]
P_rem[row_i, c_idx] = 0.0
P_rem[row_i, null_i] += mass
Q_rem = P_rem[:n_trans, :n_trans]
R_rem = P_rem[:n_trans, n_trans:]
B_rem = np.linalg.solve(np.eye(n_trans) - Q_rem, R_rem)
p_rem = float(B_rem[0, 0])
eff = max(0.0, 1.0 - p_rem / max(self.base_conversion_prob_, 1e-12))
removal[ch] = eff
tot_eff = max(sum(removal.values()), 1e-12)
self.removal_effects_ = {ch: round(removal[ch], 6) for ch in self.config.channels}
self.attribution_shares_ = {
ch: round(removal[ch] / tot_eff, 6) for ch in self.config.channels
}
return self
class ExactShapleyMTA:
"""Exact Cooperative Game Shapley Attribution over all 2^M channel coalitions."""
def __init__(self, channels: tuple[str, ...]) -> None:
self.channels = channels
self.coalition_values_: dict[frozenset[str], float] = {}
self.shapley_values_: dict[str, float] = {}
self.attribution_shares_: dict[str, float] = {}
self.grand_coalition_value_: float = 0.0
def fit_from_coalition_fn(
self,
coalition_fn: Any,
) -> ExactShapleyMTA:
"""Compute exact Shapley values directly from any coalition value callable v(S)."""
m = len(self.channels)
values: dict[frozenset[str], float] = {}
for r in range(m + 1):
for comb in itertools.combinations(self.channels, r):
S = frozenset(comb)
values[S] = 0.0 if not S else float(coalition_fn(S))
self.coalition_values_ = values
self.grand_coalition_value_ = values[frozenset(self.channels)]
phi: dict[str, float] = {}
fact = [math.factorial(i) for i in range(m + 1)]
denom = float(fact[m])
for ch in self.channels:
others = [c for c in self.channels if c != ch]
total_contrib = 0.0
for r in range(m):
weight = (fact[r] * fact[m - r - 1]) / denom
for comb in itertools.combinations(others, r):
S = frozenset(comb)
S_plus = S | {ch}
total_contrib += weight * (values[S_plus] - values[S])
phi[ch] = total_contrib
self.shapley_values_ = phi
pos_sum = max(sum(max(v, 0.0) for v in phi.values()), 1e-12)
self.attribution_shares_ = {
ch: round(max(phi[ch], 0.0) / pos_sum, 6) for ch in self.channels
}
return self
def fit(self, journeys: list[dict[str, Any]]) -> ExactShapleyMTA:
"""Fit a logistic conversion counterfactual v(S) from journeys and solve exact Shapley."""
m = len(self.channels)
X = np.zeros((len(journeys), m), dtype=np.float64)
y = np.zeros(len(journeys), dtype=np.int64)
ch_to_idx = {ch: i for i, ch in enumerate(self.channels)}
for row_i, j in enumerate(journeys):
for touch in j["path"]:
if touch in ch_to_idx:
X[row_i, ch_to_idx[touch]] = 1.0
y[row_i] = 1 if j["converted"] else 0
clf = LogisticRegression(C=2.0, max_iter=500, random_state=42).fit(X, y)
base_prob_empty = float(clf.predict_proba(np.zeros((1, m), dtype=np.float64))[0, 1])
def _coalition_lift(S: frozenset[str]) -> float:
mask = np.array([1.0 if ch in S else 0.0 for ch in self.channels], dtype=np.float64)
X_masked = X * mask[None, :]
mean_p = float(np.mean(clf.predict_proba(X_masked)[:, 1]))
return max(0.0, mean_p - base_prob_empty)
return self.fit_from_coalition_fn(_coalition_lift)
def generate_marketing_ab_experiment(
n_users: int = 3200,
ad_cost_per_treated: float = 18.0,
seed: int = 42,
) -> dict[str, Any]:
"""Generate (1) randomized A/B holdout for CUPED and (2) biased observational cohort for iROAS."""
rng = np.random.default_rng(seed)
# 1. Randomized A/B Holdout (W independent of pre-experiment covariates)
pre_spend = np.exp(rng.normal(4.3, 0.55, size=n_users)) # pre-experiment spend correlated with post
engagement = rng.normal(0.0, 1.0, size=n_users)
w_rand = rng.binomial(1, 0.5, size=n_users)
true_ate_ab = 11.5
noise_ab = rng.normal(0.0, 26.0, size=n_users)
y_post_ab = 20.0 + 0.85 * pre_spend + 12.0 * engagement + true_ate_ab * w_rand + noise_ab
ab_df = pd.DataFrame(
{
"pre_spend_30d": pre_spend,
"engagement": engagement,
"treated": w_rand,
"post_spend": y_post_ab,
}
)
# 2. Observational Brand-Search Campaign (Strong Positive Selection Bias!)
pre_obs = np.exp(rng.normal(4.1, 0.50, size=n_users))
eng_obs = rng.normal(0.0, 1.0, size=n_users)
intent = 0.70 * ((pre_obs - np.mean(pre_obs)) / np.std(pre_obs)) + 0.75 * eng_obs
prop_true = 1.0 / (1.0 + np.exp(-(0.95 * intent)))
w_obs = rng.binomial(1, prop_true)
# True causal increment is modest (~$33.3 => true iROAS ~1.85); organic baseline rises w/ intent
mu0 = 45.0 + 0.65 * pre_obs + 42.0 * np.maximum(intent, -1.5)
tau_i = 33.3 + 4.0 * np.tanh(eng_obs)
y0_obs = mu0 + rng.normal(0.0, 16.0, size=n_users)
y1_obs = y0_obs + tau_i
y_obs = np.where(w_obs == 1, y1_obs, y0_obs)
obs_df = pd.DataFrame(
{
"pre_spend_30d": pre_obs,
"engagement": eng_obs,
"intent_proxy": intent,
"treated": w_obs,
"revenue": y_obs,
"true_tau": tau_i,
}
)
return {
"ab_df": ab_df,
"true_ate_ab": true_ate_ab,
"obs_df": obs_df,
"true_ate_obs": float(np.mean(tau_i)),
"true_iroas_obs": float(np.mean(tau_i) / ad_cost_per_treated),
"ad_cost_per_treated": ad_cost_per_treated,
}
def estimate_cuped_ate(ab_df: pd.DataFrame) -> dict[str, float]:
"""Estimate CUPED variance-reduced ATE (Deng et al. WSDM 2013) on randomized A/B test."""
y = ab_df["post_spend"].to_numpy(dtype=np.float64)
x_pre = ab_df["pre_spend_30d"].to_numpy(dtype=np.float64)
w = ab_df["treated"].to_numpy(dtype=np.int64)
# Optimal pooled theta = Cov(Y, X_pre) / Var(X_pre)
cov_yx = float(np.cov(y, x_pre, ddof=1)[0, 1])
var_x = float(np.var(x_pre, ddof=1))
theta = cov_yx / max(var_x, 1e-12)
y_cuped = y - theta * (x_pre - float(np.mean(x_pre)))
m1 = w == 1
m0 = w == 0
ate_raw = float(np.mean(y[m1]) - np.mean(y[m0]))
ate_cuped = float(np.mean(y_cuped[m1]) - np.mean(y_cuped[m0]))
var_ate_raw = float(np.var(y[m1], ddof=1) / np.sum(m1) + np.var(y[m0], ddof=1) / np.sum(m0))
var_ate_cuped = float(
np.var(y_cuped[m1], ddof=1) / np.sum(m1) + np.var(y_cuped[m0], ddof=1) / np.sum(m0)
)
var_red_pct = 100.0 * (1.0 - var_ate_cuped / max(var_ate_raw, 1e-12))
rho_yx = float(np.corrcoef(y, x_pre)[0, 1])
return {
"theta_cuped": round(theta, 4),
"rho_y_xpre": round(rho_yx, 4),
"raw_ate": round(ate_raw, 4),
"cuped_ate": round(ate_cuped, 4),
"raw_se": round(math.sqrt(var_ate_raw), 4),
"cuped_se": round(math.sqrt(var_ate_cuped), 4),
"variance_reduction_pct": round(var_red_pct, 2),
}
def _fit_cross_fitted_aipw_ate(
X: np.ndarray,
w: np.ndarray,
y: np.ndarray,
n_folds: int = 5,
propensity_clip: float = 0.04,
seed: int = 42,
) -> tuple[float, float]:
"""Estimate ATE and standard error via 5-fold cross-fitted AIPW Doubly Robust score."""
kf = KFold(n_splits=n_folds, shuffle=True, random_state=seed)
mu0_hat = np.zeros_like(y, dtype=np.float64)
mu1_hat = np.zeros_like(y, dtype=np.float64)
e_hat = np.zeros_like(y, dtype=np.float64)
for tr_idx, va_idx in kf.split(X):
X_tr, w_tr, y_tr = X[tr_idx], w[tr_idx], y[tr_idx]
X_va = X[va_idx]
m0_reg = Ridge(alpha=1.0).fit(X_tr[w_tr == 0], y_tr[w_tr == 0])
m1_reg = Ridge(alpha=1.0).fit(X_tr[w_tr == 1], y_tr[w_tr == 1])
prop_clf = LogisticRegression(C=2.0, max_iter=500, random_state=seed).fit(X_tr, w_tr)
mu0_hat[va_idx] = m0_reg.predict(X_va)
mu1_hat[va_idx] = m1_reg.predict(X_va)
probs = prop_clf.predict_proba(X_va)[:, 1]
e_hat[va_idx] = np.clip(probs, propensity_clip, 1.0 - propensity_clip)
psi = (
(mu1_hat - mu0_hat)
+ w * (y - mu1_hat) / e_hat
- (1 - w) * (y - mu0_hat) / (1.0 - e_hat)
)
tau_dr = float(np.mean(psi))
se_dr = float(np.std(psi, ddof=1) / math.sqrt(len(psi)))
return tau_dr, se_dr
def evaluate_multichannel_holdout_iroas(
n_obs: int = 3600,
n_holdout: int = 3600,
n_folds: int = 5,
propensity_clip: float = 0.04,
seed: int = 42,
) -> dict[str, Any]:
"""Estimate channel iROAS via LT vs AIPW-DR on multi-channel logs, then run a genuine holdout test."""
channels = ("Brand Search", "Display", "Social")
costs = {"Brand Search": 20.0, "Display": 16.0, "Social": 16.0}
rng = np.random.default_rng(seed + 17)
pre_obs = np.exp(rng.normal(4.1, 0.50, size=n_obs))
eng_obs = rng.normal(0.0, 1.0, size=n_obs)
intent_obs = 0.70 * ((pre_obs - np.mean(pre_obs)) / np.std(pre_obs)) + 0.75 * eng_obs
X_obs = np.column_stack([pre_obs, eng_obs, intent_obs])
y0_obs = (
45.0 + 0.65 * pre_obs + 38.0 * np.maximum(intent_obs, -1.5) + rng.normal(0.0, 14.0, size=n_obs)
)
# Multi-channel exposures & true lifts: Brand Search captures high organic-intent clicks;
# Display and Social drive genuine positive net lift.
p_brand = 1.0 / (1.0 + np.exp(-(-0.15 + 1.45 * intent_obs)))
p_disp = 1.0 / (1.0 + np.exp(-(-0.55 - 0.55 * intent_obs + 0.35 * eng_obs)))
p_soc = 1.0 / (1.0 + np.exp(-(-0.45 - 0.45 * intent_obs + 0.45 * eng_obs)))
exposures = {
"Brand Search": rng.binomial(1, p_brand),
"Display": rng.binomial(1, p_disp),
"Social": rng.binomial(1, p_soc),
}
lifts = {
"Brand Search": 15.0 + 2.0 * np.tanh(eng_obs),
"Display": 37.6 + 3.0 * np.tanh(eng_obs),
"Social": 35.2 + 3.0 * np.tanh(eng_obs),
}
y_obs = y0_obs + sum(exposures[c] * lifts[c] for c in channels)
# Last-Touch attribution priority near checkout favors Brand Search over upper-funnel exposures
lt_arr = np.where(
exposures["Brand Search"] == 1,
0,
np.where(exposures["Social"] == 1, 2, np.where(exposures["Display"] == 1, 1, -1)),
)
lt_roas: dict[str, float] = {}
dr_iroas: dict[str, float] = {}
dr_se_iroas: dict[str, float] = {}
for c_idx, ch in enumerate(channels):
w_c = exposures[ch].astype(np.int64)
lt_mask = lt_arr == c_idx
lt_rev_per_click = float(np.sum(y_obs[lt_mask]) / max(int(np.sum(w_c)), 1))
lt_roas[ch] = round(lt_rev_per_click / costs[ch], 4)
tau_c, se_c = _fit_cross_fitted_aipw_ate(
X_obs,
w_c,
y_obs,
n_folds=n_folds,
propensity_clip=propensity_clip,
seed=seed + 31 + c_idx,
)
dr_iroas[ch] = round(tau_c / costs[ch], 4)
dr_se_iroas[ch] = round(se_c / costs[ch], 4)
lt_best = max(channels, key=lambda c: lt_roas[c])
lt_weights = {c: (1.0 if c == lt_best else 0.0) for c in channels}
excess_dr = {c: max(dr_iroas[c] - 1.0, 0.0) for c in channels}
tot_excess = sum(excess_dr.values())
if tot_excess <= 1e-12:
best_dr = max(channels, key=lambda c: dr_iroas[c])
dr_weights = {c: (1.0 if c == best_dr else 0.0) for c in channels}
else:
dr_weights = {c: round(excess_dr[c] / tot_excess, 6) for c in channels}
# Independent out-of-sample randomized holdout evaluation (50/50 RCT per policy)
rng_h = np.random.default_rng(seed + 101)
pre_h = np.exp(rng_h.normal(4.1, 0.50, size=n_holdout))
eng_h = rng_h.normal(0.0, 1.0, size=n_holdout)
intent_h = 0.70 * ((pre_h - np.mean(pre_h)) / np.std(pre_h)) + 0.75 * eng_h
y0_h = 45.0 + 0.65 * pre_h + 38.0 * np.maximum(intent_h, -1.5) + rng_h.normal(0.0, 14.0, size=n_holdout)
lifts_h = np.column_stack(
[
15.0 + 2.0 * np.tanh(eng_h),
37.6 + 3.0 * np.tanh(eng_h),
35.2 + 3.0 * np.tanh(eng_h),
]
)
cost_vec = np.array([costs[c] for c in channels], dtype=np.float64)
def _run_holdout_arm(weights: dict[str, float], arm_seed: int) -> float:
r_arm = np.random.default_rng(arm_seed)
w_rct = r_arm.binomial(1, 0.5, size=n_holdout)
probs = np.array([weights[c] for c in channels], dtype=np.float64)
probs = probs / np.sum(probs)
ch_draw = r_arm.choice(len(channels), size=n_holdout, p=probs)
y_arm = y0_h + w_rct * lifts_h[np.arange(n_holdout), ch_draw]
lift_est = float(np.mean(y_arm[w_rct == 1]) - np.mean(y_arm[w_rct == 0]))
mean_cost = float(np.mean(cost_vec[ch_draw[w_rct == 1]]))
return round(lift_est / max(mean_cost, 1e-12), 4)
return {
"channels": list(channels),
"lt_observed_roas": lt_roas,
"dr_estimated_iroas": dr_iroas,
"dr_estimated_se": dr_se_iroas,
"lt_policy_weights": lt_weights,
"dr_policy_weights": dr_weights,
"lt_policy_holdout_iroas": _run_holdout_arm(lt_weights, seed + 201),
"dr_policy_holdout_iroas": _run_holdout_arm(dr_weights, seed + 202),
}
def estimate_iroas_aipw_dr(
obs_df: pd.DataFrame,
ad_cost_per_treated: float = 18.0,
n_folds: int = 5,
propensity_clip: float = 0.04,
seed: int = 42,
) -> dict[str, float]:
"""Cross-fitted AIPW Doubly Robust iROAS vs Naive / Last-Touch Selection-Biased ROAS."""
X = obs_df.loc[:, ["pre_spend_30d", "engagement", "intent_proxy"]].to_numpy(dtype=np.float64)
w = obs_df["treated"].to_numpy(dtype=np.int64)
y = obs_df["revenue"].to_numpy(dtype=np.float64)
# Naive difference-in-means & unadjusted Last-Touch checkout ROAS (both severe selection bias)
naive_diff = float(np.mean(y[w == 1]) - np.mean(y[w == 0]))
naive_iroas_diff = naive_diff / ad_cost_per_treated
last_touch_roas = float(np.mean(y[w == 1]) / ad_cost_per_treated)
tau_dr, se_dr = _fit_cross_fitted_aipw_ate(
X,
w,
y,
n_folds=n_folds,
propensity_clip=propensity_clip,
seed=seed,
)
iroas_dr = tau_dr / ad_cost_per_treated
mc_holdout = evaluate_multichannel_holdout_iroas(
n_obs=max(len(obs_df), 2400),
n_holdout=max(len(obs_df), 2400),
n_folds=n_folds,
propensity_clip=propensity_clip,
seed=seed,
)
return {
"naive_diff_ate": round(naive_diff, 4),
"naive_diff_roas": round(naive_iroas_diff, 4),
"last_touch_biased_roas": round(last_touch_roas, 4),
"aipw_dr_ate": round(tau_dr, 4),
"aipw_dr_se": round(se_dr, 4),
"iroas_dr": round(iroas_dr, 4),
"lt_policy_holdout_iroas": float(mc_holdout["lt_policy_holdout_iroas"]),
"dr_policy_holdout_iroas": float(mc_holdout["dr_policy_holdout_iroas"]),
}
def run_full_lab04_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run complete Lab 04 benchmarks and assemble workbench_panels for chapter.html."""
rfm_res = audit_rfm_scaling_and_oot_stability(seed=seed, quick=quick)
manifold_res = audit_tsne_clustering_distortion(seed=seed, quick=quick)
cfg_mta = MarkovMTAConfig(seed=seed)
n_journeys = 2000 if quick else 4000
journeys, true_shares = generate_multi_channel_journeys(
n_journeys=n_journeys, channels=cfg_mta.channels, seed=seed
)
lt_shares = compute_last_touch_attribution(journeys, cfg_mta.channels)
ft_shares = compute_first_touch_attribution(journeys, cfg_mta.channels)
markov = AbsorbingMarkovMTA(cfg_mta).fit(journeys)
shapley = ExactShapleyMTA(cfg_mta.channels).fit(journeys)
# Compare L1 deviation against true structural shares
def _l1_err(pred: dict[str, float]) -> float:
return round(sum(abs(pred[c] - true_shares[c]) for c in cfg_mta.channels), 4)
lt_l1 = _l1_err(lt_shares)
mk_l1 = _l1_err(markov.attribution_shares_)
sh_l1 = _l1_err(shapley.attribution_shares_)
exp_cfg = ExperimentationConfig(n_users=1800 if quick else 3200, seed=seed)
exp_data = generate_marketing_ab_experiment(
n_users=exp_cfg.n_users,
ad_cost_per_treated=exp_cfg.ad_cost_per_treated,
seed=seed,
)
cuped_res = estimate_cuped_ate(exp_data["ab_df"])
iroas_res = estimate_iroas_aipw_dr(
exp_data["obs_df"],
ad_cost_per_treated=exp_cfg.ad_cost_per_treated,
n_folds=exp_cfg.n_folds,
propensity_clip=exp_cfg.propensity_clip,
seed=seed,
)
true_iroas = round(float(exp_data["true_iroas_obs"]), 4)
shap_eff_diff = abs(
sum(shapley.shapley_values_.values()) - shapley.grand_coalition_value_
)
# Assemble canonical workbench_panels (6 KPIs, 4 Bars, 4 Tables)
sil_km = manifold_res["two_moons_kmeans_silhouette"]
sil_db = manifold_res["two_moons_dbscan_silhouette"]
dens_hdb = manifold_res["varying_density_hdbscan_ref_ari"]
tsne_m = manifold_res["tsne_ref_metrics"]
pac_m = manifold_res["pacmap_ref_metrics"]
pca_m = manifold_res["pca_metrics"]
lap_m = manifold_res["laplacian_metrics"]
r_true = manifold_res["true_cluster2_to_cluster0_radius_ratio"]
r_tsne = manifold_res["tsne_cluster2_to_cluster0_radius_ratio"]
kpis = [
{
"id": "kpi_rfm_scaling_rescue",
"label": "RFM Scaling Trap Rescue (ARI)",
"value": (
f"{rfm_res['raw_kmeans_train_ari']:.3f} -> "
f"{rfm_res['scaled_kmeans_train_ari']:.3f}"
),
"unit": "Train ARI",
"status": "ok",
"detail": (
f"Raw Monetary variance={rfm_res['monetary_raw_variance_share']:.4%}; "
f"log1p+RobustScaler boosts K-Means++ ARI & GMM ARI={rfm_res['gmm_train_ari']:.3f}."
),
},
{
"id": "kpi_oot_cluster_stability",
"label": "Out-of-Time (OOT) Cluster Stability",
"value": f"ARI {rfm_res['oot_frozen_vs_refit_stability_ari']:.3f}",
"unit": f"(Truth {rfm_res['oot_frozen_vs_truth_ari']:.3f})",
"status": "ok",
"detail": (
f"Temporal split train_day<={rfm_res['train_max_day']} < "
f"oot_day>={rfm_res['oot_min_day']}; GMM OOT ARI={rfm_res['gmm_oot_ari']:.3f}, "
f"min EM ELBO delta={rfm_res['gmm_min_elbo_delta']:.1e}."
),
},
{
"id": "kpi_nonconvex_hdbscan_vs_kmeans",
"label": "Two-Moons & Density HDBSCAN vs KMeans",
"value": (
f"HDBSCAN {manifold_res['two_moons_hdbscan_ref_ari']:.3f} vs "
f"KM {manifold_res['two_moons_kmeans_ari']:.3f}"
),
"unit": "ARI",
"status": "ok",
"detail": (
f"Silhouette trap: K-Means={sil_km:.3f} > DBSCAN={sil_db:.3f} "
f"despite K-Means failing crescents; Varying-Density HDBSCAN ARI={dens_hdb:.3f}."
),
},
{
"id": "kpi_manifold_local_vs_global",
"label": "Manifold Local vs Global Preservation",
"value": f"PaCMAP rho={pac_m['global_spearman_rho']:.3f}",
"unit": f"vs tSNE {tsne_m['global_spearman_rho']:.3f}",
"status": "warn",
"detail": (
f"t-SNE Trust@10={tsne_m['trustworthiness_k']:.3f} but warps cluster radius "
f"({r_true:.2f}x -> {r_tsne:.2f}x); PaCMAP Trust@10={pac_m['trustworthiness_k']:.3f}."
),
},
{
"id": "kpi_markov_shapley_mta",
"label": "Markov & Exact Shapley MTA vs Last-Touch",
"value": f"L1 Err {lt_l1:.3f} -> {mk_l1:.3f}",
"unit": f"(Shapley {sh_l1:.3f})",
"status": "ok",
"detail": (
f"Last-Touch inflates Paid Search to {lt_shares['Paid Search']:.1%} "
f"(true {true_shares['Paid Search']:.1%}); "
f"Markov={markov.attribution_shares_['Paid Search']:.1%}, "
f"Shapley eff diff={shap_eff_diff:.1e}."
),
},
{
"id": "kpi_cuped_and_iroas_dr",
"label": "CUPED Variance Cut & AIPW-DR iROAS",
"value": (
f"-{cuped_res['variance_reduction_pct']:.1f}% Var | "
f"iROAS {iroas_res['iroas_dr']:.2f}x"
),
"unit": f"(True {true_iroas:.2f}x)",
"status": "ok",
"detail": (
f"CUPED cuts SE {cuped_res['raw_se']:.2f}->{cuped_res['cuped_se']:.2f}; "
f"AIPW-DR removes selection bias ({iroas_res['naive_diff_roas']:.2f}x -> "
f"{iroas_res['iroas_dr']:.2f}x) & boosts holdout iROAS "
f"({iroas_res['lt_policy_holdout_iroas']:.2f}x -> "
f"{iroas_res['dr_policy_holdout_iroas']:.2f}x)."
),
},
]
bars = [
{
"id": "bar_clustering_ari_comparison",
"title": "Clustering Recovery (ARI): RFM Scale Trap & Non-Convex Two-Moons",
"metric_label": "ARI",
"items": [
{
"label": "rfm_raw_euclidean_kmeans",
"value": max(rfm_res["raw_kmeans_train_ari"], 1e-3),
"display": f"{rfm_res['raw_kmeans_train_ari']:.3f}",
"css_class": "is-slow",
},
{
"label": "rfm_log1p_robust_kmeans",
"value": rfm_res["scaled_kmeans_train_ari"],
"display": f"{rfm_res['scaled_kmeans_train_ari']:.3f}",
"css_class": "is-fast",
},
{
"label": "rfm_oot_frozen_stability",
"value": rfm_res["oot_frozen_vs_refit_stability_ari"],
"display": f"{rfm_res['oot_frozen_vs_refit_stability_ari']:.3f}",
"css_class": "is-fast",
},
{
"label": "moons_kmeans_failure",
"value": max(manifold_res["two_moons_kmeans_ari"], 1e-3),
"display": f"{manifold_res['two_moons_kmeans_ari']:.3f}",
"css_class": "is-slow",
},
{
"label": "moons_hdbscan_ref",
"value": manifold_res["two_moons_hdbscan_ref_ari"],
"display": f"{manifold_res['two_moons_hdbscan_ref_ari']:.3f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_manifold_global_preservation",
"title": "Manifold Global Distance Preservation (Spearman rho_S) vs Local Trust@10",
"metric_label": "Spearman rho_S",
"items": [
{
"label": "pca_global_spearman",
"value": max(pca_m["global_spearman_rho"], 1e-3),
"display": f"rho={pca_m['global_spearman_rho']:.3f}",
"css_class": "is-fast",
},
{
"label": "pacmap_global_spearman",
"value": max(pac_m["global_spearman_rho"], 1e-3),
"display": (
f"rho={pac_m['global_spearman_rho']:.3f} "
f"(Trust {pac_m['trustworthiness_k']:.2f})"
),
"css_class": "is-fast",
},
{
"label": "tsne_global_spearman",
"value": max(tsne_m["global_spearman_rho"], 1e-3),
"display": (
f"rho={tsne_m['global_spearman_rho']:.3f} "
f"(Trust {tsne_m['trustworthiness_k']:.2f})"
),
"css_class": "is-mid",
},
{
"label": "laplacian_global_spearman",
"value": max(lap_m["global_spearman_rho"], 1e-3),
"display": f"rho={lap_m['global_spearman_rho']:.3f}",
"css_class": "is-mid",
},
],
},
{
"id": "bar_mta_channel_attribution",
"title": "MTA Channel Share Error (L1 vs True Lift) & Paid-Search Over-Credit",
"metric_label": "L1 Error",
"items": [
{
"label": "last_touch_l1_err",
"value": lt_l1,
"display": f"{lt_l1:.3f} (Search={lt_shares['Paid Search']:.1%})",
"css_class": "is-slow",
},
{
"label": "absorbing_markov_l1_err",
"value": mk_l1,
"display": (
f"{mk_l1:.3f} (Search={markov.attribution_shares_['Paid Search']:.1%})"
),
"css_class": "is-fast",
},
{
"label": "exact_shapley_l1_err",
"value": sh_l1,
"display": (
f"{sh_l1:.3f} (Search={shapley.attribution_shares_['Paid Search']:.1%})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_cuped_and_iroas_bias",
"title": (
"Causal Experimentation: Selection-Biased ROAS vs AIPW-DR iROAS "
f"(True ~{true_iroas:.2f}x)"
),
"metric_label": "ROAS / iROAS",
"items": [
{
"label": "naive_observational_diff_roas",
"value": iroas_res["naive_diff_roas"],
"display": f"{iroas_res['naive_diff_roas']:.2f}x (Biased)",
"css_class": "is-slow",
},
{
"label": "last_touch_brand_roas",
"value": iroas_res["last_touch_biased_roas"],
"display": f"{iroas_res['last_touch_biased_roas']:.2f}x (Biased)",
"css_class": "is-slow",
},
{
"label": "aipw_dr_causal_iroas",
"value": iroas_res["iroas_dr"],
"display": f"{iroas_res['iroas_dr']:.2f}x (True {true_iroas:.2f}x)",
"css_class": "is-fast",
},
{
"label": "dr_budget_holdout_iroas",
"value": iroas_res["dr_policy_holdout_iroas"],
"display": (
f"{iroas_res['dr_policy_holdout_iroas']:.2f}x vs "
f"LT {iroas_res['lt_policy_holdout_iroas']:.2f}x"
),
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "table_rfm_clustering_and_oot",
"title": "RFM Segmentation: Raw Scale Trap, Full-Covariance GMM EM & OOT Stability",
"columns": [
"experiment",
"raw_or_baseline",
"remediated_method",
"diagnostic_detail",
"status",
],
"rows": [
[
"rfm_scale_trap",
f"Raw KM ARI={rfm_res['raw_kmeans_train_ari']:.3f}",
f"log1p+Robust ARI={rfm_res['scaled_kmeans_train_ari']:.3f}",
f"Monetary var share={rfm_res['monetary_raw_variance_share']:.2%}",
"SCALE_RESCUED",
],
[
"oot_cluster_stability",
f"Train max_day={rfm_res['train_max_day']}",
f"OOT min_day={rfm_res['oot_min_day']}",
f"Frozen vs Refit ARI={rfm_res['oot_frozen_vs_refit_stability_ari']:.3f}",
"OOT_STABLE_PASS",
],
[
"gmm_em_monotonicity",
f"EM iters={rfm_res['gmm_em_iters']}",
f"OOT ARI={rfm_res['gmm_oot_ari']:.3f}",
f"min delta ELBO={rfm_res['gmm_min_elbo_delta']:.2e}",
"MONOTONIC_ELBO",
],
[
"tier2_sklearn_parity",
f"KM parity ARI={rfm_res['kmeans_tier2_sklearn_parity_ari']:.3f}",
f"GMM parity ARI={rfm_res['gmm_tier2_sklearn_ari']:.3f}",
(
f"Sil={rfm_res['scaled_kmeans_silhouette']:.3f}, "
f"DBI={rfm_res['scaled_kmeans_dbi']:.3f}"
),
"TIER2_PARITY",
],
],
},
{
"id": "table_density_and_manifold_benchmarks",
"title": "Non-Convex / Varying-Density Clustering & Manifold Fidelity Audit",
"columns": [
"benchmark",
"kmeans_or_tsne",
"dbscan_or_pacmap",
"hdbscan_or_pca",
"verdict",
],
"rows": [
[
"two_moons_ari",
f"KMeans ARI={manifold_res['two_moons_kmeans_ari']:.3f}",
f"DBSCAN ARI={manifold_res['two_moons_dbscan_ari']:.3f}",
(
f"HDBSCAN ARI={manifold_res['two_moons_hdbscan_ref_ari']:.3f} "
f"(sk {manifold_res['two_moons_hdbscan_sk_ari']:.3f})"
),
"DENSITY_WINS",
],
[
"varying_density_ari",
"KMeans convex split",
f"DBSCAN fixed-eps={manifold_res['varying_density_dbscan_ari']:.3f}",
f"HDBSCAN EOM={manifold_res['varying_density_hdbscan_ref_ari']:.3f}",
"HDBSCAN_ADAPTIVE",
],
[
"manifold_trust_k10",
f"t-SNE={tsne_m['trustworthiness_k']:.3f}",
f"PaCMAP={pac_m['trustworthiness_k']:.3f}",
f"PCA={pca_m['trustworthiness_k']:.3f}",
"HIGH_LOCAL_FIDELITY",
],
[
"manifold_global_rho",
f"t-SNE={tsne_m['global_spearman_rho']:.3f}",
f"PaCMAP={pac_m['global_spearman_rho']:.3f}",
f"Radius warp t-SNE={r_tsne:.2f}x (True {r_true:.2f}x)",
"NEVER_CLUSTER_TSNE",
],
],
},
{
"id": "table_mta_channel_attribution",
"title": "Multi-Touch Attribution: Last-Touch Bias vs Absorbing Markov & Exact Shapley",
"columns": ["channel", "true_structural", "last_touch", "markov_removal", "exact_shapley"],
"rows": [
[
ch,
f"{true_shares[ch]:.1%}",
f"{lt_shares[ch]:.1%}",
f"{markov.attribution_shares_[ch]:.1%}",
f"{shapley.attribution_shares_[ch]:.1%}",
]
for ch in cfg_mta.channels
],
},
{
"id": "table_cuped_and_iroas_experimentation",
"title": "Marketing Causal Experimentation: CUPED Variance Reduction & AIPW-DR iROAS",
"columns": [
"estimator",
"estimate_or_ate",
"uncertainty_or_roas",
"ground_truth_ref",
"audit_verdict",
],
"rows": [
[
"ab_raw_difference",
f"ATE=${cuped_res['raw_ate']:.2f}",
f"SE=${cuped_res['raw_se']:.2f}",
f"True=${exp_data['true_ate_ab']:.2f}",
"HIGH_VARIANCE",
],
[
"ab_cuped_adjusted",
f"ATE=${cuped_res['cuped_ate']:.2f}",
(
f"SE=${cuped_res['cuped_se']:.2f} "
f"(-{cuped_res['variance_reduction_pct']:.1f}% var)"
),
f"rho={cuped_res['rho_y_xpre']:.3f}",
"CUPED_PASS_GE25",
],
[
"obs_naive_last_touch",
f"Diff=${iroas_res['naive_diff_ate']:.2f}",
(
f"Naive={iroas_res['naive_diff_roas']:.2f}x | "
f"LT={iroas_res['last_touch_biased_roas']:.2f}x"
),
f"True iROAS={true_iroas:.2f}x",
"SELECTION_BIASED",
],
[
"obs_aipw_dr_iroas",
f"ATE_DR=${iroas_res['aipw_dr_ate']:.2f}",
(
f"iROAS_DR={iroas_res['iroas_dr']:.2f}x "
f"(SE=${iroas_res['aipw_dr_se']:.2f})"
),
(
f"Policy {iroas_res['dr_policy_holdout_iroas']:.2f}x > "
f"{iroas_res['lt_policy_holdout_iroas']:.2f}x"
),
"CAUSAL_PARITY_PASS",
],
],
},
]
return {
"config": {"seed": seed, "quick": quick},
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
"rfm_segmentation": rfm_res,
"manifold_and_density": manifold_res,
"mta_attribution": {
"n_journeys": n_journeys,
"base_conversion_prob": round(markov.base_conversion_prob_, 4),
"true_shares": true_shares,
"last_touch_shares": lt_shares,
"first_touch_shares": ft_shares,
"markov_removal_effects": markov.removal_effects_,
"markov_shares": markov.attribution_shares_,
"shapley_shares": shapley.attribution_shares_,
"shapley_efficiency_abs_diff": float(shap_eff_diff),
"last_touch_l1_error": lt_l1,
"markov_l1_error": mk_l1,
"shapley_l1_error": sh_l1,
},
"experimentation": {
"true_ate_ab": exp_data["true_ate_ab"],
"true_ate_obs": round(float(exp_data["true_ate_obs"]), 4),
"true_iroas_obs": true_iroas,
"cuped": cuped_res,
"iroas": iroas_res,
},
}
"""End-to-end CLI benchmark runner for Lab 04: Marketing Segmentation, Manifolds & MTA/CUPED."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import marketing_seg_mta_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 marketing_seg_mta_lab.mta_and_experimentation import run_full_lab04_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for Lab 04 Marketing Analytics demo."""
parser = argparse.ArgumentParser(
description="Run Lab 04: Marketing Segmentation, Manifolds, MTA & Causal Experimentation."
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample sizes for fast CI verification.",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch12_lab04_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Run benchmarks, print formatted diagnostics, and export workbench JSON."""
args = parse_args(argv)
payload = run_full_lab04_benchmarks(seed=args.seed, quick=args.quick)
rfm = payload["rfm_segmentation"]
man = payload["manifold_and_density"]
mta = payload["mta_attribution"]
exp = payload["experimentation"]
cuped = exp["cuped"]
iroas = exp["iroas"]
print("=== Lab 04: Marketing Segmentation, Manifolds, MTA & Experimentation ===")
print(
f"[1] RFM Scale Trap: Raw KM ARI={rfm['raw_kmeans_train_ari']:.4f}"
f" -> log1p+Robust ARI={rfm['scaled_kmeans_train_ari']:.4f}"
f" | OOT Stability ARI={rfm['oot_frozen_vs_refit_stability_ari']:.4f}"
f" | GMM EM min_delta={rfm['gmm_min_elbo_delta']:.2e}"
)
print(
f"[2] Two-Moons & Density: KM ARI={man['two_moons_kmeans_ari']:.4f}"
f" | DBSCAN ARI={man['two_moons_dbscan_ari']:.4f}"
f" | HDBSCAN ARI={man['two_moons_hdbscan_ref_ari']:.4f}"
f" | Varying-Density HDBSCAN={man['varying_density_hdbscan_ref_ari']:.4f}"
)
print(
f"[3] Manifolds (k=10): PaCMAP rho_S={man['pacmap_ref_metrics']['global_spearman_rho']:.4f}"
f" (Trust={man['pacmap_ref_metrics']['trustworthiness_k']:.4f})"
f" vs t-SNE rho_S={man['tsne_ref_metrics']['global_spearman_rho']:.4f}"
f" (Trust={man['tsne_ref_metrics']['trustworthiness_k']:.4f})"
)
print(
f"[4] MTA L1 Error vs True Lift: Last-Touch={mta['last_touch_l1_error']:.4f}"
f" | Markov={mta['markov_l1_error']:.4f}"
f" | Exact Shapley={mta['shapley_l1_error']:.4f}"
f" (Eff diff={mta['shapley_efficiency_abs_diff']:.1e})"
)
print(
f"[5] CUPED & AIPW-DR iROAS: Var Cut=-{cuped['variance_reduction_pct']:.1f}%"
f" | Biased Naive={iroas['naive_diff_roas']:.2f}x / LT={iroas['last_touch_biased_roas']:.2f}x"
f" -> iROAS_DR={iroas['iroas_dr']:.2f}x (True={exp['true_iroas_obs']:.2f}x)"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(
json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
newline="\n",
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 unit, mathematical invariant, leakage, and security AST tests for Lab 04."""
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 scipy.stats import spearmanr
from sklearn.cluster import HDBSCAN
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.manifold import trustworthiness as sk_trustworthiness
from sklearn.metrics import (
adjusted_rand_score,
calinski_harabasz_score,
davies_bouldin_score,
normalized_mutual_info_score,
silhouette_score,
)
from marketing_seg_mta_lab.clustering_and_manifolds import (
DBSCANReference,
DensityClusterConfig,
FullCovarianceGMM,
GMMConfig,
HDBSCANHierarchyReference,
KMeansPlusPlus,
ManifoldConfig,
NeighborEmbeddingReference,
PCAReference,
RFMClusteringConfig,
adjusted_rand_index_ref,
audit_rfm_scaling_and_oot_stability,
audit_tsne_clustering_distortion,
calinski_harabasz_score_ref,
davies_bouldin_score_ref,
generate_nonconvex_two_moons_and_density_cohorts,
generate_temporal_rfm_marketing_cohorts,
normalized_mutual_info_ref,
silhouette_score_ref,
trustworthiness_at_k,
)
from marketing_seg_mta_lab.mta_and_experimentation import (
AbsorbingMarkovMTA,
ExactShapleyMTA,
ExperimentationConfig,
MarkovMTAConfig,
compute_last_touch_attribution,
estimate_cuped_ate,
estimate_iroas_aipw_dr,
evaluate_multichannel_holdout_iroas,
generate_marketing_ab_experiment,
generate_multi_channel_journeys,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
def test_01_pydantic_configs_strict_forbid() -> None:
cfg_km = RFMClusteringConfig()
cfg_gmm = GMMConfig()
cfg_dens = DensityClusterConfig()
cfg_man = ManifoldConfig()
cfg_mta = MarkovMTAConfig()
cfg_exp = ExperimentationConfig()
assert cfg_km.n_clusters == 4 and cfg_gmm.reg_covar == 1e-5
assert cfg_dens.min_cluster_size == 12 and cfg_man.n_components == 2
assert len(cfg_mta.channels) == 5 and cfg_exp.ad_cost_per_treated == 18.0
with pytest.raises(ValidationError):
RFMClusteringConfig(unknown_param=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
GMMConfig(reg_covar=0.0)
def test_02_temporal_rfm_zero_leakage_split() -> None:
cohorts = generate_temporal_rfm_marketing_cohorts(n_train=500, n_oot=350, seed=42)
assert int(cohorts.train_df["snapshot_day"].max()) < int(cohorts.oot_df["snapshot_day"].min())
assert set(cohorts.train_df["customer_id"]).isdisjoint(set(cohorts.oot_df["customer_id"]))
def test_03_rfm_scaling_rescue_beats_raw_euclidean() -> None:
res = audit_rfm_scaling_and_oot_stability(seed=42, quick=True)
assert res["monetary_raw_variance_share"] > 0.98
assert res["raw_kmeans_train_ari"] < 0.45
assert res["scaled_kmeans_train_ari"] > 0.80
assert res["kmeans_tier2_sklearn_parity_ari"] > 0.90
def test_04_oot_cluster_stability_and_gmm_monotonic_elbo() -> None:
res = audit_rfm_scaling_and_oot_stability(seed=42, quick=True)
assert res["oot_frozen_vs_refit_stability_ari"] >= 0.75
assert res["oot_frozen_vs_truth_ari"] >= 0.75
assert res["gmm_oot_ari"] >= 0.75
assert res["gmm_min_elbo_delta"] >= -1e-9
assert res["gmm_tier2_sklearn_ari"] > 0.85
# Direct per-iteration ELBO / Log-Likelihood monotonicity check
rng = np.random.default_rng(7)
X = np.vstack([rng.normal(0.0, 0.5, size=(60, 3)), rng.normal(3.0, 0.7, size=(60, 3))])
gmm = FullCovarianceGMM(GMMConfig(n_components=2, max_iter=30, tol=1e-9, seed=7)).fit(X)
assert len(gmm.log_likelihood_history_) >= 3
diffs = np.diff(np.asarray(gmm.log_likelihood_history_))
assert np.all(diffs >= -1e-9), f"EM non-monotonic step observed: {diffs}"
def test_05_nonconvex_dbscan_and_hdbscan_beat_kmeans_and_silhouette_trap() -> None:
shapes = generate_nonconvex_two_moons_and_density_cohorts(n_moons=220, n_density=210, seed=42)
X_m, y_m = shapes["X_moons"], shapes["y_moons"]
km_m = KMeansPlusPlus(RFMClusteringConfig(n_clusters=2, seed=42)).fit_predict(X_m)
db_m = DBSCANReference(eps=0.22, min_samples=5).fit_predict(X_m)
hdb_m = HDBSCANHierarchyReference(min_samples=5, min_cluster_size=12).fit_predict(X_m)
assert adjusted_rand_index_ref(y_m, km_m) < 0.40
assert adjusted_rand_index_ref(y_m, db_m) > 0.85
assert adjusted_rand_index_ref(y_m, hdb_m) > 0.85
# Silhouette convexity trap: K-Means gets higher Silhouette on Two-Moons despite failing geometry
sil_km = silhouette_score_ref(X_m, km_m)
sil_db = float(silhouette_score(X_m[db_m >= 0], db_m[db_m >= 0]))
assert sil_km > sil_db
# Varying density: HDBSCAN handles 3 density scales far better than single-eps DBSCAN
X_d, y_d = shapes["X_density"], shapes["y_density"]
db_d = DBSCANReference(eps=0.35, min_samples=5).fit_predict(X_d)
hdb_d = HDBSCANHierarchyReference(min_samples=5, min_cluster_size=12).fit_predict(X_d)
assert adjusted_rand_index_ref(y_d, hdb_d) > adjusted_rand_index_ref(y_d, db_d) + 0.15
def test_06_internal_and_external_validity_metrics_match_sklearn() -> None:
rng = np.random.default_rng(11)
X = np.vstack(
[
rng.normal(-2.0, 0.4, (40, 3)),
rng.normal(2.0, 0.4, (40, 3)),
rng.normal(6.0, 0.5, (40, 3)),
]
)
y_true = np.array([0] * 40 + [1] * 40 + [2] * 40)
km = KMeansPlusPlus(RFMClusteringConfig(n_clusters=3, seed=11)).fit(X)
assert km.labels_ is not None
y_pred = km.labels_
assert math.isclose(
silhouette_score_ref(X, y_pred), float(silhouette_score(X, y_pred)), abs_tol=1e-6
)
assert math.isclose(
davies_bouldin_score_ref(X, y_pred), float(davies_bouldin_score(X, y_pred)), abs_tol=1e-6
)
assert math.isclose(
calinski_harabasz_score_ref(X, y_pred),
float(calinski_harabasz_score(X, y_pred)),
rel_tol=1e-6,
)
assert math.isclose(
adjusted_rand_index_ref(y_true, y_pred), float(adjusted_rand_score(y_true, y_pred)), abs_tol=1e-8
)
assert math.isclose(
normalized_mutual_info_ref(y_true, y_pred),
float(normalized_mutual_info_score(y_true, y_pred)),
abs_tol=1e-6,
)
def test_07_pca_svd_variance_monotonicity_and_reconstruction() -> None:
rng = np.random.default_rng(19)
X = rng.normal(0.0, 1.0, size=(120, 6))
X[:, 1] = 0.8 * X[:, 0] + rng.normal(0.0, 0.2, size=120)
pca_ref = PCAReference(n_components=4).fit(X)
assert pca_ref.cumulative_variance_ratio_ is not None
assert np.all(np.diff(pca_ref.cumulative_variance_ratio_) >= -1e-12)
assert math.isclose(float(pca_ref.cumulative_variance_ratio_[-1]), 1.0, abs_tol=1e-10)
sk_pca = PCA(n_components=4).fit(X)
assert np.allclose(pca_ref.explained_variance_ratio_, sk_pca.explained_variance_ratio_, atol=1e-10)
pca2 = PCAReference(2).fit(X)
err2 = float(np.mean((X - pca2.inverse_transform(pca2.transform(X))) ** 2))
err4 = float(np.mean((X - pca_ref.inverse_transform(pca_ref.transform(X))) ** 2))
assert err4 < err2
def test_08_manifold_trustworthiness_and_global_preservation_pacmap_vs_tsne() -> None:
rng = np.random.default_rng(23)
X = rng.normal(0.0, 1.0, size=(90, 8))
Y_pca = PCAReference(2).fit_transform(X)
trust_ref = trustworthiness_at_k(X, Y_pca, k=8)
trust_sk = float(sk_trustworthiness(X, Y_pca, n_neighbors=8))
assert math.isclose(trust_ref, trust_sk, abs_tol=1e-6)
man = audit_tsne_clustering_distortion(seed=42, quick=True)
assert man["tsne_ref_metrics"]["trustworthiness_k"] > 0.80
assert man["pacmap_ref_metrics"]["trustworthiness_k"] > 0.80
assert man["pacmap_ref_metrics"]["global_spearman_rho"] > man["tsne_ref_metrics"]["global_spearman_rho"]
# Verify t-SNE warps cluster radius ratio vs true ratio (~4.0x)
true_ratio = man["true_cluster2_to_cluster0_radius_ratio"]
assert abs(man["tsne_cluster2_to_cluster0_radius_ratio"] - true_ratio) > abs(
man["pca_cluster2_to_cluster0_radius_ratio"] - true_ratio
)
def test_09_absorbing_markov_row_sums_fundamental_matrix_and_removal_effect() -> None:
cfg = MarkovMTAConfig(seed=42)
journeys, true_shares = generate_multi_channel_journeys(n_journeys=2200, channels=cfg.channels, seed=42)
mk = AbsorbingMarkovMTA(cfg).fit(journeys)
assert mk.transition_matrix_ is not None
assert mk.Q_ is not None and mk.fundamental_matrix_ is not None
# Stochastic transition matrix: every row sums strictly to 1.0
assert np.allclose(mk.transition_matrix_.sum(axis=1), 1.0, atol=1e-12)
# Exact Fundamental Matrix identity: (I - Q) @ N == I
n_trans = mk.Q_.shape[0]
assert np.allclose((np.eye(n_trans) - mk.Q_) @ mk.fundamental_matrix_, np.eye(n_trans), atol=1e-10)
assert math.isclose(sum(mk.attribution_shares_.values()), 1.0, abs_tol=1e-4)
lt = compute_last_touch_attribution(journeys, cfg.channels)
lt_err = sum(abs(lt[c] - true_shares[c]) for c in cfg.channels)
mk_err = sum(abs(mk.attribution_shares_[c] - true_shares[c]) for c in cfg.channels)
assert mk_err < lt_err
def test_10_exact_shapley_efficiency_symmetry_and_dummy_axioms() -> None:
channels = ("A", "B", "Dummy")
def _toy_game(S: frozenset[str]) -> float:
# A and B are symmetric; Dummy adds 0 marginal value to every coalition
has_a = "A" in S
has_b = "B" in S
if has_a and has_b:
return 10.0
if has_a or has_b:
return 4.0
return 0.0
sh = ExactShapleyMTA(channels).fit_from_coalition_fn(_toy_game)
assert math.isclose(sum(sh.shapley_values_.values()), 10.0, abs_tol=1e-12)
assert math.isclose(sh.shapley_values_["A"], 5.0, abs_tol=1e-12)
assert math.isclose(sh.shapley_values_["B"], 5.0, abs_tol=1e-12)
assert math.isclose(sh.shapley_values_["Dummy"], 0.0, abs_tol=1e-12)
# Full marketing journey Efficiency + Last-Touch comparison
cfg = MarkovMTAConfig(seed=42)
journeys, true_shares = generate_multi_channel_journeys(n_journeys=2200, channels=cfg.channels, seed=42)
sh_mkt = ExactShapleyMTA(cfg.channels).fit(journeys)
assert math.isclose(sum(sh_mkt.shapley_values_.values()), sh_mkt.grand_coalition_value_, abs_tol=1e-12)
lt = compute_last_touch_attribution(journeys, cfg.channels)
lt_err = sum(abs(lt[c] - true_shares[c]) for c in cfg.channels)
sh_err = sum(abs(sh_mkt.attribution_shares_[c] - true_shares[c]) for c in cfg.channels)
assert sh_err < lt_err
def test_11_cuped_unbiasedness_and_variance_reduction_ge_25pct() -> None:
exp = generate_marketing_ab_experiment(n_users=2500, seed=42)
cuped = estimate_cuped_ate(exp["ab_df"])
assert cuped["variance_reduction_pct"] >= 25.0
assert cuped["cuped_se"] < cuped["raw_se"]
assert abs(cuped["cuped_ate"] - exp["true_ate_ab"]) < 3.0 * cuped["cuped_se"]
def test_12_aipw_dr_iroas_overcomes_last_touch_selection_bias() -> None:
exp = generate_marketing_ab_experiment(n_users=2500, ad_cost_per_treated=18.0, seed=42)
res = estimate_iroas_aipw_dr(exp["obs_df"], ad_cost_per_treated=18.0, n_folds=5, seed=42)
true_iroas = exp["true_iroas_obs"]
assert abs(res["iroas_dr"] - true_iroas) < 0.35
assert abs(res["iroas_dr"] - true_iroas) < abs(res["naive_diff_roas"] - true_iroas)
assert abs(res["iroas_dr"] - true_iroas) < abs(res["last_touch_biased_roas"] - true_iroas)
assert res["dr_policy_holdout_iroas"] > res["lt_policy_holdout_iroas"]
def test_13_tier2_hdbscan_and_tsne_parity() -> None:
shapes = generate_nonconvex_two_moons_and_density_cohorts(n_moons=180, n_density=180, seed=42)
hdb_ref = HDBSCANHierarchyReference(min_samples=5, min_cluster_size=12).fit_predict(
shapes["X_moons"]
)
hdb_sk = HDBSCAN(min_samples=5, min_cluster_size=12, copy=True).fit_predict(shapes["X_moons"])
assert adjusted_rand_index_ref(shapes["y_moons"], hdb_ref) > 0.85
assert adjusted_rand_index_ref(shapes["y_moons"], hdb_sk) > 0.85
rng = np.random.default_rng(42)
X = rng.normal(0.0, 1.0, size=(75, 6))
cfg_tsne = ManifoldConfig(perplexity=15.0, n_iter=150, seed=42)
Y_ref = NeighborEmbeddingReference("tsne", cfg_tsne).fit_transform(X)
Y_sk = TSNE(
n_components=2, perplexity=15.0, init="pca", learning_rate="auto", random_state=42
).fit_transform(X)
assert trustworthiness_at_k(X, Y_ref, k=6) > 0.70
assert float(spearmanr(Y_ref[:, 0], Y_sk[:, 0]).statistic) != 0.0 # deterministic finite coords
def test_14_cli_demo_execution_and_workbench_json_schema(tmp_path: Path) -> None:
out_json = tmp_path / "ch12_lab04_results.json"
cmd = [
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
]
proc = subprocess.run(
cmd,
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
assert out_json.is_file()
data = json.loads(out_json.read_text(encoding="utf-8"))
expected_keys = (
"config",
"workbench_panels",
"rfm_segmentation",
"manifold_and_density",
"mta_attribution",
"experimentation",
)
for key in expected_keys:
assert key in data
wp = data["workbench_panels"]
assert len(wp["kpis"]) == 6
assert len(wp["bars"]) == 4
assert len(wp["tables"]) == 4
assert data["rfm_segmentation"]["oot_frozen_vs_refit_stability_ari"] >= 0.75
assert data["experimentation"]["cuped"]["variance_reduction_pct"] >= 25.0
def test_15_security_only_ast_deserialization_guard() -> None:
py_files = (
sorted((LAB_ROOT / "src").rglob("*.py"))
+ sorted((LAB_ROOT / "scripts").rglob("*.py"))
+ sorted((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 4
for pf in py_files:
tree = ast.parse(pf.read_text(encoding="utf-8"), filename=str(pf))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, (
f"Unsafe deserialization import '{alias.name}' in {pf}"
)
elif isinstance(node, ast.ImportFrom) and node.module is not None:
root_mod = node.module.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, (
f"Unsafe deserialization from-import '{node.module}' in {pf}"
)
def test_16_multichannel_holdout_iroas_genuine_policy_evaluation() -> None:
res42 = evaluate_multichannel_holdout_iroas(n_obs=2600, n_holdout=2600, seed=42)
res99 = evaluate_multichannel_holdout_iroas(n_obs=2600, n_holdout=2600, seed=99)
assert math.isclose(sum(res42["lt_policy_weights"].values()), 1.0, abs_tol=1e-5)
assert math.isclose(sum(res42["dr_policy_weights"].values()), 1.0, abs_tol=1e-5)
assert res42["lt_observed_roas"]["Brand Search"] > res42["lt_observed_roas"]["Display"]
assert res42["dr_estimated_iroas"]["Display"] > res42["dr_estimated_iroas"]["Brand Search"]
assert res42["dr_policy_holdout_iroas"] > res42["lt_policy_holdout_iroas"] + 0.8
# Finite-sample randomized holdout outcomes vary cleanly across seeds (not hardcoded constants)
assert res42["dr_policy_holdout_iroas"] != res99["dr_policy_holdout_iroas"]
RFM (Recency, Frequency, Monetary, Promo), vì sao chạy thẳng K-Means++ trên thang đo Euclid thô lại sụp đổ về ARI = 0.2082, và quy trình chuẩn sản xuất khắc phục thế nào?Monetary chiếm 99.8147%). log1p nén đuôi phải và RobustScaler khớp chỉ trên train chống rò rỉ tương lai, phục hồi Train ARI = 0.9729 và OOT ARI = 1.000.
Expectation-Maximization (EM) cho mô hình hỗn hợp Gaussian (Full-Covariance GMM)?EM cực đại hóa cận dưới ELBO ở bước M sau khi triệt tiêu KL ở bước E. Trong Lab 04, bước tăng nhỏ nhất qua 9 vòng lặp là 2.80e-07 >= 0, đạt GMM Train ARI = 0.9908 và OOT ARI = 1.000.
Two-Moons có nhiễu ngoại lai và 3 cụm Gaussian lệch mật độ (0.18 / 0.45 / 0.95), kết luận nào ĐÚNG khi so sánh K-Means, DBSCAN, và HDBSCAN?Silhouette đo tỷ lệ khoảng cách nội cụm/ngoại cụm theo tâm lồi nên phạt nặng hình trăng khuyết phi lồi. HDBSCAN (Campello et al., PAKDD 2013) dùng d_mreach-k, Prim MST và cực đại hóa ổn định EOM trên cây nén nên thích nghi đa mật độ.
Agglomerative) và nhóm giảm chiều tuyến tính (PCA, TruncatedSVD, ICA)?SVD trực tiếp ổn định số học hơn và bảo đảm phương sai giải thích tích lũy tăng đơn điệu tới 1.000 (Test 07). TruncatedSVD giữ nguyên định dạng CSR tránh nổ RAM.
4 cụm dữ liệu 12 chiều (trong đó cụm 2 rộng gấp 4.08x cụm 0) xuống không gian 2D, kết quả nào phản ánh ĐÚNG sự đánh đổi cục bộ/toàn cục giữa t-SNE, UMAP, PaCMAP và PCA?t-SNE chuẩn hóa mật độ cục bộ qua perplexity và KL bất đối xứng phạt nhẹ khi đẩy sai cặp xa, phá hủy kích thước/khoảng cách tương đối giữa các cụm. PaCMAP (Wang et al., JMLR 2021) cân bằng cặp gần, trung gian và xa giữ vững cấu trúc toàn cục.
n = 500,000 người dùng với d = 128 đặc trưng dưới ràng buộc RAM < 16 GB và độ trễ suy luận < 2 ms. Theo Ma trận Độ phức tạp ML Cổ điển, cặp lựa chọn nào KHẢ THI và cặp nào VỠ TRẬN?n x n kiểu float64 ở n = 500k tốn 8 * 2.5e11 = 2 TB RAM, đánh sập tức thì cả Kernel SVM lẫn Ward. Ngược lại, K-Means++, GBDT Hist (uint8) và HNSW mở rộng tuyến tính/logarit.
4,000 hành trình đa kênh (Paid Search, Social, Display, Email, Organic), vì sao Last-Touch gán tới 77.1% công lao cho Paid Search (trong khi đóng góp cấu trúc thật chỉ 10.0%), và Absorbing Markov / Exact Shapley giải quyết ra sao?1.0 (Test 09); hiệu ứng loại bỏ đo mức sụt xác suất chuyển đổi khi cắt nút kênh c. Exact Shapley kiểm toán đủ 4 tiên đề, gán đúng 0.0 cho kênh giả Dummy và đạt sai số L1 = 0.2854 nhỏ nhất.
Lab 04), chiến dịch Paid Brand Search quan sát báo cáo Last-Touch ROAS = 8.15x (Naive Diff = 4.17x) trong khi hiệu quả nhân quả thật chỉ là 1.86x. Kết hợp CUPED và AIPW-DR đem lại kết quả nào?W làm CUPED thiên lệch nặng (post-treatment bias). Chỉ dùng biến tiền thử nghiệm bảo toàn tính không chệch với mức giảm phương sai 68.9% >= 25% (Test 11), còn AIPW-DR loại bỏ thiên lệch chọn lọc nâng mạnh holdout iROAS (Tests 12, 16).
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 — Phá bẫy Thang đo RFM, Định lý K-Means++ O(log K) & Ổn định OOT (ARI >= 0.75) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích phương sai Euclid \(\|\mathbf{x}_i - \mathbf{x}_j\|_2^2 = \sum_{m=1}^d (x_{im}-x_{jm})^2\) để thấy cột monetary_usd thống trị 99.81%; bảo đảm RobustScaler chỉ gọi .fit() trên train_df (snapshot_day <= 90).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy generate_temporal_rfm_marketing_cohorts + preprocess_rfm_features + KMeansPlusPlus (khởi tạo D^2 đa điểm n_init=10), rồi dùng align_clusters_hungarian kiểm chứng ổn định giữa dự báo đóng băng trên oot_df và refit OOT.
Tiêu chí Đáp án & Số đối chứng
Raw K-Means++ sụp ở ARI = 0.2082; sau log1p + RobustScaler đạt Train ARI = 0.9729 (khớp Tier 2 sklearn 0.9758), và OOT Stability ARI = 1.0000 >= 0.75 trên tập oot_df (snapshot_day >= 91).
Bài tập 2 — Dẫn xuất EM Full-Covariance GMM (ELBO), Lỗi Suy biến Kỳ dị & Chứng minh Đơn điệu 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng bất đẳng thức Jensen trên \(\ln\sum_k \pi_k \mathcal{N}_k\) để tách ELBO và \(D_{\mathrm{KL}}(q \|\ p(z\mid x,\theta))\); viết phép tính log-sum-exp trừ đi max trước khi lấy exp.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm nghiệm FullCovarianceGMM với reg_covar=1e-5 và đối chiếu mảng hiệu số np.diff(gmm.elbo_history_) qua tất cả vòng lặp EM cùng so sánh adjusted_rand_score với sklearn.mixture.GaussianMixture.
Tiêu chí Đáp án & Số đối chứng
Mọi bước lặp EM có delta_ELBO >= 2.80e-07 >= 0 (đơn điệu tuyệt đối qua 9 vòng lặp), GMM Train ARI = 0.9908, OOT ARI = 1.000, và khớp Tier 2 sklearn với ARI = 1.000.
Bài tập 3 — Phi lồi Two-Moons, Bẫy Silhouette & HDBSCAN (Mutual Reachability MST + EOM) 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết công thức khoảng cách khả đạt tương hỗ \(d_{\text{mreach-}k}(a,b) = \max\{\operatorname{core}_k(a),\operatorname{core}_k(b),d(a,b)\}\) và cơ chế tính ổn định cụm \(S(C) = \sum_{x\in C}(\lambda_{\text{death}}(x,C)-\lambda_{\text{birth}}(C))\) trên cây nén.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
So sánh KMeansPlusPlus, DBSCANReference, và HDBSCANHierarchyReference trên dữ liệu từ generate_nonconvex_two_moons_and_density_cohorts, đồng thời đo silhouette_score_ref trên Two-Moons.
Tiêu chí Đáp án & Số đối chứng
Trên Two-Moons, DBSCAN (1.000) & HDBSCAN (0.9875) thắng áp đảo K-Means (0.1335) dù K-Means đạt Silhouette = 0.4641 > DBSCAN 0.3247; trên 3 cụm lệch mật độ, HDBSCAN đạt 0.9848 vượt xa DBSCAN ngưỡng cứng 0.7404.
Bài tập 4 — PCA SVD, Ma trận Độ phức tạp ML & Cuộc đối đầu Cục bộ/Toàn cục (t-SNE vs. PaCMAP) 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích vì sao X^T X bình phương số điều kiện kappa(X)^2 và cách TruncatedSVD giữ nguyên thưa CSR; đối chiếu công thức Trustworthiness@k và mất mát 3 pha NB/MN/FP của PaCMAP.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy PCAReference, LaplacianEigenmapsReference, NeighborEmbeddingReference (tsne & pacmap), và audit_tsne_clustering_distortion để kiểm tra tỷ lệ bán kính cụm C2/C0.
Tiêu chí Đáp án & Số đối chứng
t-SNE đạt Trust@10 = 0.9658 nhưng bóp méo tỷ lệ bán kính 4.084x -> 0.981x (Spearman = 0.6126); PaCMAP bảo toàn đồng thời Trust@10 = 0.9025 và Spearman = 0.8918; PCA đạt Spearman = 0.9848 với bán kính 3.417x.
Bài tập 5 — Chuỗi Markov Hấp thụ (I-Q)^-1 R & Giá trị Shapley Chính xác Cho Quy bổ Đa chạm 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh ma trận cơ bản \(\mathbf{N}=(\mathbf{I}-\mathbf{Q})^{-1} = \sum_{t=0}^\infty \mathbf{Q}^t\) tồn tại khi chuỗi là hấp thụ; kiểm tra tổng mỗi hàng của transition_matrix_ bằng 1.0.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Huấn luyện AbsorbingMarkovMTA và ExactShapleyMTA trên generate_multi_channel_journeys, đối chiếu tiên đề Efficiency / Dummy và sai số L1 so với Last-Touch.
Tiêu chí Đáp án & Số đối chứng
Last-Touch phóng đại Paid Search lên 77.1% (L1 = 1.3424); Absorbing Markov hạ lỗi xuống 0.4894 ((I-Q)N = I khớp < 1e-10); Exact Shapley hạ lỗi còn 0.2854 với sai số tổng hiệu quả 0.0e+00 và kênh Dummy = 0.0.
Bài tập 6 — Giảm Phương sai CUPED (>= 25%) & Khử Chọn lọc iROAS Bằng Cross-Fitted AIPW-DR 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\hat{\theta}^* = \operatorname{Cov}(Y,X_{\text{pre}})/\operatorname{Var}(X_{\text{pre}})\) cực tiểu hóa phương sai và bảo toàn không chệch nhờ ngẫu nhiên hóa \(X_{\text{pre}} \perp W\); thiết kế cross-fitting K=5 nếp cho AIPW-DR.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy estimate_cuped_ate, estimate_iroas_aipw_dr, và chạy trọn bộ pytest -p no:cacheprovider -v (16/16) + ruff check + mypy src + run_lab_demo.py.
Tiêu chí Đáp án & Số đối chứng
CUPED giảm -68.94% phương sai (SE $1.8206 -> $1.0147, vượt xa ngưỡng 25%); AIPW-DR sửa ROAS thiên lệch chọn lọc từ 4.17x/8.15x -> 1.81x (chân lý 1.86x) và nâng holdout policy iROAS từ 0.68x -> 2.17x.