Chương 03 — Lý thuyết Xác suất, Thống kê Suy luận, Kiểm định A/B SOTA & Dự báo Conformal
Từ Tiên đề Kolmogorov, Bayes Liên hợp, Họ Hàm mũ, Delta Tỷ lệ, CRLB & Wilson/Bootstrap đến CUPED/MLRATE, Suy luận Mọi thời điểm mSPRT/Ville/e-BH & Dự báo Bảo toàn Không phân phối (SCP, CQR, RAPS/SAPS, ACI, LLM Factuality).
Unit ID:
T1-P1-U03
Track & Part: Track 1 (DSAI) — Part 1: Mathematical Foundations, Statistical Inference & Causal Decision Science (part-01-math-stats-and-causal)
Truy xuất Giáo trình Gốc (R27): Lesson 2 (Math for ML — Probability & Statistics: Foundation of probability: probability theory & bayes theorem; Probability distributions: normal, bernoulli, binomial, poison (chuẩn hóa thành Poisson); Describe the data: expectation, variance, covariance & correlation; Statistical inference: hypothesis testing and confidence intervals) (Phần Linear Algebra và Calculus củaR27được phủ trọn vẹn tại Chương 02T1-P1-U02; phần giao thoa nhân quả & switchback nối trực tiếp sang Chương 05T1-P1-U05)
Bài thực hành Song hành (Lab 03):labs/ch03-probability-inference-and-testing-workbench/(prob_stats_lab)
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn học phần T1-P1-U03 (Chương 03 và prob_stats_lab), học viên có đủ năng lực để:
- Suy diễn & Phân tích Nền tảng Xác suất và Cấu trúc Họ Hàm mũ (Mathematical Rigor): Thiết lập bộ ba xác suất Kolmogorov \((\Omega, \mathcal{F}, P)\) và Định lý Bayes (Bayes' Theorem); suy diễn trọn vẹn cả bốn họ tiên nghiệm liên hợp (Conjugate Families) cùng phân phối dự báo hậu nghiệm (Posterior Predictive) quá phân tán; chứng minh Định lý Giới hạn Poisson (Poisson Limit Theorem), điều kiện hóa Phần bù Schur và độc lập có điều kiện qua ma trận chính xác \(\boldsymbol{\Lambda}\) (\(\Lambda_{ij}=0\)) của phân phối Chuẩn Đa biến (
MVN), đạo hàm tích lũy (\(\nabla A, \nabla^2 A\)) của họ hàm mũ chính tắc (Canonical Exponential Family),LoTE/LoTV, Bổ đề Hoeffding, và phương sai tỷ lệ theo Phương pháp Delta Đa biến (Multivariate Delta Method). - Chứng minh Đảm bảo Ước lượng, Khoảng Tin cậy & Kiểm định Tần suất (Statistical Rigor): Thiết lập sự tương đương giữa
MLEvàMAPchuẩn hóa (\(L_2\) Ridge / \(L_1\) Lasso) cùng Cận dưới Cramér–Rao (CRLB); suy diễn dạng đóng Khoảng Tin cậy Wilson (Wilson Score CI); chứng minh tính phân phối đều \(\operatorname{Uniform}(0,1)\) của \(p\)-value dưới \(H_0\), công thức cỡ mẫuMDE, tính hợp lệ mẫu hữu hạn \((1+\#)/(B+1)\) của kiểm định hoán vị chuẩn hóa (Studentized Permutation),FWERHolm vàFDRBenjamini–Hochberg; đồng thời chẩn đoán các chế độ sụp đổ kinh điển như Wald ở biên, bẫy trung vị của Mann–Whitney, và bất nhất bootstrap trên thống kê thứ tự cực trị (\(\max X_i\)). - Thiết kế Hệ thống Thử nghiệm Giảm phương sai, Chống Nhìn trộm & An toàn Đa kiểm định (SOTA Experimentation Rigor): Suy diễn và triển khai
CUPED(\(1-\rho_{Y,X}^2\)), mô hình tương tácLin ANCOVA2, vàCUPAC/MLRATEkhớp chéo \(K\)-nếp (\(K\)-fold Cross-Fitting); phát hiện sụp đổ tỷ lệ khi \(\operatorname{CV}(\bar{X}) > 0.1\) (giải cứu bằng khoảng Fieller) và đảo dấu trung bình hình học/số học LogNormal (khắc phục bằng bộ ước lượng bôi trơn Duan — Duan smearing); chứng minh Bất đẳng thức Ville để triệt tiêu sụp đổ LIL khi nhìn trộm (Peeking) thông quamSPRTdạng đóng, chi tiêu alphaO'Brien–Fleming, quy trìnhe-value Dirichlet–Multinomial choSRM, vàe-BHdưới phụ thuộc tùy ý. - Xây dựng Lớp Bao Dự báo Conformal Không phân phối cho ML Bảng & LLM (SOTA 2024–2026 UQ Rigor): Chứng minh định lý hiệu lực biên mẫu hữu hạn của Dự báo Conformal Tách (
SCP— Split Conformal Prediction) dưới giả thiết Tính hoán vị (Exchangeability) và bóc trần sụp đổ độ phủ dưới chuẩn của phân vị ngây thơ \(\lceil(1-\alpha)n_{\text{cal}}\rceil\); thiết kế khoảng bất đẳng phương saiCQR(Conformalized Quantile Regression), tập phân loạiLAC/APS/RAPS/SAPS, bộ điều khiển trôi trực tuyếnACI/DtACI/NexCPđạt hối tiếc \(O(1/T)\); và triển khaiCRC/ Conformal Factuality cắt tỉa mệnh đề ảo giác cho hệ thống RAG. - Kiểm chứng Đầu–Cuối bằng Workbench Pure-Stdlib + NumPy (
prob_stats_lab): Tự cài đặt từ đầu toàn bộ hàm toán học đặc biệt (math.erfc, Acklam+Halleynorm_ppf, phân số liên tục Lentzgammaincc/betainc,Welford,LSE,Decimaltrần hạng Conformal) và vượt qua14/14kiểm thử tự độngpytestvới 0 phụ thuộc vàoscipy,sklearn,statsmodels, haytorch.
Tình huống Mở đầu: Bốn Thảm họa Thống kê Phá vỡ Hệ thống ML & Thử nghiệm Thực tế#
Trong khoa học dữ liệu và kỹ thuật học máy sản xuất (production DSAI), các thất bại đắt giá nhất ít khi đến từ lỗi cú pháp mã nguồn; chúng xuất phát từ việc áp dụng máy móc các công thức thống kê lý tưởng lên dữ liệu lệch đuôi, phụ thuộc cụm, hoặc bị giám sát liên tục:
- Ảo ảnh Nhìn trộm LIL & Thiên lệch
SRM0.35%Vô hình (Peeking & Invisible SRM Trap): Một đội sản phẩm theo dõi bảng điều khiển A/B cố định mỗi giờ sẽ tự động đẩy Tỷ lệ Dương tính Giả (False Positive Rate — FPR) từ mức danh nghĩa \(5\%\) lên quá \(50\%\) (và hội tụ chắc chắn tới \(100\%\) theo Luật Logarit Lặp — Law of the Iterated Logarithm, LIL). Song song đó, một tỷ lệ phân tách lưu lượng tưởng chừng vô hại50.35% / 49.65%trên \(200{,}000\) lượt truy cập (100,700Đối chứng vs.99,300Thử nghiệm — thiếu đúng1,400sự kiện ghi nhận ở nhóm Thử nghiệm) đã kích hoạtSRM(Sample Ratio Mismatch) ở mức \(\chi^2 = 9.80\), \(p = 0.001745\), tạo ra thiên lệch chọn lọc không ngẫu nhiên (MNAR) làm thổi phồng giả tạo tỷ lệ chuyển đổi. - Ảo ảnh Tỷ lệ Cụm
2.59x& Đảo dấu LogNormal (Clustered Ratio & LogNormal Sign-Reversal): Khi tính sai số chuẩn (Standard Error — SE) của chỉ số tỷ lệ (Cancel RatehoặcCTR) ở cấp phiên/lần hiển thị thay vì đơn vị ngẫu nhiên hóa là người dùng, SE thực tế bị đánh giá thấp đi \(\sqrt{\text{DEFF}} \approx 2.5\times\text{–}5\times\) (2.59xtrong mô phỏng cụm người dùng), đẩyFPRvượt quá \(35\%\). Tệ hơn nữa, khi kiểm định độ trễ hoặc doanh thu đuôi nặng bằng phép biến đổi \(\ln(Y)\) mà quên bộ ước lượng bôi trơn Duan, một cải thiện thực sự \(-31.4\%\) về độ trễ trung bình số học bị đảo dấu thành một sự tụt lùi \(+10.1\%\) ở trung bình hình học! - Ghi nhớ Nhiễu In-Sample
CUPAC& Sụp đổ Conformal Sai-một-bậc (CUPAC Overfit & Off-by-One Conformal Collapse): Đưa vector nhúng tiền thử nghiệm chiều cao (\(d=100\)) vào mô hình giảm phương sai mà khớp trực tiếp trong mẫu (in-sample) trên các phân khúc nhỏ tạo ra mức giảm phương sai ảo28.6%trên nhiễu trắng thuần túy và làm sai lệch SE. Trong khi đó, thay công thức hạng bảo toàn chính xác \(\lceil(n_{\text{cal}}+1)(1-\alpha)\rceil\) bằngnp.quantile(scores, 1 - alpha)khiến độ phủ thực nghiệm ở \(n_{\text{cal}}=10, \alpha=0.10\) tụt từ \(90\%\) xuống \(81.82\%\), đồng thời sụp đổ ở các vùng nhiễu cao bất đẳng phương sai hoặc khi luồng dữ liệu trôi khỏi tính hoán vị. - Sụp đổ ABI
scipy& Bẫy Triệt tiêu Số học (ABI Crash & Floating-Point Cancellation): Công thức phương sai một lượt sách giáo khoa \(\frac{1}{n}\sum x_i^2 - \bar{x}^2\) cho kết quả âm khi dữ liệu có trung bình \(\mu = 10^9, \sigma = 1\); nhân trực tiếp \(10{,}000\) hợp lý xác suất gây tràn dướifloat64(< 4.94e-324) thành0/0 = NaN; còn việc gọi trực tiếpscipy/sklearntrong môi trường dùngNumPy 2.xgây sập ABI (_ARRAY_API not found). Điều này đòi hỏi kỹ sư phải làm chủ bộ hàm đặc biệt bằng Python thuần + NumPy (math.erfc, Acklam+Halleynorm_ppf, phân số liên tục Lentz, thuật toánWelford, vàLSE).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P1-U03)#
Ranh giới Part 1: Học phần gốc Lesson 2 (
R27, Math for ML) gồm ba khối:Linear Algebra,Calculus, vàProbability & Statistics. Chương 02 (T1-P1-U02) phủ 100% hai khối đầu; Chương 03 (T1-P1-U03) phủ trọn vẹn 100% khốiProbability & Statistics, đồng thời mở cầu nối sang suy luận nhân quả / thiết kế switchback ở Chương 05 (T1-P1-U05) và đánh giá chống rò rỉ / hiệu chuẩn chi phí ở Chương 07 (T1-P2).
Nội dung Gốc (01-track-dsai-raw-curriculum.md, Dòng R27) |
Nâng cấp Chuẩn SOTA 2026 (ch-03) |
Mục trong Chương 03 | Mô-đun & Kiểm thử (prob_stats_lab) |
|---|---|---|---|
| Foundation of probability: probability theory & bayes theorem | Bộ ba Kolmogorov \((\Omega, \mathcal{F}, P)\) & \(\sigma\)-đại số (Borel vs. Vitali), chứng minh tiên đề cộng đếm được, nghịch lý Borel–Kolmogorov, độc lập từng đôi \(\not\Rightarrow\) toàn phần, LTP, Định lý Bayes, ổn định Log-Sum-Exp (LSE), 4 Họ Tiên nghiệm Liên hợp (Beta–Binomial, Gamma–Poisson Shape–Rate, Dirichlet–Categorical + Laplace/Jeffreys, Normal–Normal độ chính xác \(\tau_{\text{prec}}\)) & phân phối dự báo hậu nghiệm quá phân tán |
Trụ cột 1 (§1.1) + Widget bayesian-conjugate-clt-explorer |
distributions_and_bayes.py (log_sum_exp, beta_binomial_update, gamma_poisson_update, dirichlet_categorical_update, normal_normal_update), Tests 1, 2 |
| Probability distributions: normal, bernoulli, binomial, poison (chuẩn hóa thành Poisson) | Bảng phân loại 12 phân phối (Bernoulli, Binomial, Categorical, Multinomial PSD/suy biến, Poisson, Normal, MVN, Student-t ảnh hưởng giảm dần, Exponential, Gamma Shape–Rate, Beta, LogNormal bất định mô-men & lệch Jensen), chứng minh Giới hạn Poisson, Phần bù Schur & Ma trận Chính xác \(\boldsymbol{\Lambda}\) của MVN (\(\Lambda_{ij}=0 \iff X_i \perp X_j \mid X_{-\{i,j\}}\)), Họ Hàm mũ Chính tắc (\(\nabla A = \mathbb{E}[\mathbf{T}]\), \(\nabla^2 A = \operatorname{Cov}(\mathbf{T})\), đủ Fisher–Neyman, \(\text{KL}=\text{CE}=\text{MLE}\)), cùng đảo dấu LogNormal & bôi trơn Duan |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.1) + Trụ cột 3 (§3.1 Case 5) + Widget bayesian-conjugate-clt-explorer |
distributions_and_bayes.py (poisson_limit_tv_distance, mvn_schur_conditional, mahalanobis_sq), inference_and_experimentation.py (duan_smearing_mean, lognormal_inversion_demo), Tests 2, 3, 9 |
| Describe the data: expectation, variance, covariance & correlation | Phương sai trực tuyến Welford & gộp song song Chan (chống triệt tiêu ở \(\mu = 10^9\)), chứng minh LoTE & LoTV, hiệp phương sai PSD, Pearson \(\rho_{Y,X}\) vs. Spearman trung vị hạng \(\rho_S\) vs. Thông tin Tương hỗ \(I(X;Y)\) (3 phản ví dụ: \(Y=X^2\), \(Y=e^X\), ngoại lai), phân tầng tập trung (Markov/Chebyshev/Hoeffding), WLLN/SLLN/CLT & cảnh báo Berry–Esseen \(O(\mu_{3,\text{abs}}/(\sigma^3\sqrt{n}))\), Phương pháp Delta Đa biến & phương sai tỷ lệ cụm tuyến tính hóa, phác thảo gộp phân vị DDSketch |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1, §2.4) + Trụ cột 3 (§3.1 Cases 3, 5) + Widget bayesian-conjugate-clt-explorer |
distributions_and_bayes.py (WelfordAccumulator, spearman_midrank_corr, discrete_mutual_information, compute_dependence_profile, benchmark_berry_esseen_clt), inference_and_experimentation.py (delta_method_ratio_test, fieller_ratio_ci), Tests 1, 3, 4, 9 |
| Statistical inference: hypothesis testing and confidence intervals | Nền tảng Ước lượng & Khoảng: MLE vs. MAP (\(L_2\)/\(L_1\)), điểm số Fisher/CRLB, suy diễn Wilson Score vs. sụp đổ Wald, Bootstrap (Percentile, Basic phản xạ, BCa, Cluster, Block, sụp đổ \(\max X_i\)); Kiểm định & Đa kiểm định: Neyman–Pearson, \(p\)-value \(\operatorname{Uniform}(0,1)\) dưới \(H_0\), MDE, Welch \(t\), Pearson \(\chi^2\) (SRM), Mann–Whitney U (ưu thế ngẫu nhiên vs. trung vị!), hoán vị chuẩn hóa \((1+\#)/(B+1)\), FWER (Bonferroni/Holm) vs. BH-FDR/BY; SOTA 2024–2026: CUPED/Lin ANCOVA2/CUPAC/MLRATE, nhìn trộm LIL, chứng minh Bất đẳng thức Ville, mSPRT, O'Brien–Fleming, GROW, e-BH, e-process Dirichlet cho SRM, và Dự báo Conformal Không phân phối (SCP, CQR, LAC/APS/RAPS/SAPS, RLCP/Mondrian, ACI/DtACI/NexCP, CRC & Conformal Factuality cho LLM) |
Trụ cột 1 (§1.4–§1.6) + Trụ cột 2 (§2.1–§2.4) + Trụ cột 3 (§3.1–§3.4) + Mermaid 1, 2, 3 + Widgets peeking-msprt-cuped-simulator, conformal-prediction-explorer |
inference_and_experimentation.py + conformal.py (wilson_score_interval, welch_t_test, mann_whitney_u_test, studentized_permutation_test, bootstrap_ci, srm_chisq_guard, cuped_adjust, msprt_confidence_sequence, obrien_fleming_boundaries, multiple_testing_control, split_conformal_calibrate, cqr_calibrate_and_predict, calibrate_and_predict_sets, adaptive_conformal_inference, conformal_factuality_prune), Tests 4–14 |
(Tham chiếu chéo R28 Nhân quả & T1-P2 Hiệu chuẩn) |
(Vi phạm SUTVA / Tràn hiệu ứng Switchback theo không-thời gian; hiệu chuẩn nhạy chi phí & chống rò rỉ dữ liệu) | Nối cầu tại §3.1 Case 3 & §3.2 \(\to\) Chương 05 & Chương 07 | Kiểm chứng tại Lab Chương 05 & Chương 07 |
Bảng Ký hiệu Toán học & Quy ước Phân giải Trùng lặp (Unified Disambiguated Notation)#
Chính sách Khử trùng lặp Ký hiệu Xuyên suốt Chương 03 &
prob_stats_lab:
- Phân biệt tám vai trò của \(\tau\): \(\tau_{\text{prec}} := \sigma^{-2}\) là độ chính xác (precision) trong họ Normal–Normal; \(\sigma_{\text{prior}}^2\) là phương sai tiên nghiệm trong MAP–Ridge (\(\lambda_{\text{Ridge}} = \sigma^2/\sigma_{\text{prior}}^2\)); \(\tau_{\text{mix}}^2\) là phương sai pha trộn Gaussian của
mSPRT(tham số mãtau_sq); \(\tau_{\text{ATE}}\) (và \(\hat{\tau}_{\text{CUPED}}, \hat{\tau}_{\text{Lin}}, \hat{\tau}_{\text{MLRATE}}\)) là Tác động Điều trị Trung bình (Average Treatment Effect), tách biệt với \(\hat{\Delta}_t = \bar{Y}_{1,t} - \bar{Y}_{0,t}\); \(\hat{\tau}_{\text{fact}}\) là ngưỡng cắt tỉa mệnh đề trong Conformal Factuality; \(\tau_{\text{stop}}\) là thời điểm dừng phụ thuộc dữ liệu; \(\tau_q \in (0, 1)\) là mức phân vị trong hàm mất mát pinball \(\rho_{\tau_q}\); và \(\tau_{\text{int}}\) là thời gian tự tương quan tích phân chuỗi thời gian.- Phân biệt các vai trò của \(\rho\) và ký hiệu
mSPRT/ Conformal: Dùng \(\rho_{Y,X}\) cho tương quan tuyến tính Pearson, \(\rho_S\) cho tương quan hạng Spearman, \(\rho_{\text{ICC}}\) cho tương quan nội cụm, \(\rho_{\text{decay}} \in (0, 1)\) cho trọng số suy giảmNexCP, \(\rho_{\tau_q}\) cho hàm pinball, \(\rho_x(y)\) cho xác suất tích lũy chặt trongAPS, và \(\mu_{3,\text{abs}} := \mathbb{E}[\lvert X_1-\mu\rvert^3]\) cho mô-men tâm tuyệt đối bậc ba trong Định lý Berry–Esseen. Dành \(\Lambda_t(\Delta)\) cho tỷ số hợp lý điểm và chuẩn hóa \(E_t\) cho tiến trìnhe-value (\(E_t^{\text{SRM}}\) choSRM), \(M_t\) cho siêu martingale trừu tượng trong Bất đẳng thức Ville, \(r_t(\alpha)\) cho bán kính dãy tin cậymSPRT, \(p_{\text{any},t} := \min_{0 \le s \le t}\min(1, 1/E_s)\) cho \(p\)-value hợp lệ mọi thời điểm, \(S_i = s(X_i, Y_i)\) (chữ hoa) cho điểm bất tương thích Conformal, \(\hat{q}_{\text{cal}}\) cho ngưỡng phân vị mẫu hữu hạn tại hạng \(k = \lceil(n_{\text{cal}}+1)(1-\alpha)\rceil\), \(R_{\text{ratio}} = \mu_Y/\mu_X\) cho ước lượng tỷ lệ, và \(\theta_{\text{cuped}}\) cho hệ số biến kiểm soátCUPED(\(\hat{\theta}_{\text{out}}\) trongMLRATE).- Khóa Tham số hóa Gamma Hình dạng–Tốc độ (
Shape–Rate Lock): Chương 03 luôn dùng Hình dạng–Tốc độ \(\operatorname{Gamma}(\alpha, \beta)\) với \(\mathbb{E}[\lambda] = \alpha/\beta\) và \(\operatorname{Var}(\lambda) = \alpha/\beta^2\), cảnh báo tường minh khi gọinumpy.random.gamma(shape=alpha, scale=1.0/beta)vốn dùng Hình dạng–Thang đo (Shape–Scale).
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa Xuyên suốt Chương 03 | Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (prob_stats_lab) |
|---|---|---|---|---|
| \((\Omega, \mathcal{F}, P)\) | Bộ ba | Không gian mẫu \(\Omega\), \(\sigma\)-đại số \(\mathcal{F}\), độ đo cộng đếm được \(P\) | — | — |
| \(Z_{\text{ev}} := p(\mathcal{D})\) | \(\mathbb{R}_{>0}\) | Hợp lý biên (Bayesian evidence) \(\int p(\mathcal{D}\mid\boldsymbol{\theta})p(\boldsymbol{\theta})\,d\boldsymbol{\theta}\) | Tránh trùng chữ \(Z\) của \(Z_n \sim \mathcal{N}(0,1)\) | — |
| \(\operatorname{Gamma}(\alpha, \beta)\) | Phân phối | Tham số hóa Shape–Rate (\(\alpha\) hình dạng, \(\beta\) tốc độ, kỳ vọng \(\alpha/\beta\)) | numpy dùng scale = 1/beta |
alpha0, beta0_rate |
| \(\tau_{\text{prec}} := \sigma^{-2}\) | \(\mathbb{R}_{>0}\) | Độ chính xác Normal–Normal (\(\tau_{\text{prec},n} = \tau_{\text{prec},0} + n\tau_{\text{prec}}\)) | Tách biệt khỏi các nghĩa khác của \(\tau\) | tau_prec |
| \(\sigma_{\text{prior}}^2\) | \(\mathbb{R}_{>0}\) | Phương sai tiên nghiệm trọng số \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \sigma_{\text{prior}}^2 \mathbf{I}_d)\) trong MAP–Ridge | Thay thế \(\tau^2\) tránh trùng mSPRT |
— |
| \(\boldsymbol{\eta}, \mathbf{T}(x), A(\boldsymbol{\eta})\) | \(\mathbb{R}^d, \mathbb{R}^d, \mathbb{R}\) | Tham số tự nhiên, thống kê đủ, hàm log-phân hoạch họ hàm mũ | \(\nabla A = \mathbb{E}[\mathbf{T}],\; \nabla^2 A = \operatorname{Cov}(\mathbf{T})\) | — |
| \(\boldsymbol{\Lambda} := \boldsymbol{\Sigma}^{-1}\) | \(\mathbb{R}^{d\times d}\) | Ma trận chính xác MVN (\(\Lambda_{ij}=0 \iff X_i \perp X_j \mid X_{-\{i,j\}}\)) | Tách biệt khỏi tỷ số hợp lý \(\Lambda_t(\Delta)\) | precision_subblock |
| \(\rho_{Y,X}, \rho_S, \rho_{\text{ICC}}\) | \([-1, 1]\) | Tương quan Pearson, tương quan hạng Spearman, tương quan nội cụm | Tách khỏi \(\mu_{3,\text{abs}}, \rho_{\text{decay}}, \rho_{\tau_q}, \rho_x(y)\) | pearson_r, spearman_rho |
| \(\mu_{3,\text{abs}}\) | \(\mathbb{R}_{\ge 0}\) | Mô-men tâm tuyệt đối bậc ba \(\mathbb{E}[\lvert X_1 - \mu \rvert^3]\) trong Berry–Esseen | Không dùng \(\rho\) trơn trong Berry–Esseen | berry_esseen_bound |
| \(s(\theta; \mathbf{x}), \mathcal{I}_n(\theta)\) | \(\mathbb{R}, \mathbb{R}_{\ge 0}\) | Điểm số Fisher \(\partial_\theta \ln p(\mathbf{x}\mid\theta)\) & Thông tin Fisher \(\operatorname{Var}(s)\) | Tách khỏi độ lệch chuẩn \(s_k\) và điểm \(S_i\) | — |
| \(W_i \in \{0, 1\}\) | \(\{0, 1\}\) | Chỉ báo nhóm điều trị (0 đối chứng, 1 thử nghiệm); cửa sổ cuộn dùng \(W_{\text{win}}\) |
Không dùng \(W\) trơn cho cửa sổ | treatment_mask |
| \(\tau_{\text{ATE}}, \hat{\Delta}_t\) | \(\mathbb{R}\) | Tác động nhân quả ATE (CUPED/MLRATE); hiệu trung bình tức thời \(\bar{Y}_{1,t} - \bar{Y}_{0,t}\) |
Tách biệt khỏi \(\tau_{\text{prec}}, \tau_{\text{mix}}^2, \tau_{\text{stop}}\) | ate_adj, delta_hat |
| \(\theta_{\text{cuped}}, \hat{\theta}_{\text{out}}\) | \(\mathbb{R}\) | Hệ số biến kiểm soát CUPED & hệ số hiệu chuẩn ngoài MLRATE |
Tách biệt khỏi \(\theta \in \Theta\) và \(R_{\text{ratio}}\) | theta_outer |
| \(R_{\text{ratio}}, \hat{R}_g\) | \(\mathbb{R}\) | Tham số tỷ lệ \(\mu_Y/\mu_X\) và ước lượng gộp theo cụm \(\bar{Y}_g/\bar{X}_g\) | Thay \(\theta = \mu_Y/\mu_X\) | rate_ctrl, rate_trt |
| \(\tau_{\text{mix}}^2, V_t\) | \(\mathbb{R}_{>0}\) | Phương sai pha trộn mSPRT \(\Delta \sim \mathcal{N}(0, \tau_{\text{mix}}^2)\); phương sai ước lượng \(V_t\) |
Không dùng \(\tau^2\) trơn | tau_sq, pooled_var |
| \(E_t, E_t^{\text{SRM}}, M_t\) | \([0, \infty]\) | e-value / e-process (\(\sup_{P\in\mathcal{H}_0}\mathbb{E}_P[E_{\tau_{\text{stop}}}]\le 1\)); siêu martingale \(M_t\) |
Chuẩn hóa thống nhất từ \(\Lambda_t\) | e_value, e_value_dirichlet |
| \(r_t(\alpha), p_{\text{any},t}\) | \(\mathbb{R}_{\ge 0}, [0, 1]\) | Bán kính dãy tin cậy mọi thời điểm; \(p\)-value \(\min_{s\le t}\min(1, 1/E_s)\) | Thay cho \(w_t\) và \(p_t^{\text{AV}}\) | half_width, always_valid_p |
| \(S_i = s(X_i, Y_i), \hat{q}_{\text{cal}}\) | \(\mathbb{R}, \mathbb{R}\cup\{\infty\}\) | Điểm bất tương thích \(S_i\) & ngưỡng tại \(k = \lceil(n_{\text{cal}}+1)(1-\alpha)\rceil\) (Decimal) |
Phân biệt \(\hat{q}_{\text{cal}}\) với phân vị \(\hat{q}_{\tau_q}(x)\) | cal_scores, q_hat, k_rank |
| \(\alpha, \alpha_t, \alpha_{\text{SRM}}\) | \((0, 1)\) / \(\mathbb{R}\) | Mức sai lầm Loại I / sai phủ mục tiêu; mức động ACI \(\alpha_t\); cổng SRM (0.001) |
Tách khỏi tham số hình dạng \(\alpha\) | alpha, alpha_trajectory |
| \(\rho_x(y), \rho_{\text{decay}}, \hat{\tau}_{\text{fact}}\) | \([0, 1]\) | Khối lượng tích lũy chặt APS; suy giảm trọng số NexCP; ngưỡng cắt tỉa LLM |
Khử trùng lặp hoàn toàn | lam_reg, k_reg, tau_fact |
Trụ cột 1 — Nền tảng Xác suất, Phân phối, Ước lượng & Kiểm định Thống kê từ Nguyên lý Gốc (First-Principles Mathematical & Statistical Rigor)#
1.1 Không gian Xác suất, Định lý Bayes, LSE & Bốn Họ Tiên nghiệm Liên hợp (Probability Triple, Bayes, LSE & Conjugate Families)#
Bộ ba Xác suất Kolmogorov \((\Omega, \mathcal{F}, P)\) & Các Hệ quả Suy diễn Trực tiếp#
Lý thuyết xác suất hiện đại (Kolmogorov, 1933) được tiên đề hóa trên bộ ba không gian xác suất (Probability Triple) \((\Omega, \mathcal{F}, P)\):
- Không gian mẫu (\(\Omega\) — Sample Space): Tập hợp khác rỗng mọi kết cục sơ cấp \(\omega \in \Omega\) (ví dụ \(\Omega = \{0,1\}^n\) cho \(n\) lần tung đồng xu, hoặc \(\Omega = \mathbb{R}^d\) cho dữ liệu đặc trưng liên tục).
-
\(\sigma\)-Đại số biến cố (\(\mathcal{F} \subseteq 2^\Omega\) — Event Space / \(\sigma\)-Algebra): Họ các tập con đo được của \(\Omega\) thỏa mãn ba tiên đề đóng: (i) \(\Omega \in \mathcal{F}\) (do đó \(\emptyset = \Omega^c \in \mathcal{F}\)); (ii) đóng dưới phép lấy phần bù (\(A \in \mathcal{F} \implies A^c := \Omega \setminus A \in \mathcal{F}\)); và (iii) đóng dưới phép hợp đếm được (\(\{A_i\}_{i=1}^\infty \subseteq \mathcal{F} \implies \bigcup_{i=1}^\infty A_i \in \mathcal{F}\), kéo theo đóng dưới giao đếm được theo luật De Morgan).
Vì sao không thể luôn chọn \(\mathcal{F} = 2^\Omega\)? Trên không gian hữu hạn hoặc đếm được, \(2^\Omega\) hoạt động hoàn hảo. Nhưng trên \(\Omega = \mathbb{R}\) không đếm được, xây dựng tập không đo được Vitali (dùng Tiên đề Chọn — Axiom of Choice) chứng minh rằng không tồn tại độ đo cộng đếm được bất biến tịnh tiến nào gán được xác suất nhất quán cho mọi tập con trong \(2^{\mathbb{R}}\). Do đó ta phải khóa về \(\sigma\)-đại số Borel \(\mathcal{B}(\mathbb{R}) := \sigma(\{(-\infty, x] : x \in \mathbb{R}\})\) — \(\sigma\)-đại số nhỏ nhất chứa mọi khoảng mở/nửa đóng.
-
Độ đo xác suất (\(P: \mathcal{F} \to [0, 1]\) — Probability Measure): Thỏa mãn Ba Tiên đề Kolmogorov:
- Tiên đề 1 (Không âm): \(P(A) \ge 0\;\forall A \in \mathcal{F}\).
- Tiên đề 2 (Chuẩn hóa): \(P(\Omega) = 1\).
- Tiên đề 3 (Cộng tính đếm được — Countable / \(\sigma\)-Additivity): Với mọi dãy vô hạn đếm được các biến cố rời nhau từng đôi một \(\{A_i\}_{i=1}^\infty \subseteq \mathcal{F}\) (\(A_i \cap A_j = \emptyset\) khi \(i \ne j\)):
\[P\!\left(\bigcup_{i=1}^\infty A_i\right) = \sum_{i=1}^\infty P(A_i).\]
Từ ba tiên đề gốc này suy diễn trực tiếp mọi định luật xác suất nền tảng không cần giả thiết bổ sung:
- Tập rỗng & Cộng tính hữu hạn: Đặt \(A_i = \emptyset\;\forall i \ge 1\) vào Tiên đề 3 cho \(P(\emptyset) = \sum_{i=1}^\infty P(\emptyset) \implies P(\emptyset) = 0\) (vì \(P(\emptyset) \in [0, 1]\) không thể cộng vô hạn lần cho tổng bằng chính nó nếu dương). Tiếp tục đặt \(A_{k+1}=A_{k+2}=\dots=\emptyset\) thu được cộng tính hữu hạn \(P(\bigsqcup_{i=1}^k A_i) = \sum_{i=1}^k P(A_i)\).
- Phần bù & Đơn điệu: Từ \(\Omega = A \sqcup A^c\) suy ra \(P(A^c) = 1 - P(A) \in [0, 1]\). Nếu \(A \subseteq B\), tách \(B = A \sqcup (B \setminus A)\) cho \(P(B) = P(A) + P(B \setminus A) \ge P(A)\).
- Bao hàm–Loại trừ (Inclusion–Exclusion): Từ \(A \cup B = A \sqcup (B \setminus A)\) và \(B = (A \cap B) \sqcup (B \setminus A)\) suy ra \(P(A \cup B) = P(A) + P(B) - P(A \cap B)\), tổng quát thành:
\[P\!\left(\bigcup_{i=1}^n A_i\right) = \sum_{k=1}^n (-1)^{k-1}\sum_{1 \le i_1 < \dots < i_k \le n} P(A_{i_1} \cap \dots \cap A_{i_k}).\]
- Cộng tính dưới đếm được / Bất đẳng thức Boole (Union Bound): Với họ \(\{A_i\}_{i=1}^\infty \subseteq \mathcal{F}\) bất kỳ (không cần rời nhau), rời hóa bằng \(B_1 = A_1\) và \(B_i = A_i \setminus \bigcup_{j=1}^{i-1} A_j \subseteq A_i\). Khi đó \(\bigcup_{i=1}^\infty A_i = \bigsqcup_{i=1}^\infty B_i\), suy ra:
\[P\!\left(\bigcup_{i=1}^\infty A_i\right) = \sum_{i=1}^\infty P(B_i) \le \sum_{i=1}^\infty P(A_i).\](Bất đẳng thức này trực tiếp sinh ra kiểm soát đa kiểm định Bonferroni và cận tổng quát hóa PAC trên lớp giả thuyết hữu hạn \(\mathcal{H}\).)
- Tính liên tục của xác suất (đòi hỏi cộng tính đếm được, không chỉ hữu hạn):
- Liên tục từ dưới: Nếu \(A_1 \subseteq A_2 \subseteq \dots\) hội tụ về \(A = \bigcup_{n=1}^\infty A_n\), rời hóa \(B_1=A_1, B_n=A_n \setminus A_{n-1}\) cho \(P(A) = \sum_{n=1}^\infty P(B_n) = \lim_{N \to \infty}\sum_{n=1}^N P(B_n) = \lim_{N \to \infty} P(A_N)\). (Bước cuối trong chứng minh Bất đẳng thức Ville §2.2 dùng trực tiếp tính chất này.)
- Liên tục từ trên: Nếu \(A_1 \supseteq A_2 \supseteq \dots\) với \(A = \bigcap_{n=1}^\infty A_n\), áp dụng liên tục từ dưới cho dãy tăng \(A_n^c \uparrow A^c\) cho \(P(A_n) \to P(A)\).
Biến ngẫu nhiên đo được, CDF, PMF vs. PDF & Bẫy Mật độ \(> 1\)#
Một biến ngẫu nhiên thực (Random Variable — RV) là hàm đo được \((\mathcal{F}, \mathcal{B}(\mathbb{R}))\), tức là ánh xạ \(X: \Omega \to \mathbb{R}\) sao cho tạo ảnh \(X^{-1}(B) := \{\omega \in \Omega : X(\omega) \in B\} \in \mathcal{F}\) với mọi tập Borel \(B \in \mathcal{B}(\mathbb{R})\). Ánh xạ đẩy tiến (pushforward) tạo ra luật phân phối \(P_X(B) := P(X^{-1}(B))\) và Hàm phân phối tích lũy (CDF) \(F_X(x) := P(X \le x)\), đặc trưng duy nhất bởi 3 tính chất: (1) không giảm, (2) liên tục phải (\(\lim_{h \downarrow 0} F_X(x+h) = F_X(x)\)), và (3) giới hạn \(\lim_{x \to -\infty} F_X(x) = 0\), \(\lim_{x \to +\infty} F_X(x) = 1\).
- Biến rời rạc (
PMF): Đạo hàm Radon–Nikodym đối với độ đo đếm; \(p_X(x) := P(X = x) \in [0, 1]\) và \(\sum_{x \in \mathcal{X}} p_X(x) = 1\). - Biến liên tục tuyệt đối (
PDF): Đạo hàm Radon–Nikodym đối với độ đo Lebesgue; tồn tại \(p_X: \mathbb{R} \to \mathbb{R}_{\ge 0}\) để \(F_X(x) = \int_{-\infty}^x p_X(t)\,dt\).Bẫy Mật độ tại Điểm & Mật độ Lớn hơn 1: Với biến liên tục, \(P(X = x) = \int_x^x p_X(t)\,dt = 0\) tại mọi điểm đơn lẻ \(x\) dù \(\{X = x\} \ne \emptyset\). Quan trọng hơn, \(p_X(x)\) KHÔNG phải xác suất và hoàn toàn có thể lớn hơn \(1\): ví dụ \(\operatorname{Uniform}(0, 0.1)\) có mật độ \(p_X(x) = 10\) trên \((0, 0.1)\), hay phân phối chuẩn hẹp \(\mathcal{N}(0, 0.01^2)\) đạt đỉnh mật độ \(p_X(0) \approx 39.89\), khiến log-hợp lý \(\ln p_X(x)\) dương hợp lệ trong mô hình mật độ (Normalizing Flows, VAEs)! Ngoài ra, dữ liệu học máy thường có phân phối hỗn hợp (mixed discrete–continuous), chẳng hạn đầu ra kích hoạt
ReLU\(\max(0, Z)\) có một nguyên tử điểm khối lượng \(0.5\) tại \(0\) và mật độ liên tục trên \((0, \infty)\).
Xác suất Có điều kiện, Độc lập & Định lý Bayes#
Với mọi \(B \in \mathcal{F}\) có \(P(B) > 0\), xác suất có điều kiện là \(P(A \mid B) := \frac{P(A \cap B)}{P(B)}\).
Định lý 1.1 (Tính hợp lệ Kolmogorov của Xác suất Có điều kiện): Với \(B\) cố định (\(P(B) > 0\)), \(Q(\cdot) := P(\cdot \mid B)\) là một độ đo xác suất hợp lệ trên \((\Omega, \mathcal{F})\).
Chứng minh: (1) \(Q(A) = P(A\cap B)/P(B) \ge 0\); (2) \(Q(\Omega) = P(\Omega\cap B)/P(B) = P(B)/P(B) = 1\); (3) với mọi dãy rời nhau từng đôi \(\{A_i\}_{i=1}^\infty\), các tập \(\{A_i \cap B\}_{i=1}^\infty\) cũng rời nhau từng đôi, nên theo Tiên đề 3:
Nghịch lý Borel–Kolmogorov (Điều kiện hóa trên Biến cố Xác suất \(0\)): Khi \(P(Y = y) = 0\) với biến liên tục, không thể định nghĩa \(P(X \in A \mid Y = y)\) qua giới hạn \(0/0\) của các lân cận co dần mà không cố định phép tham số hóa giới hạn (ví dụ điều kiện hóa trên đường tròn lớn của mặt cầu theo vĩ độ \(\phi = 0\) cho mật độ khác hẳn so với kinh độ \(\lambda = 0\)!). Mật độ có điều kiện chặt chẽ \(p_{X|Y}(x \mid y) := \frac{p_{X,Y}(x, y)}{p_Y(y)}\) (khi \(p_Y(y) > 0\)) phải đi qua phép phân rã xác suất có điều kiện chính quy (regular conditional disintegration) đối với một độ đo trội cố định.
- Quy tắc Dây chuyền (Chain Rule): Lặp lại \(P(A_1 \cap A_2) = P(A_1)P(A_2 \mid A_1)\) (khi \(P(\bigcap_{j=1}^{n-1} A_j) > 0\)) cho phép nhân tử hóa chính xác mọi phân phối đồng thời:
\[P\!\left(\bigcap_{i=1}^n A_i\right) = P(A_1)\prod_{i=2}^n P\!\left(A_i \,\middle|\, A_1, \dots, A_{i-1}\right).\](Trong mô hình ngôn ngữ tự hồi quy — autoregressive LLM, phân tích \(p(w_1, \dots, w_T) = \prod_{t=1}^T p(w_t \mid w_{<t})\) là đẳng thức chính xác tuyệt đối, không hề có giả thiết cắt cụt Markov.)
- Độc lập Từng đôi \(\not\Rightarrow\) Độc lập Toàn phần (Pairwise vs. Mutual Independence): Họ \(\{A_1, \dots, A_n\}\) độc lập toàn phần (mutually independent) iff \(P(\bigcap_{i\in S} A_i) = \prod_{i \in S} P(A_i)\) với mọi tập con khác rỗng \(S \subseteq \{1, \dots, n\}\). Phản ví dụ kinh điển: Tung hai đồng xu công bằng độc lập \(C_1, C_2 \in \{0, 1\}\). Đặt \(A = \{C_1 = 1\}\), \(B = \{C_2 = 1\}\), và \(C = \{C_1 = C_2\}\) (chẵn lẻ XNOR). Ta có \(P(A)=P(B)=P(C)=1/2\) và \(P(A\cap B)=P(A\cap C)=P(B\cap C)=1/4 = \frac{1}{2}\cdot\frac{1}{2}\) (độc lập từng đôi!). Tuy nhiên \(A \cap B \cap C = \{C_1=1, C_2=1\}\) có \(P(A\cap B\cap C) = 1/4 \ne (1/2)^3 = 1/8\).
- Độc lập Có điều kiện vs. Thiên lệch Va chạm (Collider Bias): \(X \perp\!\!\!\perp Y \mid Z \iff p(x, y \mid z) = p(x \mid z)p(y \mid z)\). Lưu ý hai chiều đều sai: \(X \perp\!\!\!\perp Y \not\Rightarrow X \perp\!\!\!\perp Y \mid Z\) (khi \(Z\) là nút va chạm \(X \to Z \leftarrow Y\), ví dụ \(Z = X + Y\), việc quan sát \(Z\) tạo ra phụ thuộc giả giữa \(X\) và \(Y\) — cơ chế cốt lõi gây thiên lệch trong
SRM!) và \(X \perp\!\!\!\perp Y \mid Z \not\Rightarrow X \perp\!\!\!\perp Y\) (nguyên nhân chung \(Z\) trong Naive Bayes).
Định lý 1.2 (Định lý Xác suất Toàn phần — LTP & Định lý Bayes): Cho \(\{B_k\}_{k \ge 1} \subseteq \mathcal{F}\) là phân hoạch đo được đếm được của \(\Omega\) (\(B_i \cap B_j = \emptyset\) với \(i \ne j\), \(\bigcup_k B_k = \Omega\)) thỏa \(P(B_k) > 0\). Với mọi biến cố \(A \in \mathcal{F}\):
và nếu \(P(A) > 0\), Định lý Bayes cho:
Chứng minh: Do \(A = A \cap \big(\bigsqcup_k B_k\big) = \bigsqcup_k (A \cap B_k)\) là hợp rời nhau từng đôi, Tiên đề 3 cho \(P(A) = \sum_k P(A \cap B_k) = \sum_k P(A \mid B_k)P(B_k)\). Nhân \(P(B_k \mid A) P(A) = P(A \cap B_k) = P(A \mid B_k)P(B_k)\), chia cho \(P(A) > 0\) và thế mẫu số bằng LTP hoàn tất chứng minh. \(\blacksquare\) (Dạng liên tục: \(p(x) = \int p(x \mid z)p(z)\,dz\).)
Giải phẫu Suy luận Bayes Tham số & Bẫy Thường gặp#
Cho tập dữ liệu \(\mathcal{D} = \{x_1, \dots, x_n\}\) và vector tham số \(\boldsymbol{\theta} \in \Theta\):
| Thành phần | Công thức | Vai trò Toán học & Thống kê | Bẫy Thường gặp & Điều kiện Biên |
|---|---|---|---|
| Tiên nghiệm (Prior) | \(p(\boldsymbol{\theta})\) | Mã hóa tri thức miền / thiên lệch quy nạp trước khi thấy \(\mathcal{D}\). | Tiên nghiệm không chính quy (Improper prior) (\(\int p(\boldsymbol{\theta})\,d\boldsymbol{\theta} = \infty\), vd. \(p(\mu) \propto 1\)) có thể cho hậu nghiệm không khả tích ở mô hình phân tầng và làm hỏng hệ số Bayes (Nghịch lý Lindley). |
| Hợp lý (Likelihood) | \(\mathcal{L}(\boldsymbol{\theta}; \mathcal{D}) := p(\mathcal{D} \mid \boldsymbol{\theta})\) | Xác suất/mật độ của \(\mathcal{D}\) theo hàm của \(\boldsymbol{\theta}\) (\(\prod_{i=1}^n p(x_i \mid \boldsymbol{\theta})\) khi i.i.d.). | KHÔNG phải phân phối xác suất trên \(\boldsymbol{\theta}\)! Tổng tích phân \(\int_\Theta p(\mathcal{D} \mid \boldsymbol{\theta})\,d\boldsymbol{\theta} \ne 1\) nói chung. |
| Bằng chứng (Evidence) | \(Z_{\text{ev}} := p(\mathcal{D}) = \int_\Theta p(\mathcal{D}\mid\boldsymbol{\theta})p(\boldsymbol{\theta})\,d\boldsymbol{\theta}\) | Hằng số chuẩn hóa bảo toàn \(\int p(\boldsymbol{\theta}\mid\mathcal{D})\,d\boldsymbol{\theta}=1\); quyết định tỷ số chọn mô hình \(p(\mathcal{M}_1\mid\mathcal{D})/p(\mathcal{M}_2\mid\mathcal{D})\). | Tạo Dao cạo Occam Bayes tự động (mô hình quá phức tạp trải loãng khối lượng tiên nghiệm khiến \(Z_{\text{ev}}\) giảm). Thường bất khả tích ở chiều cao \(d\), phải xấp xỉ Laplace, MCMC, hoặc Suy luận Biến phân (\(\text{ELBO} \le \ln Z_{\text{ev}}\)). |
| Hậu nghiệm (Posterior) | \(p(\boldsymbol{\theta} \mid \mathcal{D}) \propto p(\mathcal{D}\mid\boldsymbol{\theta})p(\boldsymbol{\theta})\) | Niềm tin cập nhật về \(\boldsymbol{\theta}\) kết hợp tiên nghiệm và dữ liệu. | Bất biến tuần tự: Cập nhật \(\mathcal{D}_1\) rồi \(\mathcal{D}_2\) (khi \(\mathcal{D}_1 \perp \mathcal{D}_2 \mid \boldsymbol{\theta}\)) cho hậu nghiệm đồng nhất với cập nhật gộp \((\mathcal{D}_1, \mathcal{D}_2)\). |
| Dự báo Hậu nghiệm (Posterior Predictive) | \(p(\tilde{x} \mid \mathcal{D}) = \int_\Theta p(\tilde{x}\mid\boldsymbol{\theta})p(\boldsymbol{\theta}\mid\mathcal{D})\,d\boldsymbol{\theta}\) | Phân phối cho mẫu tương lai \(\tilde{x}\) đã tích phân khử bất định tham số \(\boldsymbol{\theta}\). | Luôn rộng hơn và hiệu chuẩn tốt hơn dự báo thế điểm \(p(\tilde{x}\mid\hat{\boldsymbol{\theta}}_{\text{MLE}})\), vốn đánh giá thấp phương sai khi \(n\) nhỏ. |
Tràn dưới Tích Xác suất & Ổn định Log-Sum-Exp (LSE)#
Nhân \(n = 10{,}000\) số hạng hợp lý \(p(x_i \mid \boldsymbol{\theta}) \approx 0.1\) tạo ra \(10^{-10000}\), lập tức tràn dưới (underflow) thành đúng 0.0 trong float64 IEEE-754 (ngưỡng subnormal cực tiểu \(\approx 4.94 \times 10^{-324}\)), khiến phép chia chuẩn hóa trong Định lý Bayes cho 0/0 = NaN. Do đó toàn bộ tính toán xác suất phải thực hiện trong không gian log \(\ell_k := \ln p(\mathcal{D} \mid \mathcal{M}_k) + \ln p(\mathcal{M}_k) = \sum_{i=1}^n \ln p(x_i \mid \mathcal{M}_k) + \ln p(\mathcal{M}_k)\), rồi khôi phục bằng thủ thuật Log-Sum-Exp (LSE) dịch chuyển qua cực đại \(m := \max_{1 \le j \le K} \ell_j\):
Vì \(\ell_j - m \le 0\) với mọi \(j\) và \(\ell_{j^*} - m = 0\) tại ít nhất một chỉ số \(j^*\), mỗi số hạng \(\exp(\ell_j - m) \in [0, 1]\) với ít nhất một số hạng đúng bằng \(1.0\). Kết quả là \(\operatorname{LSE}(\boldsymbol{\ell}) \in [m,\; m + \ln K]\) hoàn toàn miễn nhiễm tràn trên và tràn dưới miễn là có ít nhất một \(\ell_j > -\infty\) (nếu mọi \(\ell_j = -\infty\), quy ước trả về \(-\infty\)).
Bốn Họ Tiên nghiệm Liên hợp Dạng đóng & Phân phối Dự báo Quá phân tán#
Một họ tiên nghiệm \(\mathcal{P}\) là liên hợp (conjugate) với họ hợp lý \(\{p(x \mid \boldsymbol{\theta})\}\) nếu với mọi tiên nghiệm \(p(\boldsymbol{\theta}) \in \mathcal{P}\) và mọi tập dữ liệu \(\mathcal{D}\), hậu nghiệm \(p(\boldsymbol{\theta} \mid \mathcal{D})\) vẫn nằm trong chính họ \(\mathcal{P}\).
1. Họ Beta–Binomial (và Beta–Bernoulli)
- Tiên nghiệm & Hợp lý: \(\theta \sim \operatorname{Beta}(\alpha, \beta)\) (\(\alpha, \beta > 0\)) trên \((0, 1)\) với \(p(\theta) = \frac{1}{B(\alpha, \beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\), \(B(\alpha,\beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\); hợp lý \(K \mid \theta \sim \operatorname{Binomial}(n, \theta)\) với \(k\) thành công trên \(n\) phép thử.
- Suy diễn Hậu nghiệm: Bỏ các thừa số không phụ thuộc \(\theta\):
\[p(\theta \mid k, n) \propto \big[\theta^k (1 - \theta)^{n-k}\big]\big[\theta^{\alpha-1}(1-\theta)^{\beta-1}\big] = \theta^{(\alpha + k)-1}(1-\theta)^{(\beta + n - k)-1} \implies \theta \mid k, n \sim \operatorname{Beta}(\alpha', \beta'),\]trong đó \(\alpha' := \alpha + k\) và \(\beta' := \beta + n - k\).
- Mô-men, Co rút & Giới hạn Tiên nghiệm Đặc biệt: Kỳ vọng hậu nghiệm là tổ hợp lồi giữa trung bình tiên nghiệm \(\frac{\alpha}{\alpha+\beta}\) và
MLE\(\hat{p} = \frac{k}{n}\):\[\mathbb{E}[\theta \mid k, n] = \frac{\alpha + k}{\alpha + \beta + n} = \left(\frac{\alpha+\beta}{\alpha+\beta+n}\right)\frac{\alpha}{\alpha+\beta} + \left(\frac{n}{\alpha+\beta+n}\right)\frac{k}{n}, \qquad \operatorname{Var}(\theta \mid k, n) = \frac{\alpha'\beta'}{(\alpha'+\beta')^2(\alpha'+\beta'+1)} = O(n^{-1}).\]Mode hậu nghiệm (MAP, hợp lệ khi \(\alpha' > 1, \beta' > 1\)) là \(\hat{\theta}_{\text{MAP}} = \frac{\alpha+k-1}{\alpha+\beta+n-2}\). Khi \(\operatorname{Beta}(1, 1) = \operatorname{Uniform}(0,1)\) thu được Quy tắc Kế tiếp Laplace \(\frac{k+1}{n+2}\); \(\operatorname{Beta}(1/2, 1/2)\) là tiên nghiệm bất biến Jeffreys; còn tiên nghiệm không chính quy Haldane \(\alpha,\beta \to 0^+\) khôi phục \(\hat{p} = k/n\) khi \(0 < k < n\) nhưng làm hậu nghiệm sụp đổ bất khả tích tại biên \(k=0\) hoặc \(k=n\). - Bằng chứng & Dự báo Hậu nghiệm \(m\) phép thử Quá phân tán (Beta–Binomial Predictive):
\[Z_{\text{ev}} = P(K = k \mid n) = \binom{n}{k}\frac{B(\alpha+k, \beta+n-k)}{B(\alpha, \beta)}.\]Với \(1\) phép thử mới \(\tilde{X} \in \{0, 1\}\), \(P(\tilde{X}=1\mid\mathcal{D}) = \frac{\alpha'}{\alpha'+\beta'}\). Với \(m\) phép thử tương lai \(\tilde{K} \mid \theta \sim \operatorname{Binomial}(m, \theta)\):\[P(\tilde{K}=\tilde{k}\mid\mathcal{D}) = \int_0^1 \binom{m}{\tilde{k}}\theta^{\tilde{k}}(1-\theta)^{m-\tilde{k}}\frac{\theta^{\alpha'-1}(1-\theta)^{\beta'-1}}{B(\alpha',\beta')}\,d\theta = \binom{m}{\tilde{k}}\frac{B(\alpha'+\tilde{k},\; \beta'+m-\tilde{k})}{B(\alpha',\beta')}.\]Áp dụng
LoTEvàLoTV(§1.3) với \(s' := \alpha' + \beta'\) và \(\mathbb{E}[\theta(1-\theta)] = \mathbb{E}[\theta]-\mathbb{E}[\theta^2] = \frac{\alpha'}{s'} - \frac{\alpha'(\alpha'+1)}{s'(s'+1)} = \frac{\alpha'\beta'}{s'(s'+1)}\):\[\mathbb{E}[\tilde{K}\mid\mathcal{D}] = m\frac{\alpha'}{s'}, \qquad \operatorname{Var}(\tilde{K}\mid\mathcal{D}) = m\mathbb{E}[\theta(1-\theta)] + m^2\operatorname{Var}(\theta) = m\frac{\alpha'\beta'(\alpha'+\beta'+m)}{(\alpha'+\beta')^2(\alpha'+\beta'+1)}.\]Nhân tử \(\frac{\alpha'+\beta'+m}{\alpha'+\beta'+1} > 1\) (khi \(m > 1\)) chính là hệ số quá phân tán phản ánh bất định nhận thức về \(\theta\) mà mô hình nhị thức thế điểm bỏ sót.
2. Họ Gamma–Poisson (Khóa Hình dạng–Tốc độ & Dự báo Nhị thức Âm)
-
Khóa Tham số hóa Shape–Rate: Sử dụng \(\lambda \sim \operatorname{Gamma}(\alpha, \beta)\) với \(\alpha > 0\) (hình dạng — shape) và \(\beta > 0\) (tốc độ — rate) trên \((0, \infty)\):
\[p(\lambda) = \frac{\beta^\alpha}{\Gamma(\alpha)}\lambda^{\alpha-1}e^{-\beta\lambda}, \qquad \mathbb{E}[\lambda] = \frac{\alpha}{\beta}, \qquad \operatorname{Var}(\lambda) = \frac{\alpha}{\beta^2}.\]Cảnh báo Xung đột Tham số hóa NumPy:
numpy.random.gamma(shape, scale)dùng Hình dạng–Thang đo (\(\theta_{\text{scale}} = 1/\beta\)). Truyền nhầm \(\beta\) vàoscalesẽ nghịch đảo kỳ vọng tiên nghiệm từ \(\alpha/\beta\) thành \(\alpha\beta\)! Luôn gọirng.gamma(shape=alpha, scale=1.0/beta_rate). -
Suy diễn Hậu nghiệm: Với \(x_1, \dots, x_n \stackrel{\text{i.i.d.}}{\sim} \operatorname{Poisson}(\lambda)\) và tổng \(S := \sum_{i=1}^n x_i\) (hoặc với mức phơi nhiễm không đồng nhất \(X_i \sim \operatorname{Poisson}(\lambda T_i)\)):
\[p(\lambda \mid x_{1:n}) \propto \big(\lambda^S e^{-\lambda \sum T_i}\big)\big(\lambda^{\alpha-1}e^{-\beta\lambda}\big) = \lambda^{(\alpha+S)-1}e^{-(\beta + \sum T_i)\lambda} \implies \lambda \mid \mathcal{D} \sim \operatorname{Gamma}\!\left(\alpha' := \alpha + S,\;\; \beta' := \beta + \sum_{i=1}^n T_i\right),\](với \(T_i = 1\) thì \(\beta' = \beta + n\)). Kỳ vọng hậu nghiệm \(\mathbb{E}[\lambda \mid \mathcal{D}] = \frac{\alpha + S}{\beta + n}\) thực hiện co rút Bayes thực nghiệm cho tỷ lệ nhấp hiếm (
CTR) hay tỷ lệ lỗi máy chủ. - Suy diễn Dự báo Hậu nghiệm (
Negative Binomial): Cho một quan sát mới \(\tilde{X} \mid \lambda \sim \operatorname{Poisson}(\lambda)\) (\(\tilde{x} \in \mathbb{N}_0\)):\[P(\tilde{X}=\tilde{x}\mid\mathcal{D}) = \int_0^\infty \frac{\lambda^{\tilde{x}}e^{-\lambda}}{\tilde{x}!}\frac{{\beta'}^{\alpha'}}{\Gamma(\alpha')}\lambda^{\alpha'-1}e^{-\beta'\lambda}\,d\lambda = \frac{{\beta'}^{\alpha'}}{\tilde{x}!\,\Gamma(\alpha')} \int_0^\infty \lambda^{\alpha'+\tilde{x}-1}e^{-(\beta'+1)\lambda}\,d\lambda.\]Thay tích phân chuẩn Gamma \(\int_0^\infty \lambda^{A-1}e^{-B\lambda}\,d\lambda = \Gamma(A)/B^A\) với \(A=\alpha'+\tilde{x}, B=\beta'+1, \tilde{x}!=\Gamma(\tilde{x}+1)\):\[P(\tilde{X}=\tilde{x}\mid\mathcal{D}) = \frac{\Gamma(\alpha'+\tilde{x})}{\Gamma(\tilde{x}+1)\Gamma(\alpha')}\left(\frac{\beta'}{\beta'+1}\right)^{\alpha'}\left(\frac{1}{\beta'+1}\right)^{\tilde{x}} \implies \tilde{X} \mid \mathcal{D} \sim \operatorname{NegBin}\!\left(r = \alpha',\; p_{\text{stop}} = \frac{\beta'}{\beta'+1}\right).\]Kỳ vọng dự báo là \(\frac{\alpha'}{\beta'}\) và phương sai là \(\frac{\alpha'}{\beta'}\big(1 + \frac{1}{\beta'}\big) > \frac{\alpha'}{\beta'}\), tự động mô hình hóa quá phân tán dữ liệu đếm (count overdispersion). Về mặt số học, luôn tính \(\ln P(\tilde{X}=\tilde{x}\mid\mathcal{D})\) bằngmath.lgammavì \(\Gamma(\alpha)\) tràn trênfloat64(> 1.797e308) ngay khi \(\alpha \ge 171.62\).
3. Họ Dirichlet–Categorical (và Dirichlet–Multinomial) + Cầu nối Làm trơn Laplace / Jeffreys
- Mô hình & Hậu nghiệm: Tiên nghiệm trên đơn hình \(\Delta^{K-1} = \{\boldsymbol{\theta} \in \mathbb{R}_{\ge 0}^K : \sum_{k=1}^K \theta_k = 1\}\) với \(\boldsymbol{\alpha} \in \mathbb{R}_{>0}^K\) và \(\alpha_0 := \sum_{k=1}^K \alpha_k\):
\[p(\boldsymbol{\theta}) = \frac{1}{B(\boldsymbol{\alpha})}\prod_{k=1}^K \theta_k^{\alpha_k - 1}, \qquad B(\boldsymbol{\alpha}) := \frac{\prod_{k=1}^K \Gamma(\alpha_k)}{\Gamma(\alpha_0)}, \qquad \mathbb{E}[\theta_k] = \frac{\alpha_k}{\alpha_0},\quad \operatorname{Cov}(\theta_j, \theta_k) = \frac{\alpha_0\alpha_j\delta_{jk} - \alpha_j\alpha_k}{\alpha_0^2(\alpha_0+1)}.\]Kết hợp hợp lý đếm lớp \(\mathbf{c} = (c_1, \dots, c_K)^\top\) (\(\sum c_k = n\)) cho hậu nghiệm \(\boldsymbol{\theta} \mid \mathbf{c} \sim \operatorname{Dirichlet}(\boldsymbol{\alpha} + \mathbf{c})\).
- Dự báo Hậu nghiệm & Cầu nối Làm trơn:
- Với \(1\) mẫu mới: \(P(\tilde{X}=k\mid\mathbf{c}) = \frac{B(\boldsymbol{\alpha}+\mathbf{c}+\mathbf{e}_k)}{B(\boldsymbol{\alpha}+\mathbf{c})} = \frac{\alpha_k + c_k}{\alpha_0 + n}\).
- Với \(m\) mẫu mới \(\tilde{\mathbf{c}}\) (Dirichlet–Multinomial / Pólya Urn): \(P(\tilde{\mathbf{c}}\mid\mathbf{c}) = \frac{m!}{\prod_{k=1}^K \tilde{c}_k!}\frac{B(\boldsymbol{\alpha}+\mathbf{c}+\tilde{\mathbf{c}})}{B(\boldsymbol{\alpha}+\mathbf{c})}\).
- Đặt tiên nghiệm đối xứng \(\alpha_k = \epsilon > 0\) (\(\alpha_0 = K\epsilon\)) cho ra chính xác làm trơn cộng Lidstone: \(\hat{\theta}_k^{(\epsilon)} = \frac{c_k + \epsilon}{n + K\epsilon}\). Chọn \(\epsilon = 1\) (\(\operatorname{Dir}(\mathbf{1}_K)\) phẳng) cho Làm trơn Laplace (Add-One) ngăn một từ vắng mặt (\(c_k=0\)) triệt tiêu toàn bộ log-hợp lý Naive Bayes; chọn \(\epsilon = 1/2\) (\(\operatorname{Dir}(\frac{1}{2}\mathbf{1}_K) \propto (\det \mathcal{I}(\boldsymbol{\theta}))^{1/2}\)) cho Làm trơn Jeffreys / Krichevsky–Trofimov, đạt dư thừa KL tối ưu minimax \(O(K\ln n)\) trong mã hóa tuần tự phổ quát.
4. Họ Normal–Normal (Đã biết \(\sigma^2\) — Bổ túc Bình phương theo Độ chính xác \(\tau_{\text{prec}}\))
- Mô hình & Định luật Cộng tính Độ chính xác: Đặt độ chính xác (precision) \(\tau_{\text{prec}} := \sigma^{-2} > 0\) và độ chính xác tiên nghiệm \(\tau_{\text{prec},0} := \sigma_0^{-2} > 0\). Với \(\mu \sim \mathcal{N}(\mu_0, \sigma_0^2)\) và \(x_1, \dots, x_n \stackrel{\text{i.i.d.}}{\sim} \mathcal{N}(\mu, \sigma^2)\), dùng hằng đẳng thức \(\sum_{i=1}^n (x_i - \mu)^2 = \sum_{i=1}^n (x_i - \bar{x})^2 + n(\bar{x} - \mu)^2\), khai triển \(-2\ln p(\mu \mid x_{1:n})\) (bỏ hằng số không chứa \(\mu\)):
\[\begin{aligned} -2\ln p(\mu \mid x_{1:n}) &= \tau_{\text{prec},0}(\mu - \mu_0)^2 + \tau_{\text{prec}}\sum_{i=1}^n (x_i - \mu)^2 + C \\ &= (\tau_{\text{prec},0} + n\tau_{\text{prec}})\mu^2 - 2(\tau_{\text{prec},0}\mu_0 + n\tau_{\text{prec}}\bar{x})\mu + C' \\ &= (\tau_{\text{prec},0} + n\tau_{\text{prec}})\left(\mu - \frac{\tau_{\text{prec},0}\mu_0 + n\tau_{\text{prec}}\bar{x}}{\tau_{\text{prec},0} + n\tau_{\text{prec}}}\right)^2 + C''. \end{aligned}\]Lấy mũ \(-\frac{1}{2}(\dots)\) thu được hậu nghiệm chuẩn xác \(\mu \mid x_{1:n} \sim \mathcal{N}(\mu_n, \sigma_n^2)\) với:\[\tau_{\text{prec},n} := \frac{1}{\sigma_n^2} = \tau_{\text{prec},0} + n\tau_{\text{prec}} = \frac{1}{\sigma_0^2} + \frac{n}{\sigma^2}, \qquad \mu_n = \frac{\tau_{\text{prec},0}\mu_0 + n\tau_{\text{prec}}\bar{x}}{\tau_{\text{prec},0} + n\tau_{\text{prec}}} = \frac{\sigma^2\mu_0 + n\sigma_0^2\bar{x}}{\sigma^2 + n\sigma_0^2}.\]
- Phân rã Dự báo Hậu nghiệm (Nhận thức vs. Ngẫu nhiên): Viết mẫu mới \(\tilde{X} = \mu + \tilde{\varepsilon}\) với \(\mu \mid \mathcal{D} \sim \mathcal{N}(\mu_n, \sigma_n^2)\) độc lập có điều kiện với \(\tilde{\varepsilon} \sim \mathcal{N}(0, \sigma^2)\) suy ra trực tiếp:
\[\tilde{X} \mid \mathcal{D} \sim \mathcal{N}\!\left(\mu_n,\;\; \underbrace{\sigma_n^2}_{\text{Epistemic } O(n^{-1})} + \underbrace{\sigma^2}_{\text{Aleatoric}}\right).\](Lưu ý: Nếu \(\sigma^2\) cũng chưa biết dưới tiên nghiệm liên hợp Normal–Inverse-Gamma, việc tích phân khử cả \(\mu\) và \(\sigma^2\) cho phân phối dự báo Student-\(t\) đuôi nặng hơn Chuẩn.)
| Cặp Liên hợp | Tiên nghiệm | Hợp lý (\(n\) mẫu) | Siêu tham số Hậu nghiệm | Phân phối Dự báo \(p(\tilde{x} \mid \mathcal{D})\) |
|---|---|---|---|---|
| Beta–Binomial | \(\operatorname{Beta}(\alpha, \beta)\) | \(\operatorname{Binomial}(n, \theta)\) (\(k\) thành công) | \(\alpha' = \alpha + k,\; \beta' = \beta + n - k\) | Đơn: \(\operatorname{Bern}\!\left(\frac{\alpha'}{\alpha'+\beta'}\right)\); \(m\) thử: \(\operatorname{BetaBin}(m, \alpha', \beta')\) |
| Gamma–Poisson | \(\operatorname{Gamma}(\alpha, \beta)\) (Shape–Rate) | \(\operatorname{Poisson}(\lambda)\) (\(\sum x_i = S\)) | \(\alpha' = \alpha + S,\; \beta' = \beta + n\) | \(\operatorname{NegBin}\!\left(r = \alpha',\; p_{\text{stop}} = \frac{\beta'}{\beta'+1}\right)\) |
| Dirichlet–Categorical | \(\operatorname{Dir}(\boldsymbol{\alpha})\) | \(\operatorname{Cat}(\boldsymbol{\theta})\) (đếm \(\mathbf{c}\)) | \(\boldsymbol{\alpha}' = \boldsymbol{\alpha} + \mathbf{c}\) | Đơn: \(\operatorname{Cat}\!\left(\frac{\boldsymbol{\alpha}+\mathbf{c}}{\alpha_0+n}\right)\); \(m\) rút: \(\operatorname{DirMult}(m, \boldsymbol{\alpha}')\) |
| Normal–Normal (biết \(\sigma^2\)) | \(\mathcal{N}(\mu_0, \tau_{\text{prec},0}^{-1})\) | \(\mathcal{N}(\mu, \tau_{\text{prec}}^{-1})\) (trung bình \(\bar{x}\)) | \(\tau_{\text{prec},n} = \tau_{\text{prec},0} + n\tau_{\text{prec}},\; \mu_n = \frac{\tau_{\text{prec},0}\mu_0 + n\tau_{\text{prec}}\bar{x}}{\tau_{\text{prec},n}}\) | \(\mathcal{N}(\mu_n,\; \tau_{\text{prec},n}^{-1} + \sigma^2)\) |
1.2 Phân phối Cốt lõi, Giới hạn Poisson, MVN Schur & Họ Hàm mũ Chính tắc (Core Distributions, Poisson Limit, MVN & Canonical Exponential Family)#
Bảng Tham chiếu 12 Phân phối Cốt lõi trong ML/DS#
Ký hiệu Hàm sinh Mô-men (MGF) \(M_X(t) := \mathbb{E}[e^{tX}]\) (tồn tại trên khoảng mở quanh \(0\) nếu hữu hạn) và Hàm sinh Tích lũy (CGF) \(K_X(t) := \ln M_X(t)\) với \(\kappa_1 = K_X'(0) = \mathbb{E}[X]\), \(\kappa_2 = K_X''(0) = \operatorname{Var}(X)\).
| Phân phối | Miền giá trị (Support) | PMF / PDF \(p(x)\) | \(\mathbb{E}[X]\) | \(\operatorname{Var}(X)\) | MGF \(M_X(t)\) | Vai trò Cốt lõi trong ML / DS |
|---|---|---|---|---|---|---|
| \(\operatorname{Bernoulli}(p)\) (\(p\in[0,1]\)) | \(\{0, 1\}\) | \(p^x(1-p)^{1-x}\) | \(p\) | \(p(1-p)\) | \((1-p) + pe^t\) | Nhãn nhị phân, mục tiêu hồi quy logistic, mặt nạ dropout |
| \(\operatorname{Binomial}(n, p)\) (\(n \in \mathbb{N}_+\)) | \(\{0,\dots,n\}\) | \(\binom{n}{x}p^x(1-p)^{n-x}\) | \(np\) | \(np(1-p)\) | \(((1-p)+pe^t)^n\) | Tổng chuyển đổi A/B chân trời cố định, đếm bootstrap |
| \(\operatorname{Categorical}(\boldsymbol{\pi})\) (\(\boldsymbol{\pi}\in\Delta^{K-1}\)) | \(\{1,\dots,K\}\) | \(\prod_{k=1}^K \pi_k^{\mathbb{I}[x=k]}\) | \(\mathbb{E}[\mathbf{e}_X] = \boldsymbol{\pi}\) | \(\operatorname{diag}(\boldsymbol{\pi}) - \boldsymbol{\pi}\boldsymbol{\pi}^\top\) | \(\sum_{k=1}^K \pi_k e^{t_k}\) (one-hot) | Đầu ra Softmax đa lớp, phân phối token tiếp theo của LLM |
| \(\operatorname{Multinomial}(n, \boldsymbol{\pi})\) | \(\{\mathbf{c}\in\mathbb{N}_0^K : \sum c_k = n\}\) | \(\frac{n!}{\prod_k c_k!}\prod_{k=1}^K \pi_k^{c_k}\) | \(n\boldsymbol{\pi}\) | \(n(\operatorname{diag}(\boldsymbol{\pi}) - \boldsymbol{\pi}\boldsymbol{\pi}^\top)\) | \((\sum_{k=1}^K \pi_k e^{t_k})^n\) | Đếm BoW/chủ đề, phân bổ lưu lượng đa biến thể SRM |
| \(\operatorname{Poisson}(\lambda)\) (\(\lambda > 0\)) | \(\mathbb{N}_0 = \{0,1,2,\dots\}\) | \(\frac{\lambda^x e^{-\lambda}}{x!}\) | \(\lambda\) | \(\lambda\) | \(\exp(\lambda(e^t - 1))\) | Sự kiện hiếm, tốc độ truy cập, hồi quy đếm |
| \(\operatorname{Normal}(\mu, \sigma^2)\) (\(\sigma > 0\)) | \(\mathbb{R}\) | \(\frac{1}{\sqrt{2\pi}\sigma}\exp(-\frac{(x-\mu)^2}{2\sigma^2})\) | \(\mu\) | \(\sigma^2\) | \(\exp(\mu t + \frac{1}{2}\sigma^2 t^2)\) | Nhiễu Gaussian (\(\leftrightarrow\) MSE), giới hạn CLT, khởi tạo trọng số |
| \(\operatorname{MVN}(\boldsymbol{\mu}, \boldsymbol{\Sigma})\) (\(\boldsymbol{\Sigma}\succ 0\)) | \(\mathbb{R}^d\) | \((2\pi)^{-d/2}\lvert\boldsymbol{\Sigma}\rvert^{-1/2}\exp(-\frac{1}{2}D_M^2)\) | \(\boldsymbol{\mu}\) | \(\boldsymbol{\Sigma}\) | \(\exp(\boldsymbol{\mu}^\top\mathbf{t} + \frac{1}{2}\mathbf{t}^\top\boldsymbol{\Sigma}\mathbf{t})\) | Gaussian Process, Kalman Filter, phát hiện OOD Mahalanobis |
| \(\operatorname{Student-}t_\nu(\mu, \sigma^2)\) (\(\nu>0\)) | \(\mathbb{R}\) | \(\frac{\Gamma(\frac{\nu+1}{2})}{\sqrt{\nu\pi}\sigma\Gamma(\frac{\nu}{2})}(1+\frac{(x-\mu)^2}{\nu\sigma^2})^{-\frac{\nu+1}{2}}\) | \(\mu\) (iff \(\nu>1\)) | \(\frac{\nu}{\nu-2}\sigma^2\) (iff \(\nu>2\)) | Không tồn tại (\(\forall t \ne 0\)) | Hồi quy bền vững ngoại lai, kiểm định \(t\) mẫu nhỏ |
| \(\operatorname{Exponential}(\lambda)\) (\(\lambda>0\)) | \([0, \infty)\) | \(\lambda e^{-\lambda x}\) | \(\frac{1}{\lambda}\) | \(\frac{1}{\lambda^2}\) | \(\frac{\lambda}{\lambda - t}\) (\(t < \lambda\)) | Thời gian chờ không nhớ, mô hình sinh tồn |
| \(\operatorname{Gamma}(\alpha, \beta)\) (Shape–Rate) | \((0, \infty)\) | \(\frac{\beta^\alpha}{\Gamma(\alpha)}x^{\alpha-1}e^{-\beta x}\) | \(\frac{\alpha}{\beta}\) | \(\frac{\alpha}{\beta^2}\) | \((1 - \frac{t}{\beta})^{-\alpha}\) (\(t < \beta\)) | Độ trễ/biên độ dương lệch phải, \(\chi^2_k = \operatorname{Gamma}(k/2, 1/2)\) |
| \(\operatorname{Beta}(\alpha, \beta)\) (\(\alpha,\beta > 0\)) | \((0, 1)\) | \(\frac{1}{B(\alpha,\beta)}x^{\alpha-1}(1-x)^{\beta-1}\) | \(\frac{\alpha}{\alpha+\beta}\) | \(\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\) | \(1 + \sum_{k=1}^\infty (\prod_{r=0}^{k-1}\frac{\alpha+r}{\alpha+\beta+r})\frac{t^k}{k!}\) | Tiên nghiệm tỷ lệ/CTR, Thompson Sampling bandits |
| \(\operatorname{LogNormal}(\mu, \sigma^2)\) | \((0, \infty)\) | \(\frac{1}{x\sigma\sqrt{2\pi}}\exp(-\frac{(\ln x - \mu)^2}{2\sigma^2})\) | \(e^{\mu + \frac{\sigma^2}{2}}\) | \((e^{\sigma^2}-1)e^{2\mu+\sigma^2}\) | Không tồn tại (\(t > 0\)) | GMV/doanh thu lệch đuôi, độ trễ SLO, nhiễu nhân |
Chứng minh Hiệp phương sai Multinomial PSD & Suy biến Hạng \(\le K - 1\)#
Biểu diễn \(\mathbf{C} = \sum_{m=1}^n \mathbf{Z}^{(m)}\) với \(\mathbf{Z}^{(m)} \stackrel{\text{i.i.d.}}{\sim} \operatorname{Categorical}(\boldsymbol{\pi})\) dạng one-hot. Với một phép rút đơn lẻ \(\mathbf{Z}\), \(\mathbb{E}[Z_i] = \pi_i\), \(\mathbb{E}[Z_i^2] = \pi_i\), \(\mathbb{E}[Z_i Z_j] = 0\) (\(i \ne j\)), suy ra \(\operatorname{Cov}(Z_i, Z_j) = \pi_i\delta_{ij} - \pi_i\pi_j\), tức \(\boldsymbol{\Sigma}_1 = \operatorname{diag}(\boldsymbol{\pi}) - \boldsymbol{\pi}\boldsymbol{\pi}^\top\), và do độc lập \(\boldsymbol{\Sigma} = n\boldsymbol{\Sigma}_1\). Với mọi \(\mathbf{v}\in\mathbb{R}^K\), \(\mathbf{v}^\top\boldsymbol{\Sigma}\mathbf{v} = \operatorname{Var}(\mathbf{v}^\top\mathbf{C}) \ge 0\) (PSD). Nhưng vì \(\mathbf{1}^\top \mathbf{C} = n\) là hằng số, \(\boldsymbol{\Sigma}\mathbf{1} = n(\boldsymbol{\pi} - \boldsymbol{\pi}(\boldsymbol{\pi}^\top\mathbf{1})) = \mathbf{0}\): ma trận \(\boldsymbol{\Sigma}\) luôn suy biến với \(\operatorname{rank}(\boldsymbol{\Sigma}) \le K - 1\). Đây chính là lý do kiểm định Pearson \(\chi^2\) mất đúng \(1\) bậc tự do (\(\text{df} = K - 1\)).
Chứng minh Chặt chẽ Định lý Giới hạn Poisson (Poisson Limit Theorem)#
Định lý 1.3 (Luật Biến cố Hiếm / Giới hạn Poisson): Cho \(X_n \sim \operatorname{Binomial}(n, p_n)\) với \(p_n = \frac{\lambda}{n}\) (\(\lambda > 0\) cố định; tổng quát hơn \(n p_n \to \lambda\)). Khi đó với mọi số nguyên không âm \(k \in \mathbb{N}_0\) cố định:
Chứng minh (Hội tụ từng điểm PMF): Với \(n > \max(k, \lambda)\):
Cho \(n \to \infty\) với \(k\) cố định: (1) tích hữu hạn gồm \(k\) thừa số \(\prod_{j=0}^{k-1}(1 - j/n) \to 1\); (2) theo giới hạn cơ bản \(\lim_{n\to\infty}(1 + x/n)^n = e^x\), ta có \((1 - \frac{\lambda}{n})^n \to e^{-\lambda}\); và (3) \((1 - \frac{\lambda}{n})^{-k} \to 1^{-k} = 1\). Nhân các giới hạn thu được \(\lim_{n\to\infty} P(X_n = k) = \frac{\lambda^k e^{-\lambda}}{k!}\). \(\blacksquare\)
(Chứng minh thay thế qua MGF: \(M_{X_n}(t) = \big(1 + \frac{\lambda(e^t-1)}{n}\big)^n \to \exp(\lambda(e^t-1))\), trùng khớp MGF duy nhất của \(\operatorname{Poisson}(\lambda)\). Cảnh báo thực tế: phân phối Poisson ép đẳng phân tán \(\operatorname{Var}(X) = \mathbb{E}[X] = \lambda\), trong khi dữ liệu đếm người dùng luôn quá phân tán \(\operatorname{Var}(X) > \mathbb{E}[X]\) do tính không đồng nhất giữa người dùng — đòi hỏi chuyển sang Negative Binomial hoặc hỗn hợp Gamma–Poisson.)
Phân phối Chuẩn Đa biến (MVN): Phần bù Schur, Ma trận Chính xác \(\boldsymbol{\Lambda}\) & Phản ví dụ \(Y = SX\)#
Cho \(\mathbf{X} \sim \mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\Sigma})\) với \(\boldsymbol{\Sigma} \in \mathbb{R}^{d\times d}\) đối xứng xác định dương (\(\boldsymbol{\Sigma} \succ 0\)) và ma trận chính xác (precision matrix) \(\boldsymbol{\Lambda} := \boldsymbol{\Sigma}^{-1} \succ 0\):
- Khoảng cách Mahalanobis & Quy luật \(\chi^2_d\): Định nghĩa \(D_M(\mathbf{x}; \boldsymbol{\mu}, \boldsymbol{\Sigma}) := \sqrt{(\mathbf{x} - \boldsymbol{\mu})^\top \boldsymbol{\Sigma}^{-1}(\mathbf{x} - \boldsymbol{\mu})}\). Sử dụng nhân tử làm trắng \(\boldsymbol{\Sigma}^{-1/2}\) (qua phân rã phổ hoặc \(\mathbf{L}^{-1}\) từ Cholesky \(\boldsymbol{\Sigma} = \mathbf{L}\mathbf{L}^\top\)), vector chuẩn hóa \(\mathbf{Z} := \boldsymbol{\Sigma}^{-1/2}(\mathbf{X} - \boldsymbol{\mu})\) thỏa \(\mathbf{Z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_d)\), suy ra:
\[D_M(\mathbf{X}; \boldsymbol{\mu}, \boldsymbol{\Sigma})^2 = \|\mathbf{Z}\|_2^2 = \sum_{i=1}^d Z_i^2 \sim \chi^2_d,\]bất biến dưới mọi phép biến đổi affine khả nghịch \(\mathbf{X} \mapsto \mathbf{A}\mathbf{X} + \mathbf{b}\) và cho phép kiểm định OOD theo phân vị \(\chi^2_d\).
- Độc lập Có điều kiện trong Ma trận Chính xác \(\boldsymbol{\Lambda}\): Trong khi \(\Sigma_{ij} = 0\) chỉ biểu thị độc lập biên (marginal independence), cấu trúc độc lập có điều kiện khi biết toàn bộ các tọa độ còn lại \(\mathbf{X}_{-\{i,j\}}\) nằm hoàn toàn trong \(\boldsymbol{\Lambda}\):
\[\Lambda_{ij} = 0 \quad (i \ne j) \iff X_i \perp\!\!\!\perp X_j \mid \mathbf{X}_{-\{i,j\}}.\]Chứng minh: Khai triển dạng toàn phương \(\frac{1}{2}(\mathbf{x} - \boldsymbol{\mu})^\top\boldsymbol{\Lambda}(\mathbf{x} - \boldsymbol{\mu})\) theo \((x_i, x_j)\) khi cố định \(\mathbf{x}_{-\{i,j\}}\), số hạng chéo duy nhất giữa \(x_i\) và \(x_j\) là \(\Lambda_{ij}(x_i - \mu_i)(x_j - \mu_j)\). Vì vậy mật độ có điều kiện \(p(x_i, x_j \mid \mathbf{x}_{-\{i,j\}})\) tách nhân tử thành \(g_1(x_i, \mathbf{x}_{-\{i,j\}})\,g_2(x_j, \mathbf{x}_{-\{i,j\}})\) khi và chỉ khi \(\Lambda_{ij} = 0\). \(\blacksquare\)
-
Định lý 1.4 (Biên hóa & Điều kiện hóa MVN qua Phần bù Schur): Phân hoạch \(\mathbf{X} = \begin{bmatrix}\mathbf{X}_1 \\ \mathbf{X}_2\end{bmatrix} \in \mathbb{R}^{d_1 + d_2}\) với \(\boldsymbol{\mu} = \begin{bmatrix}\boldsymbol{\mu}_1 \\ \boldsymbol{\mu}_2\end{bmatrix}\), \(\boldsymbol{\Sigma} = \begin{bmatrix}\boldsymbol{\Sigma}_{11} & \boldsymbol{\Sigma}_{12} \\ \boldsymbol{\Sigma}_{21} & \boldsymbol{\Sigma}_{22}\end{bmatrix}\), và \(\boldsymbol{\Lambda} = \boldsymbol{\Sigma}^{-1} = \begin{bmatrix}\boldsymbol{\Lambda}_{11} & \boldsymbol{\Lambda}_{12} \\ \boldsymbol{\Lambda}_{21} & \boldsymbol{\Lambda}_{22}\end{bmatrix}\) (\(\boldsymbol{\Sigma}_{22} \succ 0, \boldsymbol{\Lambda}_{11} \succ 0\)). Khi đó:
- Biên: \(\mathbf{X}_1 \sim \mathcal{N}(\boldsymbol{\mu}_1, \boldsymbol{\Sigma}_{11})\).
- Có điều kiện (Dạng Hiệp phương sai): \(\mathbf{X}_1 \mid (\mathbf{X}_2 = \mathbf{x}_2) \sim \mathcal{N}(\boldsymbol{\mu}_{1|2},\; \boldsymbol{\Sigma}_{1|2})\), trong đó:
\[\boldsymbol{\mu}_{1|2} = \boldsymbol{\mu}_1 + \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}(\mathbf{x}_2 - \boldsymbol{\mu}_2), \qquad \boldsymbol{\Sigma}_{1|2} = \boldsymbol{\Sigma}_{11} - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\Sigma}_{21}.\]
- Có điều kiện (Dạng Đối ngẫu Chính xác): \(\boldsymbol{\Sigma}_{1|2} = \boldsymbol{\Lambda}_{11}^{-1}\) và \(\boldsymbol{\mu}_{1|2} = \boldsymbol{\mu}_1 - \boldsymbol{\Lambda}_{11}^{-1}\boldsymbol{\Lambda}_{12}(\mathbf{x}_2 - \boldsymbol{\mu}_2)\).
Chứng minh:
- Biên: Thay \(\mathbf{t} = [\mathbf{t}_1^\top, \mathbf{0}^\top]^\top\) vào MGF của \(\mathbf{X}\) cho \(M_{\mathbf{X}_1}(\mathbf{t}_1) = \exp(\boldsymbol{\mu}_1^\top\mathbf{t}_1 + \frac{1}{2}\mathbf{t}_1^\top\boldsymbol{\Sigma}_{11}\mathbf{t}_1)\), nhận diện duy nhất \(\mathcal{N}(\boldsymbol{\mu}_1, \boldsymbol{\Sigma}_{11})\).
- Khử tương quan tuyến tính: Đặt \(\mathbf{Z} := \mathbf{X}_1 - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\mathbf{X}_2\). Do \((\mathbf{Z}, \mathbf{X}_2)\) là biến đổi tuyến tính của vector Gaussian đồng thời \(\mathbf{X}\), cặp \((\mathbf{Z}, \mathbf{X}_2)\) cũng là Gaussian đồng thời với hiệp phương sai chéo:
\[\operatorname{Cov}(\mathbf{Z}, \mathbf{X}_2) = \boldsymbol{\Sigma}_{12} - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\Sigma}_{22} = \mathbf{0}.\]Vì vậy \(\mathbf{Z} \perp\!\!\!\perp \mathbf{X}_2\), suy ra luật có điều kiện của \(\mathbf{Z}\) khi biết \(\mathbf{X}_2 = \mathbf{x}_2\) trùng với luật biên của \(\mathbf{Z}\) có kỳ vọng \(\boldsymbol{\mu}_1 - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\mu}_2\) và hiệp phương sai \(\operatorname{Cov}(\mathbf{Z}) = \boldsymbol{\Sigma}_{11} - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\Sigma}_{21}\) (phần bù Schur của \(\boldsymbol{\Sigma}_{22}\)). Viết \(\mathbf{X}_1 = \mathbf{Z} + \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\mathbf{X}_2\) cho ngay \(\mathcal{N}(\boldsymbol{\mu}_{1|2}, \boldsymbol{\Sigma}_{1|2})\).
- Đối ngẫu Chính xác: Từ \(\boldsymbol{\Sigma}\boldsymbol{\Lambda} = \mathbf{I}\), khối trái dưới cho \(\boldsymbol{\Sigma}_{21}\boldsymbol{\Lambda}_{11} + \boldsymbol{\Sigma}_{22}\boldsymbol{\Lambda}_{21} = \mathbf{0} \implies \boldsymbol{\Lambda}_{21} = -\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\Sigma}_{21}\boldsymbol{\Lambda}_{11}\), và theo tính đối xứng \(\boldsymbol{\Lambda}_{12} = \boldsymbol{\Lambda}_{21}^\top = -\boldsymbol{\Lambda}_{11}\boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1} \implies -\boldsymbol{\Lambda}_{11}^{-1}\boldsymbol{\Lambda}_{12} = \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\). Thế vào khối trái trên \(\boldsymbol{\Sigma}_{11}\boldsymbol{\Lambda}_{11} + \boldsymbol{\Sigma}_{12}\boldsymbol{\Lambda}_{21} = \mathbf{I}\) thu được \((\boldsymbol{\Sigma}_{11} - \boldsymbol{\Sigma}_{12}\boldsymbol{\Sigma}_{22}^{-1}\boldsymbol{\Sigma}_{21})\boldsymbol{\Lambda}_{11} = \mathbf{I} \implies \boldsymbol{\Sigma}_{1|2} = \boldsymbol{\Lambda}_{11}^{-1}\). \(\blacksquare\)
Phản ví dụ Chuẩn biên + Hiệp phương sai \(0 \not\Rightarrow\) Chuẩn Đồng thời hay Độc lập (
Y = S X): Cho \(X \sim \mathcal{N}(0, 1)\) và \(S \in \{-1, +1\}\) độc lập với \(P(S=1)=P(S=-1)=1/2\); đặt \(Y := S X\). Theo tính đối xứng của \(X\), \(Y \sim \mathcal{N}(0, 1)\) biên, và \(\operatorname{Cov}(X, Y) = \mathbb{E}[S]\mathbb{E}[X^2] = 0\). Thế nhưng \(|Y| = |X|\) tất định (phân bố trên chữ thập \(y = \pm x\)), chứng tỏ \((X, Y)\) phụ thuộc cực mạnh và không là Chuẩn Đa biến!
Sắc thái của Student-t, Exponential & LogNormal#
- \(\operatorname{Student-}t_\nu(\mu, \sigma^2)\): Đuôi đa thức phân rã theo \(|x|^{-(\nu+1)}\), nên \(\mathbb{E}[|X|^m] < \infty \iff m < \nu\) (Cauchy \(\nu=1\) vô định cả kỳ vọng lẫn phương sai; \(\nu=2\) có kỳ vọng nhưng phương sai vô hạn) và không có MGF. Thay thế sai số Gaussian bằng \(r_i \sim t_\nu(0, \sigma^2)\) tạo NLL \(\ell(r) = \frac{\nu+1}{2}\ln(1 + \frac{r^2}{\nu\sigma^2})\) có hàm ảnh hưởng giảm dần (redescending influence):
\[\psi(r) = \frac{\partial \ell}{\partial r} = \frac{(\nu+1)r}{\nu\sigma^2 + r^2} \xrightarrow{|r| \to \infty} 0,\]chủ động giảm trọng số của ngoại lai cực lớn về \(0\) (mạnh hơn cả Huber loss vốn giữ nguyên \(\pm\delta\)).
- \(\operatorname{Exponential}(\lambda)\): Phân phối liên tục duy nhất có tính chất không nhớ (memoryless): \(P(X > s + t \mid X > s) = e^{-\lambda t} = P(X > t)\), tương ứng tỷ lệ nguy cơ (hazard rate) hằng số \(h(t) = \lambda\).
- \(\operatorname{LogNormal}(\mu, \sigma^2)\): Đặt \(X = e^Z\) với \(Z \sim \mathcal{N}(\mu, \sigma^2)\), biến đổi Jacobian \(\left|\frac{dz}{dx}\right| = \frac{1}{x}\) cho mật độ \(p_X(x) = \frac{1}{x\sigma\sqrt{2\pi}}\exp\big(-\frac{(\ln x - \mu)^2}{2\sigma^2}\big)\). Từ MGF Gaussian \(M_Z(k)\), mọi mô-men bậc nguyên đều hữu hạn: \(\mathbb{E}[X^k] = \exp(k\mu + \frac{1}{2}k^2\sigma^2)\), nên \(\mathbb{E}[X] = e^{\mu+\sigma^2/2} > \operatorname{Median}(X) = e^\mu > \operatorname{Mode}(X) = e^{\mu-\sigma^2}\). Tuy nhiên LogNormal không có MGF (\(M_X(t)=\infty\;\forall t>0\)) và là phản ví dụ kinh điển cho tính bất định mô-men (dãy mọi mô-men không xác định duy nhất phân phối). Hơn nữa, hồi quy OLS trên \(\ln Y\) trả ra \(\hat{\mu}(x) = \mathbb{E}[\ln Y \mid x]\) khiến phép dịch ngược ngây thơ
exp(y_hat_log)dự đoán trung vị thay vì trung bình số học, gây thiên lệch suy giảm Jensen bằng nhân tử \(e^{-\sigma^2/2}\) (tụt \(39.3\%\) ở \(\sigma = 1\)!). Khắc phục bằng \(\exp(\hat{\mu}(x) + \frac{1}{2}\hat{\sigma}^2)\) hoặc phi tham số bằng bộ ước lượng bôi trơn Duan \(\frac{1}{n}\sum_{i=1}^n e^{r_i} \cdot e^{\hat{\mu}(x)}\) (§2.1).
Thống nhất qua Họ Hàm mũ Chính tắc (Canonical Exponential Family)#
Một họ phân phối thuộc họ hàm mũ chính tắc (Canonical Exponential Family) nếu viết được dưới dạng:
trên miền tham số tự nhiên \(\Omega := \{\boldsymbol{\eta} \in \mathbb{R}^d : A(\boldsymbol{\eta}) < \infty\}\) (thay \(\int\) bằng \(\sum\) với biến rời rạc).
Định lý 1.5 (Tính lồi & Đạo hàm Tích lũy của Hàm Log-Phân hoạch \(A(\boldsymbol{\eta})\)):
- Tập \(\Omega\) là tập lồi trong \(\mathbb{R}^d\) và hàm \(A(\boldsymbol{\eta})\) lồi trên \(\Omega\).
- Trên phần trong mở \(\Omega^\circ\) (nơi Định lý Hội tụ Bị chặn cho phép hoán đổi đạo hàm và tích phân):
\[\nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)], \qquad \nabla^2_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \operatorname{Cov}_{\boldsymbol{\eta}}\big(\mathbf{T}(X)\big) = \mathcal{I}(\boldsymbol{\eta}) \succeq \mathbf{0},\]và \(A(\boldsymbol{\eta})\) lồi chặt (\(\nabla^2 A(\boldsymbol{\eta}) \succ \mathbf{0}\)) khi và chỉ khi biểu diễn là tối tiểu (minimal, không tồn tại \(\mathbf{v}\ne\mathbf{0}\) để \(\mathbf{v}^\top\mathbf{T}(X)\) là hằng số hầu chắc chắn).
Chứng minh đầy đủ:
- Tính lồi bằng Bất đẳng thức Hölder: Lấy \(\boldsymbol{\eta}_1, \boldsymbol{\eta}_2 \in \Omega\) và \(\lambda \in (0, 1)\), đặt \(p = 1/\lambda > 1\) và \(q = 1/(1-\lambda) > 1\) (\(\frac{1}{p}+\frac{1}{q}=1\)). Áp dụng bất đẳng thức Hölder cho \(f(x) = [h(x)e^{\boldsymbol{\eta}_1^\top\mathbf{T}(x)}]^\lambda\) và \(g(x) = [h(x)e^{\boldsymbol{\eta}_2^\top\mathbf{T}(x)}]^{1-\lambda}\):
\[\int h(x)e^{(\lambda\boldsymbol{\eta}_1 + (1-\lambda)\boldsymbol{\eta}_2)^\top\mathbf{T}(x)}\,dx \le \left(\int h(x)e^{\boldsymbol{\eta}_1^\top\mathbf{T}(x)}\,dx\right)^\lambda \left(\int h(x)e^{\boldsymbol{\eta}_2^\top\mathbf{T}(x)}\,dx\right)^{1-\lambda} < \infty.\]Lấy logarit hai vế suy ra \(\lambda\boldsymbol{\eta}_1 + (1-\lambda)\boldsymbol{\eta}_2 \in \Omega\) và \(A(\lambda\boldsymbol{\eta}_1 + (1-\lambda)\boldsymbol{\eta}_2) \le \lambda A(\boldsymbol{\eta}_1) + (1-\lambda)A(\boldsymbol{\eta}_2)\).
- Gradient bậc nhất (\(\nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)]\)):
\[\nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \frac{\nabla_{\boldsymbol{\eta}}\int h(x)e^{\boldsymbol{\eta}^\top\mathbf{T}(x)}\,dx}{\int h(x)e^{\boldsymbol{\eta}^\top\mathbf{T}(x)}\,dx} = \int \mathbf{T}(x)\frac{h(x)e^{\boldsymbol{\eta}^\top\mathbf{T}(x)}}{e^{A(\boldsymbol{\eta})}}\,dx = \int \mathbf{T}(x)p(x\mid\boldsymbol{\eta})\,dx = \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)].\]
- Hessian bậc hai & Thông tin Fisher (\(\nabla^2_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \operatorname{Cov}_{\boldsymbol{\eta}}(\mathbf{T}(X)) = \mathcal{I}(\boldsymbol{\eta})\)): Lưu ý \(\nabla_{\boldsymbol{\eta}} p(x\mid\boldsymbol{\eta}) = p(x\mid\boldsymbol{\eta})\big(\mathbf{T}(x) - \nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta})\big) = p(x\mid\boldsymbol{\eta})\big(\mathbf{T}(x) - \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)]\big)\). Lấy vi phân phương trình \(\nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \int \mathbf{T}(x)p(x\mid\boldsymbol{\eta})\,dx\) theo quy ước Numerator Layout (\(\frac{\partial\mathbf{f}}{\partial\boldsymbol{\eta}^\top}\)):
\[\begin{aligned} \nabla^2_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) &= \int \mathbf{T}(x)\big(\nabla_{\boldsymbol{\eta}} p(x\mid\boldsymbol{\eta})\big)^\top\,dx \\ &= \int \mathbf{T}(x)\big(\mathbf{T}(x) - \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)]\big)^\top p(x\mid\boldsymbol{\eta})\,dx \\ &= \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)\mathbf{T}(X)^\top] - \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)]\mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}(X)]^\top = \operatorname{Cov}_{\boldsymbol{\eta}}\big(\mathbf{T}(X)\big). \end{aligned}\]Với mọi \(\mathbf{v} \in \mathbb{R}^d\), \(\mathbf{v}^\top\nabla^2 A(\boldsymbol{\eta})\mathbf{v} = \operatorname{Var}_{\boldsymbol{\eta}}(\mathbf{v}^\top\mathbf{T}(X)) \ge 0\), và vì \(-\nabla^2_{\boldsymbol{\eta}}\ln p(x\mid\boldsymbol{\eta}) = \nabla^2_{\boldsymbol{\eta}} A(\boldsymbol{\eta})\) không phụ thuộc \(x\), Thông tin Fisher đúng bằng \(\mathcal{I}(\boldsymbol{\eta}) = \nabla^2_{\boldsymbol{\eta}} A(\boldsymbol{\eta})\). \(\blacksquare\)
| Phân phối | \(h(x)\) | Thống kê đủ \(\mathbf{T}(x)\) | Tham số tự nhiên \(\boldsymbol{\eta}\) | Hàm Log-phân hoạch \(A(\boldsymbol{\eta})\) | Kỳ vọng \(\nabla_{\boldsymbol{\eta}} A(\boldsymbol{\eta}) = \mathbb{E}[\mathbf{T}(X)]\) |
|---|---|---|---|---|---|
| \(\operatorname{Bernoulli}(p)\) | \(1\) | \(x\) | \(\ln\frac{p}{1-p}\) (logit) | \(\ln(1+e^\eta)\) (softplus) | \(\sigma(\eta) = \frac{1}{1+e^{-\eta}} = p\) |
| \(\operatorname{Categorical}(\boldsymbol{\pi})\) (tối tiểu, \(d=K-1\)) | \(1\) | \([\mathbb{I}[x=1], \dots, \mathbb{I}[x=K-1]]^\top\) | \(\eta_k = \ln\frac{\pi_k}{\pi_K}\) | \(\ln(1 + \sum_{k=1}^{K-1} e^{\eta_k})\) | \(\pi_k = \frac{e^{\eta_k}}{1 + \sum_{j=1}^{K-1} e^{\eta_j}}\) (softmax) |
| \(\operatorname{Poisson}(\lambda)\) | \(\frac{1}{x!}\) | \(x\) | \(\ln\lambda\) | \(e^\eta\) | \(e^\eta = \lambda\) |
| \(\operatorname{Exponential}(\lambda)\) | \(1\) | \(x\) | \(-\lambda\) (\(\eta < 0\)) | \(-\ln(-\eta)\) | \(-\frac{1}{\eta} = \frac{1}{\lambda}\) |
| \(\operatorname{Normal}(\mu, \sigma^2)\) (cố định \(\sigma^2\)) | \(\frac{1}{\sqrt{2\pi}\sigma}e^{-x^2/(2\sigma^2)}\) | \(\frac{x}{\sigma}\) | \(\frac{\mu}{\sigma}\) | \(\frac{\eta^2}{2}\) | \(\eta = \frac{\mu}{\sigma}\) |
| \(\operatorname{Normal}(\mu, \sigma^2)\) (chưa biết \(\mu,\sigma^2\)) | \(\frac{1}{\sqrt{2\pi}}\) | \(\begin{bmatrix} x \\ x^2 \end{bmatrix}\) | \(\begin{bmatrix} \frac{\mu}{\sigma^2} \\ -\frac{1}{2\sigma^2} \end{bmatrix}\) (\(\eta_2<0\)) | \(-\frac{\eta_1^2}{4\eta_2}-\frac{1}{2}\ln(-2\eta_2)\) | \(\begin{bmatrix} -\frac{\eta_1}{2\eta_2} \\ \frac{\eta_1^2}{4\eta_2^2}-\frac{1}{2\eta_2} \end{bmatrix} = \begin{bmatrix} \mu \\ \mu^2+\sigma^2 \end{bmatrix}\) |
| \(\operatorname{Gamma}(\alpha, \beta)\) (Shape–Rate) | \(1\) | \(\begin{bmatrix} \ln x \\ x \end{bmatrix}\) | \(\begin{bmatrix} \alpha - 1 \\ -\beta \end{bmatrix}\) (\(\eta_1>-1, \eta_2<0\)) | \(\ln\Gamma(\eta_1+1) - (\eta_1+1)\ln(-\eta_2)\) | \(\begin{bmatrix} \psi(\alpha)-\ln\beta \\ \alpha/\beta \end{bmatrix}\) (\(\psi=\Gamma'/\Gamma\)) |
| \(\operatorname{Beta}(\alpha, \beta)\) | \(1\) | \(\begin{bmatrix} \ln x \\ \ln(1-x) \end{bmatrix}\) | \(\begin{bmatrix} \alpha - 1 \\ \beta - 1 \end{bmatrix}\) (\(\eta_i>-1\)) | \(\ln B(\eta_1+1, \eta_2+1)\) | \(\begin{bmatrix} \psi(\alpha)-\psi(\alpha+\beta) \\ \psi(\beta)-\psi(\alpha+\beta) \end{bmatrix}\) |
Cảnh báo Softmax Quá tham số hóa (Overparameterized Softmax Nullspace): Trong học sâu, lớp Softmax \(K\) chiều dùng logit dư \(\boldsymbol{\eta} \in \mathbb{R}^K\) với \(\mathbf{T}(x) = \mathbf{e}_x\) (ràng buộc \(\sum_k T_k(x) = 1\)) và \(A(\boldsymbol{\eta}) = \ln\sum_{k=1}^K e^{\eta_k}\). Hệ quả là phép dịch \(\boldsymbol{\eta} \mapsto \boldsymbol{\eta} + c\mathbf{1}\) giữ nguyên phân phối, còn ma trận Hessian \(\nabla^2 A(\boldsymbol{\eta}) = \operatorname{diag}(\boldsymbol{\pi}) - \boldsymbol{\pi}\boldsymbol{\pi}^\top\) có hạng \(K-1\) với không gian hạch (null space) \(\operatorname{span}\{\mathbf{1}\}\).
- Thống kê Đủ Fisher–Neyman & Đẳng thức
KL = Cross-Entropy = MLE: Theo Định lý Phân nhân tử Fisher–Neyman, \(\mathbf{S}(\mathbf{X})\) là thống kê đủ cho \(\boldsymbol{\theta}\) iff \(p(\mathbf{x}\mid\boldsymbol{\theta}) = g_{\boldsymbol{\theta}}(\mathbf{S}(\mathbf{x}))\tilde{h}(\mathbf{x})\). Trong họ hàm mũ chính tắc, \(\mathbf{S}(\mathbf{x}_{1:n}) = \sum_{i=1}^n \mathbf{T}(x_i)\) có chiều cố định \(d\) bất kể \(n\) lớn bao nhiêu (và Định lý Pitman–Koopman–Darmois chứng minh trên miền giá trị cố định, chỉ họ hàm mũ mới có tính chất nén thống kê đủ chiều hữu hạn này!). Hơn nữa, với phân phối dữ liệu thực nghiệm \(\hat{P}_n = \frac{1}{n}\sum_{i=1}^n \delta_{x_i}\) và \(\bar{\mathbf{T}} := \frac{1}{n}\sum_{i=1}^n \mathbf{T}(x_i)\):\[D_{\text{KL}}(\hat{P}_n \,\|\, P_{\boldsymbol{\theta}}) = H(\hat{P}_n, P_{\boldsymbol{\theta}}) - H(\hat{P}_n) = -\frac{1}{n}\sum_{i=1}^n \ln p_{\boldsymbol{\theta}}(x_i) - H(\hat{P}_n),\]cho thấy \(\arg\min \text{Forward KL} = \arg\min \text{Cross-Entropy} = \arg\max \text{Likelihood}\). Trong họ hàm mũ chính tắc, cực đại hóa hợp lý quy về bài toán tối ưu lồi toàn cục \(\min_{\boldsymbol{\eta}\in\Omega}\{A(\boldsymbol{\eta}) - \boldsymbol{\eta}^\top\bar{\mathbf{T}}\}\) với điều kiện dừng trùng khớp đúng Khớp Mô-men (Moment Matching): \(\nabla_{\boldsymbol{\eta}} A(\hat{\boldsymbol{\eta}}_{\text{MLE}}) = \mathbb{E}_{\hat{\boldsymbol{\eta}}_{\text{MLE}}}[\mathbf{T}(X)] = \bar{\mathbf{T}}\) — hợp nhất toàn bộ Mô hình Tuyến tính Tổng quát (GLMs) từ Hồi quy Logistic, Softmax, Poisson tới Bình phương Tối thiểu dưới một nguyên lý duy nhất.
1.3 Mô-men, Đo lường Phụ thuộc, Bất đẳng thức Tập trung, CLT/Berry–Esseen & Phương pháp Delta (Moments, Dependence, Concentration, Limit Theorems & Delta Ratio)#
Kỳ vọng, Phương sai & Triệt tiêu Số học (Welford & Chan)#
- Kỳ vọng: \(\mathbb{E}[X] := \int x\,dP_X(x)\) (khi \(\mathbb{E}[|X|] < \infty\)), luôn tuyến tính \(\mathbb{E}[\sum_i a_i X_i + b] = \sum_i a_i\mathbb{E}[X_i] + b\) mà không cần giả thiết độc lập. Với hàm đo được \(g(X)\),
LOTUS(Law of the Unconscious Statistician) cho \(\mathbb{E}[g(X)] = \int g(x)p_X(x)\,dx\). - Phương sai & Hiệp phương sai: \(\operatorname{Var}(X) := \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2\), \(\operatorname{Cov}(X, Y) := \mathbb{E}[(X - \mathbb{E}[X])(Y - \mathbb{E}[Y])]\), và \(\operatorname{Var}(\sum_i X_i) = \sum_i \operatorname{Var}(X_i) + 2\sum_{i<j}\operatorname{Cov}(X_i, X_j)\).
Bẫy Triệt tiêu Số học (
Catastrophic Cancellation) & Thuật toánWelford(1962) /Chan(1979):
Công thức một lượt sách giáo khoa \(\hat{\sigma}^2 = \frac{1}{n}\sum_{i=1}^n x_i^2 - \bar{x}^2\) sụp đổ hoàn toàn khi \(\mu \gg \sigma\). Với dữ liệu \(x_i = 10^9 + \varepsilon_i\) (\(\varepsilon_i \sim \mathcal{N}(0, 1)\)), giá trị \(x_i^2 \approx 10^{18}\) nằm gần giới hạn ~15.95 chữ số thập phân củafloat64(ULP(10^18) ≈ 128), quét sạch toàn bộ phần dư \(\varepsilon_i^2 \sim 1\) và thường cho phương sai âm!
Thuật toán Trực tuyến
Welford: Duy trì bộ đếm \(k\), trung bình chạy \(\bar{x}_k\), và tổng bình phương quy tâm \(M_{2,k}\) (khởi tạo \(\bar{x}_0 = M_{2,0} = 0\)):\[\delta_1 := x_k - \bar{x}_{k-1}, \qquad \bar{x}_k := \bar{x}_{k-1} + \frac{\delta_1}{k}, \qquad \delta_2 := x_k - \bar{x}_k, \qquad M_{2,k} := M_{2,k-1} + \delta_1\delta_2, \qquad s^2 = \frac{M_{2,n}}{n - 1}.\]Chứng minh quy nạp \(M_{2,k} = \sum_{i=1}^k (x_i - \bar{x}_k)^2\): Dùng \(\delta_2 = x_k - \bar{x}_{k-1} - \frac{\delta_1}{k} = \frac{k-1}{k}\delta_1\) và \(\bar{x}_k - \bar{x}_{k-1} = \frac{\delta_1}{k}\):
\[\sum_{i=1}^k (x_i - \bar{x}_k)^2 = \sum_{i=1}^{k-1}\big((x_i - \bar{x}_{k-1}) - (\bar{x}_k - \bar{x}_{k-1})\big)^2 + \delta_2^2 = M_{2,k-1} + (k-1)\frac{\delta_1^2}{k^2} + \frac{(k-1)^2}{k^2}\delta_1^2 = M_{2,k-1} + \frac{k-1}{k}\delta_1^2 = M_{2,k-1} + \delta_1\delta_2.\]Gộp Song song
Chan et al.: Khi tổng hợp hai phân mảnh \((n_A, \bar{x}_A, M_{2,A})\) và \((n_B, \bar{x}_B, M_{2,B})\) trên cụm phân tán:\[\delta := \bar{x}_B - \bar{x}_A, \qquad n = n_A + n_B, \qquad \bar{x} = \bar{x}_A + \delta\frac{n_B}{n}, \qquad M_2 = M_{2,A} + M_{2,B} + \delta^2\frac{n_A n_B}{n}.\]
Chứng minh LoTE, LoTV (Định luật Eve) & Ma trận Hiệp phương sai PSD#
Định lý 1.6 (LoTE & LoTV / Định luật Eve): Giả sử \(\mathbb{E}[Y^2] < \infty\).
- Định luật Kỳ vọng Toàn phần (
LoTE— Tower Property): \(\mathbb{E}[Y] = \mathbb{E}_X\big[\mathbb{E}[Y \mid X]\big]\). Chứng minh: Trong trường hợp liên tục (tổng quát qua Radon–Nikodym), theo Định lý Fubini (do \(\mathbb{E}[|Y|] < \infty\)): \(\mathbb{E}_X[\mathbb{E}[Y \mid X]] = \int p_X(x)\left(\int y\,p_{Y|X}(y \mid x)\,dy\right)dx = \iint y\,p_{X,Y}(x, y)\,dx\,dy = \mathbb{E}[Y]\). \(\blacksquare\) - Định luật Phương sai Toàn phần (
LoTV— Eve's Law):\[\operatorname{Var}(Y) = \mathbb{E}_X\big[\operatorname{Var}(Y \mid X)\big] + \operatorname{Var}_X\big(\mathbb{E}[Y \mid X]\big).\]Chứng minh đầy đủ: Đặt \(m(X) := \mathbb{E}[Y \mid X]\); theoLoTE, \(\mathbb{E}[m(X)] = \mathbb{E}[Y] =: \mu\). Cộng và trừ \(m(X)\) bên trong bình phương:\[\operatorname{Var}(Y) = \mathbb{E}\Big[\big((Y - m(X)) + (m(X) - \mu)\big)^2\Big] = \mathbb{E}\big[(Y - m(X))^2\big] + \mathbb{E}\big[(m(X) - \mu)^2\big] + 2\mathbb{E}\big[(Y - m(X))(m(X) - \mu)\big].\]Xét số hạng chéo bằngLoTEđiều kiện hóa theo \(X\) (vì \(m(X)-\mu\) là hàm của \(X\) nên rút ra khỏi \(\mathbb{E}[\cdot \mid X]\)):\[\mathbb{E}\big[(Y - m(X))(m(X) - \mu)\big] = \mathbb{E}_X\Big[(m(X)-\mu)\,\mathbb{E}[Y - m(X) \mid X]\Big] = \mathbb{E}_X\big[(m(X)-\mu)(m(X)-m(X))\big] = 0.\]Số hạng thứ nhất quaLoTEbằng \(\mathbb{E}_X[\mathbb{E}[(Y-m(X))^2\mid X]] = \mathbb{E}_X[\operatorname{Var}(Y\mid X)]\), số hạng thứ hai là \(\operatorname{Var}_X(m(X))\). \(\blacksquare\)
(Ý nghĩa ML: Tổng phương sai = phương sai nội cụm chưa giải thích + phương sai giữa các cụm đã giải thích, trực tiếp dẫn tới tiêu chuẩn tách nhánh CART/Random Forest và \(R^2\) tối ưu Bayes \(\operatorname{Var}(\mathbb{E}[Y\mid X])/\operatorname{Var}(Y)\).)
Định lý 1.7 (Hiệp phương sai PSD & Cận Tương quan Cauchy–Schwarz):
- Ma trận \(\boldsymbol{\Sigma} := \mathbb{E}[(\mathbf{X}-\boldsymbol{\mu})(\mathbf{X}-\boldsymbol{\mu})^\top] \in \mathbb{R}^{d\times d}\) đối xứng và nửa xác định dương (
PSD), thỏa \(\operatorname{Cov}(\mathbf{A}\mathbf{X}+\mathbf{b}) = \mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top\): với mọi \(\mathbf{v}\in\mathbb{R}^d\), \(\mathbf{v}^\top\boldsymbol{\Sigma}\mathbf{v} = \mathbb{E}[(\mathbf{v}^\top(\mathbf{X}-\boldsymbol{\mu}))^2] = \operatorname{Var}(\mathbf{v}^\top\mathbf{X}) \ge 0\) (và trên \(n\) mẫu quy tâm trong \(\mathbb{R}^d\), \(\operatorname{rank}(\hat{\boldsymbol{\Sigma}}) \le \min(n-1, d)\)). - Với hai biến vô hướng có \(0 < \sigma_X^2, \sigma_Y^2 < \infty\), đặt \(\tilde{X}=X-\mu_X, \tilde{Y}=Y-\mu_Y\). Tam thức bậc hai \(0 \le \mathbb{E}[(\tilde{X}-t\tilde{Y})^2] = \sigma_Y^2 t^2 - 2\operatorname{Cov}(X,Y)t + \sigma_X^2\;\forall t\in\mathbb{R}\) có biệt thức không dương \(4\operatorname{Cov}(X,Y)^2 - 4\sigma_X^2\sigma_Y^2 \le 0 \implies |\operatorname{Cov}(X,Y)| \le \sigma_X\sigma_Y \implies |\rho_{Y,X}| \le 1\), đạt dấu bằng iff \(Y = aX + b\) hầu chắc chắn (\(a \ne 0\)). \(\blacksquare\)
Đo lường Phụ thuộc: Pearson \(\rho_{Y,X}\) vs. Spearman \(\rho_S\) vs. Thông tin Tương hỗ \(I(X; Y)\)#
- Tương quan Tuyến tính Pearson (\(\rho_{Y,X}\)): \(r_{Y,X} = \frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum(x_i-\bar{x})^2}\sqrt{\sum(y_i-\bar{y})^2}}\). Chỉ đo liên kết tuyến tính; sụp đổ trước phi tuyến mạnh và cực kỳ nhạy ngoại lai.
-
Tương quan Hạng Spearman (\(\rho_S\)): Thay mỗi giá trị bằng hạng trung bình phân số (fractional midrank) \(R(x_i), R(y_i) \in [1, n]\) (lấy trung bình các hạng khi có giá trị trùng — ties) rồi tính tương quan Pearson trên cặp \((R(x_i), R(y_i))\).
Bẫy Đồng hạng (Tie Trap): Công thức rút gọn phổ biến \(1 - \frac{6\sum d_i^2}{n(n^2-1)}\) chỉ đúng khi không có giá trị trùng lặp! Trên dữ liệu đếm/thứ bậc có nhiều giá trị trùng, công thức rút gọn cho kết quả sai lệch — luôn tính trực tiếp tương quan Pearson của hạng trung bình phân số.
-
Thông tin Tương hỗ (Mutual Information — \(I(X; Y)\)): Phân kỳ KL giữa phân phối đồng thời và tích các phân phối biên:
\[I(X; Y) := D_{\text{KL}}\big(P_{X,Y} \,\|\, P_X \otimes P_Y\big) = \iint p(x,y)\ln\frac{p(x,y)}{p(x)p(y)}\,dx\,dy = H(X) - H(X\mid Y) \ge 0,\](thay \(\iint\) bằng \(\sum_{x,y}\) với biến rời rạc). Theo bất đẳng thức Gibbs/Jensen, \(I(X; Y) = 0 \iff X \perp\!\!\!\perp Y\), phát hiện mọi quan hệ phụ thuộc bất kể tuyến tính hay đơn điệu. Trong không gian liên tục, ước lượng qua phân khoảng thô chịu thiên lệch rời rạc hóa, trong khi bộ ước lượng \(k\)-NN Kraskov–Stögbauer–Grassberger (
KSG) loại bỏ chia giỏ (binning).
Ba Phản ví dụ Kinh điển Phân tách Pearson, Spearman & Mutual Information:
- \(Y = X^2\) (\(\rho_{Y,X} = \rho_S = 0\), nhưng \(I(X; Y) > 0\)): Với \(X \sim \mathcal{N}(0, 1)\), \(\operatorname{Cov}(X, X^2) = \mathbb{E}[X^3] = 0 \implies \rho_{Y,X} = 0\), và do đối xứng chẵn, \(\rho_S = 0\). Trên mẫu rời rạc đều \(x = [-2,-1,0,1,2], y = [4,1,0,1,4]\), hạng trung bình là \(R_X = [1,2,3,4,5]\) và \(R_Y = [4.5, 2.5, 1, 2.5, 4.5]\) cho chính xác \(r = r_S = 0\). Thế nhưng \(H(X)=\ln 5\) và \(H(X\mid Y) = \frac{1}{5}(0) + \frac{2}{5}\ln 2 + \frac{2}{5}\ln 2 = \frac{4}{5}\ln 2\), suy ra:
\[I(X; Y) = \ln 5 - \frac{4}{5}\ln 2 \approx 1.6094 - 0.5545 = \mathbf{1.0549\text{ nats}} > 0!\]
- \(Y = e^X\) với \(X \sim \mathcal{N}(0, \sigma^2)\) (Pearson gần \(0\), Spearman đúng bằng \(1\)): Từ MGF Gaussian \(M_X(t)=e^{\sigma^2 t^2/2}\), ta có \(\mathbb{E}[X e^X]=M_X'(1)=\sigma^2 e^{\sigma^2/2}\), \(\mathbb{E}[e^X]=e^{\sigma^2/2}\), \(\operatorname{Var}(e^X)=e^{\sigma^2}(e^{\sigma^2}-1)\), cho ra công thức giải tích chính xác:
\[\rho_{Y,X} = \frac{\sigma}{\sqrt{e^{\sigma^2} - 1}} \xrightarrow{\sigma = 3} \frac{3}{\sqrt{e^9 - 1}} \approx \mathbf{0.0333} \qquad \text{trong khi } \rho_S(X, e^X) = \mathbf{1.000}!\]
- Độ nhạy Ngoại lai (Single-Outlier Flip): Lấy \(9\) điểm thẳng hàng \((i, i)\) (\(i=1,\dots,9\)) thêm đúng \(1\) điểm lỗi \((10, -100)\): Pearson tụt từ \(+1.0\) xuống âm sâu (\(r \approx -0.60\)), còn Spearman giữ giá trị dương (\(\rho_S \approx +0.45\)) bảo toàn cấu trúc đơn điệu của 9 điểm sạch.
Phân tầng Bất đẳng thức Tập trung (Markov, Chebyshev, Chernoff, Hoeffding)#
- Bất đẳng thức Markov (\(X \ge 0\), \(\mathbb{E}[X] < \infty\)): Với mọi \(a > 0\), \(P(X \ge a) \le \frac{\mathbb{E}[X]}{a}\).
Chứng minh: Do \(X \ge 0\), \(X \ge a\,\mathbb{I}[X \ge a]\) khắp nơi; lấy kỳ vọng hai vế suy ra \(\mathbb{E}[X] \ge a P(X \ge a)\). \(\blacksquare\) (Thất bại nếu \(X\) có thể nhận giá trị âm.) - Bất đẳng thức Chebyshev (\(\operatorname{Var}(X) = \sigma^2 < \infty\)): Với mọi \(\varepsilon > 0\), \(P(|X - \mu| \ge \varepsilon) \le \frac{\sigma^2}{\varepsilon^2}\).
Chứng minh: Áp dụng Markov cho biến không âm \((X - \mu)^2 \ge 0\) tại ngưỡng \(\varepsilon^2\). \(\blacksquare\) - Phương pháp Chernoff, Bổ đề Hoeffding & Bất đẳng thức Hoeffding:
- Cận Chernoff: Với mọi \(\lambda > 0\), \(P(X - \mu \ge t) = P(e^{\lambda(X-\mu)} \ge e^{\lambda t}) \le \inf_{\lambda > 0} e^{-\lambda t} M_{X-\mu}(\lambda)\).
- Bổ đề 1.8 (Bổ đề Hoeffding): Cho \(Z\) thỏa \(\mathbb{E}[Z] = 0\) và \(a \le Z \le b\) hầu chắc chắn. Khi đó với mọi \(\lambda \in \mathbb{R}\):
\[M_Z(\lambda) = \mathbb{E}[e^{\lambda Z}] \le \exp\!\left(\frac{\lambda^2 (b - a)^2}{8}\right).\]Chứng minh: Đặt CGF \(\psi(\lambda) := \ln\mathbb{E}[e^{\lambda Z}]\), ta có \(\psi(0)=0\), \(\psi'(0)=\mathbb{E}[Z]=0\), và đạo hàm bậc hai:\[\psi''(\lambda) = \frac{\mathbb{E}[Z^2 e^{\lambda Z}]}{\mathbb{E}[e^{\lambda Z}]} - \left(\frac{\mathbb{E}[Z e^{\lambda Z}]}{\mathbb{E}[e^{\lambda Z}]}\right)^2 = \operatorname{Var}_{Q_\lambda}(Z),\]trong đó \(dQ_\lambda(z) := \frac{e^{\lambda z}}{\mathbb{E}[e^{\lambda Z}]}\,dP(z)\) là độ đo nghiêng hàm mũ trên \([a, b]\). Theo bất đẳng thức Popoviciu, với mọi phân phối \(Q\) trên \([a, b]\) và tâm \(m = \frac{a+b}{2}\) (nên \(|Z - m| \le \frac{b-a}{2}\)):\[\operatorname{Var}_Q(Z) = \min_{c \in \mathbb{R}}\mathbb{E}_Q[(Z - c)^2] \le \mathbb{E}_Q[(Z - m)^2] \le \frac{(b - a)^2}{4}.\]Do đó \(\psi''(\lambda) \le \frac{(b-a)^2}{4}\;\forall\lambda\). Khai triển Taylor quanh \(0\) tồn tại \(\xi\) giữa \(0\) và \(\lambda\) để \(\psi(\lambda) = \psi(0) + \psi'(0)\lambda + \frac{1}{2}\psi''(\xi)\lambda^2 \le \frac{\lambda^2(b-a)^2}{8}\). Lấy mũ hai vế hoàn tất chứng minh. \(\blacksquare\)
- Định lý 1.9 (Bất đẳng thức Hoeffding): Cho \(X_1, \dots, X_n\) độc lập với \(a_i \le X_i \le b_i\) hầu chắc chắn và \(\bar{X}_n = \frac{1}{n}\sum_{i=1}^n X_i\). Với mọi \(t > 0\):
\[P\big(|\bar{X}_n - \mathbb{E}[\bar{X}_n]| \ge t\big) \le 2\exp\!\left(-\frac{2n^2 t^2}{\sum_{i=1}^n (b_i - a_i)^2}\right) \qquad \Big(= 2\exp(-2nt^2) \text{ khi } X_i \in [0, 1]\Big).\]Chứng minh: Đặt \(Z_i = X_i - \mathbb{E}[X_i]\) (bề rộng \(b_i - a_i\)). Nhờ độc lập và Bổ đề Hoeffding, \(P(\bar{X}_n - \mathbb{E}[\bar{X}_n] \ge t) \le e^{-\lambda n t}\prod_{i=1}^n \mathbb{E}[e^{\lambda Z_i}] \le \exp(-\lambda n t + \frac{\lambda^2}{8}\sum (b_i-a_i)^2)\). Tối ưu \(\lambda^* = \frac{4nt}{\sum(b_i-a_i)^2}\) cho \(e^{-2n^2t^2 / \sum(b_i-a_i)^2}\), lặp lại cho \(-Z_i\) và lấy union bound cho thừa số \(2\). \(\blacksquare\)
| Bất đẳng thức | Giả thiết | Tốc độ Suy giảm theo \((n, t)\) cho \(\bar{X}_n\) | Chế độ Chặt & Bẫy Lỏng lẻo |
|---|---|---|---|
| Markov | \(X \ge 0\), \(\mathbb{E}[X] < \infty\) | \(O(t^{-1})\) (1 biến) | Sai nếu \(X\) mang dấu âm; bỏ qua hoàn toàn phương sai. |
| Chebyshev | \(\operatorname{Var}(X_i) = \sigma^2 < \infty\) | \(O(\frac{\sigma^2}{n t^2})\) | Chặt cho đuôi nặng chỉ có 2 mô-men; cực lỏng cho tổng bị chặn/Gaussian. |
| Hoeffding | Độc lập \(X_i \in [a_i, b_i]\) | \(2\exp(-\frac{2nt^2}{(b-a)^2})\) | Suy giảm hàm mũ theo \(nt^2\)! Rất lỏng khi \(\sigma^2 \ll (b-a)^2\) (vd. CTR hiếm \(p=0.001\) trên \([0,1]\): Hoeffding giả định phương sai \(1/4 = 0.25\) thay vì \(0.001\), đòi hỏi Bất đẳng thức Bernstein nhạy phương sai \(\exp(-\frac{nt^2/2}{\sigma^2 + (b-a)t/3})\)). |
Luật Số lớn (WLLN/SLLN), CLT & Cảnh báo Berry–Esseen#
- Luật Số lớn Yếu (
WLLN) & Mạnh (SLLN): Khi \(X_i\) i.i.d. có \(\sigma^2 < \infty\), Chebyshev chứng minh ngay \(\bar{X}_n \xrightarrow{P} \mu\) vì \(P(|\bar{X}_n-\mu|\ge\varepsilon) \le \frac{\sigma^2}{n\varepsilon^2} \to 0\) (Khinchin mở rộng chỉ cần \(\mathbb{E}[|X_1|] < \infty\)).SLLNmạnh hơn khẳng định \(\bar{X}_n \xrightarrow{\text{a.s.}} \mu\) (khi \(\mu_4 = \mathbb{E}[(X_1-\mu)^4] < \infty\), \(\mathbb{E}[(\bar{X}_n-\mu)^4] = O(n^{-2})\), nên \(\sum_{n=1}^\infty P(|\bar{X}_n-\mu|\ge\varepsilon) \le \sum O(n^{-2})/\varepsilon^4 < \infty\), kéo theo \(|\bar{X}_n-\mu|<\varepsilon\) với mọi \(n\) đủ lớn h.c.c. theo bổ đề Borel–Cantelli). Trường hợp sụp đổ: Nếu \(X_i \stackrel{\text{i.i.d.}}{\sim}\operatorname{Cauchy}(0, 1)\), \(\mathbb{E}[|X_1|]=\infty\) và \(\bar{X}_n \stackrel{d}{=} X_1\;\forall n\) — lấy trung bình không hề giảm phương sai! - Định lý Giới hạn Trung tâm (
CLTLindeberg–Lévy): Nếu \(X_i\) i.i.d. với \(0 < \sigma^2 < \infty\), thì \(Z_n := \frac{\sqrt{n}(\bar{X}_n-\mu)}{\sigma} \xrightarrow{d} \mathcal{N}(0, 1)\). (Chứng minh qua hàm đặc trưng \(\varphi_Y(t)=\mathbb{E}[e^{itY}]\): với \(Y_k=(X_k-\mu)/\sigma\), \(\varphi_{Y_1}(s) = 1 - \frac{s^2}{2} + o(s^2) \implies \varphi_{Z_n}(t) = [\varphi_{Y_1}(t/\sqrt{n})]^n = (1 - \frac{t^2}{2n} + o(n^{-1}))^n \to e^{-t^2/2}\), rồi áp dụng Định lý Liên tục Lévy.) - Định lý Berry–Esseen (Cảnh báo Quy tắc Ngón tay cái "\(n \ge 30\)"): Nếu mô-men tâm tuyệt đối bậc ba \(\mu_{3,\text{abs}} := \mathbb{E}[|X_1 - \mu|^3] < \infty\), sai số phân phối chuẩn đồng nhất bị chặn bởi (Shevtsova, 2011):
\[\sup_{x \in \mathbb{R}}\big|P(Z_n \le x) - \Phi(x)\big| \le \frac{C_{\text{BE}}\,\mu_{3,\text{abs}}}{\sigma^3\sqrt{n}}, \qquad C_{\text{BE}} \le 0.4748.\]Với phân phối đối xứng như \(\operatorname{Uniform}(-1, 1)\), \(n=30\) hội tụ rất tốt. Ngược lại, với biến cố hiếm \(\operatorname{Bernoulli}(p = 0.001)\), độ lệch chuẩn hóa \(\mu_{3,\text{abs}}/\sigma^3 \approx \frac{1}{\sqrt{p}} \approx 31.6\), buộc cần \(n \gg 10^4\) mẫu trước khi khoảng tin cậy \(z\) đạt đúng \(95\%\) độ phủ; tương tự cho doanh thu LogNormal đuôi nặng (
sigma = 1.2) nơi \(n=30\) sụp đổ độ phủ nghiêm trọng.
Định lý 1.10 (Phương pháp Delta Đa biến & Phương sai Tỷ lệ Cụm Tuyến tính hóa)#
Cho \(\{\hat{\boldsymbol{\mu}}_n\}\) trong \(\mathbb{R}^d\) thỏa \(\sqrt{n}(\hat{\boldsymbol{\mu}}_n - \boldsymbol{\mu}) \xrightarrow{d} \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma})\), và hàm \(g: \mathbb{R}^d \to \mathbb{R}^k\) khả vi tại \(\boldsymbol{\mu}\) với Jacobian Numerator-Layout \(\mathbf{J}_g(\boldsymbol{\mu}) = \frac{\partial g}{\partial \boldsymbol{\mu}^\top}\big|_{\boldsymbol{\mu}} \in \mathbb{R}^{k\times d}\). Khi đó:
Chứng minh: Khai triển Taylor bậc nhất \(g(\hat{\boldsymbol{\mu}}_n) - g(\boldsymbol{\mu}) = \mathbf{J}_g(\boldsymbol{\mu})(\hat{\boldsymbol{\mu}}_n - \boldsymbol{\mu}) + R_n\) với \(R_n = o(\|\hat{\boldsymbol{\mu}}_n - \boldsymbol{\mu}\|_2)\). Vì \(\sqrt{n}(\hat{\boldsymbol{\mu}}_n - \boldsymbol{\mu}) = O_P(1)\) và \(\|\hat{\boldsymbol{\mu}}_n - \boldsymbol{\mu}\|_2 \xrightarrow{P} 0\), nên \(\sqrt{n}R_n \xrightarrow{P} \mathbf{0}\). Định lý Slutsky và phép biến đổi tuyến tính MVN hoàn tất chứng minh. \(\blacksquare\)
Suy diễn Chính xác Phương sai Chỉ số Tỷ lệ (\(\hat{R}_{\text{ratio}} = \bar{Y}/\bar{X}\)): Với \(n\) đơn vị ngẫu nhiên hóa (người dùng/cụm) i.i.d. mang cặp tổng \((X_i, Y_i)\) (\(\mu_X \ne 0\)), đặt \(R_{\text{ratio}} := \mu_Y/\mu_X\) và \(g(x, y) = y/x\):
- Tính Jacobian tại \(\boldsymbol{\mu} = (\mu_X, \mu_Y)^\top\): \(\mathbf{J}_g(\boldsymbol{\mu}) = \begin{bmatrix} -\frac{\mu_Y}{\mu_X^2} & \frac{1}{\mu_X} \end{bmatrix}\).
- Nhân \(\mathbf{J}_g(\boldsymbol{\mu})\boldsymbol{\Sigma}\mathbf{J}_g(\boldsymbol{\mu})^\top\) với \(\boldsymbol{\Sigma} = \begin{bmatrix}\sigma_X^2 & \sigma_{XY} \\ \sigma_{XY} & \sigma_Y^2\end{bmatrix}\):
\[\sigma_{\text{ratio}}^2 = \frac{\mu_Y^2}{\mu_X^4}\sigma_X^2 - 2\frac{\mu_Y}{\mu_X^3}\sigma_{XY} + \frac{1}{\mu_X^2}\sigma_Y^2 = \frac{1}{\mu_X^2}\left(\sigma_Y^2 - 2 R_{\text{ratio}}\sigma_{XY} + R_{\text{ratio}}^2\sigma_X^2\right).\]
- Thay thế các đại lượng mẫu và viết lại qua thặng dư ảnh hưởng tuyến tính hóa \(Z_i := Y_i - \hat{R}_{\text{ratio}} X_i\) (thỏa \(\bar{Z} = \bar{Y} - \frac{\bar{Y}}{\bar{X}}\bar{X} = 0\)):
\[\widehat{\operatorname{Var}}\!\left(\frac{\bar{Y}}{\bar{X}}\right) = \frac{1}{n\,\bar{X}^2}\left(s_Y^2 - 2\hat{R}_{\text{ratio}}\,s_{XY} + \hat{R}_{\text{ratio}}^2 s_X^2\right) \equiv \frac{1}{n(n-1)\,\bar{X}^2}\sum_{i=1}^n \big(Y_i - \hat{R}_{\text{ratio}} X_i\big)^2.\]Dạng tổng bình phương vế phải luôn không âm tuyệt đối (miễn nhiễm triệt tiêu dấu chấm động khi \(Y_i \approx \hat{R}_{\text{ratio}} X_i\)) và biến phép kiểm định tỷ lệ thành phép kiểm định trên các giá trị độc lập ở cấp đơn vị ngẫu nhiên hóa!
1.4 Ước lượng Điểm, Thông tin Fisher, CRLB, Wilson Score & Bootstrap (Point Estimation, CRLB, Wilson vs. Wald & Bootstrap)#
MLE vs. MAP & Sự Tương đương Chuẩn hóa \(L_2\)/\(L_1\)#
- Ước lượng Hợp lý Cực đại (
MLE): \(\hat{\boldsymbol{\theta}}_{\text{MLE}} := \arg\max_{\boldsymbol{\theta}\in\Theta}\sum_{i=1}^n \ln p(x_i \mid \boldsymbol{\theta})\). Nhất quán, tiệm cận chuẩn hiệu quả (\(\sqrt{n}(\hat{\boldsymbol{\theta}}_{\text{MLE}}-\boldsymbol{\theta}_0)\xrightarrow{d}\mathcal{N}(\mathbf{0}, \mathcal{I}(\boldsymbol{\theta}_0)^{-1})\)), và bất biến dưới phép tái tham số hóa (\(\widehat{g(\boldsymbol{\theta})}_{\text{MLE}} = g(\hat{\boldsymbol{\theta}}_{\text{MLE}})\)). Tuy nhiênMLEcó thể bị thiên lệch trên mẫu hữu hạn (ví dụ phương sai \(\hat{\sigma}^2_{\text{MLE}} = \frac{1}{n}\sum (X_i-\bar{X})^2\) có kỳ vọng \(\frac{n-1}{n}\sigma^2\), cần hệ số Bessel \(\frac{n}{n-1}\)). - Ước lượng Hậu nghiệm Cực đại (
MAP): \(\hat{\boldsymbol{\theta}}_{\text{MAP}} := \arg\min_{\boldsymbol{\theta}\in\Theta}\big\{-\sum_{i=1}^n \ln p(x_i \mid \boldsymbol{\theta}) - \ln p(\boldsymbol{\theta})\big\}\).Bẫy Không bất biến của
MAP: KhácMLE,MAPKHÔNG bất biến dưới phép đổi biến trơn \(\boldsymbol{\phi} = g(\boldsymbol{\theta})\) vì hàm mật độ tiên nghiệm chịu nhân tử Jacobian \(|\det \mathbf{J}_{g^{-1}}(\boldsymbol{\phi})|\), làm dịch chuyển vị trí mode hậu nghiệm!
Định lý 1.11 (Tương đương Đại số: Tiên nghiệm Gaussian \(\iff L_2\) Ridge & Tiên nghiệm Laplace \(\iff L_1\) Lasso): Xét hồi quy tuyến tính \(\mathbf{y} = \mathbf{X}\mathbf{w} + \boldsymbol{\varepsilon}\) với \(\varepsilon_i \stackrel{\text{i.i.d.}}{\sim}\mathcal{N}(0, \sigma^2)\) (\(\sigma > 0\) cố định), khi đó \(-\ln p(\mathbf{y}\mid\mathbf{X},\mathbf{w}) = \frac{1}{2\sigma^2}\|\mathbf{y}-\mathbf{X}\mathbf{w}\|_2^2 + \frac{n}{2}\ln(2\pi\sigma^2)\):
- Tiên nghiệm Gaussian đẳng hướng \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \sigma_{\text{prior}}^2 \mathbf{I}_d)\): \(-\ln p(\mathbf{w}) = \frac{1}{2\sigma_{\text{prior}}^2}\|\mathbf{w}\|_2^2 + \frac{d}{2}\ln(2\pi\sigma_{\text{prior}}^2)\). Nhân NLL hậu nghiệm với \(2\sigma^2\) và bỏ hằng số cho chính xác bài toán \(L_2\) Ridge:
\[\hat{\mathbf{w}}_{\text{MAP}}^{\text{Gauss}} = \arg\min_{\mathbf{w}\in\mathbb{R}^d}\left\{\|\mathbf{y}-\mathbf{X}\mathbf{w}\|_2^2 + \lambda_{\text{Ridge}}\|\mathbf{w}\|_2^2\right\}, \qquad \lambda_{\text{Ridge}} := \frac{\sigma^2}{\sigma_{\text{prior}}^2}.\]
- Tiên nghiệm Laplace độc lập \(w_j \stackrel{\text{i.i.d.}}{\sim}\operatorname{Laplace}(0, b)\) (\(p(w_j) = \frac{1}{2b}e^{-|w_j|/b}\)): \(-\ln p(\mathbf{w}) = \frac{1}{b}\|\mathbf{w}\|_1 + d\ln(2b)\). Nhân với \(2\sigma^2\) cho chính xác bài toán \(L_1\) Lasso:
\[\hat{\mathbf{w}}_{\text{MAP}}^{\text{Laplace}} = \arg\min_{\mathbf{w}\in\mathbb{R}^d}\left\{\|\mathbf{y}-\mathbf{X}\mathbf{w}\|_2^2 + \lambda_{\text{Lasso}}\|\mathbf{w}\|_1\right\}, \qquad \lambda_{\text{Lasso}} := \frac{2\sigma^2}{b}.\](Sắc thái thưa: Các trọng số bằng đúng \(0\) chỉ xuất hiện vì
MAPlấy cực trị (mode) tại đỉnh nhọn không khả vi của \(|w_j|\); còn trung bình hậu nghiệm Bayes dưới tiên nghiệm Laplace hầu như không bao giờ bằng \(0\) chính xác!) \(\blacksquare\)
Điểm số, Thông tin Fisher & Chứng minh Cận dưới Cramér–Rao (CRLB)#
Dưới điều kiện chính quy CRLB ((1) miền giá trị \(\mathcal{X} = \{\mathbf{x}: p(\mathbf{x}\mid\theta) > 0\}\) không phụ thuộc \(\theta\), và (2) \(\ell(\theta;\mathbf{x}) := \ln p(\mathbf{x}\mid\theta)\) khả vi liên tục hai lần và hoán đổi được đạo hàm với tích phân), định nghĩa hàm điểm số (score) \(s(\theta;\mathbf{x}) := \partial_\theta \ln p(\mathbf{x}\mid\theta) = \frac{\partial_\theta p(\mathbf{x}\mid\theta)}{p(\mathbf{x}\mid\theta)}\):
- Bổ đề Điểm số & Thông tin Fisher: Đạo hàm \(\int_{\mathcal{X}} p(\mathbf{x}\mid\theta)\,d\mathbf{x} = 1\) dưới dấu tích phân cho \(\mathbb{E}_\theta[s(\theta;\mathbf{X})] = \int_{\mathcal{X}} \partial_\theta p(\mathbf{x}\mid\theta)\,d\mathbf{x} = 0\), nên \(\mathcal{I}(\theta) := \operatorname{Var}_\theta(s) = \mathbb{E}_\theta[s^2]\). Đạo hàm lần hai phương trình \(\int s(\theta;\mathbf{x})p(\mathbf{x}\mid\theta)\,d\mathbf{x} = 0\) theo quy tắc tích cho \(0 = \mathbb{E}_\theta[\partial_\theta^2\ln p] + \mathbb{E}_\theta[s^2] \implies \mathcal{I}(\theta) = -\mathbb{E}_\theta[\partial_\theta^2\ln p(\mathbf{X}\mid\theta)] \ge 0\). Với \(n\) mẫu i.i.d., \(s_n = \sum_{i=1}^n s_1(\theta; X_i)\) nên \(\mathcal{I}_n(\theta) = n\,\mathcal{I}_1(\theta)\).
Định lý 1.12 (Cận dưới Cramér–Rao — CRLB): Cho \(T(\mathbf{X})\) là ước lượng bất kỳ có phương sai hữu hạn và kỳ vọng khả vi \(\psi(\theta) := \mathbb{E}_\theta[T(\mathbf{X})] = \theta + b(\theta)\). Khi \(\mathcal{I}_n(\theta) > 0\):
Chứng minh (qua Cauchy–Schwarz): Đạo hàm \(\psi(\theta) = \int T(\mathbf{x})p(\mathbf{x}\mid\theta)\,d\mathbf{x}\) dưới dấu tích phân cho \(\psi'(\theta) = \int T(\mathbf{x})s(\theta;\mathbf{x})p(\mathbf{x}\mid\theta)\,d\mathbf{x} = \mathbb{E}_\theta[T(\mathbf{X})s(\theta;\mathbf{X})]\). Do \(\mathbb{E}_\theta[s] = 0\), ta có \(\operatorname{Cov}_\theta(T, s) = \psi'(\theta)\). Áp dụng Cauchy–Schwarz \(|\operatorname{Cov}(T, s)|^2 \le \operatorname{Var}(T)\operatorname{Var}(s) = \operatorname{Var}_\theta(T)\mathcal{I}_n(\theta)\) và chia cho \(\mathcal{I}_n(\theta) > 0\) thu được điều phải chứng minh. \(\blacksquare\)
(Dấu bằng đạt được iff \(p(\mathbf{x}\mid\theta)\) thuộc họ hàm mũ 1 tham số. Phản ví dụ vi phạm chính quy: Với \(X_1, \dots, X_n \stackrel{\text{i.i.d.}}{\sim} \operatorname{Uniform}(0, \theta)\), miền \([0, \theta]\) phụ thuộc \(\theta\); UMVUE \(T(\mathbf{X}) = \frac{n+1}{n}\max_i X_i\) đạt \(\operatorname{Var}_\theta(T) = \frac{\theta^2}{n(n+2)} = O(n^{-2})\), đánh bại tốc độ \(O(n^{-1})\) của CRLB!)
Khoảng Tin cậy: Sụp đổ Wald & Suy diễn Chính xác Khoảng Wilson Score#
Với \(K \sim \operatorname{Binomial}(n, p)\), \(\hat{p} = K/n\), và phân vị chuẩn \(z := z_{1-\alpha/2}\):
- Khoảng Wald Ngây thơ \(\hat{p} \pm z\sqrt{\hat{p}(1-\hat{p})/n}\) Sụp đổ Ba mặt: (1) Khi \(K=0\) hoặc \(K=n\) (lỗi SLA/gian lận hiếm), \(\hat{p}(1-\hat{p}) = 0\) ép CI sập thành \([0, 0]\) hoặc \([1, 1]\) (tuyên bố bất định bằng \(0\)!); (2) Tại \(n=20, K=1\) (\(\hat{p}=0.05, z=1.96\)), Wald cho \([-0.0455, 0.1455]\) (xác suất âm!); (3) Coverage thực tế dao động hỗn loạn dưới \(95\%\) (Brown, Cai, DasGupta, 2001).
- Suy diễn Khoảng Điểm số Wilson (1927) bằng Đảo ngược Kiểm định Điểm số (Score Inversion): Giữ nguyên phương sai không \(\frac{p_0(1-p_0)}{n}\) và giải bất phương trình cho mọi \(p_0 \in [0, 1]\) không bị bác bỏ:
\[\left|\frac{\hat{p} - p_0}{\sqrt{\frac{p_0(1-p_0)}{n}}}\right| \le z \iff (\hat{p}-p_0)^2 \le \frac{z^2}{n}p_0(1-p_0) \iff \underbrace{\left(1+\frac{z^2}{n}\right)}_{A}p_0^2 \underbrace{-\left(2\hat{p}+\frac{z^2}{n}\right)}_{B}p_0 + \underbrace{\hat{p}^2}_{C} \le 0.\]Tính biệt thức:\[B^2 - 4AC = 4\hat{p}^2 + \frac{4\hat{p}z^2}{n} + \frac{z^4}{n^2} - 4\hat{p}^2 - \frac{4\hat{p}^2 z^2}{n} = \frac{4z^2}{n}\left(\hat{p}(1-\hat{p}) + \frac{z^2}{4n}\right).\]Chia tử và mẫu trong nghiệm \(\frac{-B \pm \sqrt{B^2-4AC}}{2A}\) cho \(2\) cho ra dạng đóng Khoảng Tin cậy Wilson:\[p_{\text{Wilson}} = \frac{\hat{p} + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat{p}(1-\hat{p})}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}.\]Khoảng Wilson luôn nằm chặt trong \([0, 1]\) với mọi \(n \ge 1, K \in \{0,\dots,n\}\): tại \(K=0, n=30, z=1.96\) cho \([0, 0.1135]\) (khớp quy tắc \(3/n = 0.10\)); tại \(K=1, n=20\) cho \([0.0089, 0.2361]\). (Lưu ý thêm: Agresti–Coull cộng giả \(+z^2/2\) thành công và \(+z^2/2\) thất bại để tâm \(\tilde{p}\) trùng tâm Wilson; Clopper–Pearson đảo ngược chính xác tổng đuôi Nhị thức cho bảo đảm \(\ge 1-\alpha\) bảo thủ.)
Suy luận Bootstrap & Các Chế độ Sụp đổ#
Rút \(B\) mẫu lặp lại có hoàn lại kích thước \(n\) (\(\mathbf{x}^{*(b)}\), thường \(B \ge 2{,}000\text{–}10{,}000\)) và ký hiệu phân vị thực nghiệm bậc \(q\) là \(\hat{\theta}^*_{(q)}\):
| Phương pháp Bootstrap | Công thức Khoảng Tin cậy | Cơ chế & Bậc chính xác | Bẫy & Khi nào cần Tránh |
|---|---|---|---|
| Percentile | \(\big[\hat{\theta}^*_{(\alpha/2)},\; \hat{\theta}^*_{(1-\alpha/2)}\big]\) | Lấy trực tiếp phân vị thực nghiệm của \(\hat{\theta}^*\); bất biến biến đổi đơn điệu; bậc \(O(n^{-1/2})\). | Sụp đổ nếu \(\hat{\theta}\) thiên lệch hoặc phương sai phụ thuộc mạnh vào \(\theta\). |
| Basic (Pivotal / Phản xạ) | \(\big[2\hat{\theta} - \hat{\theta}^*_{(1-\alpha/2)},\; 2\hat{\theta} - \hat{\theta}^*_{(\alpha/2)}\big]\) | Xấp xỉ phân phối trục \(\hat{\theta}-\theta\) bằng \(\hat{\theta}^*-\hat{\theta}\) nên khi giải cho \(\theta\) phải đảo ngược phân vị! | Bẫy đảo dấu: Đặt \(\hat{\theta}^*_{(\alpha/2)}\) làm cận dưới là sai; có thể sinh cận âm cho phương sai/tỷ lệ. |
BCa (Bias-Corrected & Accelerated) |
\(\big[\hat{\theta}^*_{(\alpha_1)},\; \hat{\theta}^*_{(\alpha_2)}\big]\) với \(\alpha_j = \Phi\!\big(z_0 + \frac{z_0 + z_{\tilde{\alpha}_j}}{1 - a(z_0 + z_{\tilde{\alpha}_j})}\big)\) | Hiệu chỉnh độ lệch trung vị \(z_0 = \Phi^{-1}(\frac{1}{B}\sum \mathbb{I}[\hat{\theta}^{*(b)} < \hat{\theta}])\) và hệ số gia tốc \(a = \frac{\sum(\bar{\theta}_{(\cdot)}-\hat{\theta}_{(-i)})^3}{6[\sum(\bar{\theta}_{(\cdot)}-\hat{\theta}_{(-i)})^2]^{3/2}}\) từ jackknife; chính xác bậc hai \(O(n^{-1})\)! | Đòi hỏi \(O(n)\) lượt jackknife và đủ \(B\) để ổn định đuôi cực trị. |
- Khắc phục Dữ liệu Phụ thuộc: Dùng Cluster Bootstrap (lấy mẫu lại nguyên cả cụm/ID người dùng để bảo toàn tương quan nội cụm trong A/B test) hoặc Moving / Stationary Block Bootstrap (cỡ khối \(\ell \sim n^{1/3}\) hoặc cỡ ngẫu nhiên hình học Politis–Romano cho chuỗi thời gian tự tương quan).
- Chứng minh Tường minh Bootstrap Thất bại trên Thống kê Thứ tự Cực trị (\(\hat{\theta}_n = \max_i X_i\)): Với \(X_1, \dots, X_n \stackrel{\text{i.i.d.}}{\sim} \operatorname{Uniform}(0, \theta)\) và \(\hat{\theta}_n = X_{(n)} = \max_i X_i\), trong tổng thể thực \(P(\hat{\theta}_n = \theta) = 0\) và \(n(\theta - \hat{\theta}_n) \xrightarrow{d}\operatorname{Exp}(1/\theta)\) (liên tục). Tuy nhiên trong mẫu bootstrap kích thước \(n\), xác suất phần tử lớn nhất \(X_{(n)}\) được bốc trúng ít nhất \(1\) lần là:
\[P\big(\hat{\theta}_n^* = \hat{\theta}_n \mid \mathbf{X}\big) = 1 - \left(1 - \frac{1}{n}\right)^n \xrightarrow{n \to \infty} 1 - e^{-1} \approx \mathbf{0.6321}!\]Phân phối bootstrap đặt một khối xác suất nguyên tử khổng lồ \(63.21\%\) tại điểm \(0\) bất chấp \(n \to \infty\)! (Khắc phục bằng \(m\)-out-of-\(n\) subsampling với \(m \to \infty, m/n \to 0\), vd. \(m = \sqrt{n}\), khiến \(1 - (1-1/n)^m \approx m/n \to 0\).)
1.5 Kiểm định Giả thuyết Tần suất, Độ mạnh & Các Kiểm định Cốt lõi (Frequentist Hypothesis Testing, MDE & Core Tests)#
Bổ đề Neyman–Pearson, Phân phối Đều của Null \(p\)-Value & Ngụy biện Công tố viên#
- Bổ đề Neyman–Pearson (Trực giác Ba lô Phân số): Kiểm định \(H_0:\theta=\theta_0\) vs. \(H_1:\theta=\theta_1\) cực đại hóa độ mạnh \(\int_{\mathcal{R}} \frac{p_1(\mathbf{x})}{p_0(\mathbf{x})} p_0(\mathbf{x})\,d\mathbf{x}\) dưới ngân sách sai lầm Loại I \(\int_{\mathcal{R}} p_0(\mathbf{x})\,d\mathbf{x} \le \alpha\). Tham lam tối ưu chọn vùng bác bỏ theo tỷ số mật độ tỷ số hợp lý \(\Lambda(\mathbf{x}) := \frac{p(\mathbf{x}\mid\theta_1)}{p(\mathbf{x}\mid\theta_0)} > k_\alpha\) luôn mạnh nhất (
MP). - Định lý 1.13 (Null \(p\)-Value Tuân theo \(\operatorname{Uniform}(0, 1)\)): Nếu dưới \(H_0\) thống kê kiểm định \(T\) có CDF liên tục tăng ngặt \(F_0(t)\), thì \(p\)-value đuôi trên \(p(T) := 1 - F_0(T)\) thỏa \(p(T) \sim \operatorname{Uniform}(0, 1)\).
Chứng minh (Probability Integral Transform): Với mọi \(u \in (0, 1)\):\[P_{H_0}\big(p(T) \le u\big) = P_{H_0}\big(1 - F_0(T) \le u\big) = P_{H_0}\big(T \ge F_0^{-1}(1 - u)\big) = 1 - F_0\big(F_0^{-1}(1 - u)\big) = u. \quad \blacksquare\](Với kiểm định rời rạc, bước nhảy của \(F_0\) khiến null \(p\)-value siêu đều \(P_{H_0}(p(T)\le u)\le u\), vẫn giữ Type I error \(\le \alpha\).) - Ngụy biện Công tố viên (
Prosecutor's Fallacy/ Đảo ngược Bayes): \(p\)-value là \(P(\text{dữ liệu cực đoan} \mid H_0)\), KHÔNG phải \(P(H_0 \mid \text{dữ liệu})\)! Giả sử chỉ \(10\%\) giả thuyết sản phẩm thực sự hiệu quả (\(P(H_1)=0.10, P(H_0)=0.90\)), kiểm định ở \(\alpha = 0.05\) và độ mạnh \(1-\beta = 0.80\). Theo Định lý Bayes, ngay cả khi chỉ điều kiện hóa trên biến cố bác bỏ \(p \le 0.05\):\[\text{FPR} = P(H_0 \mid p \le 0.05) = \frac{0.05 \times 0.90}{0.05 \times 0.90 + 0.80 \times 0.10} = \frac{0.045}{0.125} = \mathbf{36.0\%}!\]Tệ hơn nữa, điều kiện hóa trên đúng giá trị quan sát \(p = 0.04\) hai phía (\(z = 2.054\) so với phân phối \(H_1\) hai phía đạt \(80\%\) độ mạnh tại \(\mu = \pm 2.802\), mật độ \(\phi(2.054) \approx 0.0484\) vs. \(\frac{1}{2}[\phi(2.054-2.802)+\phi(2.054+2.802)] \approx 0.1510\)) đẩy xác suất hậu nghiệm \(P(H_0 \mid p=0.04)\) lên tới \(\mathbf{74.3\%}\)! Ngoài ra khi \(n \to \infty\), \(\text{SE} \propto n^{-1/2} \to 0\) khiến hiệu ứng vô nghĩa \(\Delta = 10^{-5}\) cũng cho \(p < 10^{-10}\) — luôn báo cáo kích thước tác động và khoảng tin cậy.
Suy diễn Chính xác Hiệu ứng Tối thiểu Phát hiện được (MDE) & Cỡ mẫu#
Xét hai nhánh \(n_1 = n_2 = n\), phương sai \(\sigma_1^2, \sigma_2^2\), \(\text{SE} := \sqrt{\frac{\sigma_1^2+\sigma_2^2}{n}}\), mức \(\alpha\) hai phía và độ mạnh \(1-\beta\) cho tác động thực \(\Delta := \mu_2 - \mu_1 > 0\). Bỏ qua xác suất đuôi ngược chiều dưới \(H_1\):
Giải phương trình cho \(n\) và MDE:
- Quy tắc nhanh (\(\alpha=0.05, 1-\beta=0.80, \sigma_1=\sigma_2=\sigma\)): \((1.96 + 0.8416)^2 \approx 7.849 \implies n \approx \frac{15.7\sigma^2}{\Delta^2} \approx \frac{16\sigma^2}{\Delta^2}\) mỗi nhánh.
- Phân bổ Tối ưu Neyman (\(n_2 = \kappa n_1\)): Tối thiểu hóa \(n_1 + n_2\) cho \(\frac{\sigma_1^2}{n_1} + \frac{\sigma_2^2}{n_2}\) cố định đạt tại \(\frac{n_2}{n_1} = \frac{\sigma_2}{\sigma_1}\) (cấp thêm lưu lượng cho nhánh có phương sai lớn hơn).
- Bài toán Mẫu Tỷ lệ Chuyển đổi: Phát hiện tăng từ \(p_1 = 4.0\%\) lên \(p_2 = 4.4\%\) (\(\Delta = 0.004\), nâng tương đối \(+10\%\)) tại \(\alpha=0.05, 1-\beta=0.80\) cần \(n \approx \frac{7.8491 \times (0.04\times 0.96 + 0.044\times 0.956)}{0.004^2} \approx \mathbf{39{,}473}\) người dùng mỗi nhánh (
78,946tổng).
Cơ chế Bốn Kiểm định Cốt lõi & Các Bẫy Kinh điển#
- Kiểm định \(t\) Welch (Mặc định Thay thế Student's Pooled \(t\)-Test):
Với \(v_k := s_k^2/n_k\) tính quaWelford:\[t_{\text{Welch}} = \frac{\bar{X}_1 - \bar{X}_2}{\sqrt{v_1 + v_2}}, \qquad \nu = \frac{(v_1 + v_2)^2}{\frac{v_1^2}{n_1 - 1} + \frac{v_2^2}{n_2 - 1}}, \qquad p = I_{\frac{\nu}{\nu + t_{\text{Welch}}^2}}\!\left(\frac{\nu}{2},\; \frac{1}{2}\right).\]Trong chế độ Behrens–Fisher (\(n_1 \ne n_2\) và \(\sigma_1^2 \ne \sigma_2^2\)), nếu nhóm nhỏ hơn lại có phương sai lớn hơn, phương sai gộp của Student bị kéo lệch về phía nhóm lớn và thổi phồngFPRlên \(15\%\text{–}30\%\). Welch giải quyết triệt để vấn đề này mà gần như không mất độ mạnh khi phương sai bằng nhau; đồng thời tuyệt đối không dùng kiểm định phương sai Levene/\(F\) làm bước tiền kiểm để chọn giữa Student và Welch vì tiền kiểm hai bước làm méo phân phối Type I error (Delacre et al., 2017). - Kiểm định Pearson \(\chi^2\) (
GoF& Bảng chéo \(R \times C\)):
Với tần suất quan sát \(O_{rc}\) và kỳ vọng \(E_{rc}\) (\(\sum O = \sum E = n\)): \(\chi^2 = \sum \frac{(O - E)^2}{E} \xrightarrow{d} \chi^2_{\text{df}}\) (\(\text{df} = K-1-m\) choGoF, đặc biệt \(m=0 \implies \text{df}=1\) trong cổng kiểm địnhSRM; và \(\text{df}=(R-1)(C-1)\) cho bảng độc lập \(R\times C\)), tính \(p = Q(\text{df}/2, \chi^2/2)\) qua hàm gamma không đầy đủ trên. Quy tắc Cochran: Nếu \(>20\%\) ô có \(E_{rc} < 5\) hoặc bất kỳ ô nào có \(E_{rc} < 1\), xấp xỉ \(\chi^2\) gãy; phải chuyển sang Kiểm định Chính xác Fisher hoặc Hoán vị Bảng cố định biên. -
Kiểm định Mann–Whitney U (Wilcoxon Rank-Sum) & Phản ví dụ Trung vị Bằng nhau:
Gộp \(N = n_1 + n_2\) quan sát và gán hạng trung bình phân số \(R_i\), tính \(U_1 = \sum_{i=1}^{n_1} R(X_i) - \frac{n_1(n_1+1)}{2} = \sum_i\sum_j (\mathbb{I}[X_i > Y_j] + \frac{1}{2}\mathbb{I}[X_i = Y_j])\) (lưu ý \(\frac{U_1}{n_1 n_2}\) chính là xác suất đồng thuận /ROC-AUC!). Phương sai hiệu chỉnh đồng hạng:\[\mu_U = \frac{n_1 n_2}{2}, \qquad \sigma_U^2 = \frac{n_1 n_2}{12}\left[(N+1) - \frac{\sum_{g=1}^G (t_g^3 - t_g)}{N(N-1)}\right].\]Bẫy Giải thích Sai Trung vị & Phản ví dụ Tường minh: Mann–Whitney \(U\) kiểm định ưu thế ngẫu nhiên (stochastic dominance) \(H_0: P(X > Y) + \frac{1}{2}P(X = Y) = \frac{1}{2}\), KHÔNG phải kiểm định bằng trung vị (chỉ tương đương trung vị khi giả định dịch vị trí thuần \(F_Y(t) = F_X(t-\delta)\))! Xét hai phân phối hỗn hợp liên tục:
\[X \sim \tfrac{1}{2}\operatorname{Uniform}(-1, 0) + \tfrac{1}{2}\operatorname{Uniform}(0, 10), \qquad Y \sim \tfrac{1}{2}\operatorname{Uniform}(-10, 0) + \tfrac{1}{2}\operatorname{Uniform}(0, 1).\]Cả hai đều có \(P(X \le 0) = P(Y \le 0) = 0.5 \implies \operatorname{Median}(X) = \operatorname{Median}(Y) = \mathbf{0}\) hệt nhau! Nhưng trên bốn góc phần tư đồng xác suất, \(P(X > Y) = \frac{1}{4}[0.95 + 1.0 + 0.0 + 0.95] = \mathbf{0.725} \ne 0.50\), khiến Mann–Whitney bác bỏ \(H_0\) với độ mạnh \(\sim 100\%\)!
-
Kiểm định Hoán vị Chuẩn hóa (
Studentized Permutation) & Chứng minh \((1 + \#)/(B + 1)\):- Bẫy Behrens–Fisher: Nếu \(H_0\) chỉ nói \(\mu_1 = \mu_2\) mà \(\sigma_1^2 \ne \sigma_2^2\) và \(n_1 \ne n_2\), dữ liệu gộp không có tính hoán vị! Hoán vị trực tiếp hiệu trung bình thô sẽ mất kiểm soát Type I error; bắt buộc dùng thống kê Welch \(t\) chuẩn hóa \(T(\mathbf{Z}) = t_{\text{Welch}}(\mathbf{Z})\) (Chung & Romano, 2013).
- Chứng minh Tính hợp lệ Mẫu Hữu hạn (Phipson & Smyth, 2010): Rút \(B\) hoán vị ngẫu nhiên \(\pi_1, \dots, \pi_B\), đặt:
\[p_{\text{perm}} = \frac{1 + \sum_{b=1}^B \mathbb{I}\big[|T_b| \ge |T_{\text{obs}}|\big]}{B + 1}.\]Dưới tính hoán vị \(H_0\), bộ \((|T_{\text{obs}}|, |T_1|, \dots, |T_B|)\) là \(B+1\) biến hoán vị, nên thứ hạng \(M := 1 + \sum_{b=1}^B \mathbb{I}[|T_b| \ge |T_{\text{obs}}|]\) (gán hạng lớn nhất khi đồng hạng) bị trội ngẫu nhiên bởi phân phối đều trên \(\{1, \dots, B+1\}\), tức \(P_{H_0}(M \le k) \le \frac{k}{B+1}\). Chọn \(k = \lfloor \alpha(B+1) \rfloor\) suy ra ngay:\[P_{H_0}(p_{\text{perm}} \le \alpha) = P_{H_0}\big(M \le \lfloor \alpha(B+1) \rfloor\big) \le \frac{\lfloor \alpha(B+1) \rfloor}{B+1} \le \alpha \qquad \forall B, n! \qquad \blacksquare\](Ngược lại, công thức ngây thơ \(\# / B\) có thể ra \(p = 0\) và vi phạm Type I error bất cứ khi nào \(\alpha < 1/B\).)
1.6 Khủng hoảng Đa kiểm định: FWER vs. Benjamini–Hochberg FDR (Multiple Comparisons)#
Khi chạy đồng thời \(m\) kiểm định độc lập ở mức \(\alpha = 0.05\), xác suất xuất hiện ít nhất một dương tính giả vọt lên \(P(V \ge 1) = 1 - (1 - \alpha)^m\) (64.2% tại \(m=20\), 99.4% tại \(m=100\)).
| Ma trận Quyết định trên \(m\) Giả thuyết | Không Bác bỏ (\(m - R\)) | Bác bỏ / Phát hiện (\(R\)) | Tổng |
|---|---|---|---|
| Giả thuyết Không Đúng (\(H_0\)) | \(U\) (Âm tính Đúng) | \(V\) (Dương tính Giả / Loại I) | \(m_0\) |
| Giả thuyết Đối Đúng (\(H_1\)) | \(T\) (Âm tính Giả / Loại II) | \(S\) (Dương tính Đúng) | \(m_1 = m - m_0\) |
- Kiểm soát Tỷ lệ Sai lầm Gia đình (
FWER\(\le \alpha\)): \(\text{FWER} := P(V \ge 1)\).- Bonferroni (\(p_i \le \alpha/m\)): Theo Union Bound (§1.1) mà không cần giả thiết độc lập: \(\text{FWER} = P(\bigcup_{i \in \mathcal{H}_0}\{p_i \le \alpha/m\}) \le \sum_{i\in\mathcal{H}_0} P(p_i \le \alpha/m) \le m_0\frac{\alpha}{m} \le \alpha\). \(\blacksquare\)
- Holm–Bonferroni (Bước xuống / Step-Down, 1979): Sắp xếp \(p_{(1)} \le \dots \le p_{(m)}\), bác bỏ liên tiếp từ \(i=1\) miễn là \(p_{(i)} \le \frac{\alpha}{m - i + 1}\). Chứng minh dưới phụ thuộc tùy ý: Giả sử \(V \ge 1\) và gọi \(i^*\) là chỉ số nhỏ nhất trong số các \(H_0\) thật bị bác bỏ. Vì mọi \(j < i^*\) đều đã bị bác bỏ và không thuộc \(\mathcal{H}_0\), toàn bộ \(m_0\) giả thuyết không thật phải nằm trong \(\{i^*, \dots, m\}\), ép \(m - i^* + 1 \ge m_0\). Do \(i^*\) bị bác bỏ, \(p_{(i^*)} \le \frac{\alpha}{m-i^*+1} \le \frac{\alpha}{m_0}\), suy ra \(\{V \ge 1\} \subseteq \bigcup_{i\in\mathcal{H}_0}\{p_i \le \frac{\alpha}{m_0}\} \implies \text{FWER} \le m_0\frac{\alpha}{m_0} = \alpha\). \(\blacksquare\) (Mạnh hơn hẳn Bonferroni với zero chi phí giả thiết.)
-
Tỷ lệ Phát hiện Sai (
FDR) & Thủ tục Bước lên Benjamini–Hochberg (BH, 1995) /BY(2001):
Định nghĩa \(\text{FDP} := \frac{V}{\max(R, 1)}\) và \(\text{FDR} := \mathbb{E}[\text{FDP}]\). Ở mức mục tiêu \(q \in (0, 1)\),BHquét ngược từ \(m\) xuống \(1\) tìm chỉ số lớn nhất:\[k^* := \max\left\{k \in \{1, \dots, m\} : p_{(k)} \le \frac{k}{m}q\right\},\]và bác bỏ toàn bộ \(H_{0,(1)}, \dots, H_{0,(k^*)}\) (ngay cả khi vài \(p_{(j)} > \frac{j}{m}q\) ở \(j < k^*\)!). Các \(q\)-value hiệu chỉnh đơn điệu tính bằng cực tiểu tích lũy lùi \(q_{(m)}^{\text{BH}} = \min(p_{(m)}, 1)\), \(q_{(i)}^{\text{BH}} = \min(q_{(i+1)}^{\text{BH}}, \frac{m}{i}p_{(i)})\).
- Trực giác chứng minh (độc lập /
PRDS): Viết \(\text{FDP} = \sum_{i\in\mathcal{H}_0}\sum_{k=1}^m \frac{1}{k}\mathbb{I}[p_i \le \frac{k}{m}q,\; R=k]\). Điều kiện hóa trên \(p_{-i}\), độc lập cho \(P(p_i \le \frac{k}{m}q \mid p_{-i}) = \frac{k}{m}q\), triệt tiêu đúng thừa số \(\frac{1}{k}\) trong tử số \(\frac{1}{k}\), khiến tổng nội bộ rút gọn về \(\frac{q}{m}\sum_{k=1}^m P(C_k^{(i)}) = \frac{q}{m}\) và tổng toàn bộ \(\mathcal{H}_0\) đạt \(\frac{m_0}{m}q \le q\). - Phụ thuộc Tùy ý (
BY, Benjamini & Yekutieli 2001): Khi các chỉ số có tương quan âm/tùy ý, thay \(q \mapsto \frac{q}{H_m}\) với \(H_m = \sum_{i=1}^m \frac{1}{i} \approx \ln m + \gamma_{\text{EM}}\).
- Trực giác chứng minh (độc lập /
Bảng Đối chiếu Thực nghiệm (\(m = 6\), \(\alpha = q = 0.05\))#
Dãy \(p\)-value đã sắp xếp: \(p_{(1)}=0.001,\; p_{(2)}=0.009,\; p_{(3)}=0.026,\; p_{(4)}=0.032,\; p_{(5)}=0.041,\; p_{(6)}=0.420\).
| Hạng \(i\) | \(p_{(i)}\) | Bonferroni \(\frac{0.05}{6}\) | Ngưỡng Holm \(\frac{0.05}{6-i+1}\) | Ngưỡng BH \(\frac{i}{6}(0.05)\) |
\(q_{(i)}^{\text{BH}}\) | Quyết định (\(\text{Bonf}\) / \(\text{Holm}\) / \(\text{BH}\)) |
|---|---|---|---|---|---|---|
| \(1\) | 0.001 |
0.00833 |
0.00833 |
0.00833 |
0.0060 |
Bác bỏ / Bác bỏ / Bác bỏ |
| \(2\) | 0.009 |
0.00833 |
0.01000 |
0.01667 |
0.0270 |
Giữ \(H_0\) / Bác bỏ / Bác bỏ |
| \(3\) | 0.026 |
0.00833 |
0.01250 |
0.02500 (vượt ngưỡng!) |
0.0480 (kẹp) |
Giữ \(H_0\) / Giữ \(H_0\) / Bác bỏ (được cứu bởi \(i=5\)!) |
| \(4\) | 0.032 |
0.00833 |
0.01667 |
0.03333 |
0.0480 |
Giữ \(H_0\) / Giữ \(H_0\) / Bác bỏ |
| \(5\) | 0.041 |
0.00833 |
0.02500 |
0.04167 (\(k^* = 5\)) |
0.0492 |
Giữ \(H_0\) / Giữ \(H_0\) / Bác bỏ |
| \(6\) | 0.420 |
0.00833 |
0.05000 |
0.05000 |
0.4200 |
Giữ \(H_0\) / Giữ \(H_0\) / Giữ \(H_0\) |
Trụ cột 2 — Kiến trúc SOTA 2024–2026: Giảm phương sai, Kiểm định Mọi thời điểm & Dự báo Conformal Không phân phối (SOTA 2024–2026 Experimentation, Anytime-Valid Inference & Conformal UQ)#
2.1 Giảm phương sai SOTA (CUPED, Lin ANCOVA2, CUPAC/MLRATE) & Bẫy Tỷ lệ / Đuôi nặng (Variance Reduction & Ratio/Tail Pitfalls)#
Suy diễn CUPED (Deng et al., WSDM 2013), Bẫy Quy tâm Nhánh & Lin ANCOVA2 (2013)#
Xét thí nghiệm ngẫu nhiên hóa \(N = n_1 + n_0\) đơn vị với chỉ báo nhóm \(W_i \in \{0, 1\}\), chỉ số hậu thử nghiệm \(Y_i\), và biến hiệp phương sai tiền thử nghiệm \(X_i\) đo tuyệt đối trước thời điểm ngẫu nhiên hóa (\(t \le t_{\text{assign}}\)) để đảm bảo \(X_i \perp W_i\) và \(\mathbb{E}[\bar{X}_1 - \bar{X}_0] = 0\). Định nghĩa kết quả điều chỉnh với trung bình gộp \(\bar{X} = \frac{1}{N}\sum_{i=1}^N X_i\):
- Chứng minh Không thiên lệch (
Unbiasedness): Trung bình gộp \(\bar{X}\) triệt tiêu đồng nhất trong hiệu hai nhánh:\[\hat{\tau}_{\text{CUPED}}(\theta_{\text{cuped}}) = \bar{\tilde{Y}}_1 - \bar{\tilde{Y}}_0 = (\bar{Y}_1 - \bar{Y}_0) - \theta_{\text{cuped}}(\bar{X}_1 - \bar{X}_0) \implies \mathbb{E}[\hat{\tau}_{\text{CUPED}}] = \mathbb{E}[\bar{Y}_1 - \bar{Y}_0] - \theta_{\text{cuped}}\underbrace{\mathbb{E}[\bar{X}_1 - \bar{X}_0]}_{=\,0} = \tau_{\text{ATE}}.\] - Suy diễn \(\theta_{\text{cuped}}^*\) Tối ưu & Hệ số Nhân Cỡ mẫu: Đặt \(\operatorname{Var}(\tilde{Y}) = \operatorname{Var}(Y) + \theta_{\text{cuped}}^2\operatorname{Var}(X) - 2\theta_{\text{cuped}}\operatorname{Cov}(Y, X)\). Đạo hàm theo \(\theta_{\text{cuped}}\) cho cực tiểu lồi toàn cục:
\[\theta_{\text{cuped}}^* = \frac{\operatorname{Cov}(Y, X)}{\operatorname{Var}(X)} \implies \operatorname{Var}\big(\tilde{Y}(\theta_{\text{cuped}}^*)\big) = \operatorname{Var}(Y)\!\left(1 - \frac{\operatorname{Cov}(Y, X)^2}{\operatorname{Var}(Y)\operatorname{Var}(X)}\right) = \operatorname{Var}(Y)\big(1 - \rho_{Y, X}^2\big).\]Vì cỡ mẫu yêu cầu tỷ lệ thuận với phương sai (\(N_{\text{req}} \propto \sigma^2/\Delta_{\text{MDE}}^2\)), bội số tăng tốc lưu lượng là \(\frac{N_{\text{unadj}}}{N_{\text{CUPED}}} = \frac{1}{1 - \rho_{Y, X}^2}\) (ví dụ \(\rho_{Y,X} = 0.7 \implies 1.96\times\); \(\rho_{Y,X} = 0.85 \implies 3.60\times\)).
- Bẫy Quy tâm Theo nhánh (
Arm-Centering Erasure) & Hiệu chỉnh Tương tác của Lin (2013):- Tuyệt đối dùng trung bình gộp \(\bar{X}\), CẤM quy tâm riêng từng nhánh: Nếu đặt \(\tilde{Y}_i = Y_i - \theta(X_i - \bar{X}_{W_i})\), thì \(\bar{\tilde{Y}}_1 - \bar{\tilde{Y}}_0 \equiv \bar{Y}_1 - \bar{Y}_0\) không hề thay đổi hiệu trung bình — xóa sạch 100% tác dụng giảm phương sai trong khi làm sai lệch phương sai mẫu nội nhánh!
- Phê phán Freedman (2008) & Giải pháp
Lin ANCOVA2(arXiv:1208.2301): Freedman chứng minh hồi quy không tương tác \(Y_i \sim 1 + W_i + X_i\) có thể làm tăng phương sai tiệm cận so với hiệu trung bình thuần khi tỷ lệ phân bổ \(p = n_1/N \ne 0.5\) và độ dốc giữa hai nhánh khác nhau (\(\theta_1 \ne \theta_0\)). Lin (2013) giải quyết triệt để bằng mô hình OLS có tương tác:\[Y_i = \alpha + \tau W_i + \beta(X_i - \bar{X}) + \gamma W_i(X_i - \bar{X}) + \varepsilon_i\]kèm sai số chuẩn bền vững bất đẳng phương sai Huber–WhiteHC1. Đại số cho thấy \(\hat{\tau}_{\text{Lin}} = (\bar{Y}_1 - \bar{Y}_0) - ((1-p)\hat{\theta}_1 + p\hat{\theta}_0)(\bar{X}_1 - \bar{X}_0)\), đảm bảo hiệu quả tiệm cận không bao giờ kém hơn hiệu trung bình thuần bất kể phân phối sai số hay tác động dị chất (heterogeneous effects).
Biến Kiểm soát Phi tuyến Khớp chéo (CUPAC & MLRATE) & Bằng chứng Chống Overfit#
Khi biến tiền thử nghiệm gồm hàng chục chiều nhúng hành vi \(\mathbf{Z}_{i,\text{pre}} \in \mathbb{R}^d\), dùng predictor ML phi tuyến (DoorDash CUPAC, Tang et al. 2020) hay chuẩn hóa hai pha (Meta MLRATE, Guo et al., NeurIPS 2021, arXiv:2106.07263) cắt tiếp 30%–70% phương sai:
- Giai đoạn 1 (Khớp chéo \(K\)-nếp chặt chẽ — Strict \(K\)-Fold Cross-Fitting): Chia ngẫu nhiên (phân tầng theo \(W_i\)) thành \(K\) nếp \(I_1, \dots, I_K\). Với từng nếp \(k\), huấn luyện \(\hat{f}^{(-k)}(\mathbf{Z}_{\text{pre}})\) dự đoán \(Y\) trên \(I_{-k}\) chỉ dùng đặc trưng tiền thử nghiệm (cấm tiệt \(W_i\) hoặc biến phát sinh sau \(t_{\text{assign}}\)!), rồi sinh dự báo ngoài nếp \(\hat{g}_i = \hat{f}^{(-k)}(\mathbf{Z}_{i,\text{pre}})\) cho \(i \in I_k\).
- Giai đoạn 2 (Hiệu chuẩn Ngoài theo
Lin ANCOVA2): Chạy OLS của \(Y_i\) trên \((1,\; W_i,\; \hat{g}_i - \bar{\hat{g}},\; W_i(\hat{g}_i - \bar{\hat{g}}))\) (hệ số dốc \(\hat{\theta}_{\text{out}}\)) với sai số chuẩnHC1. - Vì sao Khớp trong mẫu (In-Sample Fitting) Phá hủy Kiểm định? Nếu \(\hat{f}\) được khớp trực tiếp trên toàn bộ mẫu và đánh giá lại trên chính mẫu đó, mô hình đa chiều ghi nhớ nhiễu \(\varepsilon_i\), kéo tụt \(\widehat{\operatorname{Var}}(Y_i - \hat{g}_i)\) giả tạo và thổi phồngFPR. Trong thí nghiệm kiểm chứng (\(d=100\) đặc trưng nhiễu trắng thuần túy tại \(N=400\)),CUPEDgộp trong mẫu thổi phồng mức giảm phương sai ảo lên28.6%và làm trôi ước lượng ATE tới0.88 SE, trong khiMLRATEkhớp chéo 5-nếp giữ mức giảm phương sai trung thực ở0.6%trên nhiễu thuần túy và đạt88.9%VR (9.0xtăng tốc cỡ mẫu) khi có tín hiệu thực! Jin & Ba (Technometrics 2023) chứng minh thêm rằng nhờ xác suất phân nhánh \(p\) đã biết trong RCT,MLRATEđạt hiệu quả bán tham số tối ưu ngay cả khi mô hình ML ở Giai đoạn 1 hội tụ chậm.
Sụp đổ Chỉ số Tỷ lệ (\(\operatorname{CV}(\bar{X}) > 0.1\)) & Đảo dấu Đuôi nặng LogNormal#
- Ngưỡng Sụp đổ \(\operatorname{CV}(\bar{X}) > 0.1\) & Giải cứu bằng Khoảng Fieller:
Với tỷ số tuyến tính hóa theo cụm \(u_{g,i} = (Y_{g,i} - \hat{R}_g X_{g,i})/\bar{X}_g\) (Deng, Knoblich & Lu, KDD 2018), Díaz-Francés & Rubio (2013) chứng minh xấp xỉ chuẩn cho tỷ số hai biến chuẩn chỉ giữ nguyên độ chính xác khi hệ số biến thiên mẫu số \(\operatorname{CV}(\bar{X}) := \frac{\operatorname{SE}(\bar{X})}{|\mu_X|} \lesssim 0.1\). Khi \(\operatorname{CV}(\bar{X}) > 0.1\), xác suất \(\bar{X} \approx 0\) trở nên đáng kể, khai triển Taylor của \(1/\bar{X}\) phân kỳ, thiên lệch tỷ lệ bậc hai phình to, và phân phối tỷ số mọc đuôi nặng kiểu Cauchy (mô-men vô hạn!). Giải pháp: Dùng Tập Tin cậy Fieller chính xác bằng cách giải bất phương trình bậc hai theo \(R\):\[(\bar{Y} - R\bar{X})^2 \le z_{1-\alpha/2}^2 \widehat{\operatorname{Var}}(\bar{Y} - R\bar{X}) = z_{1-\alpha/2}^2\left(v_Y - 2R\,v_{XY} + R^2 v_X\right),\](nếu biệt thức mẫu số \(A_{\text{fieller}} = \bar{X}^2 - t_{n-1;\,1-\alpha/2}^2 v_X \le 0\), khoảng tin cậy chính xác là không bị chặn — trung thực cảnh báo tỷ lệ chưa định danh!). Ngoài ra, nếu nhóm điều trị tác động trực tiếp lên mẫu số (\(\mu_{X,1} \ne \mu_{X,0}\), ví dụ Simpson exposure dilution), bắt buộc tuyến tính hóa riêng từng nhánh quanh \(\hat{R}_w\) và áp dụngCUPEDhai biến độc lập cho cả \((Y, X)\) trước khi chia tỷ số. -
Phản ví dụ Đảo dấu LogNormal & Bộ ước lượng Bôi trơn Duan (
Duan Smearing):
Phép biến đổi \(\ln(Y)\) kiểm định trung bình hình học, không phải trung bình số học quyết định doanh thu/CPU thực tế! Theo bất đẳng thức Jensen, \(\mathbb{E}[\ln Y] < \ln\mathbb{E}[Y]\):- Phản ví dụ Đảo dấu Giải tích: Nhóm Đối chứng \(Y_0 \sim \operatorname{LogNormal}(\mu_0=0, \sigma_0^2=2)\) có \(\mathbb{E}[Y_0] = e^{0+1} \approx 2.718\); nhóm Thử nghiệm \(Y_1 \sim \operatorname{LogNormal}(\mu_1=0.2, \sigma_1^2=1)\) có \(\mathbb{E}[Y_1] = e^{0.2+0.5} \approx 2.014\). Trên thang log, \(\mathbb{E}[\ln Y_1]-\mathbb{E}[\ln Y_0] = \mathbf{+0.2 > 0}\) (tuyên bố thắng!), trong khi doanh thu trung bình số học thực sự giảm \(-25.9\%\) (\(2.014 - 2.718 = -0.704 < 0\))! Tương tự trong ví dụ độ trễ cạnh mạng (§3.1 Case 5), cải thiện thực sự \(-31.4\%\) (
15.11 ms -> 10.36 ms) bị đảo dấu thành tụt lùi \(+10.1\%\) dưới \(\exp(\bar{Z})\). - Bẫy
log1p& Winsorization: Cộng hằng số \(c\) trong \(\ln(Y+c)\) làm kết quả và \(p\)-value mất bất biến theo đơn vị tiền tệ (USD vs. cents vs. VND). Cắt ngọn (winsorization) riêng rẽ từng nhánh bơm phương sai ngưỡng giả làm phìnhFPR(luôn ước lượng ngưỡng cắt từ dữ liệu tiền thử nghiệm hoặc gộp hai nhánh). Để ước lượng trung bình số học chính xác từ mô hình log, sử dụng bộ ước lượng bôi trơn Duan (1983): \(\hat{\mu}_{\text{arith}} = \exp(\hat{\mu}_{\log})\cdot\frac{1}{n}\sum_{i=1}^n \exp(r_i)\) với \(r_i = \ln Y_i - \hat{\mu}_{\log,i}\), hoặc dùng trực tiếp Gamma GLM với liên kết log (\(\mathbb{E}[Y\mid W]=\exp(\beta_0+\beta_1 W)\)).
- Phản ví dụ Đảo dấu Giải tích: Nhóm Đối chứng \(Y_0 \sim \operatorname{LogNormal}(\mu_0=0, \sigma_0^2=2)\) có \(\mathbb{E}[Y_0] = e^{0+1} \approx 2.718\); nhóm Thử nghiệm \(Y_1 \sim \operatorname{LogNormal}(\mu_1=0.2, \sigma_1^2=1)\) có \(\mathbb{E}[Y_1] = e^{0.2+0.5} \approx 2.014\). Trên thang log, \(\mathbb{E}[\ln Y_1]-\mathbb{E}[\ln Y_0] = \mathbf{+0.2 > 0}\) (tuyên bố thắng!), trong khi doanh thu trung bình số học thực sự giảm \(-25.9\%\) (\(2.014 - 2.718 = -0.704 < 0\))! Tương tự trong ví dụ độ trễ cạnh mạng (§3.1 Case 5), cải thiện thực sự \(-31.4\%\) (
2.2 Suy luận Hợp lệ Mọi Thời điểm (LIL, Bất đẳng thức Ville, mSPRT, O'Brien–Fleming, GROW, e-BH & SRM e-Process)#
Sụp đổ Nhìn trộm Liên tục (LIL)#
Với chuỗi quan sát i.i.d. dưới \(H_0: \mathbb{E}[X_i]=\mu_0\) (\(\sigma^2 > 0\)), \(S_n = \sum_{i=1}^n (X_i - \mu_0)\) và \(Z_n = \frac{S_n}{\sigma\sqrt{n}}\). Tại một chân trời cố định \(N\), \(Z_N \xrightarrow{d}\mathcal{N}(0,1)\) giữ FPR ở \(\alpha = 5\%\). Nhưng khi đội kỹ thuật nhìn bảng điều khiển liên tục và dừng ngay khi \(|Z_n| > 1.96\), Định lý Logarit Lặp Hartman–Wintner (LIL, 1941) khẳng định:
Trong thực nghiệm 5,000 đường mẫu không hiệu ứng tới \(n=10{,}000\), FPR tăng vọt từ 5.54% (1 lần nhìn) lên 26.02% (20 lần nhìn), 44.98% (200 lần nhìn) và 54.66% khi theo dõi liên tục!
e-Values, Siêu Martingale Kiểm định & Chứng minh Trọn vẹn Bất đẳng thức Ville (1939)#
e-Variable &e-Value (Ramdas & Wang, 2024–2025,arXiv:2410.23614): Với giả thuyết không hỗn hợp \(\mathcal{H}_0\), biến ngẫu nhiên không âm \(E : \Omega \to [0, \infty]\) là mộte-variable nếu \(\sup_{P \in \mathcal{H}_0} \mathbb{E}_P[E] \le 1\) (diễn giải trực quan là hệ số nhân vốn cược bắt đầu từ$1).- Siêu Martingale Kiểm định & Tiến trình
e(e-Process): Đối với lọc thông tin \((\mathcal{F}_t)_{t \ge 0}\), tiến trình thích nghi không âm \((M_t)_{t \ge 0}\) với \(\mathbb{E}_P[M_0] \le 1\) là một \(P\)-test supermartingale nếu \(\mathbb{E}_P[M_t \mid \mathcal{F}_{t-1}] \le M_{t-1}\) h.c.c. Mộte-process \((E_t)_{t \ge 0}\) thỏa mãn \(\sup_{P\in\mathcal{H}_0}\mathbb{E}_P[E_{\tau_{\text{stop}}}] \le 1\) tại mọi thời điểm dừng \(\tau_{\text{stop}}\) phụ thuộc dữ liệu.
Định lý 2.1 (Bất đẳng thức Cực đại Ville, 1939): Cho \((M_t)_{t \ge 0}\) là siêu martingale không âm dưới \(P\) với \(\mathbb{E}_P[M_0] \le 1\). Khi đó với mọi \(\alpha \in (0, 1]\):
Chứng minh đầy đủ 4 bước:
- Thời điểm Dừng Bị chặn Cắt cụt: Cố định chân trời hữu hạn \(T \in \mathbb{N}\) và định nghĩa \(\tau_T := \min\big(\inf\{t \ge 0 : M_t \ge 1/\alpha\},\; T\big)\) (với \(\inf\emptyset := +\infty\)). Vì \(\{\tau_T = t\} \in \mathcal{F}_t\) và \(\tau_T \le T\), nên \(\tau_T\) là một thời điểm dừng bị chặn.
- Định lý Dừng Tùy chọn cho Siêu Martingale Rời rạc Bị chặn: Viết giá trị dừng dưới dạng biến đổi tiền dự báo (predictable transform):
\[M_{\tau_T} = M_0 + \sum_{t=1}^T \mathbb{I}\{\tau_T \ge t\}\,(M_t - M_{t-1}).\]Vì \(\{\tau_T \ge t\} = \{\tau_T \le t-1\}^c \in \mathcal{F}_{t-1}\) đã biết trước bước \(t\), lấy kỳ vọng dưới \(P\) và áp dụng tính chất tháp (
LoTE) cho:\[\mathbb{E}_P[M_{\tau_T}] = \mathbb{E}_P[M_0] + \sum_{t=1}^T \mathbb{E}_P\!\Big[\mathbb{I}\{\tau_T \ge t\}\underbrace{\mathbb{E}_P[M_t - M_{t-1} \mid \mathcal{F}_{t-1}]}_{\le\, 0\text{ (siêu martingale)}}\Big] \le \mathbb{E}_P[M_0] \le 1.\] - Cận Markov trên Biến cố Vượt ngưỡng: Đặt \(A_T := \{\exists t \in \{0, \dots, T\} : M_t \ge 1/\alpha\}\). Trên \(A_T\), \(M_{\tau_T} \ge 1/\alpha\); trên \(A_T^c\), tính không âm đảm bảo \(M_{\tau_T} = M_T \ge 0\). Áp dụng Bất đẳng thức Markov cho biến không âm \(M_{\tau_T}\):
\[P(A_T) \le P\!\left(M_{\tau_T} \ge \frac{1}{\alpha}\right) \le \alpha\,\mathbb{E}_P[M_{\tau_T}] \le \alpha\,\mathbb{E}_P[M_0] \le \alpha.\]
- Chuyển qua Giới hạn Vô hạn (\(T \to \infty\)): Vì \(A_1 \subseteq A_2 \subseteq \dots\) tăng lồng nhau với hợp \(\bigcup_{T=1}^\infty A_T = \{\exists t \ge 0 : M_t \ge 1/\alpha\}\), tính liên tục từ dưới của độ đo xác suất (§1.1) cho:
\[P\!\left(\exists t \ge 0 : M_t \ge \frac{1}{\alpha}\right) = \lim_{T \to \infty} P(A_T) \le \alpha. \qquad \blacksquare\]
(Đối chiếu với Markov: Markov chỉ chặn xác suất vượt ngưỡng tại một thời điểm \(T\) cố định, còn Ville nâng cấp cận đó thành đồng nhất theo thời gian trên toàn bộ quỹ đạo! Do đó đặt \(p\)-value hợp lệ mọi thời điểm \(p_{\text{any}, t} := \min_{0 \le s \le t} \min\!\big(1, \frac{1}{E_s}\big)\) đảm bảo \(P(p_{\text{any}, \tau_{\text{stop}}} \le \alpha) \le \alpha\) cho mọi chiến lược dừng/nhìn trộm!)
Suy diễn Dạng đóng Gaussian mSPRT & Dãy Tin cậy Mọi Thời điểm (Johari et al., 2022)#
Tại thời điểm \(t\), hiệu trung bình \(\hat{\Delta}_t = \bar{Y}_{1,t} - \bar{Y}_{0,t}\) có phương sai gộp \(V_t = \frac{\sigma_1^2}{n_{1,t}} + \frac{\sigma_0^2}{n_{0,t}}\) và \(\hat{\Delta}_t \mid \Delta \sim \mathcal{N}(\Delta, V_t)\). Đặt tiên nghiệm pha trộn Gaussian \(\Delta \sim \mathcal{N}(0, \tau_{\text{mix}}^2)\) (\(\tau_{\text{mix}}^2 > 0\)) lên các tỷ số hợp lý điểm \(\Lambda_t(\Delta)\):
- Dưới \(H_0\) (\(\Delta = 0\)): \(p_0(\hat{\Delta}_t) = (2\pi V_t)^{-1/2}\exp(-\frac{\hat{\Delta}_t^2}{2V_t})\).
- Hợp lý biên dưới pha trộn (\(\hat{\Delta}_t = \Delta + \varepsilon_t \sim \mathcal{N}(0, V_t + \tau_{\text{mix}}^2)\)): \(p_{\text{mix}}(\hat{\Delta}_t) = (2\pi(V_t+\tau_{\text{mix}}^2))^{-1/2}\exp(-\frac{\hat{\Delta}_t^2}{2(V_t+\tau_{\text{mix}}^2)})\).
- Chia \(p_{\text{mix}}/p_0\) và rút gọn \(\frac{1}{2V_t} - \frac{1}{2(V_t+\tau_{\text{mix}}^2)} = \frac{\tau_{\text{mix}}^2}{2V_t(V_t+\tau_{\text{mix}}^2)}\) thu được tiến trình
e-valuemSPRTdạng đóng:\[E_t = \sqrt{\frac{V_t}{V_t + \tau_{\text{mix}}^2}}\,\exp\!\left(\frac{\tau_{\text{mix}}^2 \hat{\Delta}_t^2}{2 V_t (V_t + \tau_{\text{mix}}^2)}\right).\] - Đảo ngược \(E_t(\Delta_0) < 1/\alpha\) (thay \(\hat{\Delta}_t\) bằng \(\hat{\Delta}_t - \Delta_0\)) cho Dãy Tin cậy Mọi Thời điểm \(\mathcal{C}_t(\alpha) = [\hat{\Delta}_t - r_t(\alpha),\; \hat{\Delta}_t + r_t(\alpha)]\) với bán kính chính xác:
\[r_t(\alpha) = \sqrt{\frac{V_t(V_t + \tau_{\text{mix}}^2)}{\tau_{\text{mix}}^2}\left(\ln\frac{V_t + \tau_{\text{mix}}^2}{V_t} + 2\ln\frac{1}{\alpha}\right)} = \mathcal{O}\!\left(\sqrt{\frac{\ln n}{n}}\right).\]Thực tế sản xuất chọn \(\tau_{\text{mix}} \approx |\Delta_{\text{MDE}}|/2\) (hoặc theo phương sai lịch sử của các nâng cấp thực tế). Waudby-Smith et al. (Annals of Statistics 2024,
arXiv:2103.06476) chuẩn hóaAsympCSbằng nguyên lý bất biến mạnh Strassen để hợp thức hóa việc thế \(\hat{V}_t\) mẫu vào luồng dữ liệu không bị chặn.
| Tiêu chí | Nhóm Tuần tự (O'Brien–Fleming / Lan–DeMets) |
Gaussian mSPRT (Johari et al., 2022) |
GROW e-Values (Grünwald et al., JRSS-B 2024) |
|---|---|---|---|
| Chân trời & Nhìn trộm | Khóa trước \(N_{\max}\); kiểm tra theo lịch \(t_k = n_k/N_{\max} \le 1\) (\(\alpha^*(t_k) = 2(1-\Phi(z_{\alpha/2}/\sqrt{t_k}))\)). | Chân trời vô hạn (\(N_{\max}=\infty\)); nhìn tại mọi sự kiện; mở rộng vô hạn. | Chân trời vô hạn; nhìn mọi lúc + tiếp nối tùy chọn (nhân \(E^{(1)}\cdot E^{(2)}\) qua các thử nghiệm nối tiếp!). |
| Độ mạnh & Tốc độ | Gần tối ưu tại \(N_{\max}\) (\(z_{\text{cuối}} \approx 2.02\) vs. \(1.96\)); cấm kéo dài quá \(N_{\max}\). | Rộng hơn \(\sim 15\%\text{–}30\%\) ở \(N_{\max}\) cố định; dừng rất nhanh khi hiệu ứng lớn; bề rộng \(\mathcal{O}(\sqrt{\ln n / n})\). | Tối ưu hóa tăng trưởng log-vốn Kelly tệ nhất \(\sup_E\inf_{Q}\mathbb{E}_Q[\ln E]\), thời gian dừng tiệm cận \(\frac{\ln(1/\alpha)}{\text{KL}(Q \Vert P_0)}\). |
| Tham số nhiễu | Dựa vào tính chuẩn tiệm cận của \(Z\)-score ở các mốc định kỳ. | Thế trực tiếp \(\hat{V}_t\) (xấp xỉ với \(\sigma^2\) chưa biết ở mẫu nhỏ). | e-biến chính xác mẫu hữu hạn cho kiểm định \(t\) & bảng \(2\times 2\) qua phép chiếu thông tin ngược RIPr. |
(Lưu ý frontier: Howard, Ramdas, McAuliffe & Sekhon, Annals of Statistics 2021 khâu các biên hình học thành Dãy Tin cậy đạt tốc độ tối ưu LIL \(\mathcal{O}(\sqrt{\ln\ln n / n})\).)
Đa kiểm định Dưới Phụ thuộc Tùy ý (e-BH) & e-Process Dirichlet–Multinomial cho SRM#
- Thủ tục
e-BH(Wang & Ramdas, JRSS-B 2022,arXiv:2009.02824): Xếp \(K\)e-value giảm dần \(E_{(1)} \ge E_{(2)} \ge \dots \ge E_{(K)}\), tìm \(k^* := \max\{k \in \{1,\dots,K\} : E_{(k)} \ge \frac{K}{\alpha k}\}\) và bác bỏ \(k^*\) giả thuyết đứng đầu.
Chứng minh 3 dòng Kiểm soát FDR Dưới Phụ thuộc Tùy ý: Gọi \(R = k^*\) là số bác bỏ và \(\mathcal{H}_0\) là tập giả thuyết không thật. Nếu \(i \in \mathcal{H}_0\) bị bác bỏ, bắt buộc \(E_i \ge \frac{K}{\alpha R}\), suy ra bất đẳng thức điểm \(\frac{\mathbb{I}\{i\text{ bị bác bỏ}\}}{\max(R, 1)} \le \frac{\alpha E_i}{K}\) đúng trên mọi mẫu thực nghiệm. Cộng trên \(i \in \mathcal{H}_0\) và lấy kỳ vọng (chỉ cần tính tuyến tính của kỳ vọng, KHÔNG cần độc lập hayPRDSvà KHÔNG bị phạt \(\ln K\) nhưBY):\[\operatorname{FDR} = \mathbb{E}\!\left[\frac{\sum_{i \in \mathcal{H}_0}\mathbb{I}\{i\text{ bị bác bỏ}\}}{\max(R, 1)}\right] \le \frac{\alpha}{K}\sum_{i\in\mathcal{H}_0}\mathbb{E}[E_i] \le \frac{\alpha|\mathcal{H}_0|}{K} \le \alpha. \qquad \blacksquare\] SRMe-Process Streaming (Dirichlet–Multinomial): Khi giám sát lưu lượng phân nhánh theo thời gian thực với xác suất kỳ vọng \((p_0, \dots, p_{K-1})\) và siêu tham số tập trung \(\boldsymbol{\alpha}_0 = c\cdot\mathbf{p}\) (\(\alpha_+ = \sum \alpha_{0,k} = c\)), tỷ số hợp lý hỗn hợp:\[E_t^{\text{SRM}} = \frac{\Gamma(\alpha_+)}{\Gamma(\alpha_+ + N_t)}\prod_{k=0}^{K-1}\frac{\Gamma(\alpha_{0,k} + n_{k,t})}{\Gamma(\alpha_{0,k})\,p_k^{n_{k,t}}}\]là mộte-martingale chính xác dưới \(H_0:\boldsymbol{\theta}=\mathbf{p}\) (tính hoàn toàn trong không gianlgamma), kích hoạt báo động ngay khi \(E_t^{\text{SRM}} \ge 1/\alpha_{\text{SRM}}\) mà không bao giờ bị lạm phát nhìn trộm.
2.3 Dự báo Conformal Không phân phối (Conformal Prediction: SCP, CQR, RAPS/SAPS, ACI & Conformal LLM Factuality)#
Vì sao Khoảng Tham số & Softmax Thô Sụp đổ, và Vì sao Tính hoán vị là Đủ#
Khoảng hồi quy tham số \(\hat{y}(x) \pm z_{1-\alpha/2}\hat{\sigma}\) phá sản khi phần dư lệch đuôi hoặc phương sai phụ thuộc đầu vào (bất đẳng phương sai — heteroscedasticity). Trong học sâu, hàm softmax thường xuyên quá tự tin (overconfident, Guo et al., 2017) vì tối ưu cross-entropy đẩy chuẩn logit \(\|\mathbf{z}(x)\| \to \infty\), còn mạng ReLU tuyến tính từng mảnh gán xác suất \(\to 1.0\) cho các điểm ngoài phân phối (OOD, Hein et al., 2019). Các phương pháp hiệu chuẩn hậu kỳ (Temperature Scaling, Platt, Isotonic) chỉ đảm bảo tiệm cận khi phân phối tĩnh và không có bất kỳ đảm bảo mẫu hữu hạn nào.
Dự báo Conformal (Conformal Prediction — CP) bao bọc mọi bộ dự báo hộp đen \(\hat{f}\) để tạo ra đảm bảo độ phủ mẫu hữu hạn, phi phân phối chỉ dưới điều kiện cấu trúc duy nhất là Tính hoán vị (Exchangeability): dãy \((Z_1, \dots, Z_m)\) có tính hoán vị nếu \((Z_{\pi(1)}, \dots, Z_{\pi(m)}) \stackrel{d}{=} (Z_1, \dots, Z_m)\) với mọi hoán vị \(\pi \in S_m\). Mọi dãy i.i.d. đều hoán vị, nhưng tính hoán vị yếu hơn hẳn i.i.d.: phép lấy mẫu không hoàn lại từ tập hữu hạn (chia ngẫu nhiên train/cal/test) hay hỗn hợp Bayes theo định lý de Finetti đều hoán vị dù các mẫu tương quan âm với nhau.
Dự báo Conformal Tách (SCP) — Chứng minh Trọn vẹn 4 Bước & Bẫy Biên#
Chia rời tập dữ liệu thành \(\mathcal{D} = \mathcal{D}_{\text{train}} \sqcup \mathcal{D}_{\text{cal}}\) (\(|\mathcal{D}_{\text{cal}}| = n_{\text{cal}}\)). Huấn luyện \(\hat{f}\) trên \(\mathcal{D}_{\text{train}}\), tính điểm bất tương thích (nonconformity score) \(S_i = s(X_i, Y_i)\) cho \(i=1,\dots,n_{\text{cal}}\) (ví dụ \(s(x, y) = |y - \hat{f}(x)|\)). Với mức sai phủ mục tiêu \(\alpha \in (0, 1)\), đặt chỉ số hạng:
và phát hành tập dự báo \(\widehat{C}(x) := \{y \in \mathcal{Y} : s(x, y) \le \hat{q}_{\text{cal}}\}\).
Định lý 2.2 (Hiệu lực Biên Mẫu Hữu hạn của SCP — Vovk et al., 2005; Lei et al., 2018): Nếu \((X_1, Y_1), \dots, (X_{n_{\text{cal}}}, Y_{n_{\text{cal}}}), (X_{n+1}, Y_{n+1})\) hoán vị có điều kiện trên \(\mathcal{D}_{\text{train}}\), thì:
và nếu không có đồng hạng hầu chắc chắn, cận trên sắc bén cũng đúng: \(1 - \alpha \le \mathbb{P}(Y_{n+1} \in \widehat{C}(X_{n+1})) < 1 - \alpha + \frac{1}{n_{\text{cal}}+1}\).
Chứng minh đầy đủ 4 bước (hợp lệ ngay cả khi có đồng hạng):
- Bước 1 (Biên \(n_{\text{cal}}\) nhỏ khiến \(k = n_{\text{cal}}+1\)): Nếu \((n_{\text{cal}}+1)(1-\alpha) > n_{\text{cal}}\) (tức \(n_{\text{cal}} < \frac{1-\alpha}{\alpha}\), vd. \(\alpha=0.10\) và \(n_{\text{cal}} \le 8\)), thì \(k = n_{\text{cal}}+1 \implies \hat{q}_{\text{cal}} = +\infty \implies \widehat{C}(X_{n+1}) = \mathcal{Y}\), xác suất phủ bằng \(1 \ge 1-\alpha\) (và \(1 < 1 - \alpha + \frac{1}{n_{\text{cal}}+1}\) hiển nhiên đúng).
-
Bước 2 (Bổ đề Tương đương Tất định trên Đa tập Đầy đủ — Đúng cả khi có đồng hạng): Giả sử \(1 \le k \le n_{\text{cal}}\). Xét đa tập không thứ tự gồm cả \(n_{\text{cal}}+1\) điểm số \(\mathcal{S} = \{| S_1, \dots, S_{n_{\text{cal}}}, S_{n+1} |\}\) sắp không giảm thành \(U_1 \le U_2 \le \dots \le U_{n_{\text{cal}}+1}\). Chứng minh tương đương logic:
\[\left\{S_{n+1} \le S_{(k)}\right\} \iff \left\{S_{n+1} \le U_k\right\}.\]- (\(\Rightarrow\) Phản chứng): Nếu \(S_{n+1} > U_k\), thì ít nhất \(k\) phần tử của \(\mathcal{S}\) thỏa \(U_1 \le \dots \le U_k < S_{n+1}\) và không phần tử nào trong đó là \(S_{n+1}\). Do vậy cả \(k\) phần tử này đều nằm trong \(\mathcal{D}_{\text{cal}}\), ép \(S_{(k)} \le U_k < S_{n+1}\).
- (\(\Leftarrow\) Trực tiếp): Nếu \(S_{n+1} \le U_k\), theo định nghĩa \(U_k\), có tối đa \(k-1\) phần tử của \(\mathcal{S}\) nhỏ hơn ngặt \(U_k\). Mọi điểm hiệu chuẩn nhỏ hơn ngặt \(S_{n+1}\) cũng nhỏ hơn ngặt \(U_k\), nên \(\mathcal{D}_{\text{cal}}\) có tối đa \(k-1\) điểm nhỏ hơn ngặt \(S_{n+1}\), buộc \(S_{(k)} \ge S_{n+1}\).
3. Bước 3 (Đối xứng Hạng dưới Tính hoán vị): Điều kiện hóa trên đa tập \(\mathcal{S}\). Vì \((S_1, \dots, S_{n_{\text{cal}}}, S_{n+1})\) hoán vị, xác suất \(S_{n+1}\) rơi vào từng vị trí \(j \in \{1,\dots,n_{\text{cal}}+1\}\) là như nhau bằng \(\frac{1}{n_{\text{cal}}+1}\). Do Bước 2:
\[\mathbb{P}\!\left(Y_{n+1} \in \widehat{C}(X_{n+1}) \mid \mathcal{S}\right) = \mathbb{P}\!\left(S_{n+1} \le U_k \mid \mathcal{S}\right) = \frac{|\{j \in \{1,\dots,n_{\text{cal}}+1\} : U_j \le U_k\}|}{n_{\text{cal}}+1}.\]4. Bước 4 (Cận Dưới & Cận Trên Sắc bén): Luôn có ít nhất \(k\) vị trí (\(j=1,\dots,k\)) thỏa \(U_j \le U_k\), kết hợp \(k \ge (n_{\text{cal}}+1)(1-\alpha)\) và lấy kỳ vọng theo \(\mathcal{S}\) cho \(\mathbb{P}(Y_{n+1}\in\widehat{C}(X_{n+1})) \ge \frac{k}{n_{\text{cal}}+1} \ge 1-\alpha\). Khi không có đồng hạng h.c.c., số vị trí đúng bằng \(k\) và dùng \(\lceil x \rceil < x + 1\) cho cận trên \(1-\alpha + \frac{1}{n_{\text{cal}}+1}\). \(\blacksquare\)
Phản ví dụ Phân vị Ngây thơ (
81.82%Thay vì90%) & Định cỡ \(n_{\text{cal}}\) của Vovk:
Nếu lấy nhầmk_naive = ceil((1 - alpha) * n_cal)(tứcnp.quantile(scores, 1 - alpha)thiếu hiệu chỉnh \((n_{\text{cal}}+1)/n_{\text{cal}}\)) tại \(\alpha = 0.10, n_{\text{cal}} = 10\), ta được \(k_{\text{naive}} = 9\), cho độ phủ chính xác \(\frac{9}{10+1} = \mathbf{81.82\% < 90\%}\)! Hơn nữa, điều kiện hóa trên một tập \(\mathcal{D}_{\text{cal}}\) cố định triển khai trong production, Vovk (2012) chứng minh độ phủ thực tế tuân theo \(R(\mathcal{D}_{\text{cal}}) \sim \operatorname{Beta}(k,\; n_{\text{cal}}+1-k)\) với \(\operatorname{Std}(R) \approx \sqrt{\frac{\alpha(1-\alpha)}{n_{\text{cal}}+2}}\), đòi hỏi \(n_{\text{cal}} \ge 1{,}000\text{–}2{,}000\) để giữ biến động độ phủ dưới \(1\%\).
Bất đẳng phương sai (CQR) & Giới hạn Độ phủ Có điều kiện (Mondrian / RLCP)#
- Hồi quy Phân vị Conformal (
CQR— Romano, Patterson & Candès, NeurIPS 2019,arXiv:1905.03222):SCPchuẩn cho khoảng bề rộng cố định \(2\hat{q}_{\text{cal}}\), vừa thừa thãi ở vùng nhiễu thấp vừa thiếu hụt ở vùng biến động cao.CQRhuấn luyện hai ước lượng phân vị \(\hat{q}_{\alpha/2}(x) \le \hat{q}_{1-\alpha/2}(x)\) bằng hàm mất mát pinball \(\rho_{\tau_q}(y, \hat{q}) = \max(\tau_q(y-\hat{q}), (\tau_q-1)(y-\hat{q}))\) (ép không cắt chéo), tính điểm có dấu (signed nonconformity score) trên \(\mathcal{D}_{\text{cal}}\):\[S_i = \max\!\left(\hat{q}_{\alpha/2}(X_i) - Y_i,\;\; Y_i - \hat{q}_{1-\alpha/2}(X_i)\right),\]rồi xuất khoảng thích nghi \(\widehat{C}_{\text{CQR}}(x) = [\hat{q}_{\alpha/2}(x) - \hat{q}_{\text{cal}},\; \hat{q}_{1-\alpha/2}(x) + \hat{q}_{\text{cal}}]\) (nếu mô hình phân vị gốc quá rộng khiến \(\hat{q}_{\text{cal}} < 0\),CQRtự động thu hẹp khoảng!). Biến thểCQR-rchuẩn hóa \(S_i\) cho độ trải \(w(X_i) = \hat{q}_{1-\alpha/2}(X_i) - \hat{q}_{\alpha/2}(X_i) + \epsilon\) khi thang nhiễu chênh lệch nhiều bậc độ lớn. - Định lý Bất khả thi Độ phủ Có điều kiện (Vovk, 2012; Barber, Candès, Ramdas & Tibshirani, 2021,
arXiv:1903.04684): Với \(\mathcal{X} = \mathbb{R}^d\) liên tục (không nguyên tử), mọi thủ tục phi phân phối mẫu hữu hạn đạt \(\mathbb{P}_P(Y_{n+1} \in \widehat{C}(X_{n+1}) \mid X_{n+1}=x) \ge 1-\alpha\) hầu khắp \(x\) trên mọi \(P\) bắt buộc có bề rộng kỳ vọng vô hạn \(\mathbb{E}_P[\operatorname{Leb}(\widehat{C}(X_{n+1}))] = \infty\). Để tiến gần độ phủ có điều kiện trong thực tiễn 2023–2026: (1) Mondrian / Clustered CP (Ding et al., NeurIPS 2023) hiệu chuẩn riêng \(\hat{q}^{(g)}\) theo nhóm hoặc cụm lớp hiếm; (2)RLCP— Randomly Localized CP (Hore & Barber, JRSS-B 2024,arXiv:2310.07850) nhiễu hóa điểm kiểm tra \(\tilde{X}_{n+1} \sim H(X_{n+1}, \cdot)\) và gán trọng số hạt nhân bảo toàn hiệu lực biên chính xác kèm độ phủ cục bộ; và (3) Shift-Class Conditional CP (Gibbs, Cherian & Candès, JRSS-B 2024) kiểm soát sai phủ trên lớp hàm dịch chuyển \(\mathcal{F}\).
Tập Dự báo Phân loại (LAC vs. APS vs. RAPS vs. SAPS)#
Sắp xếp xác suất dự báo \(\hat{p}_{\pi_x(1)}(x) \ge \dots \ge \hat{p}_{\pi_x(K)}(x)\), với hạng \(k_y\) sao cho \(\pi_x(k_y)=y\) và tổng xác suất chặt \(\rho_x(y) := \sum_{j=1}^{k_y-1}\hat{p}_{\pi_x(j)}(x)\):
| Phương pháp | Điểm Bất tương thích \(s(x, y, U)\) (\(U \sim \operatorname{Uniform}(0,1)\)) | Đặc tính & Cạm bẫy Sản xuất |
|---|---|---|
LAC (Sadinle et al., JASA 2019) |
\(1 - \hat{p}_y(x)\) | Tối thiểu kích thước tập kỳ vọng, nhưng sinh tập rỗng \(\emptyset\) khi \(\max_y \hat{p}_y(x) < 1-\hat{q}\) và thiếu phủ ở mẫu khó. |
APS (Romano et al., NeurIPS 2020) |
\(\rho_x(y) + U\,\hat{p}_y(x)\) | Thích nghi tốt theo độ mơ hồ đầu vào, nhưng đuôi xác suất nhiễu ở bài toán nhiều lớp phình kích thước tập quá lớn. |
RAPS (Angelopoulos et al., ICLR 2021) |
\(\rho_x(y) + U\,\hat{p}_y(x) + \lambda(k_y - k_{\text{reg}})_+\) | Phạt tuyến tính hạng \(> k_{\text{reg}}\), thu gọn mạnh kích thước tập trong khi giữ nguyên bảo đảm \(1-\alpha\). |
SAPS (Huang et al., ICML 2024, arXiv:2310.06430) |
\(\begin{cases} U\,\hat{p}_{\pi_x(1)}(x) & k_y=1 \\ \hat{p}_{\pi_x(1)}(x) + \lambda(k_y-2+U) & k_y>1 \end{cases}\) | Loại bỏ hoàn toàn đuôi xác suất nhiễu \(\hat{p}_{\pi_x(2..K)}\), chỉ giữ độ tin cậy top-1 và hạng \(k_y\), vượt trội RAPS trên mạng sâu lệch chuẩn. |
(Lưu ý: Mọi siêu tham số \(k_{\text{reg}}, \lambda\) phải tinh chỉnh trên tập riêng tách biệt khỏi \(\mathcal{D}_{\text{cal}}\); nếu hệ thống cấm tập rỗng, bật allow_zero_sets=False để luôn giữ lại \(\pi_x(1)\) giúp bảo toàn độ phủ \(\ge 1-\alpha\).)
Tiền tuyến 2024–2026: Luồng Trôi Không Hoán vị (ACI/DtACI/NexCP), CRC & Conformal Factuality cho LLM#
-
Suy luận Conformal Thích nghi (
ACI— Gibbs & Candès, NeurIPS 2021) & Chứng minh Hối tiếc \(O(1/T)\) Không cần Hoán vị:
Khi luồng trực tuyến mất tính hoán vị do trôi khái niệm (concept drift),ACIxuất tập \(\widehat{C}_t(X_t)\) theo ngưỡng động \(\alpha_t\) (quy ước \(\widehat{C}_t = \mathcal{Y}\) nếu \(\alpha_t \le 0\) và \(\widehat{C}_t = \emptyset\) nếu \(\alpha_t \ge 1\)), quan sát lỗi \(\operatorname{err}_t := \mathbb{I}\{Y_t \notin \widehat{C}_t(X_t)\}\) và cập nhật:\[\alpha_{t+1} = \alpha_t + \gamma(\alpha - \operatorname{err}_t), \qquad \gamma > 0.\]Chứng minh Hối tiếc \(O(1/T)\) Hoàn chỉnh (đúng cho mọi chuỗi đối kháng bất kỳ): Bắt đầu từ \(\alpha_1 \in (0, 1)\), nếu \(\alpha_t \le 0\) thì \(\operatorname{err}_t = 0 \implies \alpha_{t+1} = \alpha_t + \gamma\alpha > \alpha_t\); nếu \(\alpha_t \ge 1\) thì \(\operatorname{err}_t = 1 \implies \alpha_{t+1} = \alpha_t - \gamma(1-\alpha) < \alpha_t\). Quy nạp suy ra \(\alpha_t \in [-\gamma(1-\alpha),\; 1+\gamma\alpha]\) với mọi \(t \ge 1\), nên \(|\alpha_{T+1}-\alpha_1| \le 1+\gamma\). Cộng dồn (telescoping) từ \(t=1\) tới \(T\):
\[\alpha_{T+1} - \alpha_1 = \gamma\sum_{t=1}^T (\alpha - \operatorname{err}_t) \implies \left|\frac{1}{T}\sum_{t=1}^T \operatorname{err}_t - \alpha\right| = \frac{|\alpha_1 - \alpha_{T+1}|}{\gamma T} \le \frac{1 + \gamma}{\gamma T} = \mathcal{O}\!\left(\frac{1}{T}\right). \qquad \blacksquare\]DtACI(Gibbs & Candès, JMLR 2024,arXiv:2208.08401): Chạy song song \(K\) chuyên giaACItrên lưới \(\{\gamma_1,\dots,\gamma_K\}\) và kết hợp bằng trọng số hàm mũ trên hàm mất mát pinball, đạt hối tiếc cục bộ \(O(\sqrt{\ln K / |I|})\) mà không cần chỉnh tay \(\gamma\).NexCP(Barber et al., Annals of Statistics 2023,arXiv:2202.13415): Gán trọng số suy giảm \(w_i = \rho_{\text{decay}}^{n+1-i}\) cho điểm quá khứ, cho cận độ phủ chính xác \(1 - \alpha - \sum_{i=1}^n \tilde{w}_i d_{\text{TV}}(S, S^{(i)})\). 2. Kiểm soát Rủi ro Conformal (CRC— Angelopoulos et al., ICLR 2024 Spotlight,arXiv:2208.02814): Mở rộng từ lỗi nhị phân 0-1 sang bất kỳ hàm mất mát bị chặn đơn điệu giảm \(\ell(\widehat{C}_\lambda(x), y) \in [0, B]\) (vd.FNRphân đoạn ảnh, tỷ lệ ảo giác RAG) bằng cách chọn \(\hat{\lambda} := \inf\{\lambda : \frac{n}{n+1}\hat{R}_n(\lambda) + \frac{B}{n+1} \le \alpha\}\), đảm bảo \(\mathbb{E}[\ell_{n+1}(\hat{\lambda})] \le \alpha\) trên mẫu hữu hạn. 3. Conformal LLM,Conformal Factuality& Hệ sinh thái Python 2024–2026:- Conformal Language Modeling (Quach et al., ICLR 2024) dùng
CRCchọn quy tắc dừng lấy mẫu để chứa ít nhất một câu trả lời đúng với xác suất \(\ge 1-\alpha\). - Conformal Factuality (Mohri & Hashimoto, ICML 2024,
arXiv:2402.10978; Cherian, Gibbs & Candès, NeurIPS 2024,arXiv:2406.09714) tách bản nháp LLM/RAG thành các mệnh đề nguyên tử (atomic sub-claims) \(\{c_{i,1},\dots,c_{i,m_i}\}\) có điểm tin cậy \(r_{i,j}\), hiệu chuẩn ngưỡng \(\hat{\tau}_{\text{fact}}\) trên điểm sai cực đại \(S_i = \max(\{r_{i,j} : y_{i,j}=0\} \cup \{-0.01\})\) và cắt tỉa mọi mệnh đề \(\le \hat{\tau}_{\text{fact}}\) để đảm bảo không chứa mệnh đề bịa đặt với xác suất \(\ge 1-\alpha\). Kết hợp cùng Conformal Abstention (arXiv:2405.01563) và Conformal Alignment (NeurIPS 2024) để chuyển ca mơ hồ (\(|\widehat{C}(x)| > 1\)) sang con người hoặc mô hình biên giới (frontier model). Trong công nghiệp Python, lớp bọc này chuẩn hóa quaMAPIEv1.x (.fit()/.conformalize(),CQR,ACI,CRC) vàTorchCP(arXiv:2402.12683, GPU-batchedLAC/APS/RAPS/SAPS).
2.4 Tính toán Số học Đặc biệt bằng Python Thuần & NumPy (Pure-Stdlib Special Functions & Zero-ABI Contract)#
Trong các container suy luận cạnh nhẹ hoặc môi trường NumPy 2.x nơi gói scipy/sklearn cũ sụp đổ vì xung đột C-ABI (_ARRAY_API not found), toàn bộ hàm phân phối kiểm định thống kê vẫn được tính chính xác tới \(\le 10^{-11}\text{–}10^{-15}\) chỉ bằng Python chuẩn math / decimal + NumPy:
math.erfccho Chuẩn tắc (norm_cdf,norm_sf_two_sided): Tính \(\Phi(x) = \frac{1}{2}\operatorname{erfc}(-x/\sqrt{2})\) và xác suất đuôi hai phía \(2(1 - \Phi(|z|)) = \operatorname{erfc}(|z|/\sqrt{2})\) trực tiếp qua hàm lỗi bùmath.erfc, triệt tiêu hoàn toàn lỗi mất chữ số từ phép trừ \(1 - \operatorname{erf}(z)\) xuống tận ngưỡng subnormalfloat64(1e-308).- Xấp xỉ Minimax Peter Acklam + 1 Bước Halley (
norm_ppf): Sử dụng đa thức hữu tỷ minimax của Peter Acklam (sai số tương đối \(\sim 1.15 \times 10^{-9}\)) kết hợp đối xứng đuôi dưới (\(p > 0.5 \mapsto -\Phi^{-1}(1-p)\)) và một bước tinh chỉnh bậc ba của phương pháp Halley để đạt độ chính xác máy~1e-15xuống tới \(z = -30\). - Phân số Liên tục Lentz Sửa đổi (
gammaincc&betainc/t_sf_two_sided):- Hàm Gamma không đầy đủ trên chuẩn hóa \(Q(a, x)\) cho kiểm định \(\chi^2_\nu\) (\(a = \nu/2, x = \chi^2/2\)) dùng nghiệm đóng cho \(\nu=1\) (\(\operatorname{erfc}(\sqrt{x})\)) và \(\nu=2\) (\(e^{-x}\)), chuỗi lũy thừa khi \(x < a + 1\), và phân số liên tục Lentz sửa đổi trực tiếp trên \(Q(a, x)\) khi \(x \ge a + 1\) (tránh mất chữ số \(1 - P(a, x)\)), đồng thời kẹp log-tiền tố tại
-745.0chống trànexp. - Hàm Beta không đầy đủ chuẩn hóa \(I_x(a, b)\) cho kiểm định Welch \(t_\nu\) (\(p = I_{\nu/(\nu+t^2)}(\nu/2, 1/2)\)) áp dụng phản xạ đối xứng \(I_x(a, b) = 1 - I_{1-x}(b, a)\) khi \(x \ge \frac{a+1}{a+b+2}\) để phân số liên tục Lentz hội tụ nhanh trong \(\le 30\) vòng lặp (và chuyển mượt về
norm_sf_two_sidedkhi \(\nu > 10^7\)).
- Hàm Gamma không đầy đủ trên chuẩn hóa \(Q(a, x)\) cho kiểm định \(\chi^2_\nu\) (\(a = \nu/2, x = \chi^2/2\)) dùng nghiệm đóng cho \(\nu=1\) (\(\operatorname{erfc}(\sqrt{x})\)) và \(\nu=2\) (\(e^{-x}\)), chuỗi lũy thừa khi \(x < a + 1\), và phân số liên tục Lentz sửa đổi trực tiếp trên \(Q(a, x)\) khi \(x \ge a + 1\) (tránh mất chữ số \(1 - P(a, x)\)), đồng thời kẹp log-tiền tố tại
- Tính Hạng Conformal Chính xác bằng
Decimal: Phép nhân dấu chấm độngfloat64khiến biểu thức150 * (1.0 - 0.18)cho ra123.00000000000001, làmmath.ceil(...)nhảy sai lên124thay vì123! Tính bằngint(math.ceil(Decimal(n + 1) * (Decimal("1") - Decimal(str(alpha)))))loại bỏ hoàn toàn lỗi làm tròn nhị phân ở mọi kích thước mẫu.
Trụ cột 3 — Công nghệ 2026, Case Studies Công nghiệp & Cẩm nang Phòng vệ Thống kê (Named Industry Case Studies, Failure Modes, Decision Playbooks & Defensive NumPy Code)#
3.1 Năm Nghiên cứu Tình huống Thực tế Từ Hệ thống Production (5 Named Industry Case Studies)#
Case 1 — Netflix Experimentation Platform & Spotify Confidence: Giám sát Liên tục & Bài toán Nhìn trộm#
- Bối cảnh & Thông số Production: Netflix thử nghiệm thuật toán tiền nạp bộ đệm video
ABRqua đợt phát hành tín hiệu canary (canary release) trên \(100{,}000\) lượt phát mỗi nhánh trong 48 giờ, theo dõiplay_delay(thời gian từ khi bấm Phát đến khung hình đầu tiên; mức nền \(\mu_C = 420\text{ ms}\), \(\sigma = 240\text{ ms}\)) cùng các tiến trình đếm sự cố (playback_failures,rebuffer_events). - Sụp đổ Nhìn trộm & Giải pháp Hai Làn (
mSPRTvs.O'Brien–Fleming): Dưới giả thuyết không thực (\(\Delta=0\), ngưỡng danh nghĩa \(|Z_n| > 1.96\) ở \(\alpha=0.05\)), mô phỏng \(5{,}000\) quỹ đạo cho thấyFPRbùng phát từ5.54%(1 lần nhìn cố định) lên26.02%(20 lần nhìn),44.98%(200 lần nhìn) và54.66%khi theo dõi liên tục từng sự kiện.- Làn Canary Thời gian thực (
mSPRTtrên Flink/Kafka): Netflix và các nền tảng canary chạymSPRTe-process (kết hợp tiến trình đếm Dirichlet–Multinomial anytime-valid trong Netflix Part 2, Lindon et al., 2024), giữFPRdưới kiểm soát (4.48% <= 5%) cho phép dừng khẩn cấp ngay khiplay_delaytăng bất thường \(+18\text{ ms}\), đổi lại bề rộng khoảng tin cậy \(\mathcal{O}(\sqrt{\ln n / n})\) rộng hơn \(\sim 1.5\times\text{–}2\times\) ở \(N\) cố định. - Làn Sản phẩm Định kỳ (
O'Brien–FlemingGSD tại SpotifyConfidence): Khi biết trước \(N_{\max}\) và lịch kiểm tra kho dữ liệu hàng ngày \(t_k \in \{0.25, 0.50, 0.75, 1.0\}\), đường biên chi tiêu alpha Lan–DeMets đặt ngưỡng \(z_1 \approx 4.05\) ở \(25\%\) lưu lượng và giữ ngưỡng cuối \(z_4 \approx 2.02\) gần sát \(1.96\) — bảo toàn tối đa độ mạnh cho các cải tiến tinh tế (\(+0.3\%\) giữ chân) và chống bẫy "Peeking Problem 2.0" từ độ trễ trưởng thành hành vi người dùng (Ankargren et al., 2023).
- Làn Canary Thời gian thực (
Case 2 — Booking.com, Microsoft ExP & DoorDash CUPAC: Phá án SRM 0.35% & Giảm phương sai Khớp chéo#
- Phần A — Cái bẫy
SRM50.35% / 49.65%Vô hình: Một thử nghiệm thanh toán nhắm tỷ lệ chia50/50trên \(N = 200{,}000\) khách hàng ghi nhận100,700Đối chứng (50.35%) vs.99,300Thử nghiệm (49.65%), kèm mức tăng chuyển đổi hấp dẫn \(+1.8\%\) (\(p = 0.004\)). Kiểm địnhsrm_chisq_guardphát hiện ngay:\[\chi^2 = \frac{(100{,}700 - 100{,}000)^2}{100{,}000} + \frac{(99{,}300 - 100{,}000)^2}{100{,}000} = \mathbf{9.80} \implies p = \operatorname{erfc}\!\left(\sqrt{\frac{9.80}{2}}\right) = \mathbf{0.001745 < 0.002}.\]Đúng1,400người dùng Thử nghiệm đã biến mất (ví dụ gói JS mới gây trễ \(+180\text{ ms}\) làm rớt nhóm thiết bị yếu trước khi gửi tín hiệu phơi nhiễm). Loại bỏ \(1{,}400\) phiên thoát trang khỏi mẫu số tự động đẩy giả tỷ lệ chuyển đổi từ \(4.0\%\) lên \(4{,}000 / 99{,}300 = 4.028\%\). Cả Booking.com và Microsoft ExP ghi nhận6%–10%toàn bộ thử nghiệm production thất bạiSRM(Fabijan et al., KDD 2019). Quy tắc sắt: cách ly ngay lập tức, phân cắt \(\chi^2\) theobrowser/OS/app_version, và tuyệt đối không tái trọng số hậu kỳ. - Phần B — Tăng tốc 30%–60% bằng
CUPAC&MLRATEKhớp chéo: Trên dữ liệu GMV thưa (90% phiên bằng$0), DoorDashCUPACvà MetaMLRATEhuấn luyện mô hình phi tuyến ngoài nếp \(\hat{f}^{(-k)}(\mathbf{Z}_{\text{pre}})\) từ lịch sử 7–28 ngày trước phân nhánh để rút ngắn thời gian chạy thử nghiệm 30%–60% (DoorDash giảm \(\sim 40\%\) thời lượng switchback). Tại \(N=400\) với \(d=100\) chiều nhiễu, khớp chéo 5-nếp triệt tiêu hoàn toàn ảo giác giảm phương sai28.6%của khớp trong mẫu xuống còn0.6%, đồng thời đạt88.9%VR (9.0xtăng tốc) khi nhúng mang tín hiệu thực.
Case 3 — Uber & Lyft: Tỷ lệ Cụm 2.59x & Cầu nối Giao thoa Switchback sang Chương 05#
- Cú sập Tỷ lệ Cấp Phiên: Thử nghiệm UX đón xe trên \(N_C = N_T = 20{,}000\) hành khách tạo ra \(\sim 120{,}000\) phiên/nhánh (phân bố luật lũy thừa Pareto: người dùng thường đi \(1\text{–}2\) chuyến, khách đi làm đi \(30\text{–}80\) chuyến) đo chỉ số
Cancel Rate = Total Cancels / Total Sessions. Tính sai số chuẩn nhị thức ở cấp phiên bỏ qua tương quan nội cụm \(\rho_{\text{ICC}} > 0\) và độ phân tán cỡ cụm \(X_i\), tạo hiệu ứng thiết kế Kish \(\text{DEFF} \approx 1 + \rho_{\text{ICC}}(\mathbb{E}[X^2]/\mathbb{E}[X] - 1) \in [4, 25]\) (đánh giá thấp SE từ \(2\times\) tới \(5\times\)). Trong mô phỏng cụm người dùng (\(N=2{,}000\)/nhánh), SE ngây thơ báo0.00312trong khi SE cụm thực bằng0.00806(2.59xlớn hơn!), đẩyFPRthực vượt35%! Khắc phục chuẩn bằng gộp \((Y_i, X_i)\) tại đúng đơn vị ngẫu nhiên hóa và dùng thặng dư tuyến tính hóa \(u_i = (Y_i - \hat{R}X_i)/\bar{X}\) kết hợp Welch DF (và kiểm tra Fieller khi \(\operatorname{CV}(\bar{X}) > 0.1\)). - Vi phạm
SUTVA& Cầu nối Switchback (Chương 05): Trong thị trường hai phía (two-sided marketplace), tài xế là nguồn cung dùng chung hữu hạn. Giảm giá cho nhóm Thử nghiệm có thể cướp tài xế từ nhóm Đối chứng (cannibalization), thổi phồng hiệu ứng giả tới \(2\times\) dưới thử nghiệm ngẫu nhiên theo người dùng! Uber và Lyft giải quyết bằng Thiết kế Switchback Theo Không-Thời gian (Geo-Temporal Switchback, Bojinov, Simchi-Levi & Zhao, Management Science 2023) kèm khoảng đệm rửa trôi (washout buffer) để triệt tiêu hiệu ứng tràn theo thời gian (temporal carryover) — nội dung được phân tích sâu ở Chương 05 (T1-P1-U05).
Case 4 — Phân loại Lâm sàng, Gian lận & Enterprise RAG (CQR, RAPS, ACI, Conformal Factuality)#
- Một bộ hồi quy phân vị
XGBoostdự báo thời gian nằm viện ICU hoặc ETA giao hàng thường chỉ đạt78%–84%độ phủ thực nghiệm ngoài mẫu thay vì mức cam kết \(90\%\), trong khi khoảngSCPbề rộng cố định quá rộng vào ngày thường và thiếu hụt vào giờ cao điểm bão lũ. Bọc bằngCQR(chi phí< 0.5 mstại suy luận nhờ tra cứu ngưỡng tĩnh) giữ trọn \(\ge 90\%\) độ phủ đồng thời trên cả vùng nhiễu thấp lẫn nhiễu cao. - Với phân loại rủi ro đa lớp / gian lận,
RAPS/SAPStự động chuyển ca mơ hồ (\(|\widehat{C}(x)| > 1\)) cho chuyên viên kiểm duyệt;ACItự điều chỉnh \(\alpha_t\) khi bùng phát dịch bệnh hoặc làn sóng gian lận mới; còn trong hệ thống Enterprise RAG, Conformal Factuality tách câu trả lời thành mệnh đề nguyên tử và cắt tỉa dưới ngưỡng \(\hat{\tau}_{\text{fact}}\) để cam kết xác suất không chứa thông tin bịa đặt \(\ge 1-\alpha\).
Case 5 — Cloudflare & Datadog: Phác thảo DDSketch, Đảo dấu Độ trễ & Bẫy Bootstrap Chuỗi Bursty#
- Phác thảo Gộp
DDSketch(VLDB 2019): Trung bình cộng các giá trị \(p_{99}\) từ từng máy chủ/POP là sai hoàn toàn về toán học. Datadog và Cloudflare dùng cấu trúc giỏ logarit có thể gộp (mergeable sketch)DDSketchbảo toàn sai số tương đối \(|\hat{q}_p - q_p| \le \varepsilon |q_p|\) (vd. \(\varepsilon = 1\%\)) khi tổng hợp toàn cầu. - Đảo dấu LogNormal (
-31.4%biến thành+10.1%): Trong thử nghiệm tối ưu hóa định tuyến cạnh mạng giữa Control \(\operatorname{LogNormal}(2.0, 1.2)\) và Treatment \(\operatorname{LogNormal}(2.1, 0.7)\) (\(n=50{,}000\)/nhánh), độ trễ trung bình số học thực tế giảm mạnh từ15.11 msxuống10.36 ms(-31.4%), nhưng biến đổi \(\ln(Y)\) rồi lấy \(\exp(\bar{Z})\) lại báo trung bình hình học tăng từ7.37 mslên8.11 ms(+10.1%thụt lùi giả tạo!). Khắc phục bằng bôi trơn Duan hoặc Gamma GLM liên kết log. - Bẫy Bootstrap Chuỗi Tự tương quan & Đuôi Cực trị: Nhiễu nghẽn mạng và GC pause luôn xảy ra theo chùm (
AR(1)với \(\phi = 0.85\)). Trên chuỗi \(n=4{,}000\) yêu cầu, SE thực của \(p_{95}\) bằng1.295 ms, nhưng bootstrapi.i.d.ngây thơ chỉ ước lượng ra0.595 ms(đánh giá thấp2.18x), liên tục báo giả tụt SLO! Phải chuyển sang Moving Block Bootstrap (nâng SE lên0.923 ms) cho \(p_{90}\text{–}p_{95}\), và chuyển sang \(m\)-out-of-\(n\) subsampling hoặc Lý thuyết Giá trị Cực trị (EVT/ GPD Peaks-Over-Threshold) cho \(p_{99.9}\) nơi chỉ có vài điểm dữ liệu định nghĩa đuôi.
3.2 Sáu Chế độ Lỗi Thống kê Kinh điển & Chẩn đoán Pháp y (Six Production Statistical Failure Modes)#
| Chế độ Lỗi | Triệu chứng Quan sát | Nguyên nhân Gốc rễ Toán học | Tín hiệu Phát hiện | Biện pháp Khắc phục Chuẩn xác |
|---|---|---|---|---|
1. Nhìn trộm Liên tục (Peeking / Optional Stopping) |
Dashboard xanh (p < 0.05) vào Ngày 2–3, nhưng kết quả phẳng lặng sau phát hành (25%–50% tính năng thắng bị hụt hơi). |
Quá trình chuẩn hóa tuân theo LIL \(\limsup \lvert Z_n \rvert / \sqrt{2\ln\ln n} = 1\), đẩy xác suất vượt ngưỡng cố định \(1.96\) lên 54.7% -> 100%. |
Cỡ mẫu dừng tương quan với các lần tụt \(p\)-value; thời gian kết thúc tụ quanh \(p \approx 0.045\). | Khóa lịch O'Brien–Fleming cố định \(N_{\max}\), hoặc thay hoàn toàn \(p\)-value tĩnh bằng mSPRT / e-process (Ville). |
2. Bỏ qua SRM & Mất dữ liệu Dị biệt |
Chia 50/50 nhưng đếm được 50.35% / 49.65% kèm lift phi thực tế ở nhánh ít người hơn. |
Ngẫu nhiên hóa chỉ đúng trên tập được gán; mất tín hiệu lệch nhánh tạo nút va chạm \(W \to O \leftarrow U\) (MNAR). |
Cổng srm_chisq_guard báo \(p < 0.001\) tập trung ở browser/OS/app_version cụ thể. |
Cách ly ngay (Quarantine), chia lát kỹ thuật tìm lỗi beacon, ghi log phơi nhiễm phía server-side; cấm tái trọng số hậu kỳ. |
3. Rò rỉ Hiệp phương sai Hậu thử nghiệm trong CUPED/CUPAC |
Giảm phương sai ảo 70%+ nhưng làm méo hoặc triệt tiêu hoàn toàn hiệu ứng điều trị thực. |
Vi phạm \(X(1)=X(0)\) khiến \(-\theta(X_T-X_C)\) trừ mất hiệu ứng trung gian \(-\theta\mathbb{E}[X(1)-X(0)]\) và mở collider. | Kiểm tra cân bằng tiền thử nghiệm thấy \(\lvert t \rvert > 3\) hoặc \(\lvert\text{SMD}\rvert > 0.02\) trên biến \(X\). | Chốt điểm thời gian \(t_{\text{feat}} \le t_{\text{assign}} - \Delta_{\text{buf}}\), kiểm định tự động assert abs(smd) < 0.02, và bắt buộc khớp chéo \(K\)-nếp. |
| 4. Lệch Đơn vị Ngẫu nhiên hóa vs. Đơn vị Phân tích | p < 1e-6 ở cấp click/phiên nhưng doanh thu/giữ chân cấp người dùng đứng yên. |
Tương quan nội cụm \(\rho_{\text{ICC}} > 0\) và cỡ cụm lệch tạo \(\text{DEFF} \in [4, 25]\), ép SE giả nhỏ đi \(2\times\text{–}5\times\). | \(\text{SE}_{\text{cluster}} / \text{SE}_{\text{naive}} > 1.3\times\); biểu đồ QQ các phép thử A/A cong lồi về phía \(0\). | Gộp \((Y_i, X_i)\) tại đúng đơn vị ngẫu nhiên hóa, dùng Clustered Delta Method (delta_method_ratio_test) hoặc Cluster Bootstrap + A/A định kỳ. |
| 5. Sai-một-bậc Conformal + Trôi Chuỗi Không Hoán vị | Độ phủ thực tế chỉ đạt 75%–82% thay vì 90% hoặc lỗi im lặng khi \(n_{\text{cal}} \le 8\). |
Thiếu hiệu chỉnh \((n_{\text{cal}}+1)\), lỗi làm tròn float64 ceil, hoặc phân phối trôi khỏi tính hoán vị / lệch nhóm phụ. |
Tỷ lệ sai phủ cửa sổ trượt \(>\alpha + 2\sqrt{\alpha(1-\alpha)/W}\); chênh lệch độ phủ giữa các nhóm \(>5\%\). | Tính k_rank bằng Decimal có cận dự phòng \(+\infty\); dùng Mondrian/RLCP theo nhóm và ACI/DtACI cho luồng trôi. |
6. Lời nguyền Người thắng & Câu cá Chỉ số (Metric Fishing) |
Chọn nhánh/chỉ số đẹp nhất trong \(6 \times 15 = 90\) kiểm định (\(+4.2\%, p=0.018\)), kiểm chứng lại chỉ còn \(+0.4\%\). | Bùng nổ FWER \(1-(1-0.05)^{90} = 99.0\%\) cộng thiên lệch chọn lọc \(\mathbb{E}[\hat{\Delta}_{(1)}\mid\text{chọn}] > \Delta_{(1)}\). |
Các phép thử xác nhận hậu kỳ co rút \(< 30\%\) mức lift báo cáo ban đầu. | Đăng ký trước 1 OEC Chính + Guardrails; kiểm soát bằng BH-FDR / e-BH và co rút Bayes thực nghiệm / thử nghiệm giữ lại (holdout). |
3.3 Cẩm nang Quyết định & Kiến trúc Cổng Kiểm định Tự động (Decision Playbooks, Gatekeeper Architecture & Checklist)#
Cẩm nang 1: Ma trận Chọn Kiểm định Giả thuyết & Bộ Ước lượng A/B#
| Tình huống & Chế độ Dữ liệu | Đơn vị Ngẫu nhiên hóa vs. Phân tích | Hình dạng Đuôi / Phân phối | Chế độ Giám sát & Đa kiểm định | Kiểm định / Bộ ước lượng Khuyến nghị | Hàng rào & Cạm bẫy Bắt buộc Kiểm tra |
|---|---|---|---|---|---|
| Chuyển đổi Chuẩn / Trung bình Nhị phân (\(N \ge 5{,}000\)/nhánh) | Ngẫu nhiên người dùng, 1 mẫu/người | Bernoulli (\(\mu \in [0.01, 0.99]\)) | Chân trời cố định (1 lần nhìn \(N_{\max}\)) | Welch \(t\)-test + Khớp chéo CUPED/MLRATE |
Chạy cổng SRM (\(\alpha_{\text{SRM}}=0.001\)) và kiểm cân bằng hiệp phương sai (SMD < 0.02) trước. |
Biến cố Hiếm (\(N\hat{p} < 10\), vd. lỗi 0.05%) |
Ngẫu nhiên người dùng | Quá nhiều số \(0\) / Poisson | Cố định hoặc canary | Fisher Exact / Mid-\(p\) hoặc e-process Dirichlet |
Xấp xỉ chuẩn \(z\) sụp đổ khi \(N\hat{p}<10\); dùng khoảng Wilson Score thay Wald. |
Chỉ số Tỷ lệ (CTR, Cancel Rate, GMV/Hour) |
Cụm người dùng / phiên tương quan | Tương quan nội cụm + lệch phải | Cố định hoặc GSD | Clustered Delta Method (delta_method_ratio_test) + Welch DF |
Cấm dùng SE cấp phiên; kiểm \(\operatorname{CV}(\bar{X}) > 0.1\) để bật khoảng Fieller. |
Cảnh báo Canary Liên tục (play_delay, 5xx) |
Luồng sự kiện hoặc người dùng | Liên tục hoặc đếm | Nhìn trộm liên tục / dừng sớm | mSPRT / Dãy Tin cậy e-process (msprt_confidence_sequence) |
Chọn \(\tau_{\text{mix}} \approx \text{MDE}/2\); cấm dùng \(p\)-value tĩnh trên dashboard trực tiếp. |
| Thử nghiệm Sản phẩm Theo lịch (biết \(N_{\max}\)) | Người dùng hoặc vùng địa lý | Bất kỳ (với CLT hoặc MLRATE) |
\(K\) lần kiểm tra định kỳ | Nhóm Tuần tự (O'Brien–Fleming \(\alpha\)-spending) |
Khóa lịch nhìn trước khi chạy; kiểm soát độ trễ trưởng thành hành vi ("Peeking 2.0"). |
Độ trễ / Doanh thu Lệch Đuôi Nặng (p95/p99, AOV) |
Yêu cầu / Chuỗi thời gian | Đuôi phải nặng + tự tương quan (\(\phi>0\)) | Cố định hoặc cửa sổ SLO | Gamma GLM (log-link), Duan Smearing, Block Bootstrap, m-out-of-n/EVT |
Cấm lấy \(\exp(\overline{\ln Y})\) làm trung bình số học; cấm bootstrap i.i.d. trên chuỗi có chùm. |
| Đa nhánh (\(K > 2\)) / Đa chỉ số (\(m\) KPIs) | Người dùng hoặc cụm | Tương quan tùy ý giữa các KPI | Cố định hoặc tuần tự | BH-FDR (cố định) hoặc e-BH (phụ thuộc tùy ý & tuần tự) |
Đăng ký trước 1 OEC chính; dùng co rút Bayes thực nghiệm chống Winner's Curse. |
| Giao thoa Thị trường Hai phía (dùng chung tài xế/kho) | Khối không-thời gian Switchback | Tràn hiệu ứng theo thời gian (carryover) | Switchback cố định | Switchback Clustered Delta / Randomization Inference + đệm rửa trôi | Xử lý độ trễ tràn \(m\) và kết nối mô hình nhân quả tại Chương 05. |
Cẩm nang 2: Ma trận Chọn Phương pháp Định lượng Bất định (UQ)#
Phương pháp UQ |
Giả thiết Cấu trúc / Phân phối | Bảo đảm Độ phủ Mẫu Hữu hạn? | Thích nghi Bất đẳng phương sai? | Chi phí Tính toán Suy luận | Vùng Sử dụng Tối ưu & Cảnh báo |
|---|---|---|---|---|---|
| Chuẩn Tham số / Wald / Delta SE (\(\hat{\mu} \pm z\cdot\text{SE}\)) | CLT tiệm cận (\(n \gg 30\), phương sai hữu hạn) | Không (chỉ tiệm cận) | Không (khoảng cho trung bình ước lượng) | \(O(1)\) dạng đóng | Khoảng tin cậy tác động A/B trên trung bình & tỷ lệ. Sụp đổ khi \(n\) nhỏ hoặc đuôi siêu nặng. |
Bootstrap (BCa / Cluster / Block) |
Đơn vị / cụm / khối có tính hoán vị | Không (tiệm cận \(O(n^{-1/2})\) hoặc \(O(n^{-1})\)) | Có (qua điều kiện / phần dư) | Cao ngoại tuyến (\(B \approx 1{,}000\text{–}5{,}000\)) | Khoảng tin cậy ngoại tuyến cho trung vị, \(p_{90}\text{–}p_{95}\), tỷ lệ phức tạp. Gãy trên \(\max X_i\) và \(p_{99.9}\). |
| Hậu nghiệm Bayes Liên hợp | Hợp lý tham số + tiên nghiệm khớp đúng | Khoảng tin Bayes chính xác (phụ thuộc tiên nghiệm) | Qua mô hình phân tầng | \(O(1)\) cập nhật cộng dồn | Tỷ lệ chuyển đổi lưu lượng thấp, Thompson Sampling, co rút mẫu nhỏ. Nhạy tiên nghiệm sai. |
Split Conformal (SCP) |
Chỉ cần Tính hoán vị (phi phân phối!) | Có: \(\ge 1-\alpha\) chính xác với mọi \(n_{\text{cal}} \ge \frac{1-\alpha}{\alpha}\) | Không (bề rộng cố định \(2\hat{q}_{\text{cal}}\)) | \(O(1)\) (+1 cộng vô hướng) |
Khoảng phi tham số cho hồi quy đồng phương sai; gãy khi trôi phân phối nếu không cập nhật. |
Conformalized Quantile Regression (CQR) |
Chỉ cần Tính hoán vị | Có: \(\ge 1-\alpha\) chính xác mẫu hữu hạn | Có (học trải cục bộ \(\hat{q}_{1-\alpha/2}-\hat{q}_{\alpha/2}\)) | Thấp (2 đầu phân vị + \(\hat{q}_{\text{cal}}\)) | ETA giao hàng, dự phòng bảo hiểm, lâm sàng. Yêu cầu \(\mathcal{D}_{\text{cal}}\) tách rời hoàn toàn. |
RAPS/SAPS & Conformal Factuality |
Chỉ cần Tính hoán vị | Có: \(\ge 1-\alpha\) hiệu lực tập / mệnh đề | Có (cỡ tập / cắt tỉa co giãn theo độ khó) | Thấp (softmax hoặc chấm điểm NLI) | Leo thang kiểm duyệt con người (\(\lvert\widehat{C}(x)\rvert > 1\)), lọc ảo giác RAG & từ chối trả lời. |
Adaptive Conformal (ACI/DtACI) |
Không cần Hoán vị (cho phép trôi luồng!) | Tiệm cận dài hạn \(\lvert\frac{1}{T}\sum\operatorname{err}_t - \alpha\rvert \le \frac{1+\gamma}{\gamma T}\) | Có (kết hợp CQR / RAPS) |
\(O(1)\) cập nhật vô hướng | Gian lận biến thiên, cao điểm bệnh viện, trôi kinh tế vĩ mô. Cần nhãn phản hồi kịp thời. |
Kiến trúc Cổng Kiểm định Tự động & Danh sách Kiểm tra Sản xuất#
Danh sách Kiểm tra Sẵn sàng Sản xuất (5-Point Production Readiness Checklist):
- Toàn vẹn Phân nhánh & Log Phơi nhiễm: Băm định danh tất định bằng salt thử nghiệm (
HMAC/MurmurHash3); phát sự kiện phơi nhiễm phía server trước khi nhánh điều trị rẽ nhánh; chạy tự độngsrm_chisq_guard(..., alpha=0.001)ở các mốc 1h, 6h, 24h và kết thúc. - Vệ sinh Đặc trưng Tiền thử nghiệm: Chốt snapshot toàn bộ hiệp phương sai
CUPED/CUPACtrước \(t_{\text{assign}}\); kiểm tra tự động cân bằng hiệp phương sai (abs(smd) < 0.02); bắt buộc khớp chéo \(K\)-nếp + hiệu chuẩnMLRATE. - Trung thực Đơn vị & Đuôi Phân phối: Tính SE tỷ lệ qua thặng dư tuyến tính hóa cụm (
delta_method_ratio_test) kèm cờ cảnh báo Fieller (max_denom_cv > 0.1); xử lý độ trễ lệch đuôi bằngDDSketch+ Duan smearing / Gamma GLM / Moving Block Bootstrap. - Kỷ luật Nhìn trộm & Đa kiểm định: Tách biệt làn cảnh báo nhanh
mSPRTkhỏi làn quyết định sản phẩm cố định/GSD; khóa 1 OEC chính và kiểm soát đa kiểm định quae-BH/BH-FDR+ non-inferiority guardrails. - Hàng rào Conformal & Chống Trôi: Tính hạng Conformal bằng
Decimalkèm ngưỡng \(+\infty\) khi \(n_{\text{cal}} < \frac{1-\alpha}{\alpha}\); bọc hồi quy/RAG bằngCQR/ Conformal Factuality; theo dõi tỷ lệ sai phủ cuộn và kích hoạtACIkhi có trôi dữ liệu.
3.4 Mã nguồn Phòng vệ NumPy Chuẩn mực (Defensive Pure-NumPy Reference Snippets)#
Dưới đây là sáu nguyên thủy phòng vệ viết hoàn toàn bằng Python thuần + NumPy (tương thích NumPy 2.x, 0 phụ thuộc scipy/sklearn), ánh xạ 1-1 với gói prob_stats_lab:
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
import math
from typing import Any
import numpy as np
_SQRT2 = math.sqrt(2.0)
_SQRT2PI = math.sqrt(2.0 * math.pi)
# ==============================================================================
# 1. CHỐNG TRÀN DƯỚI LOG-SUM-EXP & TÍNH PHƯƠNG SAI WELFORD / CHAN SONG SONG
# ==============================================================================
def log_sum_exp(log_vals: np.ndarray | list[float]) -> float:
"""Tính log(sum(exp(x))) an toàn tuyệt đối trên float64."""
arr = np.asarray(log_vals, dtype=np.float64)
if arr.size == 0:
return -math.inf
m = float(np.max(arr))
if math.isinf(m) and m < 0.0:
return -math.inf
if math.isinf(m) and m > 0.0:
return math.inf
return m + math.log(float(np.sum(np.exp(arr - m))))
@dataclass
class WelfordAccumulator:
"""Bộ tích lũy trung bình và phương sai Welford (1962) + gộp song song Chan (1979)."""
count: int = 0
mean: float = 0.0
m2: float = 0.0
def update(self, x: float) -> None:
self.count += 1
d1 = float(x) - self.mean
self.mean += d1 / self.count
d2 = float(x) - self.mean
self.m2 += d1 * d2
def variance(self, ddof: int = 1) -> float:
if self.count <= ddof:
raise ValueError(f"Need count > ddof ({ddof}), got {self.count}.")
return self.m2 / float(self.count - ddof)
def merge(self, other: WelfordAccumulator) -> WelfordAccumulator:
if other.count == 0:
return WelfordAccumulator(self.count, self.mean, self.m2)
if self.count == 0:
return WelfordAccumulator(other.count, other.mean, other.m2)
total = self.count + other.count
delta = other.mean - self.mean
new_mean = self.mean + delta * (other.count / total)
new_m2 = self.m2 + other.m2 + delta * delta * (self.count * other.count / total)
return WelfordAccumulator(total, new_mean, new_m2)
# ==============================================================================
# 2. HÀM ĐẶC BIỆT THUẦN STDLIB (ERFC, ACKLAM+HALLEY PPF, LENTZ GAMMA & BETA)
# ==============================================================================
def norm_cdf(x: float) -> float:
return 0.5 * math.erfc(-x / _SQRT2)
def norm_sf_two_sided(abs_z: float) -> float:
if math.isnan(abs_z):
return float("nan")
if math.isinf(abs_z):
return 0.0
return math.erfc(abs(abs_z) / _SQRT2)
def norm_ppf(p: float) -> float:
"""Phân vị chuẩn tắc Acklam minimax + 1 bước Halley đạt độ chính xác ~1e-15."""
if not (0.0 < p < 1.0):
if p == 0.0:
return -math.inf
if p == 1.0:
return math.inf
raise ValueError(f"p must lie in (0, 1), got {p}")
sign = 1.0
if p > 0.5:
p = 1.0 - p
sign = -1.0
a = (-39.69683028665376, 220.9460984245205, -275.9285104469687,
138.3577518672690, -30.66479806614716, 2.506628277459239)
b = (-54.47609879822406, 161.5858368580409, -155.6989798598866,
66.80131188771972, -13.28068155288572)
c = (-7.784894002430293e-3, -0.3223964580411365, -2.400758277161838,
-2.549732539343734, 4.374664141464968, 2.938163982698783)
d = (7.784695709041462e-3, 0.3224671290700398, 2.445134137142996, 3.754408661907416)
if p < 0.02425:
q = math.sqrt(-2.0 * math.log(p))
x = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1.0)
else:
q = p - 0.5
r = q * q
x = ((((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q) / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1.0)
if 0.5 * x * x < 700.0:
u = (0.5 * math.erfc(-x / _SQRT2) - p) * _SQRT2PI * math.exp(0.5 * x * x)
x = x - u / (1.0 + 0.5 * x * u)
return sign * x
def gammaincc(a: float, x: float, eps: float = 1e-14, max_iter: int = 2000) -> float:
"""Regularized upper incomplete gamma Q(a, x) cho chi-square p-value."""
if x <= 0.0:
return 1.0
if a <= 0.0:
raise ValueError(f"a must be > 0, got {a}")
if a == 0.5:
return math.erfc(math.sqrt(x))
if a == 1.0:
return math.exp(-x)
log_pref = -x + a * math.log(x) - math.lgamma(a)
if log_pref < -745.0:
return 0.0 if x >= a + 1.0 else 1.0
if x < a + 1.0:
ap, term, total = a, 1.0 / a, 1.0 / a
for _ in range(max_iter):
ap += 1.0
term *= x / ap
total += term
if abs(term) <= abs(total) * eps:
break
return max(0.0, min(1.0, 1.0 - total * math.exp(log_pref)))
tiny = 1e-300
b = x + 1.0 - a
c, d = 1.0 / tiny, (1.0 / b if abs(b) > tiny else 1.0 / tiny)
h = d
for i in range(1, max_iter + 1):
an = -i * (i - a)
b += 2.0
d = max(tiny, abs(an * d + b)) * (1.0 if an * d + b >= 0.0 else -1.0)
c = max(tiny, abs(b + an / c)) * (1.0 if b + an / c >= 0.0 else -1.0)
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) <= eps:
break
return max(0.0, min(1.0, h * math.exp(log_pref)))
def _betacf(a: float, b: float, x: float, eps: float = 1e-14, max_iter: int = 500) -> float:
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c, d = 1.0, 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) >= tiny else tiny)
h = d
for m in range(1, max_iter + 1):
m2 = 2 * m
for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))):
d = 1.0 + aa * d
d = 1.0 / (d if abs(d) >= tiny else tiny)
c = 1.0 + aa / c
c = c if abs(c) >= tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) <= eps:
break
return h
def betainc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta I_x(a, b) cho Welch t-test p-value."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
log_bt = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x)
bt = 0.0 if log_bt < -745.0 else math.exp(log_bt)
if x < (a + 1.0) / (a + b + 2.0):
return max(0.0, min(1.0, bt * _betacf(a, b, x) / a))
return max(0.0, min(1.0, 1.0 - bt * _betacf(b, a, 1.0 - x) / b))
# ==============================================================================
# 3. CỔNG SRM CHI-SQUARE + DIRICHLET-MULTINOMIAL E-PROCESS
# ==============================================================================
def srm_chisq_guard(
observed_counts: np.ndarray | list[int] | list[float],
expected_probs: np.ndarray | list[float],
alpha: float = 0.001,
dirichlet_conc: float | None = 100.0,
) -> dict[str, Any]:
obs = np.asarray(observed_counts, dtype=np.float64)
probs = np.asarray(expected_probs, dtype=np.float64)
if obs.ndim != 1 or probs.ndim != 1 or obs.size != probs.size or obs.size < 2:
raise ValueError("observed_counts and expected_probs must be 1D arrays of equal length >= 2.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
if not (np.all(np.isfinite(obs)) and np.all(obs >= 0.0)):
raise ValueError("observed_counts must be finite and non-negative.")
if not (np.all(np.isfinite(probs)) and np.all(probs > 0.0)):
raise ValueError("expected_probs must be finite and strictly positive.")
prob_sum = float(np.sum(probs))
if not math.isclose(prob_sum, 1.0, rel_tol=0.0, abs_tol=1e-5):
raise ValueError(f"expected_probs must sum to 1.0, got {prob_sum:.8f}.")
probs = probs / prob_sum
total_n = float(np.sum(obs))
df = int(obs.size - 1)
if total_n <= 0.0:
return {"srm_detected": False, "chi2_stat": 0.0, "p_value": 1.0, "df": df, "e_value_dirichlet": 1.0 if dirichlet_conc else None}
expected = total_n * probs
chi2_stat = float(np.sum(((obs - expected) ** 2) / expected))
p_value = gammaincc(0.5 * df, 0.5 * chi2_stat)
e_val = None
if dirichlet_conc is not None:
a0 = dirichlet_conc * probs
log_e = math.lgamma(dirichlet_conc) - math.lgamma(dirichlet_conc + total_n)
for ak, nk, pk in zip(a0, obs, probs):
log_e += math.lgamma(ak + nk) - math.lgamma(ak) - nk * math.log(pk)
e_val = math.inf if log_e > 709.0 else math.exp(log_e)
return {"srm_detected": bool(p_value < alpha), "chi2_stat": chi2_stat, "p_value": p_value, "df": df, "e_value_dirichlet": e_val}
# ==============================================================================
# 4. CLUSTERED DELTA METHOD RATIO TEST + GIẢI CỨU FIELLER (CV > 0.1)
# ==============================================================================
def t_sf_two_sided(t_val: float, df: float) -> float:
if df > 1e7:
return norm_sf_two_sided(abs(t_val))
return betainc(0.5 * df, 0.5, df / (df + t_val * t_val))
def t_ppf_two_sided(alpha: float, df: float) -> float:
if df > 1e7:
return norm_ppf(1.0 - 0.5 * alpha)
lo, hi = 0.0, max(2.0, norm_ppf(1.0 - 0.5 * alpha))
while t_sf_two_sided(hi, df) > alpha:
hi *= 2.0
for _ in range(70):
mid = 0.5 * (lo + hi)
if t_sf_two_sided(mid, df) > alpha:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def fieller_ratio_ci(num: np.ndarray, den: np.ndarray, alpha: float = 0.05) -> tuple[float, float, bool]:
y = np.asarray(num, dtype=np.float64)
x = np.asarray(den, dtype=np.float64)
n = y.size
yb, xb = float(np.mean(y)), float(np.mean(x))
vy = float(np.var(y, ddof=1)) / n
vx = float(np.var(x, ddof=1)) / n
vxy = float(np.cov(y, x, ddof=1)[0, 1]) / n
t2 = t_ppf_two_sided(alpha, n - 1.0) ** 2
A = xb * xb - t2 * vx
if A <= 0.0:
return (-math.inf, math.inf, True)
B = -(2.0 * xb * yb - 2.0 * t2 * vxy)
C = yb * yb - t2 * vy
disc = max(0.0, B * B - 4.0 * A * C)
root_lo = (-B - math.sqrt(disc)) / (2.0 * A)
root_hi = (-B + math.sqrt(disc)) / (2.0 * A)
return (min(root_lo, root_hi), max(root_lo, root_hi), False)
def delta_method_ratio_test(
num_ctrl: np.ndarray, den_ctrl: np.ndarray, num_trt: np.ndarray, den_trt: np.ndarray, alpha: float = 0.05
) -> dict[str, Any]:
yc, xc = np.asarray(num_ctrl, dtype=np.float64), np.asarray(den_ctrl, dtype=np.float64)
yt, xt = np.asarray(num_trt, dtype=np.float64), np.asarray(den_trt, dtype=np.float64)
nc, nt = yc.size, yt.size
mxc, mxt = float(np.mean(xc)), float(np.mean(xt))
rc, rt = float(np.mean(yc)) / mxc, float(np.mean(yt)) / mxt
diff = rt - rc
uc = (yc - rc * xc) / mxc
ut = (yt - rt * xt) / mxt
var_rc = float(np.dot(uc, uc) / (nc * (nc - 1)))
var_rt = float(np.dot(ut, ut) / (nt * (nt - 1)))
se_sq = var_rc + var_rt
se = math.sqrt(se_sq)
cv_c = (math.sqrt(float(np.var(xc, ddof=1)) / nc) / abs(mxc)) if nc > 1 else 0.0
cv_t = (math.sqrt(float(np.var(xt, ddof=1)) / nt) / abs(mxt)) if nt > 1 else 0.0
if se <= 0.0:
df_w = float(nc + nt - 2)
stat = 0.0 if diff == 0.0 else math.copysign(math.inf, diff)
p_z, p_t = (1.0, 1.0) if diff == 0.0 else (0.0, 0.0)
else:
stat = diff / se
p_z = norm_sf_two_sided(abs(stat))
denom_df = (var_rc * var_rc) / (nc - 1) + (var_rt * var_rt) / (nt - 1)
df_w = (se_sq * se_sq) / denom_df if denom_df > 0.0 else float(nc + nt - 2)
p_t = betainc(0.5 * df_w, 0.5, df_w / (df_w + stat * stat))
z_crit = norm_ppf(1.0 - 0.5 * alpha)
f_c = fieller_ratio_ci(yc, xc, alpha)
f_t = fieller_ratio_ci(yt, xt, alpha)
return {"rate_ctrl": rc, "rate_trt": rt, "diff": diff, "se": se, "p_value_welch": p_t, "ci_delta": (diff - z_crit * se, diff + z_crit * se), "ci_fieller_ctrl": (f_c[0], f_c[1]), "ci_fieller_trt": (f_t[0], f_t[1]), "fieller_unbounded": bool(f_c[2] or f_t[2]), "max_denom_cv": max(cv_c, cv_t)}
# ==============================================================================
# 5. mSPRT LOG-SPACE AN TOÀN & DỰ BÁO CONFORMAL TÁCH CHÍNH XÁC BẰNG DECIMAL
# ==============================================================================
def msprt_confidence_sequence(
delta_hat: float | np.ndarray, pooled_var: float | np.ndarray, tau_sq: float, alpha: float = 0.05
) -> dict[str, Any]:
d = np.atleast_1d(np.asarray(delta_hat, dtype=np.float64))
v = np.atleast_1d(np.asarray(pooled_var, dtype=np.float64))
log_e = np.empty_like(d)
hw = np.empty_like(d)
pos = v > 0.0
if np.any(pos):
vp, dp = v[pos], d[pos]
log_e[pos] = 0.5 * (np.log(vp) - np.log(vp + tau_sq)) + (tau_sq * dp * dp) / (2.0 * vp * (vp + tau_sq))
log_term = 2.0 * math.log(1.0 / alpha) + np.logaddexp(0.0, math.log(tau_sq) - np.log(vp))
hw[pos] = np.sqrt(vp * (1.0 + vp / tau_sq) * log_term)
if np.any(~pos):
log_e[~pos] = np.where(d[~pos] == 0.0, 0.0, math.inf)
hw[~pos] = 0.0
point_p = np.exp(np.maximum(-746.0, np.minimum(0.0, -log_e)))
av_p = np.minimum.accumulate(point_p) if d.size > 1 else point_p
return {"cs_lower": d - hw, "cs_upper": d + hw, "half_width": hw, "log_e_value": log_e, "always_valid_p": av_p}
def split_conformal_calibrate(cal_scores: np.ndarray | list[float], alpha: float = 0.10) -> dict[str, Any]:
scores = np.asarray(cal_scores, dtype=np.float64)
n = scores.size
k = int(math.ceil(Decimal(n + 1) * (Decimal("1") - Decimal(str(alpha)))))
if k > n:
return {"q_hat": math.inf, "k_rank": k, "n_cal": n, "finite_sample_fallback_inf": True}
sorted_scores = np.sort(scores)
return {"q_hat": float(sorted_scores[max(1, k) - 1]), "k_rank": k, "n_cal": n, "finite_sample_fallback_inf": False}
Trụ cột 4 — Thực hành Lab 03 (prob_stats_lab) & Kiểm định Chất lượng Thống kê (Hands-On Workbench & Statistical Verification Rubric)#
Bài thực hành đồng hành tại labs/ch03-probability-inference-and-testing-workbench/ hiện thực hóa toàn bộ lý thuyết của Trụ cột 1–2 và hàng rào phòng vệ ở Trụ cột 3 thành gói Python kiểm chứng tự chủ prob_stats_lab với 14 ca kiểm thử pytest tự động.
4.1 Kiến trúc Gói prob_stats_lab & Hợp đồng Không Phụ thuộc ABI Ngoài (Zero-SciPy/Sklearn)#
labs/ch03-probability-inference-and-testing-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch03_workbench_results.json
├── src/
│ └── prob_stats_lab/
│ ├── __init__.py
│ ├── distributions_and_bayes.py
│ ├── inference_and_experimentation.py
│ └── conformal.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_prob_stats_lab.py
Hợp đồng pyproject.toml & Ràng buộc Môi trường (Python >= 3.10):
- Khai báo
name = "prob-stats-lab",version = "0.1.0",requires-python = ">=3.10",dependencies = ["numpy>=1.26", "pandas>=2.0"], và[project.optional-dependencies] dev = ["pytest>=8.0", "ruff>=0.4"]. - Cấu hình
[tool.setuptools.packages.find](where = ["src"]) và[tool.pytest.ini_options](testpaths = ["tests"],pythonpath = ["src"],addopts = "-v"). - Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật (
Security-Only AST Deserialization Ban): Mọi mô-đun củaprob_stats_labđược cài đặt thuần Python stdlib + NumPy + Pandas (miễn nhiễm trước sự cố C-ABI_ARRAY_API); đồng thờiTest 14chạy trình quét AST trên toàn bộsrc/,scripts/, vàtests/cấm tuyệt đối các thư viện giải tuần tự hóa nguy hiểm (pickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshal).
4.2 Hướng dẫn Từng bước Qua 3 Mô-đun Cốt lõi & CLI Workbench#
Mô-đun 1: Phân phối, Bayes Liên hợp, Phụ thuộc & Berry–Esseen (src/prob_stats_lab/distributions_and_bayes.py)#
Đóng gói kết quả bằng 3 @dataclass(frozen=True, slots=True):
ConjugatePosteriorResult: lưufamily,prior_params,posterior_params,posterior_mean,posterior_var,predictive_mean,predictive_var,credible_interval_95.DependenceProfile: lưupearson_r,spearman_rho,mutual_info_nats.CLTConvergenceRow: lưudist_name,sample_size,skewness,berry_esseen_bound,empirical_ks_error,empirical_95_coverage.
Các hàm chức năng chính:
log_sum_exp,WelfordAccumulator(kèm.update,.update_batch,.variance,.std,.merge), và bộ 6 hàm đặc biệt thuần Pythonnorm_cdf,norm_sf_two_sided,norm_ppf,gammaincc,betainc,t_sf_two_sided.- Bốn cập nhật liên hợp chuẩn hóa:
beta_binomial_update,gamma_poisson_update+gamma_poisson_negbin_logpmf(khóa chặt Shape–Ratealpha0, beta0_rate),dirichlet_categorical_update(Laplace/Jeffreys), vànormal_normal_update(cộng độ chính xác \(\tau_{\text{prec}}\) + phân tách epistemic/aleatoric). mvn_schur_conditional(trả về(mu_cond, cov_cond, precision_subblock_inv)),mahalanobis_sq, vàpoisson_limit_tv_distance(lam, n)tính khoảng cách TV quamath.lgamma.spearman_midrank_corr,discrete_mutual_information,compute_dependence_profile, vàbenchmark_berry_esseen_cltđối chiếu"uniform","rare_bernoulli_p0.01","lognormal_sigma1.2"trên lưới \(n \in \{10, 30, 100, 1000\}\).
Mô-đun 2: Kiểm định Giả thuyết, SRM, CUPED/MLRATE, Tỷ lệ Fieller & mSPRT (src/prob_stats_lab/inference_and_experimentation.py)#
Định nghĩa 6 @dataclass(frozen=True, slots=True): WelchTestResult, SRMResult, CupedResult, RatioTestResult, MSPRTResult, và MultipleTestingResult:
wilson_score_intervalvs.wald_interval,compute_mde_and_sample_size,welch_t_test,mann_whitney_u_test(trung bình hạng + độ đồng thuậnu1/(n1*n2)),studentized_permutation_test((1+#)/(B+1)với Welch-\(t\)), vàbootstrap_ci("percentile","basic","bca"với jackknife \(a\) + \(z_0\),"moving_block").srm_chisq_guard(tính \(\chi^2\) +e_value_dirichlet),fieller_ratio_ci, vàdelta_method_ratio_test(báo cáomax_denom_cv,fieller_unbounded,ci_fieller_ctrl,ci_fieller_trt).cuped_adjusthỗ trợ cả ba chế độ"cuped_pooled","lin_ancova2"(tương tác \(W\tilde{X}\) +HC1SE), và"mlrate_crossfit"(khớp chéo \(K\)-nếp SVD Ridge ngoài nếp + hiệu chuẩn Lin ngoài), cùngduan_smearing_meanvàlognormal_inversion_demo.msprt_confidence_sequence,obrien_fleming_boundaries,multiple_testing_control("bonferroni","holm","bh","by","ebh"), vàbenchmark_peeking_vs_msprt.
Mô-đun 3: Dự báo Conformal Không phân phối & Conformal Factuality (src/prob_stats_lab/conformal.py)#
Định nghĩa 4 @dataclass(frozen=True, slots=True): ConformalCalResult, CQRResult, SetPredictionResult, và ACIResult:
split_conformal_calibrate(tính hạng chính xác bằngDecimal, fallbackmath.infkhi \(k > n_{\text{cal}}\)).fit_linear_spline_quantile_regressor(hồi quy phân vị pinball pure-NumPy trên cơ sở spline/RBF) vàcqr_calibrate_and_predict.conformal_classification_scoresvàcalibrate_and_predict_setshỗ trợ đủ bốn bộ điểm"lac","aps","raps", và"saps"(có cờallow_zero_sets).adaptive_conformal_inference(theo dõi quỹ đạo \(\alpha_t\) và cận hối tiếc \(O(1/(\gamma T))\)),conformal_factuality_prune(cắt tỉa mệnh đề RAG dưới \(\hat{\tau}_{\text{fact}}\)), vàbenchmark_conformal_suite.
Thực thi CLI Một Lệnh & Cấu trúc Xuất artifacts/ch03_workbench_results.json#
Từ thư mục gốc labs/ch03-probability-inference-and-testing-workbench/, chạy:
python scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch03_workbench_results.json
CLI xuất đủ 4 khối báo cáo trên stdout:
[1] Probability, Conjugate Bayes, Dependence Counterexamples & Berry-Esseen CLT[2] Hypothesis Tests, SRM Guard, Variance Reduction (CUPED/Lin/MLRATE) & Ratio/LogNormal Pitfalls[3] Anytime-Valid Sequential Testing (LIL vs mSPRT, O'Brien-Fleming, e-BH)[4] Distribution-Free Conformal Prediction (SCP, CQR, RAPS/SAPS, ACI, Conformal Factuality)
Đồng thời tệp JSON artifacts/ch03_workbench_results.json xuất 5 khóa cấp cao ("config", "workbench_panels", "distributions_and_bayes", "inference_and_experimentation", "conformal"), với "workbench_panels" chứa đúng 6 KPIs (kpi_peeking_fpr, kpi_srm_guard, kpi_mlrate_vr, kpi_clustered_ratio_se, kpi_cqr_stratum_coverage, kpi_aci_drift_recovery), 4 biểu đồ cột (bar_peeking_fpr_comparison, bar_cuped_mlrate_vr, bar_conformal_coverage_audit, bar_classification_set_size), và 4 bảng dữ liệu (table_berry_esseen_clt, table_ab_variance_and_pitfalls, table_sequential_and_multiplicity, table_conformal_suite).
Chỉ số Xác minh Trực tiếp (artifacts/ch03_workbench_results.json) |
Giá trị Đo kiểm Thực tế (--seed 42 --quick) |
Trạng thái |
|---|---|---|
kpi_peeking_fpr (LIL vs. mSPRT Peeking FPR) |
3.20% vs. 42.0% LIL naive (250 luồng, alpha=0.05; fixed_1=6.00%, fixed_20=24.40%) |
ok (Đã xác minh) |
kpi_srm_guard (50.35% / 49.65% \(\chi^2\) & Dirichlet e-value) |
p = 0.001745, chi2 = 9.80, e_value_dirichlet = 23.21 > 20 ([100700, 99300] vs. 50/50) |
critical (Cảnh báo SRM kích hoạt đúng) |
kpi_mlrate_vr (MLRATE 5-fold Signal vs. Noise VR) |
96.0% (24.9x hiệu suất mẫu ở d=50; nhiễu thuần d=100: in-sample 21.8% vs. cross-fit 0.1%) |
ok (Đã xác minh) |
kpi_clustered_ratio_se (Clustered Delta vs. Naive Session SE) |
3.25x (SE_cluster = 0.01467 vs. SE_naive = 0.00451 trên cụm người dùng phân phối đuôi nặng) |
ok (Đã xác minh) |
kpi_cqr_stratum_coverage (CQR vs. SCP High-Noise Stratum) |
90.3% (width = 5.166) vs. hằng số SCP sụt xuống 68.8% (width = 5.371, mục tiêu 90%) |
ok (Đã xác minh) |
kpi_aci_drift_recovery (ACI Post-Shift Miscoverage vs. Static SCP) |
90.0% sau dịch chuyển 2.8x (regret <= 0.035) vs. SCP tĩnh sụt xuống 51.5% |
ok (Đã xác minh) |
(Ngoài ra, trong cụm 40 lớp đuôi nhiễu của table_conformal_suite, kích thước tập trung bình giảm từ 2.61 với APS xuống còn 1.625 với RAPS và 1.301 với SAPS trong khi vẫn giữ độ phủ 94.3% và 91.5%; bộ lọc Conformal Factuality giữ tỷ lệ không ảo giác 88.25% ở mức nhớ mệnh đề đúng 97.43%.)
4.3 Danh sách Kiểm tra Rigor & Hợp đồng 14 Kiểm thử Tự động (pytest Contract)#
- [x] Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật: Lõi
prob_stats_labcài đặt thuần stdlib + NumPy/Pandas (không phụ thuộcscipy/sklearn/statsmodels/torch), đồng thời trình quét AST trênsrc/,scripts/,tests/xác nhận0import giải tuần tự hóa nguy hiểm (pickle,joblib,cloudpickle,dill,shelve,marshal). - [x] Độ chính xác Số học & Độ tin cậy Biên:
norm_cdf(norm_ppf(p))khớp tới1e-12;WelfordAccumulatorổn định ở1e9 + N(0,1)(var = 0.9989vs. single-pass-128.00);Decimaltính hạng conformal không dính lỗi150 * 0.82(k_rank = 123) và trảmath.infkhi \(k > n_{\text{cal}}\). - [x] Bảo toàn Cổng Thống kê SOTA:
mlrate_crossfitgiữ VR0.1%(\(< 0.05\)) trên nhiễu trắng;mSPRTgiữ peeking FPR3.20%(\(\le 0.06\)) trong khi LIL đạt42.0%;e-BHgiữFDR <= 0.06dưới phụ thuộc tùy ý;CQRgiữ độ phủ vùng nhiễu cao90.3%(\(\ge 0.85\)) vàACIgiữ độ phủ hậu dịch chuyển90.0%đúng cận hối tiếc \(\frac{1+\gamma}{\gamma T}\). - [x] Vượt qua
14/14capytesttrongtests/test_prob_stats_lab.py(14 passed in 3.57s) không bỏ qua hay nới lỏng khẳng định.
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Kiểm chứng |
|---|---|---|
| 1 | test_special_functions_lse_and_welford_stability |
Khẳng định norm_cdf(norm_ppf(p)) == p (atol=1e-12); gammaincc (df=1,2), t_sf_two_sided (df=1 Cauchy), log_sum_exp ở [-1000,-1001]/[1000,1001], và WelfordAccumulator + .merge() (rel_err < 1e-4) trên 1e9 + N(0,1). |
| 2 | test_conjugate_updates_predictives_and_poisson_limit |
Kiểm chứng đủ 4 cập nhật liên hợp (beta_binomial_update, gamma_poisson_update Shape–Rate & NegBin, dirichlet_categorical_update, normal_normal_update) và poisson_limit_tv_distance(3.0, n) giảm ngặt \(n=50 \to 500 \to 5000\). |
| 3 | test_mvn_schur_conditioning_and_dependence_counterexamples |
Xác nhận mvn_schur_conditional khớp \(\boldsymbol{\Lambda}_{11}^{-1}\) (atol=1e-11) & mahalanobis_sq \(\approx d\); kiểm chứng đủ 3 phản ví dụ (\(Y=X^2\), \(Y=e^X\) với \(X\sim\mathcal{N}(0,9)\), và spearman_midrank_corr nhiều đồng hạng). |
| 4 | test_berry_esseen_clt_and_wilson_vs_wald_intervals |
Xác nhận uniform đạt \(\ge 0.92\) tại \(n=30\) trong khi rare_bernoulli_p0.01 và lognormal_sigma1.2 sụp độ phủ tại \(n=30\) trước khi hồi phục ở \(n=1000\); wilson_score_interval nằm chặt trong \([0, 1]\) khi wald_interval sập hoặc âm. |
| 5 | test_bootstrap_bca_block_and_max_order_breakdown |
Kiểm chứng "bca" khớp phân phối mũ lệch tốt hơn "basic"; "moving_block" cho SE \(> 1.3\times\) "percentile" trên chuỗi AR(1) (\(\phi=0.85\)); và bootstrap \(\max(X)\) đặt khối lượng trong [0.55, 0.72] tại \(\hat{\theta}^*=\hat{\theta}\) (\(1-e^{-1}\approx 0.632\)). |
| 6 | test_welch_mann_whitney_and_studentized_permutation |
Kiểm chứng welch_t_test giữ FPR \(\le 0.08\) trong Behrens–Fisher; mann_whitney_u_test bác bỏ hỗn hợp hai phân phối cùng trung vị 0 (đồng thuận ~0.725, p < 1e-6); studentized_permutation_test cho \(p \ge 1/(B+1)\). |
| 7 | test_srm_chisq_guard_and_dirichlet_e_process |
Kiểm chứng srm_chisq_guard([100700, 99300], [0.5, 0.5], alpha=0.002) ra \(\chi^2 = 9.80\), \(p \approx 0.001745\), srm_detected=True, e_value_dirichlet > 20.0; và [0, 0] trả về p_value == 1.0. |
| 8 | test_cuped_lin_ancova2_and_mlrate_crossfit |
Kiểm chứng trên \(d=50\) tín hiệu (VR > 0.70, ATE không lệch) và \(d=100\) nhiễu thuần tại \(N=400\) ("cuped_pooled" phình VR \(> 0.15\) trong khi "mlrate_crossfit" \(< 0.05\), cùng "lin_ancova2" ổn định khi \(p=0.25\)). |
| 9 | test_clustered_delta_ratio_fieller_and_lognormal_trap |
Kiểm chứng delta_method_ratio_test trên cụm luật lũy thừa cho se > 2.0 * naive_session_se, fieller_ratio_ci khi \(\operatorname{CV}(\bar{X}) > 0.25\); lognormal_inversion_demo cho log_diff > 0 cùng arith_diff < 0, và duan_smearing_mean khôi phục trong sai số 3%. |
| 10 | test_msprt_ville_peeking_and_obrien_fleming |
Kiểm chứng benchmark_peeking_vs_msprt (\(\lvert Z \rvert\) nhìn trộm FPR \(> 0.30\) vs. mSPRT \(\le 0.06\) ở \(\alpha=0.05\)); kiểm tra \(Z\) cực lớn không tràn; obrien_fleming_boundaries cho ngưỡng \(z\) giảm đơn điệu (\(z_1 > 3.8, z_4 < 2.1\)). |
| 11 | test_multiple_testing_bonferroni_holm_bh_by_and_ebh |
Kiểm chứng bài toán \(m=6\) [0.001, 0.009, 0.026, 0.032, 0.041, 0.420] bác bỏ 1/2/5 tương ứng bonferroni/holm/bh; by <= bh; và "ebh" giữ FDR <= 0.06 qua 300 mô phỏng e-value phụ thuộc tùy ý. |
| 12 | test_scp_finite_sample_coverage_and_cqr_heteroscedasticity |
Kiểm chứng split_conformal_calibrate trả math.inf tại n_cal=8, alpha=0.10, tránh lỗi float tại n_cal=149, alpha=0.18 (k_rank==123), phân vị ngây thơ thiếu phủ (< 0.85) tại n_cal=10; cqr_calibrate_and_predict giữ high_noise_coverage >= 0.85 khi SCP tụt \(< 0.80\). |
| 13 | test_raps_saps_aci_drift_and_conformal_factuality |
Kiểm chứng lac/aps/raps/saps đạt độ phủ \(\ge 0.86\) với raps/saps thu gọn kích thước tập hơn aps; adaptive_conformal_inference hồi phục độ phủ sau dịch chuyển trong [0.83, 0.96] đúng cận regret; conformal_factuality_prune đạt tỷ lệ không ảo giác \(\ge 0.85\) ở \(\alpha=0.10\). |
| 14 | test_cli_demo_script_workbench_json_and_zero_forbidden_imports |
Chạy scripts/run_lab_demo.py --seed 42 --quick --output <tmp> (returncode == 0), kiểm tra đủ 4 khối stdout + workbench_panels (6 KPIs, 4 bars, 4 tables), và quét AST Chỉ Bảo mật cấm tuyệt đối import giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực (Curated Reading List & Mastery Exercises)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Casella, G., & Berger, R. L. (2002) & Bishop, C. M. (2006). Statistical Inference (2nd ed.) và Pattern Recognition and Machine Learning.
Vì sao quan trọng: Nền móng chuẩn mực nhất về họ hàm mũ chính tắc, thống kê đủ Fisher–Neyman, Thông tin Fisher /CRLB, phương pháp Delta, và các suy diễn hậu nghiệm & phân phối dự báo liên hợp. - Deng, A., Xu, Y., Kohavi, R., & Walker, T. (2013), Lin, W. (2013,
arXiv:1208.2301), Guo, Y., et al. (MLRATE, NeurIPS 2021,arXiv:2106.07263), & Jin, Y., & Ba, S. (Technometrics 2023,arXiv:2110.13406).
Vì sao quan trọng: Hoàn thiện lý thuyết giảm phương sai từCUPEDtuyến tính qua hồi quy tương tácLin ANCOVA2chống phê phán Freedman đếnCUPAC/MLRATEkhớp chéo tối ưu bán tham số. - Fabijan, A., et al. (
SRM, KDD 2019), Deng, A., Knoblich, U., & Lu, J. (KDD 2018), & Bojinov, I., Simchi-Levi, D., & Zhao, J. (Management Science 2023).
Vì sao quan trọng: Giải phẫu tỷ lệ hỏngSRM6%–10%trong sản xuất, suy diễn phương sai tỷ lệ cụm tuyến tính hóa, và thiết kế Switchback xử lý hiệu ứng tràn nối thẳng sang Chương 05. - Johari, R., et al. (
mSPRT, Operations Research 2022,arXiv:1512.04922), Wang, R., & Ramdas, A. (e-BH, JRSS-B 2022,arXiv:2009.02824), Grünwald, P., et al. (GROW, JRSS-B 2024,arXiv:1906.07801), Waudby-Smith, I., et al. (AsympCS, Annals of Statistics 2024,arXiv:2103.06476), & Ramdas, A., & Wang, R. (2024–2025,arXiv:2410.23614).
Vì sao quan trọng: Thống nhất lý thuyết siêu martingale kiểm định, Bất đẳng thức Ville, dãy tin cậy mọi thời điểm, và kiểm soát FDRe-BHbất chấp phụ thuộc tùy ý. - Vovk, V., Gammerman, A., & Shafer, G. (2022), Romano, Y., et al. (
CQR, NeurIPS 2019,arXiv:1905.03222), Angelopoulos, A. N., et al. (RAPS, ICLR 2021;CRC, ICLR 2024,arXiv:2208.02814), Barber, R. F., et al. (NexCP, Annals of Statistics 2023,arXiv:2202.13415), & Huang, J., et al. (SAPS, ICML 2024,arXiv:2310.06430).
Vì sao quan trọng: Đặt nền tảng cho dự báo Conformal mẫu hữu hạn phi phân phối trên hồi quy bất đẳng phương sai, tập phân loại cỡ nhỏ, và kiểm soát rủi ro tổng quát không hoán vị. - Gibbs, I., & Candès, E. J. (
ACI2021;DtACI, JMLR 2024,arXiv:2208.08401), Hore, R., & Barber, R. F. (RLCP, JRSS-B 2024,arXiv:2310.07850), Mohri, C., & Hashimoto, T. (ICML 2024,arXiv:2402.10978), & Cherian, J., et al. (NeurIPS 2024,arXiv:2406.09714).
Vì sao quan trọng: Đưa điều khiển trôi trực tuyến, độ phủ cục bộ hóa ngẫu nhiên, và cam kết xác suất không ảo giác (Conformal Factuality) vào hệ thống LLM và tác tử RAG.
5.2 Tám Điểm Kiểm tra Tư duy & Nắm vững Khái niệm (Q1–Q8)#
- Q1 (
Gamma–PoissonShape–Rate vs. Shape–Scale & Quá phân tán): Vì sao truyền nhầm tham số tốc độ \(\beta\) vàonumpy.random.gamma(..., scale=beta)làm đảo ngược kỳ vọng tiên nghiệm, và tại sao dự báo hậu nghiệm \(\operatorname{NegBin}(\alpha', \frac{\beta'}{\beta'+1})\) luôn có phương sai lớn hơn kỳ vọng? - Q2 (Họ Hàm mũ Chính tắc & Ma trận Chính xác
MVN): Chứng minh ý nghĩa của \(\nabla^2 A(\boldsymbol{\eta}) = \operatorname{Cov}(\mathbf{T}(X)) = \mathcal{I}(\boldsymbol{\eta})\) trong tối ưuGLM, giải thích hạng suy biến \(K-1\) của Softmax, và giải thích vì sao \(\Lambda_{ij} = 0\) trong \(\boldsymbol{\Lambda}=\boldsymbol{\Sigma}^{-1}\) tương đương \(X_i \perp X_j \mid \mathbf{X}_{-\{i,j\}}\) chứ không phải \(\Sigma_{ij}=0\). - Q3 (Phản ví dụ Phụ thuộc,
Welford& Berry–Esseen): Trình bày ba phản ví dụ phân biệt Pearson \(\rho_{Y,X}\), Spearman \(\rho_S\) (cần midrank khi có đồng hạng) và \(I(X;Y)\); giải thích vì sao phương sai một lượt âm tại \(\mu=10^9\) và vì sao quy tắc "\(n \ge 30\)" sụp đổ trên \(\operatorname{Bernoulli}(0.001)\) theo cận Berry–Esseen. - Q4 (Ước lượng
MAP, Khoảng Wilson & Sụp đổ Bootstrap): Giải thích vì saoMAPkhông bất biến dưới đổi biến trơn; tại sao khoảng Wald sập thành \([0,0]\) khi \(K=0\) trong khi Wilson Score vẫn nằm chặt trong \([0,1]\); và vì sao bootstrap cỡ \(n\) đặt \(1-e^{-1}\approx 63.21\%\) khối lượng tại \(0\) khi ước lượng \(\max X_i\). - Q5 (Ngụy biện Công tố viên, Mann–Whitney & Bước lên
BH): Dùng Định lý Bayes giải thích tại sao \(p \le 0.05\) có thể tương ứngFPR = 36%–74.3%; chứng minh Mann–Whitney kiểm định ưu thế ngẫu nhiên chứ không phải trung vị bằng phản ví dụ hỗn hợp đồng trung vị \(0\); và giải thích cơ chế "cứu ngược" từ \(i=5\) xuống \(i=3\) trong thủ tục bước lênBHvà hiệu chỉnh \((1+\#)/(B+1)\) trong kiểm định hoán vị. - Q6 (
CUPED/Lin/MLRATE& Bẫy Tỷ lệ/Đuôi nặng): Chứng minh vì sao quy tâm theo từng nhánh xóa sạch 100% hiệu quảCUPED; vì sao khớp trong mẫu trên \(d=100\) nhiễu tạo ra \(28.6\%\) VR giả; và cách Fieller cùng bôi trơn Duan cứu hai tình huống \(\operatorname{CV}(\bar{X})>0.1\) và đảo dấu LogNormal. - Q7 (Suy luận Hợp lệ Mọi Thời điểm): Giải thích cơ chế
LILđưaFPRnhìn trộm tới \(100\%\), nêu lại 4 bước chứng minh Bất đẳng thức Ville, vai trò của \(\tau_{\text{mix}}^2\) trongmSPRT, và lý do chứng minh 3 dòng củae-BHmiễn nhiễm hoàn toàn trước tương quan tùy ý mà không mất hệ số \(\ln K\). - Q8 (Dự báo Conformal Không phân phối): Chứng minh vì sao
np.quantile(scores, 0.90)ở \(n_{\text{cal}}=10\) chỉ đạt độ phủ \(81.82\%\) thay vì \(90\%\), giải thích cáchCQRxử lý bất đẳng phương sai, cáchSAPSkhắc phục đuôi softmax nhiễu so vớiAPS/RAPS, và ý nghĩa cận hối tiếc \(O(1/T)\) củaACIcùng ngưỡng cắt tỉa \(\hat{\tau}_{\text{fact}}\) trong RAG.
5.3 Sáu Bài tập Thực hành & Chứng minh Tính điểm (Ex1–Ex6)#
- Bài tập 1 (
20%— Suy diễn Nguyên lý Gốc & Độ ổn định Số học):
Suy diễn trọn vẹn PMF dự báo Negative Binomial từ mô hình Gamma–Poisson (Shape–Rate); chứng minh \(\nabla A = \mathbb{E}[\mathbf{T}]\) và \(\nabla^2 A = \operatorname{Cov}(\mathbf{T})\) của họ hàm mũ chính tắc; và kiểm chứng bằngprob_stats_labsự vượt trội củaWelfordAccumulatortại \(\mu = 10^9\) cùng sự sụp đổ độ phủ CLT Berry–Esseen trên \(\operatorname{Bernoulli}(0.01)\) ở \(n=30\). - Bài tập 2 (
20%— Khoảng Tin cậy, Sụp đổ Bootstrap & Bẫy Phi tham số):
Suy diễn dạng đóng Khoảng Tin cậy Wilson bằng đảo ngược kiểm định điểm số; chứng minh giải tích \(\lim_{n\to\infty} P(\hat{\theta}_n^* = \hat{\theta}_n) = 1 - e^{-1}\) cho \(\hat{\theta}_n = \max X_i\); và kiểm chứng số học phản ví dụ hỗn hợp hai phân phối cùng trung vị0khiếnmann_whitney_u_testbác bỏ gần100%. - Bài tập 3 (
15%—CUPED,Lin ANCOVA2& Khớp chéoMLRATE):
Chứng minh tính không thiên lệch và hệ số giảm phương sai \(1 - \rho_{Y,X}^2\) củaCUPED; chứng minh đại số vì sao quy tâm theo nhánh phá hủy giảm phương sai; và benchmark trêncuped_adjustchứng tỏ"mlrate_crossfit"5-nếp miễn nhiễm ảo giác VR trên \(d=100\) nhiễu thuần túy và đạt hiệu suất cao vớiHC1SE khi tỷ lệ phân bổ \(p = 0.25\). - Bài tập 4 (
15%— Bất đẳng thức Ville,mSPRT& Đa kiểm địnhe-BH):
Trình bày đầy đủ 4 bước chứng minh Bất đẳng thức Ville từ thời điểm dừng bị chặn; mô phỏng 1,000 luồng không hiệu ứng đối chiếu nhìn trộm \(|Z_n|>1.96\) vớimsprt_confidence_sequence; và viết chứng minh 3 dòng củae-BHcùng kiểm chứngFDR <= 0.05dưới tương quan tùy ý. - Bài tập 5 (
15%—SCP,CQR,ACI&Conformal Factuality):
Chứng minh định lý đối xứng hạngSCP(bao gồm trường hợp đồng hạng); tái hiện phản ví dụn_cal=10, alpha=0.10đạt81.82%cho phân vị ngây thơ vs.>= 90%chosplit_conformal_calibrate; đối chiếuCQRvàSCPtrên miền bất đẳng phương sai; kiểm chứng cận hối tiếc \(O(1/T)\) củaadaptive_conformal_inferencekhi có trôi bước nhảy; và hiệu chuẩnconformal_factuality_prune. - Bài tập 6 (
15%— Khám nghiệm Pháp y Hệ thống Production):
Dùngprob_stats_labđể: (a) bắt và chẩn đoán caSRM50.35% / 49.65%quasrm_chisq_guard& Dirichlete-process; (b) khắc phục sai lệch SE2.59xcủa tỷ lệ cụm người dùng bằngdelta_method_ratio_test+ khoảng Fieller khi \(\operatorname{CV}(\bar{X}) > 0.1\); và (c) hóa giải đảo dấu LogNormal và tự tương quanAR(1)(\(\phi=0.85\)) bằngduan_smearing_meanvàbootstrap_ci(..., method="moving_block").
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 (Giới hạn Poisson, Schur MVN, Tích lũy họ hàm mũ, LoTV, CRLB, Wilson, Ville, e-BH, Đối xứng hạng SCP, Hối tiếc ACI); lõi tham chiếu prob_stats_lab thuần stdlib + NumPy/Pandas, qua rào chắn AST chỉ bảo mật và đạt 14/14 pytest; phân tích pháp y chính xác các lỗi SRM, DEFF, Fieller CV > 0.1, đảo dấu LogNormal, và thiếu phủ Conformal ngây thơ. |
| Senior Standard | 75–89% | Triển khai đúng thuần NumPy và vượt qua 14/14 kiểm thử, nhưng còn thiếu sót nhỏ ở chứng minh trường hợp đồng hạng trong SCP, quên dùng Decimal tránh lỗi ceil, thiếu lập luận chuẩn hóa Welch-\(t\) trong kiểm định hoán vị Behrens–Fisher, hoặc lý giải chưa sâu hiệu chuẩn ngoài MLRATE. |
| Needs Remediation | < 75% | Dùng scipy.stats, tính phương sai một lượt hoặc lấy \(\exp(\overline{\ln Y})\) làm trung bình số học, quy tâm CUPED riêng từng nhánh, nhìn trộm liên tục bằng \(p\)-value cố định, hoặc dùng np.quantile(..., 1 - alpha) cho dự báo Conformal. |
Type-I Error Under Sequential Peeking (alpha = 0.05)
Variance Reduction: Noise Overfit vs. Cross-Fitted Signal
Finite-Sample & High-Noise Stratum Coverage Audit (Target 90%)
Noisy-Tail 40-Class Conformal Average Set Size (alpha = 0.10)
Berry-Esseen CLT Bound vs. Empirical 95% Coverage
| dist_name | n | skewness | be_bound | empirical_coverage_95 |
|---|---|---|---|---|
| uniform | 10 | 0.0 | 0.195 | 0.948 |
| uniform | 30 | 0.0 | 0.1126 | 0.956 |
| uniform | 100 | 0.0 | 0.0617 | 0.964 |
| uniform | 1000 | 0.0 | 0.0195 | 0.96 |
| rare_bernoulli_p0.01 | 10 | 9.8494 | 1.0 | 0.072 |
| rare_bernoulli_p0.01 | 30 | 9.8494 | 0.854 | 0.24 |
| rare_bernoulli_p0.01 | 100 | 9.8494 | 0.4677 | 0.632 |
| rare_bernoulli_p0.01 | 1000 | 9.8494 | 0.1479 | 0.904 |
| lognormal_sigma1.2 | 10 | 11.1638 | 1.0 | 0.788 |
| lognormal_sigma1.2 | 30 | 11.1638 | 0.9754 | 0.848 |
| lognormal_sigma1.2 | 100 | 11.1638 | 0.5343 | 0.9 |
| lognormal_sigma1.2 | 1000 | 11.1638 | 0.169 | 0.94 |
A/B Variance Reduction, SRM & Ratio/LogNormal Forensic Audit
| estimator_or_metric | estimate | se | vr_or_inflation | status |
|---|---|---|---|---|
| srm_50.35_49.65 | 9.8 | 0.001745 | 23.21 | SRM_ALERT |
| clustered_delta_ratio | -0.00338 | 0.01467 | 3.25x_vs_naive | OK |
| cuped_pooled_noise_d100 | -0.0584 | 0.0865 | 21.8%_overfit | TRAP |
| mlrate_crossfit_noise_d100 | -0.0677 | 0.0978 | 0.1%_honest | OK |
| mlrate_crossfit_signal_d50 | 0.2969 | 0.0613 | 96.0%_VR | OK |
| lin_ancova2_hetero_p0.25 | 0.4377 | 0.0659 | 94.3%_VR | OK |
| lognormal_arith_vs_log | -4.8655 | 0.0966 | -31.7%_arith | INVERSION |
Sequential Peeking Guardrails & Multiple-Testing Control
| method | regime | fpr_or_fdr | rejections_or_threshold |
|---|---|---|---|
| fixed_1_look | n=1200 | 0.06 | z=1.960 |
| continuous_lil_naive | n_min..1200 | 0.42 | z=1.960_unsafe |
| continuous_msprt | tau_sq=0.04 | 0.032 | E_t>=20.0 |
| obrien_fleming_look1_look4 | 4_looks_alpha0.05 | 0.05 | 3.920->2.043 |
| bonferroni_m6 | FWER_m6 | 0.05 | 1 |
| holm_m6 | FWER_m6 | 0.05 | 2 |
| bh_fdr_m6 | FDR_m6 | 0.05 | 5 |
| ebh_arbitrary_dep | K=20_e_values | 0.05 | 4 |
Distribution-Free Conformal Prediction Suite (alpha = 0.10)
| method | regime | coverage | avg_width_or_size |
|---|---|---|---|
| scp_n10_naive | n_cal=10 | 0.8026 | under_covers |
| scp_n10_exact | n_cal=10 | 0.8977 | exact_rank_10 |
| scp_constant_high_noise | heteroscedastic_hi | 0.6883 | 5.371 |
| cqr_adaptive_high_noise | heteroscedastic_hi | 0.9028 | 5.166 |
| aps_40class | noisy_tail | 0.948 | 2.61 |
| raps_40class | noisy_tail | 0.943 | 1.625 |
| saps_40class | noisy_tail | 0.915 | 1.301 |
| aci_online_shift | 2.8x_scale_shift | 0.9 | regret<=0.035 |
| conformal_factuality | rag_claim_prune | 0.8825 | recall=0.974 |
02-track-1-data-science-and-ai/part-01-math-stats-and-causal/labs/ch03-probability-inference-and-testing-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "prob-stats-lab"
version = "0.1.0"
description = "Probability, Bayesian Conjugacy, SOTA Experimentation, and Distribution-Free Conformal Prediction Workbench (T1-P1-U03)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
]
[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.4"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
[tool.ruff]
line-length = 100
target-version = "py310"
"""Pure-Python stdlib + NumPy probability, inference, experimentation, and conformal prediction lab."""
from __future__ import annotations
from prob_stats_lab.conformal import (
ACIResult,
ConformalCalResult,
CQRResult,
SetPredictionResult,
adaptive_conformal_inference,
benchmark_conformal_suite,
calibrate_and_predict_sets,
conformal_classification_scores,
conformal_factuality_prune,
cqr_calibrate_and_predict,
fit_linear_spline_quantile_regressor,
split_conformal_calibrate,
)
from prob_stats_lab.distributions_and_bayes import (
CLTConvergenceRow,
ConjugatePosteriorResult,
DependenceProfile,
WelfordAccumulator,
benchmark_berry_esseen_clt,
beta_binomial_update,
betainc,
compute_dependence_profile,
dirichlet_categorical_update,
discrete_mutual_information,
gamma_poisson_negbin_logpmf,
gamma_poisson_update,
gammaincc,
log_sum_exp,
mahalanobis_sq,
mvn_schur_conditional,
norm_cdf,
norm_ppf,
norm_sf_two_sided,
normal_normal_update,
poisson_limit_tv_distance,
spearman_midrank_corr,
t_ppf_two_sided,
t_sf_two_sided,
)
from prob_stats_lab.inference_and_experimentation import (
CupedResult,
MSPRTResult,
MultipleTestingResult,
RatioTestResult,
SRMResult,
WelchTestResult,
benchmark_peeking_vs_msprt,
bootstrap_ci,
compute_mde_and_sample_size,
cuped_adjust,
delta_method_ratio_test,
duan_smearing_mean,
fieller_ratio_ci,
lognormal_inversion_demo,
mann_whitney_u_test,
msprt_confidence_sequence,
multiple_testing_control,
obrien_fleming_boundaries,
srm_chisq_guard,
studentized_permutation_test,
wald_interval,
welch_t_test,
wilson_score_interval,
)
__all__ = [
"ACIResult",
"CLTConvergenceRow",
"CQRResult",
"ConformalCalResult",
"ConjugatePosteriorResult",
"CupedResult",
"DependenceProfile",
"MSPRTResult",
"MultipleTestingResult",
"RatioTestResult",
"SRMResult",
"SetPredictionResult",
"WelchTestResult",
"WelfordAccumulator",
"adaptive_conformal_inference",
"benchmark_berry_esseen_clt",
"benchmark_conformal_suite",
"benchmark_peeking_vs_msprt",
"beta_binomial_update",
"betainc",
"bootstrap_ci",
"calibrate_and_predict_sets",
"compute_dependence_profile",
"compute_mde_and_sample_size",
"conformal_classification_scores",
"conformal_factuality_prune",
"cqr_calibrate_and_predict",
"cuped_adjust",
"delta_method_ratio_test",
"dirichlet_categorical_update",
"discrete_mutual_information",
"duan_smearing_mean",
"fieller_ratio_ci",
"fit_linear_spline_quantile_regressor",
"gamma_poisson_negbin_logpmf",
"gamma_poisson_update",
"gammaincc",
"log_sum_exp",
"lognormal_inversion_demo",
"mahalanobis_sq",
"mann_whitney_u_test",
"msprt_confidence_sequence",
"multiple_testing_control",
"mvn_schur_conditional",
"norm_cdf",
"norm_ppf",
"norm_sf_two_sided",
"normal_normal_update",
"obrien_fleming_boundaries",
"poisson_limit_tv_distance",
"spearman_midrank_corr",
"split_conformal_calibrate",
"srm_chisq_guard",
"studentized_permutation_test",
"t_ppf_two_sided",
"t_sf_two_sided",
"wald_interval",
"welch_t_test",
"wilson_score_interval",
]
"""Probability foundations, pure-stdlib special functions, conjugate Bayes, MVN, and CLT diagnostics."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import numpy as np
_SQRT2 = math.sqrt(2.0)
_SQRT2PI = math.sqrt(2.0 * math.pi)
_BE_CONSTANT = 0.4748 # Shevtsova (2011) Berry-Esseen constant
@dataclass(frozen=True, slots=True)
class ConjugatePosteriorResult:
"""Summary of an exact closed-form conjugate Bayesian posterior and predictive law."""
family: str
prior_params: dict[str, Any]
posterior_params: dict[str, Any]
posterior_mean: float | tuple[float, ...]
posterior_var: float | tuple[float, ...]
predictive_mean: float | tuple[float, ...]
predictive_var: float | tuple[float, ...]
credible_interval_95: tuple[float, float] | None
@dataclass(frozen=True, slots=True)
class DependenceProfile:
"""Comparison of linear Pearson, monotone Spearman midrank, and Mutual Information."""
pearson_r: float
spearman_rho: float
mutual_info_nats: float
@dataclass(frozen=True, slots=True)
class CLTConvergenceRow:
"""Single row in the Berry-Esseen finite-sample CLT convergence benchmark."""
dist_name: str
sample_size: int
skewness: float
berry_esseen_bound: float
empirical_ks_error: float
empirical_95_coverage: float
# ==============================================================================
# NUMERICAL STABILITY PRIMITIVES (LOG-SUM-EXP & WELFORD / CHAN)
# ==============================================================================
def log_sum_exp(log_vals: np.ndarray | list[float]) -> float:
"""Compute log(sum(exp(log_vals))) without float64 underflow or overflow."""
arr = np.asarray(log_vals, dtype=np.float64)
if arr.ndim != 1 or arr.size == 0:
raise ValueError("log_vals must be a non-empty 1D sequence.")
if np.any(np.isnan(arr)):
raise ValueError("log_vals must not contain NaN.")
if np.any(arr == math.inf):
return math.inf
m = float(np.max(arr))
if m == -math.inf:
return -math.inf
return m + math.log(float(np.sum(np.exp(arr - m))))
class WelfordAccumulator:
"""Single-pass online mean/variance accumulator with Chan et al. (1979) parallel merge."""
def __init__(self, count: int = 0, mean: float = 0.0, m2: float = 0.0) -> None:
if count < 0:
raise ValueError("count must be non-negative.")
self.count: int = int(count)
self.mean: float = float(mean)
self.m2: float = float(m2)
def update(self, x: float) -> None:
"""Incorporate a single finite scalar observation."""
val = float(x)
if not math.isfinite(val):
raise ValueError(f"Expected finite scalar observation, got {x}.")
self.count += 1
delta1 = val - self.mean
self.mean += delta1 / self.count
delta2 = val - self.mean
self.m2 += delta1 * delta2
def update_batch(self, arr: np.ndarray | list[float]) -> None:
"""Incorporate a 1D batch using centered batch moments merged via Chan's formula."""
b = np.asarray(arr, dtype=np.float64)
if b.ndim != 1:
raise ValueError("Batch input must be a 1D array.")
if b.size == 0:
return
if not np.all(np.isfinite(b)):
raise ValueError("Batch input must contain only finite numbers.")
n_b = int(b.size)
mean_b = float(np.mean(b))
centered = b - mean_b
m2_b = float(np.dot(centered, centered))
merged = self.merge(WelfordAccumulator(count=n_b, mean=mean_b, m2=m2_b))
self.count = merged.count
self.mean = merged.mean
self.m2 = merged.m2
def merge(self, other: WelfordAccumulator) -> WelfordAccumulator:
"""Merge two WelfordAccumulators via Chan's parallel variance identity."""
if self.count == 0:
return WelfordAccumulator(other.count, other.mean, other.m2)
if other.count == 0:
return WelfordAccumulator(self.count, self.mean, self.m2)
total = self.count + other.count
delta = other.mean - self.mean
new_mean = self.mean + delta * (other.count / total)
new_m2 = self.m2 + other.m2 + delta * delta * (self.count * other.count / total)
return WelfordAccumulator(count=total, mean=new_mean, m2=new_m2)
def variance(self, ddof: int = 1) -> float:
"""Return sample (ddof=1) or population (ddof=0) variance."""
if self.count <= ddof:
raise ValueError(f"Need count > ddof ({ddof}), got count={self.count}.")
return max(0.0, self.m2 / (self.count - ddof))
def std(self, ddof: int = 1) -> float:
"""Return sample or population standard deviation."""
return math.sqrt(self.variance(ddof=ddof))
# ==============================================================================
# PURE-STDLIB SPECIAL FUNCTIONS (ZERO SCIPY / SKLEARN)
# ==============================================================================
def norm_cdf(x: float) -> float:
"""Standard normal CDF accurate deep into the lower tail via math.erfc."""
val = float(x)
if math.isnan(val):
return float("nan")
return 0.5 * math.erfc(-val / _SQRT2)
def norm_sf_two_sided(abs_z: float) -> float:
"""Two-sided normal survival probability 2*(1 - Phi(|z|)) without 1 - erf cancellation."""
val = float(abs_z)
if math.isnan(val):
return float("nan")
if math.isinf(val):
return 0.0
return math.erfc(abs(val) / _SQRT2)
def norm_ppf(p: float) -> float:
"""Standard normal inverse CDF via Acklam minimax approximation + 1 Halley step."""
prob = float(p)
if math.isnan(prob):
return float("nan")
if not (0.0 < prob < 1.0):
if prob == 0.0:
return -math.inf
if prob == 1.0:
return math.inf
raise ValueError(f"p must lie in [0, 1], got {prob}.")
sign = 1.0
if prob > 0.5:
prob = 1.0 - prob
sign = -1.0
a = (
-3.969683028665376e01,
2.209460984245205e02,
-2.759285104469687e02,
1.383577518672690e02,
-3.066479806614716e01,
2.506628277459239e00,
)
b = (
-5.447609879822406e01,
1.615858368580409e02,
-1.556989798598866e02,
6.680131188771972e01,
-1.328068155288572e01,
)
c = (
-7.784894002430293e-03,
-3.223964580411365e-01,
-2.400758277161838e00,
-2.549732539343734e00,
4.374664141464968e00,
2.938163982698783e00,
)
d = (
7.784695709041462e-03,
3.224671290700398e-01,
2.445134137142996e00,
3.754408661907416e00,
)
if prob < 0.02425:
q = math.sqrt(-2.0 * math.log(prob))
x = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / (
(((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0
)
else:
q = prob - 0.5
r = q * q
x = (
(((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5])
* q
/ (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1.0)
)
if 0.5 * x * x < 700.0:
err = 0.5 * math.erfc(-x / _SQRT2) - prob
u = err * _SQRT2PI * math.exp(0.5 * x * x)
x = x - u / (1.0 + 0.5 * x * u)
return sign * x
def gammaincc(a: float, x: float, eps: float = 1e-14, max_iter: int = 2000) -> float:
"""Regularized upper incomplete gamma Q(a, x) via power series and Modified Lentz CF."""
if a <= 0.0:
raise ValueError(f"Shape parameter a must be > 0, got {a}.")
if x <= 0.0:
return 1.0
if math.isinf(x):
return 0.0
if a == 0.5:
return math.erfc(math.sqrt(x))
if a == 1.0:
return math.exp(-x)
log_prefactor = -x + a * math.log(x) - math.lgamma(a)
if log_prefactor < -745.0:
return 0.0 if x >= a + 1.0 else 1.0
if x < a + 1.0:
ap = a
term = 1.0 / a
total = term
for _ in range(max_iter):
ap += 1.0
term *= x / ap
total += term
if abs(term) <= abs(total) * eps:
break
return max(0.0, min(1.0, 1.0 - total * math.exp(log_prefactor)))
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b if abs(b) > tiny else 1.0 / tiny
h = d
for i in range(1, max_iter + 1):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) <= eps:
break
return max(0.0, min(1.0, h * math.exp(log_prefactor)))
def _betacf(a: float, b: float, x: float, eps: float = 1e-14, max_iter: int = 500) -> float:
"""Modified Lentz continued fraction for regularized incomplete beta."""
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < tiny:
d = tiny
d = 1.0 / d
h = d
for m in range(1, max_iter + 1):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < tiny:
d = tiny
c = 1.0 + aa / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < tiny:
d = tiny
c = 1.0 + aa / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) <= eps:
break
return h
def betainc(a: float, b: float, x: float, eps: float = 1e-14, max_iter: int = 500) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
if a <= 0.0 or b <= 0.0:
raise ValueError(f"Beta parameters must be > 0, got a={a}, b={b}.")
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
log_bt = (
math.lgamma(a + b)
- math.lgamma(a)
- math.lgamma(b)
+ a * math.log(x)
+ b * math.log(1.0 - x)
)
bt = 0.0 if log_bt < -745.0 else math.exp(log_bt)
if x < (a + 1.0) / (a + b + 2.0):
return max(0.0, min(1.0, bt * _betacf(a, b, x, eps=eps, max_iter=max_iter) / a))
return max(0.0, min(1.0, 1.0 - bt * _betacf(b, a, 1.0 - x, eps=eps, max_iter=max_iter) / b))
def t_sf_two_sided(t_val: float, df: float) -> float:
"""Exact two-sided Student's t survival probability P(|T_df| >= |t_val|)."""
if math.isnan(t_val) or math.isnan(df):
return float("nan")
if df <= 0.0:
raise ValueError(f"Degrees of freedom must be > 0, got {df}.")
if math.isinf(t_val):
return 0.0
if df > 1e7:
return norm_sf_two_sided(abs(t_val))
return betainc(0.5 * df, 0.5, df / (df + t_val * t_val))
def t_ppf_two_sided(alpha: float, df: float) -> float:
"""Compute positive critical t* > 0 such that P(|T_df| >= t*) = alpha."""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
if df <= 0.0:
raise ValueError(f"df must be > 0, got {df}.")
if df > 1e7:
return norm_ppf(1.0 - 0.5 * alpha)
lo = 0.0
hi = max(2.0, norm_ppf(1.0 - 0.5 * alpha))
while t_sf_two_sided(hi, df) > alpha:
hi *= 2.0
for _ in range(70):
mid = 0.5 * (lo + hi)
if t_sf_two_sided(mid, df) > alpha:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def _beta_ppf(q: float, a: float, b: float) -> float:
"""Invert Beta CDF via bisection on betainc(a, b, x)."""
lo, hi = 0.0, 1.0
for _ in range(64):
mid = 0.5 * (lo + hi)
if betainc(a, b, mid) < q:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def _gamma_ppf_rate(q: float, a: float, rate: float) -> float:
"""Invert Gamma(a, rate) CDF via bracket search + bisection on 1 - gammaincc(a, rate*x)."""
lo = 0.0
hi = max(1.0, (a / rate) + 6.0 * math.sqrt(a) / rate)
while (1.0 - gammaincc(a, rate * hi)) < q:
hi *= 2.0
for _ in range(64):
mid = 0.5 * (lo + hi)
if (1.0 - gammaincc(a, rate * mid)) < q:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
# ==============================================================================
# CONJUGATE BAYESIAN UPDATES & POSTERIOR PREDICTIVES
# ==============================================================================
def beta_binomial_update(
alpha0: float,
beta0: float,
successes: int,
trials: int,
future_m: int = 1,
) -> ConjugatePosteriorResult:
"""Beta-Binomial posterior and overdispersed m-trial Beta-Binomial predictive."""
if alpha0 <= 0.0 or beta0 <= 0.0:
raise ValueError("alpha0 and beta0 must be strictly positive.")
if trials < 0 or successes < 0 or successes > trials:
raise ValueError("Require 0 <= successes <= trials and trials >= 0.")
if future_m < 1:
raise ValueError("future_m must be >= 1.")
alpha_post = float(alpha0 + successes)
beta_post = float(beta0 + (trials - successes))
s_post = alpha_post + beta_post
post_mean = alpha_post / s_post
post_var = (alpha_post * beta_post) / (s_post * s_post * (s_post + 1.0))
pred_mean = float(future_m) * post_mean
pred_var = float(future_m) * (
alpha_post * beta_post * (s_post + future_m)
) / (s_post * s_post * (s_post + 1.0))
ci95 = (_beta_ppf(0.025, alpha_post, beta_post), _beta_ppf(0.975, alpha_post, beta_post))
return ConjugatePosteriorResult(
family="beta_binomial",
prior_params={"alpha0": float(alpha0), "beta0": float(beta0)},
posterior_params={
"alpha_post": alpha_post,
"beta_post": beta_post,
"successes": int(successes),
"trials": int(trials),
"future_m": int(future_m),
},
posterior_mean=post_mean,
posterior_var=post_var,
predictive_mean=pred_mean,
predictive_var=pred_var,
credible_interval_95=ci95,
)
def gamma_poisson_negbin_logpmf(k: int, alpha_post: float, beta_rate_post: float) -> float:
"""Log-space PMF of NegBin(r=alpha_post, p_stop=beta/(beta+1)) using math.lgamma."""
if k < 0:
raise ValueError(f"k must be >= 0, got {k}.")
if alpha_post <= 0.0 or beta_rate_post <= 0.0:
raise ValueError("alpha_post and beta_rate_post must be strictly positive.")
log_p_stop = (
math.log(beta_rate_post) - math.log(beta_rate_post + 1.0)
if beta_rate_post < 1.0
else -math.log1p(1.0 / beta_rate_post)
)
return (
math.lgamma(alpha_post + k)
- math.lgamma(k + 1)
- math.lgamma(alpha_post)
+ alpha_post * log_p_stop
- k * math.log1p(beta_rate_post)
)
def gamma_poisson_update(
alpha0: float,
beta0_rate: float,
counts: np.ndarray | list[int],
exposures: np.ndarray | list[float] | None = None,
) -> ConjugatePosteriorResult:
"""Gamma-Poisson conjugate update strictly in Shape-Rate (alpha, beta_rate) parameterization."""
if alpha0 <= 0.0 or beta0_rate <= 0.0:
raise ValueError("alpha0 and beta0_rate must be strictly positive.")
c_arr = np.asarray(counts, dtype=np.float64)
if c_arr.ndim != 1 or c_arr.size == 0 or not np.all(np.isfinite(c_arr)) or np.any(c_arr < 0.0):
raise ValueError("counts must be a non-empty 1D array of finite non-negative numbers.")
if exposures is None:
total_exposure = float(c_arr.size)
else:
e_arr = np.asarray(exposures, dtype=np.float64)
if e_arr.shape != c_arr.shape or not np.all(np.isfinite(e_arr)) or np.any(e_arr <= 0.0):
raise ValueError("exposures must match counts shape and be finite and > 0.")
total_exposure = float(np.sum(e_arr))
total_count = float(np.sum(c_arr))
alpha_post = float(alpha0 + total_count)
beta_rate_post = float(beta0_rate + total_exposure)
post_mean = alpha_post / beta_rate_post
post_var = alpha_post / (beta_rate_post * beta_rate_post)
# Single-unit predictive: NegBin(r=alpha_post, p_stop=beta/(beta+1))
pred_mean = post_mean
pred_var = pred_mean * (1.0 + 1.0 / beta_rate_post)
ci95 = (
_gamma_ppf_rate(0.025, alpha_post, beta_rate_post),
_gamma_ppf_rate(0.975, alpha_post, beta_rate_post),
)
return ConjugatePosteriorResult(
family="gamma_poisson_shape_rate",
prior_params={"alpha0": float(alpha0), "beta0_rate": float(beta0_rate)},
posterior_params={
"alpha_post": alpha_post,
"beta_rate_post": beta_rate_post,
"total_count": total_count,
"total_exposure": total_exposure,
"negbin_p_stop": beta_rate_post / (beta_rate_post + 1.0),
},
posterior_mean=post_mean,
posterior_var=post_var,
predictive_mean=pred_mean,
predictive_var=pred_var,
credible_interval_95=ci95,
)
def dirichlet_categorical_update(
alpha0: np.ndarray | list[float],
counts: np.ndarray | list[int],
) -> ConjugatePosteriorResult:
"""Dirichlet-Categorical posterior and predictive probabilities (Laplace/Jeffreys smoothing)."""
a0 = np.asarray(alpha0, dtype=np.float64)
cnt = np.asarray(counts, dtype=np.float64)
if a0.ndim != 1 or cnt.ndim != 1 or a0.size != cnt.size or a0.size < 2:
raise ValueError("alpha0 and counts must be 1D arrays of equal length >= 2.")
if not (np.all(np.isfinite(a0)) and np.all(a0 > 0.0)):
raise ValueError("alpha0 entries must be finite and > 0.")
if not (np.all(np.isfinite(cnt)) and np.all(cnt >= 0.0)):
raise ValueError("counts entries must be finite and >= 0.")
a_post = a0 + cnt
a_sum = float(np.sum(a_post))
probs = a_post / a_sum
post_mean = tuple(float(p) for p in probs)
post_var = tuple(
float(a * (a_sum - a) / (a_sum * a_sum * (a_sum + 1.0))) for a in a_post
)
pred_var = tuple(float(p * (1.0 - p)) for p in probs)
return ConjugatePosteriorResult(
family="dirichlet_categorical",
prior_params={"alpha0": [float(v) for v in a0]},
posterior_params={
"alpha_post": [float(v) for v in a_post],
"alpha_sum": a_sum,
"total_count": round(float(np.sum(cnt))),
},
posterior_mean=post_mean,
posterior_var=post_var,
predictive_mean=post_mean,
predictive_var=pred_var,
credible_interval_95=None,
)
def normal_normal_update(
mu0: float,
sigma0_sq: float,
obs: np.ndarray | list[float],
obs_var: float,
) -> ConjugatePosteriorResult:
"""Precision-additive Normal-Normal conjugate update separating epistemic & aleatoric var."""
if sigma0_sq <= 0.0 or obs_var <= 0.0:
raise ValueError("sigma0_sq and obs_var must be strictly positive.")
arr = np.asarray(obs, dtype=np.float64)
if arr.ndim != 1 or arr.size == 0 or not np.all(np.isfinite(arr)):
raise ValueError("obs must be a non-empty 1D array of finite observations.")
tau0 = 1.0 / float(sigma0_sq)
tau_obs = 1.0 / float(obs_var)
n = arr.size
x_bar = float(np.mean(arr))
tau_post = tau0 + n * tau_obs
post_var = 1.0 / tau_post
post_mean = (tau0 * float(mu0) + n * tau_obs * x_bar) / tau_post
pred_var = post_var + float(obs_var)
half = norm_ppf(0.975) * math.sqrt(post_var)
return ConjugatePosteriorResult(
family="normal_normal",
prior_params={"mu0": float(mu0), "sigma0_sq": float(sigma0_sq), "tau_prec0": tau0},
posterior_params={
"mu_post": post_mean,
"sigma_post_sq": post_var,
"tau_prec_post": tau_post,
"tau_prec_obs": tau_obs,
"n": int(n),
"sample_mean": x_bar,
},
posterior_mean=post_mean,
posterior_var=post_var,
predictive_mean=post_mean,
predictive_var=pred_var,
credible_interval_95=(post_mean - half, post_mean + half),
)
# ==============================================================================
# MVN SCHUR CONDITIONING, MAHALANOBIS DISTANCE & POISSON LIMIT TV
# ==============================================================================
def mvn_schur_conditional(
mu: np.ndarray,
cov: np.ndarray,
observed_idx: list[int] | np.ndarray,
observed_vals: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute MVN conditional (mu_cond, cov_cond, precision_subblock_inv) via Schur complement
and verify parity with the precision-matrix dual Lambda_11^{-1}.
"""
mu_arr = np.asarray(mu, dtype=np.float64)
cov_arr = np.asarray(cov, dtype=np.float64)
obs_idx = np.asarray(observed_idx, dtype=np.int64)
obs_v = np.asarray(observed_vals, dtype=np.float64)
d = mu_arr.shape[0]
if mu_arr.ndim != 1 or cov_arr.shape != (d, d):
raise ValueError("mu must be (d,) and cov must be (d, d).")
if obs_idx.ndim != 1 or obs_idx.size == 0 or obs_idx.size >= d:
raise ValueError("observed_idx must select a strict non-empty subset of coordinates.")
if np.unique(obs_idx).size != obs_idx.size or np.any(obs_idx < 0) or np.any(obs_idx >= d):
raise ValueError("observed_idx contains invalid or duplicate indices.")
if obs_v.shape != obs_idx.shape:
raise ValueError("observed_vals shape must match observed_idx.")
obs_set = set(obs_idx.tolist())
unobs_idx = np.array([i for i in range(d) if i not in obs_set], dtype=np.int64)
mu_1 = mu_arr[unobs_idx]
mu_2 = mu_arr[obs_idx]
cov_11 = cov_arr[np.ix_(unobs_idx, unobs_idx)]
cov_12 = cov_arr[np.ix_(unobs_idx, obs_idx)]
cov_22 = cov_arr[np.ix_(obs_idx, obs_idx)]
# Schur complement via Cholesky solve on cov_22
l22 = np.linalg.cholesky(cov_22)
z22 = np.linalg.solve(l22, cov_12.T)
gain_t = np.linalg.solve(l22.T, z22) # cov_22^{-1} cov_21
gain = gain_t.T
mu_cond = mu_1 + gain @ (obs_v - mu_2)
cov_cond = cov_11 - gain @ cov_12.T
cov_cond = 0.5 * (cov_cond + cov_cond.T)
# Precision dual: Lambda = Sigma^{-1}, check Lambda_11^{-1}
l_full = np.linalg.cholesky(cov_arr)
eye_d = np.eye(d, dtype=np.float64)
inv_l = np.linalg.solve(l_full, eye_d)
precision_full = inv_l.T @ inv_l
lambda_11 = precision_full[np.ix_(unobs_idx, unobs_idx)]
l_lam = np.linalg.cholesky(lambda_11)
inv_l_lam = np.linalg.solve(l_lam, np.eye(unobs_idx.size, dtype=np.float64))
precision_subblock_inv = inv_l_lam.T @ inv_l_lam
precision_subblock_inv = 0.5 * (precision_subblock_inv + precision_subblock_inv.T)
return mu_cond, cov_cond, precision_subblock_inv
def mahalanobis_sq(X: np.ndarray, mu: np.ndarray, cov: np.ndarray) -> np.ndarray:
"""Compute squared Mahalanobis distance (x - mu)^T Sigma^{-1} (x - mu) via Cholesky solve."""
x_arr = np.asarray(X, dtype=np.float64)
mu_arr = np.asarray(mu, dtype=np.float64)
cov_arr = np.asarray(cov, dtype=np.float64)
d = mu_arr.shape[0]
if cov_arr.shape != (d, d):
raise ValueError("cov must be square (d, d) matching mu.")
l_chol = np.linalg.cholesky(cov_arr)
if x_arr.ndim == 1:
if x_arr.shape[0] != d:
raise ValueError("1D X length must match d.")
z = np.linalg.solve(l_chol, x_arr - mu_arr)
return np.asarray(float(np.dot(z, z)), dtype=np.float64)
if x_arr.ndim != 2 or x_arr.shape[1] != d:
raise ValueError("X must have shape (n, d) or (d,).")
diff = (x_arr - mu_arr).T
z = np.linalg.solve(l_chol, diff)
return np.sum(z * z, axis=0)
def poisson_limit_tv_distance(lam: float, n: int) -> float:
"""Total variation distance 0.5 * sum_k |P_Bin(n, lam/n)(k) - P_Pois(lam)(k)| in log space."""
if lam <= 0.0 or n < 1:
raise ValueError("lam must be > 0 and n >= 1.")
p = lam / float(n)
if p > 1.0:
raise ValueError("Require lam <= n so p = lam/n <= 1.")
if p == 1.0:
# Binomial(n, 1) puts all mass on k = n
log_pois_n = n * math.log(lam) - lam - math.lgamma(n + 1)
return 1.0 - math.exp(log_pois_n)
k_max = max(n, math.ceil(lam + 12.0 * math.sqrt(lam) + 30.0))
log_p = math.log(p)
log_1mp = math.log1p(-p)
log_lam = math.log(lam)
lgamma_n1 = math.lgamma(n + 1)
l1_sum = 0.0
pois_mass_sum = 0.0
for k in range(k_max + 1):
lg_k1 = math.lgamma(k + 1)
p_pois = math.exp(k * log_lam - lam - lg_k1)
pois_mass_sum += p_pois
if k <= n:
log_bin = lgamma_n1 - lg_k1 - math.lgamma(n - k + 1) + k * log_p + (n - k) * log_1mp
p_bin = math.exp(log_bin)
else:
p_bin = 0.0
l1_sum += abs(p_bin - p_pois)
# Account for negligible Poisson tail beyond k_max
l1_sum += max(0.0, 1.0 - pois_mass_sum)
return 0.5 * l1_sum
# ==============================================================================
# DEPENDENCE MEASURES (PEARSON, MIDRANK SPEARMAN, MUTUAL INFORMATION)
# ==============================================================================
def _average_midranks(arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Compute 1-based fractional midranks and tie group sizes."""
_, inv, counts = np.unique(arr, return_inverse=True, return_counts=True)
cum = np.cumsum(counts, dtype=np.float64)
starts = cum - counts.astype(np.float64) + 1.0
midranks = 0.5 * (starts + cum)
return midranks[inv], counts
def _pearson_corr(x: np.ndarray, y: np.ndarray) -> float:
xc = x - float(np.mean(x))
yc = y - float(np.mean(y))
denom = math.sqrt(float(np.dot(xc, xc)) * float(np.dot(yc, yc)))
if denom <= 1e-18:
return 0.0
return max(-1.0, min(1.0, float(np.dot(xc, yc)) / denom))
def spearman_midrank_corr(x: np.ndarray | list[float], y: np.ndarray | list[float]) -> float:
"""Tie-aware Spearman rank correlation computed as Pearson correlation of fractional midranks."""
xa = np.asarray(x, dtype=np.float64)
ya = np.asarray(y, dtype=np.float64)
if xa.ndim != 1 or ya.ndim != 1 or xa.size != ya.size or xa.size < 2:
raise ValueError("x and y must be 1D arrays of equal length >= 2.")
if not (np.all(np.isfinite(xa)) and np.all(np.isfinite(ya))):
raise ValueError("x and y must be finite.")
rx, _ = _average_midranks(xa)
ry, _ = _average_midranks(ya)
return _pearson_corr(rx, ry)
def _bin_values(arr: np.ndarray, n_bins: int, force_discrete: bool) -> tuple[np.ndarray, int]:
uniq = np.unique(arr)
if force_discrete or uniq.size <= n_bins:
_, inv = np.unique(arr, return_inverse=True)
return inv, int(uniq.size)
edges = np.quantile(arr, np.linspace(0.0, 1.0, n_bins + 1))
edges = np.unique(edges)
if edges.size <= 2:
edges = np.linspace(float(np.min(arr)), float(np.max(arr)), n_bins + 1)
if edges.size <= 2 or np.allclose(edges[0], edges[-1]):
return np.zeros(arr.size, dtype=np.int64), 1
labels = np.digitize(arr, edges[1:-1], right=False)
return labels, int(edges.size - 1)
def discrete_mutual_information(
x: np.ndarray | list[float],
y: np.ndarray | list[float],
n_bins: int = 8,
is_discrete: bool = False,
) -> float:
"""Empirical mutual information I(X; Y) in nats over discrete states or quantile bins."""
xa = np.asarray(x, dtype=np.float64)
ya = np.asarray(y, dtype=np.float64)
if xa.ndim != 1 or ya.ndim != 1 or xa.size != ya.size or xa.size < 2:
raise ValueError("x and y must be 1D arrays of equal length >= 2.")
if n_bins < 2:
raise ValueError("n_bins must be >= 2.")
bx, nx = _bin_values(xa, n_bins=n_bins, force_discrete=is_discrete)
by, ny = _bin_values(ya, n_bins=n_bins, force_discrete=is_discrete)
joint = np.zeros((nx, ny), dtype=np.float64)
np.add.at(joint, (bx, by), 1.0)
pxy = joint / float(xa.size)
px = pxy.sum(axis=1, keepdims=True)
py = pxy.sum(axis=0, keepdims=True)
mask = pxy > 0.0
prod = px @ py
mi = float(np.sum(pxy[mask] * np.log(pxy[mask] / prod[mask])))
return max(0.0, mi)
def compute_dependence_profile(
x: np.ndarray | list[float],
y: np.ndarray | list[float],
n_bins: int = 8,
is_discrete_y: bool = False,
) -> DependenceProfile:
"""Compute Pearson, tie-aware Spearman midrank, and Mutual Information dependence metrics."""
xa = np.asarray(x, dtype=np.float64)
ya = np.asarray(y, dtype=np.float64)
if xa.ndim != 1 or ya.ndim != 1 or xa.size != ya.size or xa.size < 2:
raise ValueError("x and y must be 1D arrays of equal length >= 2.")
pearson_r = _pearson_corr(xa, ya)
spearman_rho = spearman_midrank_corr(xa, ya)
bx, nx = _bin_values(xa, n_bins=n_bins, force_discrete=False)
by, ny = _bin_values(ya, n_bins=n_bins, force_discrete=is_discrete_y)
joint = np.zeros((nx, ny), dtype=np.float64)
np.add.at(joint, (bx, by), 1.0)
pxy = joint / float(xa.size)
px = pxy.sum(axis=1, keepdims=True)
py = pxy.sum(axis=0, keepdims=True)
mask = pxy > 0.0
mi = max(0.0, float(np.sum(pxy[mask] * np.log(pxy[mask] / (px @ py)[mask]))))
return DependenceProfile(pearson_r=pearson_r, spearman_rho=spearman_rho, mutual_info_nats=mi)
# ==============================================================================
# BERRY-ESSEEN & FINITE-SAMPLE CLT CONVERGENCE BENCHMARK
# ==============================================================================
def _lognormal_abs_third_central_moment(sigma_z: float) -> float:
"""Exact E[|exp(Z) - mu|^3] for Z ~ N(0, sigma_z^2)."""
s2 = sigma_z * sigma_z
mu = math.exp(0.5 * s2)
a = 0.5 * s2 # log(mu)
def _trunc_moment(k: int) -> float:
return math.exp(0.5 * (k * k) * s2) * norm_cdf(a / sigma_z - k * sigma_z)
e_x1 = mu
e_x2 = math.exp(2.0 * s2)
e_x3 = math.exp(4.5 * s2)
e_cube = e_x3 - 3.0 * mu * e_x2 + 3.0 * (mu * mu) * e_x1 - (mu ** 3)
e_neg_part = (
(mu ** 3) * _trunc_moment(0)
- 3.0 * (mu ** 2) * _trunc_moment(1)
+ 3.0 * mu * _trunc_moment(2)
- _trunc_moment(3)
)
return float(e_cube + 2.0 * e_neg_part)
def benchmark_berry_esseen_clt(
n_grid: tuple[int, ...] = (10, 30, 100, 1000),
n_mc: int = 1000,
seed: int = 42,
) -> list[CLTConvergenceRow]:
"""
Benchmark finite-sample CLT KS distance and 95% Student-t CI coverage across
Uniform(0,1), rare Bernoulli(0.01), and heavy-tailed LogNormal(0, 1.2^2).
"""
if n_mc < 20:
raise ValueError("n_mc must be >= 20.")
rng = np.random.default_rng(seed)
p_rare = 0.01
sig_ln = 1.2
s2_ln = sig_ln * sig_ln
mu_ln = math.exp(0.5 * s2_ln)
var_ln = (math.exp(s2_ln) - 1.0) * math.exp(s2_ln)
sd_ln = math.sqrt(var_ln)
skew_ln = (math.exp(s2_ln) + 2.0) * math.sqrt(math.exp(s2_ln) - 1.0)
mu3_abs_ln = _lognormal_abs_third_central_moment(sig_ln)
specs: list[tuple[str, float, float, float, float]] = [
(
"uniform",
0.5,
1.0 / math.sqrt(12.0),
0.0,
(3.0 * math.sqrt(3.0)) / 4.0, # mu3_abs / sigma^3
),
(
"rare_bernoulli_p0.01",
p_rare,
math.sqrt(p_rare * (1.0 - p_rare)),
(1.0 - 2.0 * p_rare) / math.sqrt(p_rare * (1.0 - p_rare)),
(p_rare ** 2 + (1.0 - p_rare) ** 2) / math.sqrt(p_rare * (1.0 - p_rare)),
),
(
"lognormal_sigma1.2",
mu_ln,
sd_ln,
skew_ln,
mu3_abs_ln / (sd_ln ** 3),
),
]
rows: list[CLTConvergenceRow] = []
ecdf_hi = np.arange(1, n_mc + 1, dtype=np.float64) / float(n_mc)
ecdf_lo = np.arange(0, n_mc, dtype=np.float64) / float(n_mc)
for dist_name, mu_true, sd_true, skew, lyapunov_ratio in specs:
for n in n_grid:
if n < 2:
raise ValueError("All sample sizes in n_grid must be >= 2.")
if dist_name == "uniform":
samples = rng.uniform(0.0, 1.0, size=(n_mc, n))
elif dist_name == "rare_bernoulli_p0.01":
samples = (rng.random((n_mc, n)) < p_rare).astype(np.float64)
else:
samples = np.exp(rng.normal(0.0, sig_ln, size=(n_mc, n)))
means = np.mean(samples, axis=1)
sds = np.std(samples, axis=1, ddof=1)
z_scores = math.sqrt(float(n)) * (means - mu_true) / sd_true
z_sorted = np.sort(z_scores)
phi_vals = np.array([norm_cdf(float(z)) for z in z_sorted], dtype=np.float64)
ks_err = float(
max(
np.max(np.abs(phi_vals - ecdf_hi)),
np.max(np.abs(phi_vals - ecdf_lo)),
)
)
t_crit = t_ppf_two_sided(0.05, float(n - 1))
half_widths = t_crit * (sds / math.sqrt(float(n)))
covered = (means - half_widths <= mu_true) & (mu_true <= means + half_widths)
cov_95 = float(np.mean(covered))
be_bound = min(1.0, _BE_CONSTANT * lyapunov_ratio / math.sqrt(float(n)))
rows.append(
CLTConvergenceRow(
dist_name=dist_name,
sample_size=int(n),
skewness=float(skew),
berry_esseen_bound=float(be_bound),
empirical_ks_error=ks_err,
empirical_95_coverage=cov_95,
)
)
return rows
"""Hypothesis testing, SRM guards, variance reduction (CUPED/Lin/MLRATE), Delta/Fieller, mSPRT, and FDR."""
from __future__ import annotations
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import numpy as np
from prob_stats_lab.distributions_and_bayes import (
WelfordAccumulator,
_average_midranks,
gammaincc,
norm_cdf,
norm_ppf,
norm_sf_two_sided,
t_ppf_two_sided,
t_sf_two_sided,
)
@dataclass(frozen=True, slots=True)
class WelchTestResult:
"""Two-sample Welch t-test output with Welford moments and Satterthwaite degrees of freedom."""
mean_ctrl: float
mean_trt: float
diff: float
se: float
t_stat: float
df_welch: float
p_value: float
ci: tuple[float, float]
@dataclass(frozen=True, slots=True)
class SRMResult:
"""Sample Ratio Mismatch (SRM) Pearson chi-square guard + optional Dirichlet e-value."""
srm_detected: bool
chi2_stat: float
p_value: float
df: int
total_n: int | float
observed_ratios: tuple[float, ...]
alpha: float
e_value_dirichlet: float | None
@dataclass(frozen=True, slots=True)
class CupedResult:
"""Variance reduction result for CUPED, Lin's interacted ANCOVA2, or Cross-Fitted MLRATE."""
mode: str
ate_raw: float
se_raw: float
p_raw: float
ate_adj: float
se_adj: float
p_adj: float
theta_outer: float
variance_reduction: float
effective_sample_multiplier: float
y_adjusted: np.ndarray
@dataclass(frozen=True, slots=True)
class RatioTestResult:
"""Cluster-aggregated Delta Method ratio test with Fieller confidence-set diagnostics."""
rate_ctrl: float
rate_trt: float
diff: float
rel_lift: float
se: float
z_stat: float
p_value_z: float
df_welch: float
p_value_welch: float
ci_delta: tuple[float, float]
ci_fieller_ctrl: tuple[float, float]
ci_fieller_trt: tuple[float, float]
fieller_unbounded: bool
max_denom_cv: float
@dataclass(frozen=True, slots=True)
class MSPRTResult:
"""Mixture SPRT anytime-valid confidence sequence, e-value, and running anytime p-value."""
cs_lower: np.ndarray | float
cs_upper: np.ndarray | float
half_width: np.ndarray | float
log_e_value: np.ndarray | float
e_value: np.ndarray | float
always_valid_p: np.ndarray | float
reject: np.ndarray | bool
@dataclass(frozen=True, slots=True)
class MultipleTestingResult:
"""Multiplicity control output across Bonferroni, Holm, BH, BY, or Wang-Ramdas e-BH."""
method: str
rejected: np.ndarray
adjusted_values: np.ndarray
n_rejected: int
# ==============================================================================
# 1. PROPORTION INTERVALS, MDE & CLASSICAL / NONPARAMETRIC TESTS
# ==============================================================================
def wald_interval(k: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
"""Naive Wald binomial confidence interval (demonstrates boundary collapse & overshoot)."""
if n < 1 or k < 0 or k > n:
raise ValueError("Require n >= 1 and 0 <= k <= n.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
p_hat = float(k) / float(n)
z = norm_ppf(1.0 - 0.5 * alpha)
se = math.sqrt(p_hat * (1.0 - p_hat) / float(n))
return (p_hat - z * se, p_hat + z * se)
def wilson_score_interval(k: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
"""Exact Wilson (1927) score-inversion binomial confidence interval strictly inside [0, 1]."""
if n < 1 or k < 0 or k > n:
raise ValueError("Require n >= 1 and 0 <= k <= n.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
p_hat = float(k) / float(n)
z = norm_ppf(1.0 - 0.5 * alpha)
z2 = z * z
nf = float(n)
denom = 1.0 + z2 / nf
center = (p_hat + z2 / (2.0 * nf)) / denom
margin = (z * math.sqrt(p_hat * (1.0 - p_hat) / nf + z2 / (4.0 * nf * nf))) / denom
return (max(0.0, center - margin), min(1.0, center + margin))
def compute_mde_and_sample_size(
var_ctrl: float,
var_trt: float,
delta: float | None = None,
n_per_arm: int | None = None,
alpha: float = 0.05,
power: float = 0.80,
) -> dict[str, float]:
"""Compute required per-arm sample size from target delta OR MDE from fixed n_per_arm."""
if var_ctrl < 0.0 or var_trt < 0.0 or (var_ctrl + var_trt) <= 0.0:
raise ValueError("Arm variances must be non-negative with positive sum.")
if not (0.0 < alpha < 1.0) or not (0.0 < power < 1.0):
raise ValueError("alpha and power must lie in (0, 1).")
if (delta is None) == (n_per_arm is None):
raise ValueError("Provide exactly one of delta or n_per_arm.")
z_alpha = norm_ppf(1.0 - 0.5 * alpha)
z_beta = norm_ppf(power)
z_sum = z_alpha + z_beta
total_var = float(var_ctrl) + float(var_trt)
if delta is not None:
abs_d = abs(float(delta))
if abs_d <= 0.0:
raise ValueError("delta must be non-zero.")
n_req = float(math.ceil((z_sum * z_sum * total_var) / (abs_d * abs_d)))
mde_val = abs_d
else:
assert n_per_arm is not None
if n_per_arm < 2:
raise ValueError("n_per_arm must be >= 2.")
n_req = float(n_per_arm)
mde_val = z_sum * math.sqrt(total_var / n_req)
return {
"n_per_arm": n_req,
"total_n": 2.0 * n_req,
"mde": mde_val,
"z_alpha": z_alpha,
"z_beta": z_beta,
"alpha": float(alpha),
"power": float(power),
}
def welch_t_test(
ctrl: np.ndarray | list[float],
trt: np.ndarray | list[float],
alpha: float = 0.05,
) -> WelchTestResult:
"""Two-sample Welch t-test using Welford moments and Welch-Satterthwaite degrees of freedom."""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
c_arr = np.asarray(ctrl, dtype=np.float64)
t_arr = np.asarray(trt, dtype=np.float64)
if c_arr.ndim != 1 or t_arr.ndim != 1 or c_arr.size < 2 or t_arr.size < 2:
raise ValueError("ctrl and trt must be 1D arrays of length >= 2.")
if not (np.all(np.isfinite(c_arr)) and np.all(np.isfinite(t_arr))):
raise ValueError("ctrl and trt must contain finite values.")
acc_c = WelfordAccumulator()
acc_c.update_batch(c_arr)
acc_t = WelfordAccumulator()
acc_t.update_batch(t_arr)
vc = acc_c.variance(ddof=1)
vt = acc_t.variance(ddof=1)
nc = float(acc_c.count)
nt = float(acc_t.count)
vc_n = vc / nc
vt_n = vt / nt
se_sq = vc_n + vt_n
se = math.sqrt(se_sq)
diff = acc_t.mean - acc_c.mean
if se <= 0.0:
df_welch = float(acc_c.count + acc_t.count - 2)
if diff == 0.0:
t_stat = 0.0
p_val = 1.0
else:
t_stat = math.copysign(math.inf, diff)
p_val = 0.0
ci = (diff, diff)
else:
t_stat = diff / se
denom = (vc_n * vc_n) / (nc - 1.0) + (vt_n * vt_n) / (nt - 1.0)
df_welch = (se_sq * se_sq) / denom if denom > 0.0 else float(acc_c.count + acc_t.count - 2)
p_val = t_sf_two_sided(t_stat, df_welch)
t_crit = t_ppf_two_sided(alpha, df_welch)
ci = (diff - t_crit * se, diff + t_crit * se)
return WelchTestResult(
mean_ctrl=acc_c.mean,
mean_trt=acc_t.mean,
diff=diff,
se=se,
t_stat=t_stat,
df_welch=df_welch,
p_value=p_val,
ci=ci,
)
def mann_whitney_u_test(
x: np.ndarray | list[float],
y: np.ndarray | list[float],
continuity_correction: bool = True,
) -> dict[str, float]:
"""Two-sided Mann-Whitney U test with exact fractional midranks and tie-corrected variance."""
xa = np.asarray(x, dtype=np.float64)
ya = np.asarray(y, dtype=np.float64)
if xa.ndim != 1 or ya.ndim != 1 or xa.size < 1 or ya.size < 1:
raise ValueError("x and y must be non-empty 1D arrays.")
if not (np.all(np.isfinite(xa)) and np.all(np.isfinite(ya))):
raise ValueError("x and y must contain finite numbers.")
n1, n2 = xa.size, ya.size
n_tot = n1 + n2
pooled = np.concatenate([xa, ya])
ranks, tie_counts = _average_midranks(pooled)
r_sum1 = float(np.sum(ranks[:n1]))
u1 = r_sum1 - 0.5 * n1 * (n1 + 1)
u2 = float(n1 * n2) - u1
concordance = u1 / float(n1 * n2)
mu_u = 0.5 * n1 * n2
tc = tie_counts.astype(np.float64)
tie_term = float(np.sum(tc ** 3 - tc))
if n_tot <= 1:
sigma_u_sq = 0.0
else:
sigma_u_sq = (float(n1 * n2) / 12.0) * (
(n_tot + 1.0) - tie_term / float(n_tot * (n_tot - 1))
)
if sigma_u_sq <= 0.0:
return {
"u1": u1,
"u2": u2,
"concordance": concordance,
"z_stat": 0.0,
"p_value": 1.0,
"mu_u": mu_u,
"sigma_u": 0.0,
}
sigma_u = math.sqrt(sigma_u_sq)
diff = u1 - mu_u
cc = 0.5 * math.copysign(1.0, diff) if (continuity_correction and diff != 0.0) else 0.0
z_stat = (diff - cc) / sigma_u
p_val = norm_sf_two_sided(abs(z_stat))
return {
"u1": u1,
"u2": u2,
"concordance": concordance,
"z_stat": z_stat,
"p_value": p_val,
"mu_u": mu_u,
"sigma_u": sigma_u,
}
def studentized_permutation_test(
ctrl: np.ndarray | list[float],
trt: np.ndarray | list[float],
n_perm: int = 1000,
seed: int = 42,
) -> dict[str, float]:
"""
Behrens-Fisher robust studentized permutation test using Welch's t statistic
and Phipson & Smyth (2010) exact finite-sample formula (1 + count) / (B + 1).
"""
if n_perm < 1:
raise ValueError("n_perm must be >= 1.")
c_arr = np.asarray(ctrl, dtype=np.float64)
t_arr = np.asarray(trt, dtype=np.float64)
if c_arr.ndim != 1 or t_arr.ndim != 1 or c_arr.size < 2 or t_arr.size < 2:
raise ValueError("ctrl and trt must be 1D arrays of length >= 2.")
if not (np.all(np.isfinite(c_arr)) and np.all(np.isfinite(t_arr))):
raise ValueError("ctrl and trt must contain finite values.")
obs_res = welch_t_test(c_arr, t_arr)
t_obs = obs_res.t_stat
if math.isinf(t_obs):
abs_t_obs = math.inf
else:
abs_t_obs = abs(t_obs)
nc = c_arr.size
nt = t_arr.size
n_tot = nc + nt
pooled = np.concatenate([c_arr, t_arr])
rng = np.random.default_rng(seed)
batch_size = min(n_perm, 500)
n_extreme = 0
done = 0
while done < n_perm:
cur = min(batch_size, n_perm - done)
keys = rng.random((cur, n_tot))
part = np.argpartition(keys, nc, axis=1)
gc = pooled[part[:, :nc]]
gt = pooled[part[:, nc:]]
mc = np.mean(gc, axis=1)
mt = np.mean(gt, axis=1)
vc = np.var(gc, axis=1, ddof=1)
vt = np.var(gt, axis=1, ddof=1)
se = np.sqrt(vc / float(nc) + vt / float(nt))
diff = mt - mc
with np.errstate(divide="ignore", invalid="ignore"):
t_perm = np.where(se > 0.0, diff / se, np.where(diff == 0.0, 0.0, np.inf))
if math.isinf(abs_t_obs):
n_extreme += int(np.sum(np.isinf(t_perm)))
else:
n_extreme += int(np.sum(np.abs(t_perm) >= abs_t_obs - 1e-12))
done += cur
p_val = float(1 + n_extreme) / float(n_perm + 1)
return {
"t_obs": float(t_obs),
"p_value": p_val,
"n_perm": float(n_perm),
"n_extreme": float(n_extreme),
}
def bootstrap_ci(
data: np.ndarray | list[float],
stat_fn: Callable[[np.ndarray], float],
method: str = "bca",
n_boot: int = 1000,
alpha: float = 0.05,
block_len: int | None = None,
seed: int = 42,
) -> dict[str, Any]:
"""
Bootstrap confidence intervals supporting 'percentile', 'basic' (pivotal reflection),
'bca' (bias-corrected & accelerated), and 'moving_block' for autocorrelated series.
"""
valid_methods = {"percentile", "basic", "bca", "moving_block"}
if method not in valid_methods:
raise ValueError(f"method must be one of {sorted(valid_methods)}, got {method}.")
if n_boot < 10:
raise ValueError("n_boot must be >= 10.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
arr = np.asarray(data, dtype=np.float64)
if arr.ndim != 1 or arr.size < 2 or not np.all(np.isfinite(arr)):
raise ValueError("data must be a finite 1D array of length >= 2.")
n = arr.size
theta_hat = float(stat_fn(arr))
rng = np.random.default_rng(seed)
if method == "moving_block":
blk = max(1, round(n ** (1.0 / 3.0))) if block_len is None else int(block_len)
blk = min(max(1, blk), n)
n_blocks = math.ceil(n / blk)
boot_stats = np.empty(n_boot, dtype=np.float64)
offsets = np.arange(blk, dtype=np.int64)[None, :]
for b in range(n_boot):
starts = rng.integers(0, n, size=n_blocks)[:, None]
idx = ((starts + offsets) % n).ravel()[:n]
boot_stats[b] = float(stat_fn(arr[idx]))
else:
boot_stats = np.empty(n_boot, dtype=np.float64)
for b in range(n_boot):
idx = rng.integers(0, n, size=n)
boot_stats[b] = float(stat_fn(arr[idx]))
se = float(np.std(boot_stats, ddof=1))
q_low_lvl = 0.5 * alpha
q_high_lvl = 1.0 - 0.5 * alpha
if method in {"percentile", "moving_block"}:
ci_lower = float(np.quantile(boot_stats, q_low_lvl))
ci_upper = float(np.quantile(boot_stats, q_high_lvl))
elif method == "basic":
q_lo = float(np.quantile(boot_stats, q_low_lvl))
q_hi = float(np.quantile(boot_stats, q_high_lvl))
ci_lower = 2.0 * theta_hat - q_hi
ci_upper = 2.0 * theta_hat - q_lo
else:
# BCa: bias correction z0 + jackknife acceleration a
prop_less = float(np.mean(boot_stats < theta_hat))
eps_p = 1.0 / (2.0 * float(n_boot))
prop_less = min(1.0 - eps_p, max(eps_p, prop_less))
z0 = norm_ppf(prop_less)
jack = np.array([float(stat_fn(np.delete(arr, i))) for i in range(n)], dtype=np.float64)
jack_bar = float(np.mean(jack))
diff_j = jack_bar - jack
sum_sq = float(np.dot(diff_j, diff_j))
denom_a = 6.0 * (sum_sq ** 1.5)
accel = float(np.sum(diff_j ** 3) / denom_a) if denom_a > 1e-18 else 0.0
def _bca_q(z_tilde: float, fallback: float) -> float:
denom = 1.0 - accel * (z0 + z_tilde)
if abs(denom) < 1e-12:
return fallback
return min(1.0, max(0.0, norm_cdf(z0 + (z0 + z_tilde) / denom)))
a1 = _bca_q(norm_ppf(q_low_lvl), q_low_lvl)
a2 = _bca_q(norm_ppf(q_high_lvl), q_high_lvl)
ci_lower = float(np.quantile(boot_stats, min(a1, a2)))
ci_upper = float(np.quantile(boot_stats, max(a1, a2)))
return {
"estimate": theta_hat,
"ci_lower": float(ci_lower),
"ci_upper": float(ci_upper),
"se": se,
"method": method,
"n_boot": int(n_boot),
"boot_stats": boot_stats,
}
# ==============================================================================
# 2. SRM GUARD, CLUSTERED DELTA RATIO, FIELLER & VARIANCE REDUCTION
# ==============================================================================
def srm_chisq_guard(
observed_counts: np.ndarray | list[int] | list[float],
expected_probs: np.ndarray | list[float],
alpha: float = 0.001,
dirichlet_conc: float | None = 100.0,
) -> SRMResult:
"""
Pearson chi-square goodness-of-fit SRM detector with optional anytime-valid
Dirichlet-Multinomial Bayes-factor e-process.
"""
obs = np.asarray(observed_counts, dtype=np.float64)
probs = np.asarray(expected_probs, dtype=np.float64)
if obs.ndim != 1 or probs.ndim != 1 or obs.size != probs.size or obs.size < 2:
raise ValueError("observed_counts and expected_probs must be 1D arrays of equal length >= 2.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
if not (np.all(np.isfinite(obs)) and np.all(obs >= 0.0)):
raise ValueError("observed_counts must be finite and non-negative.")
if not (np.all(np.isfinite(probs)) and np.all(probs > 0.0)):
raise ValueError("expected_probs must be finite and strictly positive.")
prob_sum = float(np.sum(probs))
if not math.isclose(prob_sum, 1.0, rel_tol=0.0, abs_tol=1e-5):
raise ValueError(f"expected_probs must sum to 1.0, got {prob_sum:.8f}.")
probs = probs / prob_sum
if dirichlet_conc is not None and (not math.isfinite(dirichlet_conc) or dirichlet_conc <= 0.0):
raise ValueError("dirichlet_conc must be None or a finite positive float.")
total_n = float(np.sum(obs))
df = int(obs.size - 1)
if total_n <= 0.0:
e_val = 1.0 if dirichlet_conc is not None else None
return SRMResult(
srm_detected=False,
chi2_stat=0.0,
p_value=1.0,
df=df,
total_n=0,
observed_ratios=tuple(0.0 for _ in obs),
alpha=float(alpha),
e_value_dirichlet=e_val,
)
expected = total_n * probs
chi2_stat = float(np.sum(((obs - expected) ** 2) / expected))
p_value = gammaincc(0.5 * df, 0.5 * chi2_stat)
e_val: float | None = None
if dirichlet_conc is not None:
c = float(dirichlet_conc)
alpha_vec = c * probs
log_e = math.lgamma(c) - math.lgamma(c + total_n)
for a_k, n_k, p_k in zip(alpha_vec, obs, probs):
log_e += math.lgamma(float(a_k + n_k)) - math.lgamma(float(a_k))
if n_k > 0.0:
log_e -= float(n_k) * math.log(float(p_k))
e_val = math.inf if log_e > 709.0 else math.exp(log_e)
n_out: int | float = int(total_n) if total_n.is_integer() else total_n
ratios = tuple(float(v) for v in (obs / total_n))
return SRMResult(
srm_detected=bool(p_value < alpha),
chi2_stat=chi2_stat,
p_value=p_value,
df=df,
total_n=n_out,
observed_ratios=ratios,
alpha=float(alpha),
e_value_dirichlet=e_val,
)
def fieller_ratio_ci(
num: np.ndarray | list[float],
den: np.ndarray | list[float],
alpha: float = 0.05,
) -> tuple[float, float, bool]:
"""
Exact Fieller confidence interval for single-arm ratio E[Y] / E[X].
Returns (lower, upper, is_unbounded); flags unbounded=True when denominator CV is extreme.
"""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
y = np.asarray(num, dtype=np.float64)
x = np.asarray(den, dtype=np.float64)
if y.ndim != 1 or x.ndim != 1 or y.size != x.size or y.size < 2:
raise ValueError("num and den must be 1D arrays of equal length >= 2.")
if not (np.all(np.isfinite(y)) and np.all(np.isfinite(x))):
raise ValueError("num and den must contain finite values.")
n = float(y.size)
my = float(np.mean(y))
mx = float(np.mean(x))
yc = y - my
xc = x - mx
vy = float(np.dot(yc, yc) / (n * (n - 1.0)))
vx = float(np.dot(xc, xc) / (n * (n - 1.0)))
vyx = float(np.dot(yc, xc) / (n * (n - 1.0)))
t_crit = t_ppf_two_sided(alpha, n - 1.0)
t2 = t_crit * t_crit
a_coef = mx * mx - t2 * vx
b_coef = mx * my - t2 * vyx
c_coef = my * my - t2 * vy
if a_coef <= 0.0:
return (-math.inf, math.inf, True)
disc = max(0.0, b_coef * b_coef - a_coef * c_coef)
root = math.sqrt(disc)
lo = (b_coef - root) / a_coef
hi = (b_coef + root) / a_coef
return (min(lo, hi), max(lo, hi), False)
def delta_method_ratio_test(
num_ctrl: np.ndarray | list[float],
den_ctrl: np.ndarray | list[float],
num_trt: np.ndarray | list[float],
den_trt: np.ndarray | list[float],
alpha: float = 0.05,
) -> RatioTestResult:
"""
Two-sample cluster-aggregated Delta Method ratio test using non-negative influence-residual
variance, Welch-Satterthwaite DF, and per-arm Fieller boundedness diagnostics.
"""
yc = np.asarray(num_ctrl, dtype=np.float64)
xc = np.asarray(den_ctrl, dtype=np.float64)
yt = np.asarray(num_trt, dtype=np.float64)
xt = np.asarray(den_trt, dtype=np.float64)
for arr, name in [(yc, "num_ctrl"), (xc, "den_ctrl"), (yt, "num_trt"), (xt, "den_trt")]:
if arr.ndim != 1 or not np.all(np.isfinite(arr)):
raise ValueError(f"{name} must be a finite 1D array.")
if yc.size != xc.size or yt.size != xt.size or yc.size < 2 or yt.size < 2:
raise ValueError("Numerator and denominator arrays in each arm must have equal length >= 2.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
nc, nt = yc.size, yt.size
mean_xc = float(np.mean(xc))
mean_xt = float(np.mean(xt))
if abs(mean_xc) <= 1e-15 or abs(mean_xt) <= 1e-15:
raise ValueError("Cluster denominator mean is ~0; ratio estimator is undefined.")
r_ctrl = float(np.mean(yc)) / mean_xc
r_trt = float(np.mean(yt)) / mean_xt
diff = r_trt - r_ctrl
uc = (yc - r_ctrl * xc) / mean_xc
ut = (yt - r_trt * xt) / mean_xt
var_rc = float(np.dot(uc, uc) / (nc * (nc - 1)))
var_rt = float(np.dot(ut, ut) / (nt * (nt - 1)))
se_sq = var_rc + var_rt
se = math.sqrt(se_sq)
if se <= 0.0:
df_welch = float(nc + nt - 2)
if diff == 0.0:
stat, p_z, p_t = 0.0, 1.0, 1.0
else:
stat = math.copysign(math.inf, diff)
p_z, p_t = 0.0, 0.0
else:
stat = diff / se
p_z = norm_sf_two_sided(abs(stat))
denom_df = (var_rc * var_rc) / (nc - 1) + (var_rt * var_rt) / (nt - 1)
df_welch = (se_sq * se_sq) / denom_df if denom_df > 0.0 else float(nc + nt - 2)
p_t = t_sf_two_sided(stat, df_welch)
z_crit = norm_ppf(1.0 - 0.5 * alpha)
ci_delta = (diff - z_crit * se, diff + z_crit * se)
lo_c, hi_c, unb_c = fieller_ratio_ci(yc, xc, alpha=alpha)
lo_t, hi_t, unb_t = fieller_ratio_ci(yt, xt, alpha=alpha)
cv_c = math.sqrt(float(np.var(xc, ddof=1)) / nc) / abs(mean_xc)
cv_t = math.sqrt(float(np.var(xt, ddof=1)) / nt) / abs(mean_xt)
return RatioTestResult(
rate_ctrl=r_ctrl,
rate_trt=r_trt,
diff=diff,
rel_lift=(diff / r_ctrl) if abs(r_ctrl) > 1e-15 else float("nan"),
se=se,
z_stat=stat,
p_value_z=p_z,
df_welch=df_welch,
p_value_welch=p_t,
ci_delta=ci_delta,
ci_fieller_ctrl=(lo_c, hi_c),
ci_fieller_trt=(lo_t, hi_t),
fieller_unbounded=bool(unb_c or unb_t),
max_denom_cv=max(cv_c, cv_t),
)
def _fit_ridge_svd(
X_train: np.ndarray,
y_train: np.ndarray,
ridge_alpha: float = 1e-4,
) -> tuple[np.ndarray, np.ndarray, float, np.ndarray]:
"""Scale-safe SVD Ridge solver avoiding X.T @ X condition-number squaring."""
mu_x = np.mean(X_train, axis=0)
std_x = np.std(X_train, axis=0)
std_x = np.where(std_x > 1e-12, std_x, 1.0)
mu_y = float(np.mean(y_train))
xs = (X_train - mu_x) / std_x
yc = y_train - mu_y
if np.all(np.abs(yc) <= 1e-15):
return mu_x, std_x, mu_y, np.zeros(X_train.shape[1], dtype=np.float64)
u_mat, s_vals, vt_mat = np.linalg.svd(xs, full_matrices=False)
lam = ridge_alpha * float(X_train.shape[0])
d_filt = s_vals / (s_vals * s_vals + lam)
w = vt_mat.T @ (d_filt * (u_mat.T @ yc))
return mu_x, std_x, mu_y, w
def _lin_ancova2_hc1(
y_arr: np.ndarray,
x_2d: np.ndarray,
trt: np.ndarray,
) -> tuple[float, float, float, np.ndarray, float]:
"""
Lin (2013) interacted OLS Y ~ 1 + W + X_tilde + W*X_tilde via SVD
with Huber-White HC1 robust standard error.
"""
n, d = x_2d.shape
w_col = trt.astype(np.float64)
x_tilde = x_2d - np.mean(x_2d, axis=0)
design = np.column_stack([np.ones(n, dtype=np.float64), w_col, x_tilde, w_col[:, None] * x_tilde])
u_mat, s_vals, vt_mat = np.linalg.svd(design, full_matrices=False)
tol = max(design.shape) * float(np.max(s_vals)) * np.finfo(np.float64).eps
s_inv = np.where(s_vals > tol, 1.0 / s_vals, 0.0)
# A = (D^T D)^+ D^T = V diag(s_inv) U^T
a_mat = (vt_mat.T * s_inv[None, :]) @ u_mat.T
beta_hat = a_mat @ y_arr
resid = y_arr - design @ beta_hat
eff_p = min(n - 1, int(np.sum(s_vals > tol)))
hc1_scale = float(n) / float(max(1, n - eff_p))
row_w = a_mat[1, :]
var_hc1 = hc1_scale * float(np.sum((row_w * resid) ** 2))
se_hc1 = math.sqrt(max(0.0, var_hc1))
ate = float(beta_hat[1])
if se_hc1 <= 0.0:
p_val = 1.0 if ate == 0.0 else 0.0
else:
p_val = norm_sf_two_sided(abs(ate / se_hc1))
beta_cov = beta_hat[2 : 2 + d]
gamma_cov = beta_hat[2 + d :]
p_trt = float(np.mean(w_col))
beta_eff = beta_cov + (1.0 - p_trt) * gamma_cov
y_adj = y_arr - x_tilde @ beta_eff
theta_rep = float(beta_eff[0]) if d == 1 else 1.0
return ate, se_hc1, p_val, y_adj, theta_rep
def cuped_adjust(
y: np.ndarray | list[float],
x_pre: np.ndarray | list[float],
treatment_mask: np.ndarray | list[bool] | list[int],
mode: str = "mlrate_crossfit",
n_folds: int = 5,
ridge_alpha: float = 1e-4,
seed: int = 42,
) -> CupedResult:
"""
Variance reduction supporting:
- 'cuped_pooled': pooled scalar OLS or in-sample SVD Ridge control variate
- 'lin_ancova2': Lin (2013) interacted OLS with HC1 Huber-White robust SE
- 'mlrate_crossfit': Stratified K-fold out-of-fold SVD Ridge + Lin outer calibration
"""
valid_modes = {"cuped_pooled", "lin_ancova2", "mlrate_crossfit"}
if mode not in valid_modes:
raise ValueError(f"mode must be one of {sorted(valid_modes)}, got {mode}.")
y_arr = np.asarray(y, dtype=np.float64)
x_arr = np.asarray(x_pre, dtype=np.float64)
trt = np.asarray(treatment_mask, dtype=bool)
if y_arr.ndim != 1 or trt.ndim != 1 or y_arr.size != trt.size:
raise ValueError("y and treatment_mask must be 1D arrays of equal length.")
if x_arr.ndim == 1:
x_2d = x_arr[:, None]
elif x_arr.ndim == 2:
x_2d = x_arr
else:
raise ValueError("x_pre must be 1D or 2D.")
if x_2d.shape[0] != y_arr.size:
raise ValueError("x_pre row count must match y.")
if not (np.all(np.isfinite(y_arr)) and np.all(np.isfinite(x_2d))):
raise ValueError("y and x_pre must be finite.")
n_t = int(np.sum(trt))
n_c = int(y_arr.size - n_t)
if n_t < 2 or n_c < 2:
raise ValueError("Both control and treatment arms require >= 2 units.")
def _two_sample(vals: np.ndarray) -> tuple[float, float, float]:
vc, vt = vals[~trt], vals[trt]
diff = float(np.mean(vt) - np.mean(vc))
se = math.sqrt(float(np.var(vc, ddof=1)) / n_c + float(np.var(vt, ddof=1)) / n_t)
if se <= 0.0:
return diff, 0.0, 1.0 if diff == 0.0 else 0.0
return diff, se, norm_sf_two_sided(abs(diff / se))
ate_raw, se_raw, p_raw = _two_sample(y_arr)
if mode == "cuped_pooled":
if x_2d.shape[1] == 1:
x1 = x_2d[:, 0]
xc = x1 - float(np.mean(x1))
yc = y_arr - float(np.mean(y_arr))
denom = float(np.dot(xc, xc))
theta_out = float(np.dot(xc, yc) / denom) if denom > 1e-15 else 0.0
y_adj = y_arr - theta_out * xc
else:
mu_x, std_x, mu_y, w = _fit_ridge_svd(x_2d, y_arr, ridge_alpha=ridge_alpha)
g_hat = mu_y + ((x_2d - mu_x) / std_x) @ w
theta_out = 1.0
y_adj = y_arr - (g_hat - float(np.mean(g_hat)))
ate_adj, se_adj, p_adj = _two_sample(y_adj)
elif mode == "lin_ancova2":
ate_adj, se_adj, p_adj, y_adj, theta_out = _lin_ancova2_hc1(y_arr, x_2d, trt)
else:
rng = np.random.default_rng(seed)
k_eff = min(max(2, int(n_folds)), n_c, n_t)
fold_ids = np.empty(y_arr.size, dtype=np.int64)
for mask in (~trt, trt):
idx = np.flatnonzero(mask)
rng.shuffle(idx)
for pos, i in enumerate(idx):
fold_ids[i] = pos % k_eff
g_oof = np.empty_like(y_arr)
for k in range(k_eff):
val_mask = fold_ids == k
tr_mask = ~val_mask
mu_x, std_x, mu_y, w = _fit_ridge_svd(
x_2d[tr_mask], y_arr[tr_mask], ridge_alpha=ridge_alpha
)
g_oof[val_mask] = mu_y + ((x_2d[val_mask] - mu_x) / std_x) @ w
ate_adj, se_adj, p_adj, y_adj, theta_out = _lin_ancova2_hc1(y_arr, g_oof[:, None], trt)
var_red = 1.0 - (se_adj * se_adj) / (se_raw * se_raw) if se_raw > 0.0 else 0.0
eff_mult = (1.0 / (1.0 - var_red)) if var_red < 1.0 - 1e-12 else math.inf
return CupedResult(
mode=mode,
ate_raw=ate_raw,
se_raw=se_raw,
p_raw=p_raw,
ate_adj=ate_adj,
se_adj=se_adj,
p_adj=p_adj,
theta_outer=theta_out,
variance_reduction=var_red,
effective_sample_multiplier=eff_mult,
y_adjusted=y_adj,
)
# ==============================================================================
# 3. LOG-NORMAL ARITHMETIC VS. GEOMETRIC INVERSION & DUAN SMEARING
# ==============================================================================
def duan_smearing_mean(y_hat_log: np.ndarray | list[float], log_residuals: np.ndarray | list[float]) -> float:
"""Duan (1983) nonparametric smearing estimator correcting exp(log_hat) Jensen bias."""
yhat = np.asarray(y_hat_log, dtype=np.float64)
res = np.asarray(log_residuals, dtype=np.float64)
if yhat.ndim != 1 or res.ndim != 1 or yhat.size == 0 or res.size == 0:
raise ValueError("y_hat_log and log_residuals must be non-empty 1D arrays.")
if not (np.all(np.isfinite(yhat)) and np.all(np.isfinite(res))):
raise ValueError("Inputs must contain only finite floats.")
smear_factor = float(np.mean(np.exp(res)))
return float(np.mean(np.exp(yhat))) * smear_factor
def lognormal_inversion_demo(seed: int = 42, n_per_arm: int = 20000) -> dict[str, float]:
"""
Demonstrate Jensen's inequality sign reversal: Treatment improves true arithmetic mean
latency/revenue while log-space mean difference reverses sign; rescued by Duan smearing.
"""
if n_per_arm < 50:
raise ValueError("n_per_arm must be >= 50.")
rng = np.random.default_rng(seed)
z_ctrl = rng.normal(2.0, 1.2, size=n_per_arm)
z_trt = rng.normal(2.1, 0.7, size=n_per_arm)
y_ctrl = np.exp(z_ctrl)
y_trt = np.exp(z_trt)
ctrl_arith = float(np.mean(y_ctrl))
trt_arith = float(np.mean(y_trt))
arith_diff = trt_arith - ctrl_arith
ctrl_log_mean = float(np.mean(z_ctrl))
trt_log_mean = float(np.mean(z_trt))
log_diff = trt_log_mean - ctrl_log_mean
ctrl_geom = math.exp(ctrl_log_mean)
trt_geom = math.exp(trt_log_mean)
ctrl_duan = duan_smearing_mean(np.full(n_per_arm, ctrl_log_mean), z_ctrl - ctrl_log_mean)
trt_duan = duan_smearing_mean(np.full(n_per_arm, trt_log_mean), z_trt - trt_log_mean)
w_log = welch_t_test(z_ctrl, z_trt)
w_arith = welch_t_test(y_ctrl, y_trt)
return {
"ctrl_arith_mean": ctrl_arith,
"trt_arith_mean": trt_arith,
"arith_diff": arith_diff,
"rel_arith_change": arith_diff / ctrl_arith,
"ctrl_geom_mean": ctrl_geom,
"trt_geom_mean": trt_geom,
"log_diff": log_diff,
"rel_geom_change": (trt_geom - ctrl_geom) / ctrl_geom,
"ctrl_duan_mean": ctrl_duan,
"trt_duan_mean": trt_duan,
"p_log": w_log.p_value,
"p_arith": w_arith.p_value,
}
# ==============================================================================
# 4. ANYTIME-VALID mSPRT, O'BRIEN-FLEMING & MULTIPLE TESTING (BONF/HOLM/BH/BY/e-BH)
# ==============================================================================
def msprt_confidence_sequence(
delta_hat: float | np.ndarray,
pooled_var: float | np.ndarray,
tau_sq: float,
alpha: float = 0.05,
n_ctrl: int | np.ndarray | None = None,
n_trt: int | np.ndarray | None = None,
) -> MSPRTResult:
"""
Mixture Sequential Probability Ratio Test (mSPRT) anytime-valid confidence sequence.
Operates strictly in log-space to avoid exp(...) overflow at high Z-scores.
"""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
if tau_sq <= 0.0 or not math.isfinite(tau_sq):
raise ValueError(f"tau_sq must be finite and > 0, got {tau_sq}.")
d = np.asarray(delta_hat, dtype=np.float64)
v = np.asarray(pooled_var, dtype=np.float64)
if (n_ctrl is not None) != (n_trt is not None):
raise ValueError("Provide both n_ctrl and n_trt, or omit both when passing V_t directly.")
if n_ctrl is not None and n_trt is not None:
nc = np.asarray(n_ctrl, dtype=np.float64)
nt = np.asarray(n_trt, dtype=np.float64)
if np.any(nc <= 0.0) or np.any(nt <= 0.0):
raise ValueError("n_ctrl and n_trt must be > 0.")
v = v * (1.0 / nc + 1.0 / nt)
if d.shape != v.shape:
raise ValueError(f"Shape mismatch: delta_hat {d.shape} vs variance {v.shape}.")
if not (np.all(np.isfinite(d)) and np.all(np.isfinite(v))):
raise ValueError("delta_hat and pooled_var must be finite.")
if np.any(v < 0.0):
raise ValueError("Variance must be non-negative.")
is_scalar = d.ndim == 0
d1 = np.atleast_1d(d)
v1 = np.atleast_1d(v)
log_e = np.empty_like(d1)
hw = np.empty_like(d1)
zero_v = v1 <= 0.0
pos_v = ~zero_v
if np.any(pos_v):
vp = v1[pos_v]
dp = d1[pos_v]
vp_plus_tau = vp + tau_sq
log_e[pos_v] = 0.5 * (np.log(vp) - np.log(vp_plus_tau)) + (
tau_sq * dp * dp
) / (2.0 * vp * vp_plus_tau)
log_term = 2.0 * math.log(1.0 / alpha) + np.logaddexp(
0.0, math.log(tau_sq) - np.log(vp)
)
hw[pos_v] = np.sqrt(vp * (1.0 + vp / tau_sq) * log_term)
if np.any(zero_v):
dz = d1[zero_v]
log_e[zero_v] = np.where(dz == 0.0, 0.0, math.inf)
hw[zero_v] = 0.0
e_val = np.where(log_e > 709.0, np.inf, np.exp(np.minimum(log_e, 709.0)))
point_p = np.exp(np.maximum(-746.0, np.minimum(0.0, -log_e)))
av_p = np.minimum.accumulate(point_p, axis=-1) if d1.shape[-1] > 1 else point_p
cs_lower = d1 - hw
cs_upper = d1 + hw
reject = av_p <= alpha
if is_scalar:
return MSPRTResult(
cs_lower=float(cs_lower[0]),
cs_upper=float(cs_upper[0]),
half_width=float(hw[0]),
log_e_value=float(log_e[0]),
e_value=float(e_val[0]),
always_valid_p=float(av_p[0]),
reject=bool(reject[0]),
)
return MSPRTResult(
cs_lower=cs_lower,
cs_upper=cs_upper,
half_width=hw,
log_e_value=log_e,
e_value=e_val,
always_valid_p=av_p,
reject=reject,
)
def obrien_fleming_boundaries(
info_fractions: tuple[float, ...] | list[float],
alpha: float = 0.05,
) -> list[dict[str, float]]:
"""
Compute Lan-DeMets O'Brien-Fleming cumulative alpha spending and sequential
z-boundaries via exact 1D Brownian-motion survival quadrature.
"""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
ts = [float(t) for t in info_fractions]
if len(ts) == 0:
raise ValueError("info_fractions must be non-empty.")
if ts[0] <= 0.0 or ts[-1] > 1.0 or any(ts[i] >= ts[i + 1] for i in range(len(ts) - 1)):
raise ValueError("info_fractions must be strictly increasing inside (0, 1].")
z_alpha = norm_ppf(1.0 - 0.5 * alpha)
alpha_cum = [min(alpha, norm_sf_two_sided(z_alpha / math.sqrt(t))) for t in ts]
alpha_cum[-1] = float(alpha)
z1 = norm_ppf(1.0 - 0.5 * alpha_cum[0]) if alpha_cum[0] > 0.0 else 10.0
out: list[dict[str, float]] = [
{
"look": 1.0,
"info_fraction": ts[0],
"alpha_cumulative": alpha_cum[0],
"alpha_incremental": alpha_cum[0],
"z_boundary": z1,
"p_nominal": norm_sf_two_sided(z1),
}
]
if len(ts) == 1:
return out
n_grid = 301
b_prev = z1 * math.sqrt(ts[0])
grid_prev = np.linspace(-b_prev, b_prev, n_grid)
dx_prev = float(grid_prev[1] - grid_prev[0])
pdf_prev = np.exp(-0.5 * (grid_prev ** 2) / ts[0]) / math.sqrt(2.0 * math.pi * ts[0])
w_prev = np.full(n_grid, dx_prev, dtype=np.float64)
w_prev[0] *= 0.5
w_prev[-1] *= 0.5
weights_pdf = pdf_prev * w_prev
vec_cdf = np.vectorize(norm_cdf, otypes=[np.float64])
for k in range(1, len(ts)):
dt = ts[k] - ts[k - 1]
sd = math.sqrt(dt)
target_surv = 1.0 - alpha_cum[k]
lo, hi = 0.0, 10.0 * math.sqrt(ts[k])
for _ in range(44):
mid = 0.5 * (lo + hi)
probs = vec_cdf((mid - grid_prev) / sd) - vec_cdf((-mid - grid_prev) / sd)
surv_prob = float(np.dot(weights_pdf, probs))
if surv_prob < target_surv:
lo = mid
else:
hi = mid
bk = 0.5 * (lo + hi)
zk = bk / math.sqrt(ts[k])
out.append(
{
"look": float(k + 1),
"info_fraction": ts[k],
"alpha_cumulative": alpha_cum[k],
"alpha_incremental": alpha_cum[k] - alpha_cum[k - 1],
"z_boundary": zk,
"p_nominal": norm_sf_two_sided(zk),
}
)
if k + 1 < len(ts):
grid_new = np.linspace(-bk, bk, n_grid)
dx_new = float(grid_new[1] - grid_new[0])
diff = grid_new[:, None] - grid_prev[None, :]
kernel = np.exp(-0.5 * (diff / sd) ** 2) / (math.sqrt(2.0 * math.pi) * sd)
pdf_new = kernel @ weights_pdf
w_new = np.full(n_grid, dx_new, dtype=np.float64)
w_new[0] *= 0.5
w_new[-1] *= 0.5
grid_prev = grid_new
weights_pdf = pdf_new * w_new
return out
def multiple_testing_control(
values: np.ndarray | list[float],
alpha: float = 0.05,
method: str = "bh",
) -> MultipleTestingResult:
"""
Multiple-testing correction for p-values ('bonferroni', 'holm', 'bh', 'by')
and e-values under arbitrary dependence ('ebh', Wang & Ramdas JRSS-B 2022).
"""
valid_methods = {"bonferroni", "holm", "bh", "by", "ebh"}
if method not in valid_methods:
raise ValueError(f"method must be one of {sorted(valid_methods)}, got {method}.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
vals = np.asarray(values, dtype=np.float64)
if vals.ndim != 1 or vals.size == 0:
raise ValueError("values must be a non-empty 1D array.")
m = vals.size
if method == "ebh":
if np.any(np.isnan(vals)) or np.any(vals < 0.0):
raise ValueError("e-values for e-BH must be non-negative and non-NaN.")
order = np.argsort(-vals, kind="mergesort")
e_sorted = vals[order]
ranks = np.arange(1, m + 1, dtype=np.float64)
with np.errstate(divide="ignore", invalid="ignore"):
raw = np.where(e_sorted > 0.0, float(m) / (ranks * e_sorted), 1.0)
raw = np.minimum(1.0, raw)
adj_sorted = np.minimum.accumulate(raw[::-1])[::-1]
adjusted = np.empty(m, dtype=np.float64)
adjusted[order] = adj_sorted
rejected = adjusted <= alpha
return MultipleTestingResult(
method=method,
rejected=rejected,
adjusted_values=adjusted,
n_rejected=int(np.sum(rejected)),
)
if not (np.all(np.isfinite(vals)) and np.all(vals >= 0.0) and np.all(vals <= 1.0)):
raise ValueError("p-values must lie in [0, 1].")
if method == "bonferroni":
adjusted = np.minimum(1.0, float(m) * vals)
rejected = adjusted <= alpha
elif method == "holm":
order = np.argsort(vals, kind="mergesort")
p_sorted = vals[order]
mult = float(m) - np.arange(m, dtype=np.float64)
raw = np.minimum(1.0, mult * p_sorted)
adj_sorted = np.maximum.accumulate(raw)
adjusted = np.empty(m, dtype=np.float64)
adjusted[order] = adj_sorted
rejected = adjusted <= alpha
else:
order = np.argsort(vals, kind="mergesort")
p_sorted = vals[order]
ranks = np.arange(1, m + 1, dtype=np.float64)
scale = float(m)
if method == "by":
scale *= float(np.sum(1.0 / ranks))
raw = np.minimum(1.0, (scale / ranks) * p_sorted)
adj_sorted = np.minimum.accumulate(raw[::-1])[::-1]
adjusted = np.empty(m, dtype=np.float64)
adjusted[order] = adj_sorted
rejected = adjusted <= alpha
return MultipleTestingResult(
method=method,
rejected=rejected,
adjusted_values=adjusted,
n_rejected=int(np.sum(rejected)),
)
def benchmark_peeking_vs_msprt(
n_trajectories: int = 500,
max_n: int = 2000,
tau_sq: float = 0.04,
alpha: float = 0.05,
seed: int = 42,
) -> dict[str, Any]:
"""
Simulate null two-sample streams to measure peeking Type-I error inflation (LIL)
across 1 look, 20 looks, and continuous monitoring vs. Ville-safe mSPRT e-process.
"""
if n_trajectories < 20 or max_n < 50:
raise ValueError("Require n_trajectories >= 20 and max_n >= 50.")
rng = np.random.default_rng(seed)
n_min = min(20, max_n // 2)
xc = rng.standard_normal((n_trajectories, max_n))
xt = rng.standard_normal((n_trajectories, max_n))
n_arr = np.arange(1, max_n + 1, dtype=np.float64)[None, :]
mc = np.cumsum(xc, axis=1) / n_arr
mt = np.cumsum(xt, axis=1) / n_arr
delta = mt - mc
sc2 = np.maximum(
1e-6,
(np.cumsum(xc * xc, axis=1) - n_arr * mc * mc) / np.maximum(1.0, n_arr - 1.0),
)
st2 = np.maximum(
1e-6,
(np.cumsum(xt * xt, axis=1) - n_arr * mt * mt) / np.maximum(1.0, n_arr - 1.0),
)
vt = (sc2 + st2) / n_arr
sl = slice(n_min - 1, None)
d_sub = delta[:, sl]
v_sub = vt[:, sl]
z_sub = np.abs(d_sub) / np.sqrt(v_sub)
z_crit = norm_ppf(1.0 - 0.5 * alpha)
fpr_1 = float(np.mean(z_sub[:, -1] > z_crit))
looks_20 = np.linspace(0, z_sub.shape[1] - 1, min(20, z_sub.shape[1]), dtype=int)
fpr_20 = float(np.mean(np.any(z_sub[:, looks_20] > z_crit, axis=1)))
looks_200 = np.linspace(0, z_sub.shape[1] - 1, min(200, z_sub.shape[1]), dtype=int)
fpr_200 = float(np.mean(np.any(z_sub[:, looks_200] > z_crit, axis=1)))
fpr_cont = float(np.mean(np.any(z_sub > z_crit, axis=1)))
msprt_res = msprt_confidence_sequence(d_sub, v_sub, tau_sq=tau_sq, alpha=alpha)
reject_arr = np.asarray(msprt_res.reject, dtype=bool)
fpr_msprt = float(np.mean(np.any(reject_arr, axis=1)))
max_log_e = np.max(np.asarray(msprt_res.log_e_value, dtype=np.float64), axis=1)
return {
"n_trajectories": int(n_trajectories),
"max_n": int(max_n),
"n_min": int(n_min),
"tau_sq": float(tau_sq),
"alpha": float(alpha),
"fixed_1_look_fpr": fpr_1,
"fixed_20_looks_fpr": fpr_20,
"fixed_200_looks_fpr": fpr_200,
"continuous_lil_fpr": fpr_cont,
"continuous_msprt_fpr": fpr_msprt,
"mean_max_log_e": float(np.mean(max_log_e)),
}
"""Distribution-free Conformal Prediction: SCP, CQR, LAC/APS/RAPS/SAPS, ACI, and Conformal Factuality."""
from __future__ import annotations
import math
from collections.abc import Callable
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
import numpy as np
@dataclass(frozen=True, slots=True)
class ConformalCalResult:
"""Exact finite-sample split conformal quantile calibration summary."""
q_hat: float
k_rank: int
n_cal: int
finite_sample_fallback_inf: bool
guaranteed_min_coverage: float
unique_ratio: float
@dataclass(frozen=True, slots=True)
class CQRResult:
"""Conformalized Quantile Regression interval and stratum coverage diagnostics."""
q_hat_cal: float
lower: np.ndarray
upper: np.ndarray
coverage: float
mean_width: float
high_noise_coverage: float
low_noise_coverage: float
@dataclass(frozen=True, slots=True)
class SetPredictionResult:
"""Multi-class conformal prediction set output (LAC, APS, RAPS, or SAPS)."""
method: str
q_hat: float
prediction_sets: list[list[int]]
empirical_coverage: float
avg_set_size: float
empty_set_rate: float
@dataclass(frozen=True, slots=True)
class ACIResult:
"""Adaptive Conformal Inference online trajectory and distribution-shift regret check."""
alpha_target: float
gamma: float
alpha_trajectory: np.ndarray
errors: np.ndarray
rolling_coverage: np.ndarray
cumulative_miscoverage: float
coverage_regret_bound: float
# ==============================================================================
# 1. SPLIT CONFORMAL QUANTILE CALIBRATION (EXACT DECIMAL RANK)
# ==============================================================================
def split_conformal_calibrate(
cal_scores: np.ndarray | list[float],
alpha: float = 0.10,
) -> ConformalCalResult:
"""
Exact finite-sample split conformal quantile calibration:
k = ceil((n_cal + 1) * (1 - alpha))
Uses Decimal arithmetic to prevent IEEE-754 float ceil overshoots and returns
q_hat = +inf when k > n_cal (i.e. n_cal < (1 - alpha) / alpha).
"""
scores = np.asarray(cal_scores, dtype=np.float64)
if scores.ndim != 1 or scores.size == 0:
raise ValueError("cal_scores must be a non-empty 1D array.")
if not np.all(np.isfinite(scores)):
raise ValueError("cal_scores must contain only finite values.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
n = int(scores.size)
k = math.ceil(Decimal(n + 1) * (Decimal(1) - Decimal(str(alpha))))
unique_ratio = float(np.unique(scores).size / float(n))
if k > n:
return ConformalCalResult(
q_hat=math.inf,
k_rank=k,
n_cal=n,
finite_sample_fallback_inf=True,
guaranteed_min_coverage=1.0,
unique_ratio=unique_ratio,
)
k = max(1, k)
sorted_scores = np.sort(scores)
return ConformalCalResult(
q_hat=float(sorted_scores[k - 1]),
k_rank=k,
n_cal=n,
finite_sample_fallback_inf=False,
guaranteed_min_coverage=float(k) / float(n + 1),
unique_ratio=unique_ratio,
)
# ==============================================================================
# 2. PURE-NUMPY SPLINE QUANTILE REGRESSOR & CQR
# ==============================================================================
def fit_linear_spline_quantile_regressor(
x_train: np.ndarray,
y_train: np.ndarray,
tau_q: float,
n_knots: int = 10,
n_iters: int = 500,
lr: float = 0.08,
l2_reg: float = 1e-3,
) -> Callable[[np.ndarray], np.ndarray]:
"""
Pure-NumPy piecewise linear hinge + Gaussian RBF quantile regressor minimizing
pinball loss rho_{tau_q}(y - y_hat) via Adam without sklearn/scipy.
"""
if not (0.0 < tau_q < 1.0):
raise ValueError(f"tau_q must lie in (0, 1), got {tau_q}.")
x_arr = np.asarray(x_train, dtype=np.float64)
y_arr = np.asarray(y_train, dtype=np.float64)
if x_arr.ndim == 1:
x_2d = x_arr[:, None]
elif x_arr.ndim == 2:
x_2d = x_arr
else:
raise ValueError("x_train must be 1D or 2D.")
if y_arr.ndim != 1 or x_2d.shape[0] != y_arr.size or y_arr.size < 5:
raise ValueError("x_train and y_train must have matching length >= 5.")
if not (np.all(np.isfinite(x_2d)) and np.all(np.isfinite(y_arr))):
raise ValueError("x_train and y_train must contain finite values.")
x_mean = np.mean(x_2d, axis=0)
x_std = np.std(x_2d, axis=0)
x_std = np.where(x_std > 1e-12, x_std, 1.0)
x_norm = (x_2d - x_mean) / x_std
knots = np.quantile(x_norm, np.linspace(0.05, 0.95, max(2, int(n_knots))), axis=0)
def _featurize(x_in: np.ndarray) -> np.ndarray:
xi = np.asarray(x_in, dtype=np.float64)
if xi.ndim == 1:
xi = xi[:, None] if x_2d.shape[1] == 1 else xi[None, :]
xni = (xi - x_mean) / x_std
cols: list[np.ndarray] = [np.ones((xni.shape[0], 1), dtype=np.float64), xni]
for j in range(xni.shape[1]):
col = xni[:, j : j + 1]
kj = knots[:, j][None, :]
cols.append(np.maximum(0.0, col - kj))
cols.append(np.exp(-0.5 * ((col - kj) / 0.6) ** 2))
return np.hstack(cols)
phi = _featurize(x_2d)
w = np.zeros(phi.shape[1], dtype=np.float64)
w[0] = float(np.quantile(y_arr, tau_q))
m_adam = np.zeros_like(w)
v_adam = np.zeros_like(w)
inv_n = 1.0 / float(phi.shape[0])
b1, b2, eps = 0.9, 0.999, 1e-8
for t in range(1, max(1, int(n_iters)) + 1):
pred = phi @ w
resid = y_arr - pred
g_pred = np.where(resid > 0.0, -tau_q, np.where(resid < 0.0, 1.0 - tau_q, 0.0)) * inv_n
grad = phi.T @ g_pred
grad[1:] += l2_reg * w[1:]
m_adam = b1 * m_adam + (1.0 - b1) * grad
v_adam = b2 * v_adam + (1.0 - b2) * (grad * grad)
m_hat = m_adam / (1.0 - (b1 ** t))
v_hat = v_adam / (1.0 - (b2 ** t))
w -= lr * m_hat / (np.sqrt(v_hat) + eps)
def _predict(x_new: np.ndarray) -> np.ndarray:
return _featurize(x_new) @ w
return _predict
def cqr_calibrate_and_predict(
q_low_cal: np.ndarray,
q_high_cal: np.ndarray,
y_cal: np.ndarray,
q_low_test: np.ndarray,
q_high_test: np.ndarray,
y_test: np.ndarray,
alpha: float = 0.10,
high_noise_mask: np.ndarray | None = None,
) -> CQRResult:
"""
Conformalized Quantile Regression (Romano et al., 2019): enforce non-crossing quantiles,
calibrate signed scores max(q_low - Y, Y - q_high), and report heteroscedastic strata.
"""
ql_c = np.asarray(q_low_cal, dtype=np.float64)
qh_c = np.asarray(q_high_cal, dtype=np.float64)
yc = np.asarray(y_cal, dtype=np.float64)
ql_t = np.asarray(q_low_test, dtype=np.float64)
qh_t = np.asarray(q_high_test, dtype=np.float64)
yt = np.asarray(y_test, dtype=np.float64)
if not (ql_c.shape == qh_c.shape == yc.shape and ql_c.ndim == 1 and yc.size > 0):
raise ValueError("Calibration inputs must be matching non-empty 1D arrays.")
if not (ql_t.shape == qh_t.shape == yt.shape and ql_t.ndim == 1 and yt.size > 0):
raise ValueError("Test inputs must be matching non-empty 1D arrays.")
ql_c_nc = np.minimum(ql_c, qh_c)
qh_c_nc = np.maximum(ql_c, qh_c)
ql_t_nc = np.minimum(ql_t, qh_t)
qh_t_nc = np.maximum(ql_t, qh_t)
cal_scores = np.maximum(ql_c_nc - yc, yc - qh_c_nc)
cal_res = split_conformal_calibrate(cal_scores, alpha=alpha)
q_hat = cal_res.q_hat
lower = ql_t_nc - q_hat
upper = qh_t_nc + q_hat
covered = (yt >= lower) & (yt <= upper)
cov = float(np.mean(covered))
mean_w = float(np.mean(upper - lower))
if high_noise_mask is None:
spread = qh_t_nc - ql_t_nc
hi_mask = spread >= float(np.median(spread))
else:
hi_mask = np.asarray(high_noise_mask, dtype=bool)
if hi_mask.shape != yt.shape:
raise ValueError("high_noise_mask must match y_test shape.")
lo_mask = ~hi_mask
hi_cov = float(np.mean(covered[hi_mask])) if np.any(hi_mask) else cov
lo_cov = float(np.mean(covered[lo_mask])) if np.any(lo_mask) else cov
return CQRResult(
q_hat_cal=q_hat,
lower=lower,
upper=upper,
coverage=cov,
mean_width=mean_w,
high_noise_coverage=hi_cov,
low_noise_coverage=lo_cov,
)
# ==============================================================================
# 3. CLASSIFICATION SET PREDICTION (LAC, APS, RAPS, SAPS)
# ==============================================================================
def conformal_classification_scores(
probs: np.ndarray,
y_true: np.ndarray | None = None,
method: str = "raps",
u_rand: np.ndarray | None = None,
lam_reg: float = 0.02,
k_reg: int = 2,
seed: int = 42,
) -> np.ndarray:
"""
Compute classification nonconformity scores for 'lac', 'aps', 'raps', or 'saps'.
If y_true is provided, returns (n,) scores for the observed classes; otherwise returns
the full (n, K) score matrix across all candidate classes using shared per-sample U_i.
"""
valid_methods = {"lac", "aps", "raps", "saps"}
if method not in valid_methods:
raise ValueError(f"method must be one of {sorted(valid_methods)}, got {method}.")
p_arr = np.asarray(probs, dtype=np.float64)
if p_arr.ndim != 2 or p_arr.shape[0] < 1 or p_arr.shape[1] < 2:
raise ValueError("probs must be a 2D array of shape (n, K) with K >= 2.")
if not (np.all(np.isfinite(p_arr)) and np.all(p_arr >= 0.0)):
raise ValueError("probs must contain finite non-negative probabilities.")
row_sums = np.sum(p_arr, axis=1, keepdims=True)
if np.any(row_sums <= 0.0):
raise ValueError("Each row of probs must have strictly positive sum.")
p_norm = p_arr / row_sums
n, n_classes = p_norm.shape
if u_rand is None:
rng = np.random.default_rng(seed)
u_vec = rng.uniform(0.0, 1.0, size=n)
else:
u_vec = np.asarray(u_rand, dtype=np.float64)
if u_vec.shape != (n,):
raise ValueError("u_rand must have shape (n,).")
if method == "lac":
score_mat = 1.0 - p_norm
else:
order = np.argsort(-p_norm, axis=1, kind="mergesort")
p_sorted = np.take_along_axis(p_norm, order, axis=1)
cum_mass = np.cumsum(p_sorted, axis=1)
rho_sorted = cum_mass - p_sorted
ranks_1based = np.arange(1, n_classes + 1, dtype=np.float64)[None, :]
if method == "aps":
scores_sorted = rho_sorted + u_vec[:, None] * p_sorted
elif method == "raps":
reg_pen = float(lam_reg) * np.maximum(0.0, ranks_1based - float(k_reg))
scores_sorted = rho_sorted + u_vec[:, None] * p_sorted + reg_pen
else:
# SAPS (Huang et al., ICML 2024): keeps top-1 probability and rank penalty beyond k=1
p_top1 = p_sorted[:, :1]
scores_sorted = np.empty_like(p_sorted)
scores_sorted[:, 0] = u_vec * p_top1[:, 0]
scores_sorted[:, 1:] = p_top1 + float(lam_reg) * (
ranks_1based[:, 1:] - 2.0 + u_vec[:, None]
)
score_mat = np.empty_like(p_norm)
np.put_along_axis(score_mat, order, scores_sorted, axis=1)
if y_true is not None:
y_idx = np.asarray(y_true, dtype=np.int64)
if y_idx.shape != (n,) or np.any(y_idx < 0) or np.any(y_idx >= n_classes):
raise ValueError("y_true must be 1D integer class indices in [0, K-1].")
return score_mat[np.arange(n), y_idx]
return score_mat
def calibrate_and_predict_sets(
probs_cal: np.ndarray,
y_cal: np.ndarray,
probs_test: np.ndarray,
y_test: np.ndarray,
alpha: float = 0.10,
method: str = "raps",
lam_reg: float = 0.02,
k_reg: int = 2,
allow_zero_sets: bool = False,
seed: int = 42,
) -> SetPredictionResult:
"""Calibrate multi-class conformal threshold and construct test prediction sets."""
p_cal = np.asarray(probs_cal, dtype=np.float64)
y_c = np.asarray(y_cal, dtype=np.int64)
p_te = np.asarray(probs_test, dtype=np.float64)
y_t = np.asarray(y_test, dtype=np.int64)
if p_cal.ndim != 2 or p_te.ndim != 2 or p_cal.shape[1] != p_te.shape[1]:
raise ValueError("probs_cal and probs_test must be 2D arrays with matching number of classes.")
if y_c.shape != (p_cal.shape[0],) or y_t.shape != (p_te.shape[0],):
raise ValueError("Label vectors must match row counts of probability matrices.")
cal_scores = conformal_classification_scores(
p_cal,
y_true=y_c,
method=method,
lam_reg=lam_reg,
k_reg=k_reg,
seed=seed,
)
cal_res = split_conformal_calibrate(cal_scores, alpha=alpha)
q_hat = cal_res.q_hat
test_scores = conformal_classification_scores(
p_te,
y_true=None,
method=method,
lam_reg=lam_reg,
k_reg=k_reg,
seed=seed + 1,
)
pred_sets: list[list[int]] = []
covered_count = 0
empty_count = 0
total_size = 0
for i in range(p_te.shape[0]):
included = np.flatnonzero(test_scores[i] <= q_hat)
if included.size == 0 and not allow_zero_sets:
included = np.array([int(np.argmax(p_te[i]))], dtype=np.int64)
# Sort classes in descending predicted probability order
if included.size > 1:
included = included[np.argsort(-p_te[i, included], kind="mergesort")]
cls_list = [int(c) for c in included.tolist()]
pred_sets.append(cls_list)
if len(cls_list) == 0:
empty_count += 1
if int(y_t[i]) in cls_list:
covered_count += 1
total_size += len(cls_list)
n_test = float(p_te.shape[0])
return SetPredictionResult(
method=method,
q_hat=q_hat,
prediction_sets=pred_sets,
empirical_coverage=float(covered_count) / n_test,
avg_set_size=float(total_size) / n_test,
empty_set_rate=float(empty_count) / n_test,
)
# ==============================================================================
# 4. ADAPTIVE CONFORMAL INFERENCE (ACI) & CONFORMAL FACTUALITY
# ==============================================================================
def adaptive_conformal_inference(
stream_scores: np.ndarray,
alpha: float = 0.10,
gamma: float = 0.05,
cal_window: int = 100,
) -> ACIResult:
"""
Online Adaptive Conformal Inference (Gibbs & Candes, NeurIPS 2021) updating
alpha_{t+1} = alpha_t + gamma * (alpha - err_t) with guaranteed O(1/T) regret.
"""
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
if gamma <= 0.0 or not math.isfinite(gamma):
raise ValueError(f"gamma must be finite and > 0, got {gamma}.")
if cal_window < 1:
raise ValueError("cal_window must be >= 1.")
scores = np.asarray(stream_scores, dtype=np.float64)
if scores.ndim != 1 or scores.size < 2 or not np.all(np.isfinite(scores)):
raise ValueError("stream_scores must be a finite 1D array of length >= 2.")
n_steps = scores.size
alpha_traj = np.empty(n_steps, dtype=np.float64)
errors = np.empty(n_steps, dtype=np.float64)
rolling_cov = np.empty(n_steps, dtype=np.float64)
alpha_t = float(alpha)
roll_w = min(50, cal_window)
for t in range(n_steps):
alpha_traj[t] = alpha_t
if alpha_t <= 0.0 or t == 0:
q_t = math.inf
elif alpha_t >= 1.0:
q_t = -math.inf
else:
start_idx = max(0, t - cal_window)
win = scores[start_idx:t]
q_t = split_conformal_calibrate(win, alpha=alpha_t).q_hat
err_t = 1.0 if scores[t] > q_t else 0.0
errors[t] = err_t
alpha_t = alpha_t + gamma * (alpha - err_t)
r_start = max(0, t - roll_w + 1)
rolling_cov[t] = 1.0 - float(np.mean(errors[r_start : t + 1]))
cum_miscov = float(np.mean(errors))
regret_bound = (1.0 + float(gamma)) / (float(gamma) * float(n_steps))
return ACIResult(
alpha_target=float(alpha),
gamma=float(gamma),
alpha_trajectory=alpha_traj,
errors=errors,
rolling_coverage=rolling_cov,
cumulative_miscoverage=cum_miscov,
coverage_regret_bound=regret_bound,
)
def conformal_factuality_prune(
claim_scores_cal: list[np.ndarray],
claim_labels_cal: list[np.ndarray],
claim_scores_test: list[np.ndarray],
claim_labels_test: list[np.ndarray],
alpha: float = 0.10,
) -> dict[str, Any]:
"""
Conformal Factuality claim pruning (Mohri & Hashimoto, ICML 2024): calibrate
S_i = max({r_{i,j} : y_{i,j} == 0} U {-0.01}) and prune test claims <= tau_fact.
"""
if len(claim_scores_cal) == 0 or len(claim_scores_cal) != len(claim_labels_cal):
raise ValueError("claim_scores_cal and claim_labels_cal must have matching non-zero length.")
if len(claim_scores_test) == 0 or len(claim_scores_test) != len(claim_labels_test):
raise ValueError("claim_scores_test and claim_labels_test must have matching non-zero length.")
cal_resp_scores = np.empty(len(claim_scores_cal), dtype=np.float64)
for i, (sc, lb) in enumerate(zip(claim_scores_cal, claim_labels_cal)):
s_arr = np.asarray(sc, dtype=np.float64)
l_arr = np.asarray(lb, dtype=np.int64)
if s_arr.ndim != 1 or l_arr.shape != s_arr.shape:
raise ValueError("Each response's claim scores and labels must be matching 1D arrays.")
false_sc = s_arr[l_arr == 0]
cal_resp_scores[i] = float(np.max(false_sc)) if false_sc.size > 0 else -0.01
cal_res = split_conformal_calibrate(cal_resp_scores, alpha=alpha)
tau_fact = cal_res.q_hat
zero_halluc_count = 0
abstain_count = 0
total_true_claims = 0
retained_true_claims = 0
claims_before = 0
claims_after = 0
for sc, lb in zip(claim_scores_test, claim_labels_test):
s_arr = np.asarray(sc, dtype=np.float64)
l_arr = np.asarray(lb, dtype=np.int64)
if s_arr.ndim != 1 or l_arr.shape != s_arr.shape:
raise ValueError("Each test response's claim scores and labels must match.")
keep = s_arr > tau_fact
kept_labels = l_arr[keep]
if int(np.sum(kept_labels == 0)) == 0:
zero_halluc_count += 1
if kept_labels.size == 0:
abstain_count += 1
total_true_claims += int(np.sum(l_arr == 1))
retained_true_claims += int(np.sum(kept_labels == 1))
claims_before += int(s_arr.size)
claims_after += int(kept_labels.size)
n_te = float(len(claim_scores_test))
recall = (
float(retained_true_claims) / float(total_true_claims)
if total_true_claims > 0
else 1.0
)
return {
"tau_fact": float(tau_fact),
"k_rank": int(cal_res.k_rank),
"n_cal": int(cal_res.n_cal),
"zero_hallucination_rate": float(zero_halluc_count) / n_te,
"true_claim_recall": recall,
"mean_claims_before": float(claims_before) / n_te,
"mean_claims_after": float(claims_after) / n_te,
"abstention_rate": float(abstain_count) / n_te,
}
# ==============================================================================
# 5. END-TO-END CONFORMAL BENCHMARK SUITE
# ==============================================================================
def benchmark_conformal_suite(n_mc: int = 300, seed: int = 42) -> dict[str, Any]:
"""
Run end-to-end conformal benchmark comparing:
(a) SCP naive vs exact finite-sample rank at n_cal=10,
(b) Constant SCP vs heteroscedastic CQR across noise strata,
(c) Classification set sizes across LAC / APS / RAPS / SAPS,
(d) Static SCP vs online ACI under an abrupt volatility/shift jump,
(e) Conformal Factuality sub-claim pruning on synthetic RAG responses.
"""
if n_mc < 20:
raise ValueError("n_mc must be >= 20.")
rng = np.random.default_rng(seed)
alpha = 0.10
# (a) Small-n_cal (n=10, alpha=0.10) naive quantile vs exact conformal rank
naive_covs = np.empty(n_mc, dtype=np.float64)
exact_covs = np.empty(n_mc, dtype=np.float64)
for m in range(n_mc):
s_cal = rng.uniform(0.0, 1.0, size=10)
s_test = rng.uniform(0.0, 1.0, size=400)
q_naive = float(np.sort(s_cal)[math.ceil(10 * (1.0 - alpha)) - 1])
q_exact = split_conformal_calibrate(s_cal, alpha=alpha).q_hat
naive_covs[m] = float(np.mean(s_test <= q_naive))
exact_covs[m] = float(np.mean(s_test <= q_exact))
# (b) Heteroscedastic regression: constant SCP vs CQR
n_tr, n_cal, n_te = 700, 400, 800
x_all = rng.uniform(-2.0, 2.0, size=n_tr + n_cal + n_te)
noise_sd = 0.1 + 1.5 * np.abs(x_all)
y_all = np.sin(x_all) + noise_sd * rng.standard_normal(x_all.size)
x_tr, y_tr = x_all[:n_tr], y_all[:n_tr]
x_cal, y_cal = x_all[n_tr : n_tr + n_cal], y_all[n_tr : n_tr + n_cal]
x_te, y_te = x_all[n_tr + n_cal :], y_all[n_tr + n_cal :]
hi_noise_mask = np.abs(x_te) > 1.35
f_med = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.50, n_iters=350)
scp_cal_res = split_conformal_calibrate(np.abs(y_cal - f_med(x_cal)), alpha=alpha)
pred_te_med = f_med(x_te)
scp_lo, scp_hi = pred_te_med - scp_cal_res.q_hat, pred_te_med + scp_cal_res.q_hat
scp_cov = (y_te >= scp_lo) & (y_te <= scp_hi)
scp_overall_cov = float(np.mean(scp_cov))
scp_high_noise_cov = float(np.mean(scp_cov[hi_noise_mask]))
scp_low_noise_cov = float(np.mean(scp_cov[~hi_noise_mask]))
scp_mean_width = float(np.mean(scp_hi - scp_lo))
f_q05 = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.05, n_iters=350)
f_q95 = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.95, n_iters=350)
cqr_res = cqr_calibrate_and_predict(
f_q05(x_cal),
f_q95(x_cal),
y_cal,
f_q05(x_te),
f_q95(x_te),
y_te,
alpha=alpha,
high_noise_mask=hi_noise_mask,
)
# (c) Noisy-tail multi-class classification sets (K=40 classes)
n_cls = 40
n_cls_cal, n_cls_te = 800, 1000
def _sample_noisy_probs(n_obs: int) -> tuple[np.ndarray, np.ndarray]:
y_lbl = rng.integers(0, n_cls, size=n_obs)
logits = rng.normal(0.0, 0.35, size=(n_obs, n_cls))
regime = rng.random(n_obs)
for idx_i in range(n_obs):
if regime[idx_i] < 0.78:
logits[idx_i, y_lbl[idx_i]] += 5.0
elif regime[idx_i] < 0.91:
logits[idx_i, y_lbl[idx_i]] += 3.2
logits[idx_i, (y_lbl[idx_i] + 1) % n_cls] += 3.3
else:
logits[idx_i, (y_lbl[idx_i] + 1) % n_cls] += 4.5
logits[idx_i, y_lbl[idx_i]] += 0.9
logits -= np.max(logits, axis=1, keepdims=True)
exps = np.exp(logits * 0.9)
probs = exps / np.sum(exps, axis=1, keepdims=True)
return probs, y_lbl
p_cls_cal, y_cls_cal = _sample_noisy_probs(n_cls_cal)
p_cls_te, y_cls_te = _sample_noisy_probs(n_cls_te)
cls_results: dict[str, dict[str, float]] = {}
lam_by_method = {"lac": 0.02, "aps": 0.02, "raps": 0.05, "saps": 0.25}
for m_name in ("lac", "aps", "raps", "saps"):
res_m = calibrate_and_predict_sets(
p_cls_cal,
y_cls_cal,
p_cls_te,
y_cls_te,
alpha=alpha,
method=m_name,
lam_reg=lam_by_method[m_name],
k_reg=2,
allow_zero_sets=False,
seed=seed + 11,
)
cls_results[m_name] = {
"empirical_coverage": res_m.empirical_coverage,
"avg_set_size": res_m.avg_set_size,
"empty_set_rate": res_m.empty_set_rate,
"q_hat": res_m.q_hat,
}
# (d) Distribution shift stream: static SCP vs online ACI
t_pre, t_post = 200, 400
pre_scores = np.abs(rng.normal(0.0, 1.0, size=t_pre))
post_scores = np.abs(rng.normal(0.0, 2.8, size=t_post))
full_stream = np.concatenate([pre_scores, post_scores])
static_q = split_conformal_calibrate(pre_scores[:100], alpha=alpha).q_hat
static_post_cov = float(np.mean(post_scores <= static_q))
aci_res = adaptive_conformal_inference(full_stream, alpha=alpha, gamma=0.05, cal_window=100)
aci_post_cov = 1.0 - float(np.mean(aci_res.errors[t_pre:]))
# (e) Conformal Factuality RAG claim pruning
def _sample_rag_claims(n_resp: int) -> tuple[list[np.ndarray], list[np.ndarray]]:
s_list: list[np.ndarray] = []
l_list: list[np.ndarray] = []
for _ in range(n_resp):
m_claims = int(rng.integers(4, 9))
labels = (rng.random(m_claims) < 0.72).astype(np.int64)
if np.sum(labels) == 0:
labels[0] = 1
scores = np.where(
labels == 1,
np.clip(rng.beta(6.0, 1.5, size=m_claims), 0.0, 1.0),
np.clip(rng.beta(1.4, 5.0, size=m_claims), 0.0, 1.0),
)
s_list.append(scores)
l_list.append(labels)
return s_list, l_list
sc_cal, lb_cal = _sample_rag_claims(400)
sc_te, lb_te = _sample_rag_claims(400)
fact_res = conformal_factuality_prune(sc_cal, lb_cal, sc_te, lb_te, alpha=alpha)
return {
"n_mc": int(n_mc),
"alpha": float(alpha),
"scp_n10_naive_cov": float(np.mean(naive_covs)),
"scp_n10_exact_cov": float(np.mean(exact_covs)),
"scp_hetero_overall_cov": scp_overall_cov,
"scp_hetero_high_noise_cov": scp_high_noise_cov,
"scp_hetero_low_noise_cov": scp_low_noise_cov,
"scp_hetero_mean_width": scp_mean_width,
"cqr_overall_cov": cqr_res.coverage,
"cqr_high_noise_cov": cqr_res.high_noise_coverage,
"cqr_low_noise_cov": cqr_res.low_noise_coverage,
"cqr_mean_width": cqr_res.mean_width,
"classification_sets": cls_results,
"aci_static_post_shift_cov": static_post_cov,
"aci_online_post_shift_cov": aci_post_cov,
"aci_cumulative_miscov": aci_res.cumulative_miscoverage,
"aci_regret_bound": aci_res.coverage_regret_bound,
"conformal_factuality": fact_res,
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 03 (prob_stats_lab)."""
from __future__ import annotations
import argparse
import json
import math
import sys
from dataclasses import asdict
from pathlib import Path
from typing import Any
import numpy as np
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import prob_stats_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 prob_stats_lab.conformal import (
benchmark_conformal_suite,
split_conformal_calibrate,
)
from prob_stats_lab.distributions_and_bayes import (
WelfordAccumulator,
benchmark_berry_esseen_clt,
beta_binomial_update,
compute_dependence_profile,
dirichlet_categorical_update,
gamma_poisson_negbin_logpmf,
gamma_poisson_update,
log_sum_exp,
mvn_schur_conditional,
normal_normal_update,
poisson_limit_tv_distance,
)
from prob_stats_lab.inference_and_experimentation import (
benchmark_peeking_vs_msprt,
bootstrap_ci,
compute_mde_and_sample_size,
cuped_adjust,
delta_method_ratio_test,
lognormal_inversion_demo,
mann_whitney_u_test,
msprt_confidence_sequence,
multiple_testing_control,
obrien_fleming_boundaries,
srm_chisq_guard,
studentized_permutation_test,
wald_interval,
welch_t_test,
wilson_score_interval,
)
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy arrays, scalars, and non-finite floats into JSON-safe values."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar_val(val: float, floor: float = 1e-4) -> float:
"""Ensure bar chart values are finite strictly positive floats."""
if not math.isfinite(val):
return floor
return float(max(floor, abs(val) if val < 0.0 else val))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Probability, Inference & Conformal Workbench demo."""
parser = argparse.ArgumentParser(
description="Run Lab 03: Probability, Conjugate Bayes, Experimentation, mSPRT, and Conformal UQ."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--quick",
action="store_true",
help="Use reduced Monte Carlo & permutation budgets for sub-3s execution.",
)
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Optional output JSON file path (e.g., artifacts/ch03_workbench_results.json).",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute all 4 benchmark sections and optionally export structured JSON + workbench_panels."""
args = parse_args(argv)
rng = np.random.default_rng(args.seed)
mc_clt = 250 if args.quick else 1000
n_perm = 300 if args.quick else 1000
n_boot = 300 if args.quick else 1000
n_traj = 250 if args.quick else 1000
max_n_seq = 1200 if args.quick else 2000
mc_conf = 250 if args.quick else 500
# =========================================================================
# [1] Probability, Conjugate Bayes, Dependence Counterexamples & Berry-Esseen CLT
# =========================================================================
print("=" * 84)
print("[1] Probability, Conjugate Bayes, Dependence Counterexamples & Berry-Esseen CLT")
print("=" * 84)
lse_lo = log_sum_exp([-1000.0, -1001.0])
lse_hi = log_sum_exp([1000.0, 1001.0])
large_shift = 1e9 + rng.standard_normal(5000)
naive_var = float(np.mean(large_shift ** 2) - (np.mean(large_shift) ** 2))
acc_a = WelfordAccumulator()
acc_a.update_batch(large_shift[:2500])
acc_b = WelfordAccumulator()
acc_b.update_batch(large_shift[2500:])
acc_merged = acc_a.merge(acc_b)
welford_var = acc_merged.variance(ddof=1)
true_centered_var = float(np.var(large_shift - 1e9, ddof=1))
bb_res = beta_binomial_update(alpha0=2.0, beta0=18.0, successes=14, trials=200, future_m=50)
gp_res = gamma_poisson_update(alpha0=2.0, beta0_rate=1.0, counts=[3, 5, 2, 4, 6])
nb_logp0 = gamma_poisson_negbin_logpmf(
0,
gp_res.posterior_params["alpha_post"],
gp_res.posterior_params["beta_rate_post"],
)
dc_res = dirichlet_categorical_update([1.0, 1.0, 1.0], [12, 5, 3])
nn_res = normal_normal_update(mu0=0.0, sigma0_sq=4.0, obs=[1.4, 1.8, 0.9, 1.5], obs_var=1.0)
mu_mvn = np.array([0.5, -0.3, 1.2, 0.0], dtype=np.float64)
cov_mvn = np.array(
[
[1.0, 0.6, 0.2, 0.0],
[0.6, 1.2, 0.4, 0.1],
[0.2, 0.4, 1.5, -0.3],
[0.0, 0.1, -0.3, 0.8],
],
dtype=np.float64,
)
mu_c, cov_c, prec_inv_c = mvn_schur_conditional(
mu_mvn, cov_mvn, observed_idx=[2, 3], observed_vals=np.array([2.0, -0.5])
)
schur_prec_diff = float(np.max(np.abs(cov_c - prec_inv_c)))
tv_50 = poisson_limit_tv_distance(3.0, 50)
tv_500 = poisson_limit_tv_distance(3.0, 500)
tv_5000 = poisson_limit_tv_distance(3.0, 5000)
x_quad = np.linspace(-2.0, 2.0, 1001)
dep_quad = compute_dependence_profile(x_quad, x_quad ** 2, n_bins=8)
x_exp = rng.normal(0.0, 3.0, size=20000)
dep_exp = compute_dependence_profile(x_exp, np.exp(x_exp), n_bins=8)
clt_rows = benchmark_berry_esseen_clt(
n_grid=(10, 30, 100, 1000), n_mc=mc_clt, seed=args.seed
)
print(
f"LSE stable: [-1000,-1001]={lse_lo:.4f}, [1000,1001]={lse_hi:.4f} | "
f"Welford var at 1e9={welford_var:.4f} (naive={naive_var:.2f}, true={true_centered_var:.4f})"
)
print(
f"Conjugate Gamma-Poisson (Shape-Rate): post_mean={gp_res.posterior_mean:.4f}, "
f"pred_var={gp_res.predictive_var:.4f} > pred_mean={gp_res.predictive_mean:.4f}, "
f"NegBin P(0)={math.exp(nb_logp0):.4f}"
)
print(
f"Poisson Limit TV(lam=3): n=50 -> {tv_50:.5f}, n=500 -> {tv_500:.5f}, n=5000 -> {tv_5000:.5f} | "
f"MVN Schur vs Lambda_11^-1 max_err={schur_prec_diff:.2e}"
)
print(
f"Dependence Y=X^2: Pearson={dep_quad.pearson_r:.4f}, Spearman={dep_quad.spearman_rho:.4f}, "
f"MI={dep_quad.mutual_info_nats:.4f} nats | Y=exp(X): Pearson={dep_exp.pearson_r:.4f}, "
f"Spearman={dep_exp.spearman_rho:.4f}"
)
for row in clt_rows:
if row.sample_size in (30, 1000):
print(
f" CLT {row.dist_name:22s} n={row.sample_size:4d}: skew={row.skewness:6.2f}, "
f"BE_bound={row.berry_esseen_bound:.4f}, cov95={row.empirical_95_coverage:.3f}"
)
# =========================================================================
# [2] Hypothesis Tests, SRM Guard, Variance Reduction (CUPED/Lin/MLRATE) & Ratio/LogNormal Pitfalls
# =========================================================================
print("\n" + "=" * 84)
print("[2] Hypothesis Tests, SRM Guard, Variance Reduction (CUPED/Lin/MLRATE) & Ratio/LogNormal Pitfalls")
print("=" * 84)
wald_0_30 = wald_interval(0, 30)
wilson_0_30 = wilson_score_interval(0, 30)
wald_1_20 = wald_interval(1, 20)
wilson_1_20 = wilson_score_interval(1, 20)
mde_plan = compute_mde_and_sample_size(
var_ctrl=0.04 * 0.96, var_trt=0.044 * 0.956, delta=0.004
)
# Equal-median bimodal Mann-Whitney counterexample
n_mw = 600
u_x = rng.random(n_mw)
x_mw = np.where(u_x < 0.5, rng.uniform(-1.0, 0.0, size=n_mw), rng.uniform(0.0, 10.0, size=n_mw))
u_y = rng.random(n_mw)
y_mw = np.where(u_y < 0.5, rng.uniform(-10.0, 0.0, size=n_mw), rng.uniform(0.0, 1.0, size=n_mw))
mw_res = mann_whitney_u_test(x_mw, y_mw)
# Studentized permutation + Welch Behrens-Fisher check
w_ctrl = rng.normal(0.0, 1.0, size=80)
w_trt = rng.normal(0.0, 3.0, size=24)
welch_res = welch_t_test(w_ctrl, w_trt)
perm_res = studentized_permutation_test(w_ctrl, w_trt, n_perm=n_perm, seed=args.seed)
# AR(1) bootstrap SE comparison
n_ar = 1200
eps_ar = rng.normal(0.0, 0.4, size=n_ar)
ar_series = np.empty(n_ar, dtype=np.float64)
ar_series[0] = eps_ar[0]
for t in range(1, n_ar):
ar_series[t] = 0.85 * ar_series[t - 1] + eps_ar[t]
ar_lat = np.exp(2.0 + ar_series)
boot_iid = bootstrap_ci(ar_lat, lambda a: float(np.quantile(a, 0.95)), method="percentile", n_boot=n_boot, seed=args.seed)
boot_blk = bootstrap_ci(ar_lat, lambda a: float(np.quantile(a, 0.95)), method="moving_block", n_boot=n_boot, block_len=24, seed=args.seed)
boot_se_ratio = float(boot_blk["se"]) / float(boot_iid["se"])
# SRM 50.35% / 49.65% diagnostic
srm_warn = srm_chisq_guard([100700, 99300], [0.5, 0.5], alpha=0.002, dirichlet_conc=10000.0)
srm_ok = srm_chisq_guard([100050, 99950], [0.5, 0.5], alpha=0.001, dirichlet_conc=100.0)
# Clustered ratio metric (Pareto sessions + correlated Beta cancels)
n_usr = 1500
sess_c = np.maximum(1.0, np.round(rng.pareto(1.6, size=n_usr) * 6.0 + 1.0))
sess_t = np.maximum(1.0, np.round(rng.pareto(1.6, size=n_usr) * 6.0 + 1.0))
p_usr_c = rng.beta(1.0, 4.0, size=n_usr)
p_usr_t = rng.beta(1.05, 3.95, size=n_usr)
canc_c = rng.binomial(sess_c.astype(int), p_usr_c).astype(np.float64)
canc_t = rng.binomial(sess_t.astype(int), p_usr_t).astype(np.float64)
ratio_res = delta_method_ratio_test(canc_c, sess_c, canc_t, sess_t)
m_c_tot = float(np.sum(sess_c))
m_t_tot = float(np.sum(sess_t))
naive_sess_se = math.sqrt(
ratio_res.rate_ctrl * (1.0 - ratio_res.rate_ctrl) / m_c_tot
+ ratio_res.rate_trt * (1.0 - ratio_res.rate_trt) / m_t_tot
)
cluster_se_mult = ratio_res.se / naive_sess_se
# CUPED / Lin / MLRATE on d=50 signal vs d=100 pure noise
n_sig = 800
x_sig = rng.normal(0.0, 1.0, size=(n_sig, 50))
w_sig = rng.random(n_sig) < 0.5
true_weights = np.linspace(1.0, 0.1, 50)
y_sig = 2.0 + 0.35 * w_sig + x_sig @ true_weights + rng.normal(0.0, 0.8, size=n_sig)
cuped_sig = cuped_adjust(y_sig, x_sig, w_sig, mode="cuped_pooled", seed=args.seed)
mlrate_sig = cuped_adjust(y_sig, x_sig, w_sig, mode="mlrate_crossfit", n_folds=5, seed=args.seed)
n_noise = 400
x_noise = rng.normal(0.0, 1.0, size=(n_noise, 100))
w_noise = rng.random(n_noise) < 0.5
y_noise = rng.normal(0.0, 1.0, size=n_noise)
cuped_noise = cuped_adjust(y_noise, x_noise, w_noise, mode="cuped_pooled", seed=args.seed)
mlrate_noise = cuped_adjust(y_noise, x_noise, w_noise, mode="mlrate_crossfit", n_folds=5, seed=args.seed)
# Heterogeneous arm slopes + unbalanced p=0.25 Lin ANCOVA2
n_lin = 600
x_lin = rng.normal(0.0, 1.0, size=n_lin)
w_lin = rng.random(n_lin) < 0.25
y_lin = 1.0 + 0.4 * w_lin + 1.5 * x_lin + 2.0 * w_lin * x_lin + rng.normal(0.0, 0.7, size=n_lin)
lin_res = cuped_adjust(y_lin, x_lin, w_lin, mode="lin_ancova2", seed=args.seed)
# LogNormal sign reversal
ln_demo = lognormal_inversion_demo(seed=args.seed, n_per_arm=20000)
print(
f"SRM [100700,99300]: chi2={srm_warn.chi2_stat:.2f}, p={srm_warn.p_value:.6f}, "
f"detected={srm_warn.srm_detected}, E_dir={srm_warn.e_value_dirichlet:.2f}"
)
print(
f"Clustered Ratio SE={ratio_res.se:.5f} vs Naive Session SE={naive_sess_se:.5f} "
f"({cluster_se_mult:.2f}x inflation guard)"
)
print(
f"CUPED/MLRATE Signal (d=50): CUPED VR={cuped_sig.variance_reduction*100:.1f}%, "
f"MLRATE VR={mlrate_sig.variance_reduction*100:.1f}% ({mlrate_sig.effective_sample_multiplier:.2f}x)"
)
print(
f"Noise Overfit Guard (d=100, N=400): In-Sample CUPED VR={cuped_noise.variance_reduction*100:.1f}% "
f"vs Cross-Fit MLRATE VR={mlrate_noise.variance_reduction*100:.1f}%"
)
print(
f"LogNormal Sign Reversal: log_diff={ln_demo['log_diff']:+.4f} ({ln_demo['rel_geom_change']*100:+.1f}% geom) "
f"vs arith_diff={ln_demo['arith_diff']:+.3f} ({ln_demo['rel_arith_change']*100:+.1f}% arith)"
)
# =========================================================================
# [3] Anytime-Valid Sequential Testing (LIL vs mSPRT, O'Brien-Fleming, e-BH)
# =========================================================================
print("\n" + "=" * 84)
print("[3] Anytime-Valid Sequential Testing (LIL vs mSPRT, O'Brien-Fleming, e-BH)")
print("=" * 84)
seq_bench = benchmark_peeking_vs_msprt(
n_trajectories=n_traj, max_n=max_n_seq, tau_sq=0.04, alpha=0.05, seed=args.seed
)
obf_bounds = obrien_fleming_boundaries([0.25, 0.50, 0.75, 1.0], alpha=0.05)
p_bench_6 = [0.001, 0.009, 0.026, 0.032, 0.041, 0.420]
res_bonf = multiple_testing_control(p_bench_6, alpha=0.05, method="bonferroni")
res_holm = multiple_testing_control(p_bench_6, alpha=0.05, method="holm")
res_bh = multiple_testing_control(p_bench_6, alpha=0.05, method="bh")
res_by = multiple_testing_control(p_bench_6, alpha=0.05, method="by")
# Correlated e-BH check (K=20, 4 planted signals + 16 correlated null metrics)
e_corr_vals = np.concatenate(
[
np.array([650.0, 320.0, 190.0, 120.0]),
np.exp(rng.normal(-0.5, 0.6, size=16)),
]
)
res_ebh = multiple_testing_control(e_corr_vals, alpha=0.05, method="ebh")
# Overflow safety check on huge Z
msprt_extreme = msprt_confidence_sequence(delta_hat=5.0, pooled_var=1e-6, tau_sq=0.04, alpha=0.05)
print(
f"Peeking FPR (n_traj={n_traj}): 1-Look={seq_bench['fixed_1_look_fpr']*100:.2f}%, "
f"20-Looks={seq_bench['fixed_20_looks_fpr']*100:.2f}%, "
f"Continuous LIL={seq_bench['continuous_lil_fpr']*100:.2f}% vs "
f"mSPRT={seq_bench['continuous_msprt_fpr']*100:.2f}%"
)
print(
"O'Brien-Fleming z-bounds [0.25, 0.50, 0.75, 1.0]: "
+ ", ".join(f"{b['z_boundary']:.3f}" for b in obf_bounds)
)
print(
f"m=6 Multiplicity Rej: Bonf={res_bonf.n_rejected}, Holm={res_holm.n_rejected}, "
f"BH={res_bh.n_rejected}, BY={res_by.n_rejected} | e-BH (K=20 corr)={res_ebh.n_rejected}"
)
# =========================================================================
# [4] Distribution-Free Conformal Prediction (SCP, CQR, RAPS/SAPS, ACI, Conformal Factuality)
# =========================================================================
print("\n" + "=" * 84)
print("[4] Distribution-Free Conformal Prediction (SCP, CQR, RAPS/SAPS, ACI, Conformal Factuality)")
print("=" * 84)
conf_bench = benchmark_conformal_suite(n_mc=mc_conf, seed=args.seed)
scp_n8_inf = split_conformal_calibrate([0.1, 0.4, 0.2, 0.9, 0.5, 0.3, 0.8, 0.6], alpha=0.10)
scp_149 = split_conformal_calibrate(np.linspace(0.0, 1.0, 149), alpha=0.18)
cls_map = conf_bench["classification_sets"]
fact_map = conf_bench["conformal_factuality"]
print(
f"SCP n_cal=10 (target 90%): Naive={conf_bench['scp_n10_naive_cov']*100:.2f}% vs "
f"Exact={conf_bench['scp_n10_exact_cov']*100:.2f}% | n_cal=8 q_hat={scp_n8_inf.q_hat}, "
f"n_cal=149 alpha=0.18 k_rank={scp_149.k_rank}"
)
print(
f"Heteroscedastic High-Noise Coverage: Constant SCP={conf_bench['scp_hetero_high_noise_cov']*100:.1f}% "
f"vs CQR={conf_bench['cqr_high_noise_cov']*100:.1f}% (width={conf_bench['cqr_mean_width']:.2f})"
)
print(
f"Classification Avg Set Size (cov>=90%): LAC={cls_map['lac']['avg_set_size']:.2f}, "
f"APS={cls_map['aps']['avg_set_size']:.2f}, RAPS={cls_map['raps']['avg_set_size']:.2f}, "
f"SAPS={cls_map['saps']['avg_set_size']:.2f}"
)
print(
f"Distribution Shift Post-Cov: Static SCP={conf_bench['aci_static_post_shift_cov']*100:.1f}% "
f"vs ACI={conf_bench['aci_online_post_shift_cov']*100:.1f}% | "
f"Conformal Factuality zero_halluc={fact_map['zero_hallucination_rate']*100:.1f}% "
f"(recall={fact_map['true_claim_recall']*100:.1f}%)"
)
# =========================================================================
# BUILD STRUCTURED WORKBENCH_PANELS & JSON EXPORT
# =========================================================================
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
lil_fpr_pct = seq_bench["continuous_lil_fpr"] * 100.0
msprt_fpr_pct = seq_bench["continuous_msprt_fpr"] * 100.0
mlrate_sig_vr_pct = mlrate_sig.variance_reduction * 100.0
mlrate_noise_vr_pct = mlrate_noise.variance_reduction * 100.0
cuped_noise_vr_pct = cuped_noise.variance_reduction * 100.0
cqr_hi_cov_pct = conf_bench["cqr_high_noise_cov"] * 100.0
scp_hi_cov_pct = conf_bench["scp_hetero_high_noise_cov"] * 100.0
aci_post_pct = conf_bench["aci_online_post_shift_cov"] * 100.0
static_post_pct = conf_bench["aci_static_post_shift_cov"] * 100.0
workbench_panels = {
"kpis": [
{
"id": "kpi_peeking_fpr",
"label": "mSPRT vs. Continuous Peeking FPR",
"value": f"{msprt_fpr_pct:.2f}%",
"unit": f"vs {lil_fpr_pct:.1f}% LIL",
"status": "ok" if seq_bench["continuous_msprt_fpr"] <= 0.06 else "warn",
"detail": (
f"alpha=0.05 across {n_traj} streams: naive |Z|>1.96={lil_fpr_pct:.1f}% "
f"vs Ville mSPRT={msprt_fpr_pct:.2f}%"
),
},
{
"id": "kpi_srm_guard",
"label": "0.35% SRM Chi-Square Guard",
"value": f"p={srm_warn.p_value:.6f}",
"unit": f"chi2={srm_warn.chi2_stat:.2f}",
"status": "critical" if srm_warn.srm_detected else "ok",
"detail": (
f"[100700, 99300] vs 50/50 triggers SRM alert "
f"(E_dir={srm_warn.e_value_dirichlet:.2f} > 20)"
),
},
{
"id": "kpi_mlrate_vr",
"label": "MLRATE 5-Fold Cross-Fit VR",
"value": f"{mlrate_sig_vr_pct:.1f}%",
"unit": f"{mlrate_sig.effective_sample_multiplier:.1f}x traffic",
"status": "ok",
"detail": (
f"Signal d=50 VR={mlrate_sig_vr_pct:.1f}%; pure noise d=100 "
f"in-sample={cuped_noise_vr_pct:.1f}% vs cross-fit={mlrate_noise_vr_pct:.1f}%"
),
},
{
"id": "kpi_clustered_ratio_se",
"label": "Clustered Delta Ratio SE Guard",
"value": f"{cluster_se_mult:.2f}x",
"unit": "vs naive session SE",
"status": "ok" if cluster_se_mult > 1.5 else "warn",
"detail": (
f"User-clustered SE={ratio_res.se:.5f} vs naive binomial "
f"session SE={naive_sess_se:.5f}"
),
},
{
"id": "kpi_cqr_stratum_coverage",
"label": "CQR High-Noise Coverage",
"value": f"{cqr_hi_cov_pct:.1f}%",
"unit": f"vs {scp_hi_cov_pct:.1f}% SCP",
"status": "ok" if conf_bench["cqr_high_noise_cov"] >= 0.85 else "warn",
"detail": (
f"Target 90%: CQR={cqr_hi_cov_pct:.1f}% (width={conf_bench['cqr_mean_width']:.2f}) "
f"vs constant SCP={scp_hi_cov_pct:.1f}%"
),
},
{
"id": "kpi_aci_drift_recovery",
"label": "ACI Post-Shift Coverage",
"value": f"{aci_post_pct:.1f}%",
"unit": f"vs {static_post_pct:.1f}% static",
"status": "ok" if 83.0 <= aci_post_pct <= 96.0 else "warn",
"detail": (
f"2.8x scale shift: static SCP drops to {static_post_pct:.1f}% "
f"while ACI tracks {aci_post_pct:.1f}%"
),
},
],
"bars": [
{
"id": "bar_peeking_fpr_comparison",
"title": "Type-I Error Under Sequential Peeking (alpha = 0.05)",
"metric_label": "Empirical False Positive Rate",
"items": [
{
"label": "fixed_1_look",
"value": _pos_bar_val(seq_bench["fixed_1_look_fpr"]),
"display": f"{seq_bench['fixed_1_look_fpr']*100:.2f}%",
"css_class": "is-fast",
},
{
"label": "fixed_20_looks",
"value": _pos_bar_val(seq_bench["fixed_20_looks_fpr"]),
"display": f"{seq_bench['fixed_20_looks_fpr']*100:.2f}%",
"css_class": "is-mid",
},
{
"label": "continuous_lil_naive",
"value": _pos_bar_val(seq_bench["continuous_lil_fpr"]),
"display": f"{seq_bench['continuous_lil_fpr']*100:.2f}%",
"css_class": "is-slow",
},
{
"label": "continuous_msprt",
"value": _pos_bar_val(seq_bench["continuous_msprt_fpr"]),
"display": f"{seq_bench['continuous_msprt_fpr']*100:.2f}%",
"css_class": "is-fast",
},
],
},
{
"id": "bar_cuped_mlrate_vr",
"title": "Variance Reduction: Noise Overfit vs. Cross-Fitted Signal",
"metric_label": "Variance Reduction (1 - SE_adj^2 / SE_raw^2)",
"items": [
{
"label": "insample_noise_overfit",
"value": _pos_bar_val(cuped_noise.variance_reduction),
"display": f"{cuped_noise.variance_reduction*100:.1f}%",
"css_class": "is-slow",
},
{
"label": "mlrate_noise_honest",
"value": _pos_bar_val(max(0.0, mlrate_noise.variance_reduction)),
"display": f"{mlrate_noise.variance_reduction*100:.1f}%",
"css_class": "is-fast",
},
{
"label": "cuped_pooled_signal",
"value": _pos_bar_val(cuped_sig.variance_reduction),
"display": f"{cuped_sig.variance_reduction*100:.1f}%",
"css_class": "is-mid",
},
{
"label": "mlrate_crossfit_signal",
"value": _pos_bar_val(mlrate_sig.variance_reduction),
"display": f"{mlrate_sig.variance_reduction*100:.1f}%",
"css_class": "is-fast",
},
],
},
{
"id": "bar_conformal_coverage_audit",
"title": "Finite-Sample & High-Noise Stratum Coverage Audit (Target 90%)",
"metric_label": "Empirical Coverage",
"items": [
{
"label": "scp_n10_naive",
"value": _pos_bar_val(conf_bench["scp_n10_naive_cov"]),
"display": f"{conf_bench['scp_n10_naive_cov']*100:.2f}%",
"css_class": "is-slow",
},
{
"label": "scp_n10_exact",
"value": _pos_bar_val(conf_bench["scp_n10_exact_cov"]),
"display": f"{conf_bench['scp_n10_exact_cov']*100:.2f}%",
"css_class": "is-fast",
},
{
"label": "scp_high_noise_stratum",
"value": _pos_bar_val(conf_bench["scp_hetero_high_noise_cov"]),
"display": f"{conf_bench['scp_hetero_high_noise_cov']*100:.1f}%",
"css_class": "is-slow",
},
{
"label": "cqr_high_noise_stratum",
"value": _pos_bar_val(conf_bench["cqr_high_noise_cov"]),
"display": f"{conf_bench['cqr_high_noise_cov']*100:.1f}%",
"css_class": "is-fast",
},
],
},
{
"id": "bar_classification_set_size",
"title": "Noisy-Tail 40-Class Conformal Average Set Size (alpha = 0.10)",
"metric_label": "Mean Set Size |C(X)|",
"items": [
{
"label": "lac",
"value": _pos_bar_val(cls_map["lac"]["avg_set_size"]),
"display": f"{cls_map['lac']['avg_set_size']:.2f}",
"css_class": "is-fast",
},
{
"label": "aps",
"value": _pos_bar_val(cls_map["aps"]["avg_set_size"]),
"display": f"{cls_map['aps']['avg_set_size']:.2f}",
"css_class": "is-slow",
},
{
"label": "raps",
"value": _pos_bar_val(cls_map["raps"]["avg_set_size"]),
"display": f"{cls_map['raps']['avg_set_size']:.2f}",
"css_class": "is-mid",
},
{
"label": "saps",
"value": _pos_bar_val(cls_map["saps"]["avg_set_size"]),
"display": f"{cls_map['saps']['avg_set_size']:.2f}",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_berry_esseen_clt",
"title": "Berry-Esseen CLT Bound vs. Empirical 95% Coverage",
"columns": [
"dist_name",
"n",
"skewness",
"be_bound",
"empirical_coverage_95",
],
"rows": [
[
r.dist_name,
r.sample_size,
round(r.skewness, 4),
round(r.berry_esseen_bound, 4),
round(r.empirical_95_coverage, 4),
]
for r in clt_rows
],
},
{
"id": "table_ab_variance_and_pitfalls",
"title": "A/B Variance Reduction, SRM & Ratio/LogNormal Forensic Audit",
"columns": [
"estimator_or_metric",
"estimate",
"se",
"vr_or_inflation",
"status",
],
"rows": [
[
"srm_50.35_49.65",
round(srm_warn.chi2_stat, 4),
round(srm_warn.p_value, 6),
round(float(srm_warn.e_value_dirichlet or 0.0), 2),
"SRM_ALERT",
],
[
"clustered_delta_ratio",
round(ratio_res.diff, 5),
round(ratio_res.se, 5),
f"{cluster_se_mult:.2f}x_vs_naive",
"OK",
],
[
"cuped_pooled_noise_d100",
round(cuped_noise.ate_adj, 4),
round(cuped_noise.se_adj, 4),
f"{cuped_noise.variance_reduction*100:.1f}%_overfit",
"TRAP",
],
[
"mlrate_crossfit_noise_d100",
round(mlrate_noise.ate_adj, 4),
round(mlrate_noise.se_adj, 4),
f"{mlrate_noise.variance_reduction*100:.1f}%_honest",
"OK",
],
[
"mlrate_crossfit_signal_d50",
round(mlrate_sig.ate_adj, 4),
round(mlrate_sig.se_adj, 4),
f"{mlrate_sig.variance_reduction*100:.1f}%_VR",
"OK",
],
[
"lin_ancova2_hetero_p0.25",
round(lin_res.ate_adj, 4),
round(lin_res.se_adj, 4),
f"{lin_res.variance_reduction*100:.1f}%_VR",
"OK",
],
[
"lognormal_arith_vs_log",
round(ln_demo["arith_diff"], 4),
round(ln_demo["log_diff"], 4),
f"{ln_demo['rel_arith_change']*100:.1f}%_arith",
"INVERSION",
],
],
},
{
"id": "table_sequential_and_multiplicity",
"title": "Sequential Peeking Guardrails & Multiple-Testing Control",
"columns": [
"method",
"regime",
"fpr_or_fdr",
"rejections_or_threshold",
],
"rows": [
[
"fixed_1_look",
f"n={max_n_seq}",
round(seq_bench["fixed_1_look_fpr"], 4),
"z=1.960",
],
[
"continuous_lil_naive",
f"n_min..{max_n_seq}",
round(seq_bench["continuous_lil_fpr"], 4),
"z=1.960_unsafe",
],
[
"continuous_msprt",
"tau_sq=0.04",
round(seq_bench["continuous_msprt_fpr"], 4),
"E_t>=20.0",
],
[
"obrien_fleming_look1_look4",
"4_looks_alpha0.05",
0.05,
f"{obf_bounds[0]['z_boundary']:.3f}->{obf_bounds[-1]['z_boundary']:.3f}",
],
[
"bonferroni_m6",
"FWER_m6",
0.05,
res_bonf.n_rejected,
],
[
"holm_m6",
"FWER_m6",
0.05,
res_holm.n_rejected,
],
[
"bh_fdr_m6",
"FDR_m6",
0.05,
res_bh.n_rejected,
],
[
"ebh_arbitrary_dep",
"K=20_e_values",
0.05,
res_ebh.n_rejected,
],
],
},
{
"id": "table_conformal_suite",
"title": "Distribution-Free Conformal Prediction Suite (alpha = 0.10)",
"columns": [
"method",
"regime",
"coverage",
"avg_width_or_size",
],
"rows": [
[
"scp_n10_naive",
"n_cal=10",
round(conf_bench["scp_n10_naive_cov"], 4),
"under_covers",
],
[
"scp_n10_exact",
"n_cal=10",
round(conf_bench["scp_n10_exact_cov"], 4),
"exact_rank_10",
],
[
"scp_constant_high_noise",
"heteroscedastic_hi",
round(conf_bench["scp_hetero_high_noise_cov"], 4),
round(conf_bench["scp_hetero_mean_width"], 3),
],
[
"cqr_adaptive_high_noise",
"heteroscedastic_hi",
round(conf_bench["cqr_high_noise_cov"], 4),
round(conf_bench["cqr_mean_width"], 3),
],
[
"aps_40class",
"noisy_tail",
round(cls_map["aps"]["empirical_coverage"], 4),
round(cls_map["aps"]["avg_set_size"], 3),
],
[
"raps_40class",
"noisy_tail",
round(cls_map["raps"]["empirical_coverage"], 4),
round(cls_map["raps"]["avg_set_size"], 3),
],
[
"saps_40class",
"noisy_tail",
round(cls_map["saps"]["empirical_coverage"], 4),
round(cls_map["saps"]["avg_set_size"], 3),
],
[
"aci_online_shift",
"2.8x_scale_shift",
round(conf_bench["aci_online_post_shift_cov"], 4),
f"regret<={conf_bench['aci_regret_bound']:.3f}",
],
[
"conformal_factuality",
"rag_claim_prune",
round(fact_map["zero_hallucination_rate"], 4),
f"recall={fact_map['true_claim_recall']:.3f}",
],
],
},
],
}
payload = {
"config": vars(args),
"workbench_panels": workbench_panels,
"distributions_and_bayes": {
"log_sum_exp": {"neg1000": lse_lo, "pos1000": lse_hi},
"welford_1e9": {
"naive_single_pass_var": naive_var,
"welford_merged_var": welford_var,
"true_centered_var": true_centered_var,
},
"conjugates": {
"beta_binomial": asdict(bb_res),
"gamma_poisson": asdict(gp_res),
"gamma_poisson_negbin_p0": math.exp(nb_logp0),
"dirichlet_categorical": asdict(dc_res),
"normal_normal": asdict(nn_res),
},
"mvn_schur_vs_precision_max_err": schur_prec_diff,
"mvn_mu_cond": mu_c,
"poisson_limit_tv": {"n50": tv_50, "n500": tv_500, "n5000": tv_5000},
"dependence": {
"y_eq_x2": asdict(dep_quad),
"y_eq_exp_x": asdict(dep_exp),
},
"berry_esseen_clt": [asdict(r) for r in clt_rows],
},
"inference_and_experimentation": {
"intervals": {
"wald_0_30": wald_0_30,
"wilson_0_30": wilson_0_30,
"wald_1_20": wald_1_20,
"wilson_1_20": wilson_1_20,
"mde_4pct_to_4.4pct": mde_plan,
},
"nonparametric": {
"mann_whitney_equal_medians": mw_res,
"welch_behrens_fisher": asdict(welch_res),
"studentized_permutation": perm_res,
"ar1_bootstrap_iid_se": boot_iid["se"],
"ar1_bootstrap_block_se": boot_blk["se"],
"ar1_block_vs_iid_ratio": boot_se_ratio,
},
"srm_5035_4965": asdict(srm_warn),
"srm_balanced": asdict(srm_ok),
"clustered_ratio": {
"delta_test": asdict(ratio_res),
"naive_session_se": naive_sess_se,
"cluster_se_multiplier": cluster_se_mult,
},
"variance_reduction": {
"cuped_signal_d50": {
k: v for k, v in asdict(cuped_sig).items() if k != "y_adjusted"
},
"mlrate_signal_d50": {
k: v for k, v in asdict(mlrate_sig).items() if k != "y_adjusted"
},
"cuped_noise_d100": {
k: v for k, v in asdict(cuped_noise).items() if k != "y_adjusted"
},
"mlrate_noise_d100": {
k: v for k, v in asdict(mlrate_noise).items() if k != "y_adjusted"
},
"lin_ancova2_hetero": {
k: v for k, v in asdict(lin_res).items() if k != "y_adjusted"
},
},
"lognormal_inversion": ln_demo,
"peeking_vs_msprt": seq_bench,
"obrien_fleming_4looks": obf_bounds,
"msprt_extreme_overflow_check": asdict(msprt_extreme),
"multiplicity_m6": {
"bonferroni": res_bonf.n_rejected,
"holm": res_holm.n_rejected,
"bh": res_bh.n_rejected,
"by": res_by.n_rejected,
"ebh_k20": res_ebh.n_rejected,
},
},
"conformal": {
**conf_bench,
"scp_n8_inf_fallback": asdict(scp_n8_inf),
"scp_149_alpha018": asdict(scp_149),
},
}
out_path.write_text(
json.dumps(_sanitize_json_value(payload), indent=2),
encoding="utf-8",
)
print(f"\nSaved structured JSON report to: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14 mandatory verification contract tests for prob_stats_lab (T1-P1-U03)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
LAB_ROOT = Path(__file__).resolve().parents[1]
from prob_stats_lab import (
WelfordAccumulator,
adaptive_conformal_inference,
benchmark_berry_esseen_clt,
benchmark_peeking_vs_msprt,
beta_binomial_update,
betainc,
bootstrap_ci,
calibrate_and_predict_sets,
compute_dependence_profile,
conformal_factuality_prune,
cqr_calibrate_and_predict,
cuped_adjust,
delta_method_ratio_test,
dirichlet_categorical_update,
duan_smearing_mean,
fieller_ratio_ci,
fit_linear_spline_quantile_regressor,
gamma_poisson_negbin_logpmf,
gamma_poisson_update,
gammaincc,
log_sum_exp,
lognormal_inversion_demo,
mahalanobis_sq,
mann_whitney_u_test,
msprt_confidence_sequence,
multiple_testing_control,
mvn_schur_conditional,
norm_cdf,
norm_ppf,
normal_normal_update,
obrien_fleming_boundaries,
poisson_limit_tv_distance,
spearman_midrank_corr,
split_conformal_calibrate,
srm_chisq_guard,
studentized_permutation_test,
t_sf_two_sided,
wald_interval,
welch_t_test,
wilson_score_interval,
)
# 1
def test_special_functions_lse_and_welford_stability() -> None:
"""Verify norm_cdf/norm_ppf tails, gammaincc, Cauchy t_sf, LSE, and Welford at 1e9."""
for p in (1e-12, 1e-8, 1e-4, 0.025, 0.5, 0.975, 1.0 - 1e-8, 1.0 - 1e-12):
assert norm_cdf(norm_ppf(p)) == pytest.approx(p, abs=1e-12)
for x in (0.1, 1.5, 8.0):
assert gammaincc(0.5, x) == pytest.approx(math.erfc(math.sqrt(x)), rel=1e-12)
assert gammaincc(1.0, x) == pytest.approx(math.exp(-x), rel=1e-12)
assert betainc(2.0, 3.0, 0.4) == pytest.approx(1.0 - betainc(3.0, 2.0, 0.6), abs=1e-12)
for t in (0.0, 0.5, 1.0, 2.5, 10.0):
expected_cauchy_sf = 2.0 * (0.5 - math.atan(abs(t)) / math.pi)
assert t_sf_two_sided(t, 1.0) == pytest.approx(expected_cauchy_sf, abs=1e-12)
assert log_sum_exp([-1000.0, -1001.0]) == pytest.approx(
-1000.0 + math.log1p(math.exp(-1.0)), abs=1e-12
)
assert log_sum_exp([1000.0, 1001.0]) == pytest.approx(
1001.0 + math.log1p(math.exp(-1.0)), abs=1e-12
)
assert log_sum_exp([-math.inf, -math.inf]) == -math.inf
rng = np.random.default_rng(42)
eps = rng.standard_normal(5000)
shifted = 1e9 + eps
naive_var = float(np.mean(shifted ** 2) - (np.mean(shifted) ** 2))
true_var = float(np.var(eps, ddof=1))
acc1 = WelfordAccumulator()
for val in shifted[:2000]:
acc1.update(float(val))
acc2 = WelfordAccumulator()
acc2.update_batch(shifted[2000:])
merged = acc1.merge(acc2)
assert abs(naive_var - true_var) > 10.0
assert abs(merged.variance(ddof=1) - true_var) / true_var < 1e-4
# 2
def test_conjugate_updates_predictives_and_poisson_limit() -> None:
"""Verify all 4 conjugate updates, NegBin overdispersion, and Poisson limit TV decay."""
bb = beta_binomial_update(alpha0=2.0, beta0=8.0, successes=12, trials=50, future_m=20)
p_post = bb.posterior_mean
assert isinstance(p_post, float) and p_post == pytest.approx(14.0 / 60.0)
plugin_var = 20.0 * p_post * (1.0 - p_post)
assert float(bb.predictive_var) > plugin_var
assert bb.credible_interval_95 is not None
assert bb.credible_interval_95[0] < p_post < bb.credible_interval_95[1]
gp = gamma_poisson_update(alpha0=2.0, beta0_rate=1.0, counts=[3, 5, 2, 4, 6])
assert gp.posterior_params["alpha_post"] == pytest.approx(22.0)
assert gp.posterior_params["beta_rate_post"] == pytest.approx(6.0)
assert float(gp.predictive_var) > float(gp.predictive_mean)
nb_sum = sum(math.exp(gamma_poisson_negbin_logpmf(k, 22.0, 6.0)) for k in range(80))
assert nb_sum == pytest.approx(1.0, abs=1e-8)
dc_lap = dirichlet_categorical_update([1.0, 1.0, 1.0], [10, 0, 5])
dc_jef = dirichlet_categorical_update([0.5, 0.5, 0.5], [10, 0, 5])
assert dc_lap.predictive_mean == pytest.approx((11.0 / 18.0, 1.0 / 18.0, 6.0 / 18.0))
assert dc_jef.predictive_mean == pytest.approx((10.5 / 16.5, 0.5 / 16.5, 5.5 / 16.5))
nn = normal_normal_update(mu0=0.0, sigma0_sq=4.0, obs=[1.2, 0.8, 1.6], obs_var=1.0)
assert nn.posterior_params["tau_prec_post"] == pytest.approx(0.25 + 3.0)
assert float(nn.predictive_var) == pytest.approx(float(nn.posterior_var) + 1.0)
tv_50 = poisson_limit_tv_distance(3.0, 50)
tv_500 = poisson_limit_tv_distance(3.0, 500)
tv_5000 = poisson_limit_tv_distance(3.0, 5000)
assert tv_50 > tv_500 > tv_5000 > 0.0
# 3
def test_mvn_schur_conditioning_and_dependence_counterexamples() -> None:
"""Verify Schur/Lambda_11^-1 parity, Mahalanobis ~ d, and 3 dependence counterexamples."""
mu = np.array([0.5, -0.3, 1.2, 0.0], dtype=np.float64)
cov = np.array(
[
[1.0, 0.6, 0.2, 0.0],
[0.6, 1.2, 0.4, 0.1],
[0.2, 0.4, 1.5, -0.3],
[0.0, 0.1, -0.3, 0.8],
],
dtype=np.float64,
)
mu_cond, cov_cond, prec_inv = mvn_schur_conditional(
mu, cov, observed_idx=[2, 3], observed_vals=np.array([2.0, -0.5])
)
assert mu_cond.shape == (2,)
assert np.allclose(cov_cond, prec_inv, atol=1e-11)
rng = np.random.default_rng(42)
draws = rng.multivariate_normal(mu, cov, size=3000)
d2 = mahalanobis_sq(draws, mu, cov)
assert abs(float(np.mean(d2)) - 4.0) < 0.2
x_sym = np.linspace(-2.0, 2.0, 1001)
prof_quad = compute_dependence_profile(x_sym, x_sym ** 2, n_bins=8)
assert abs(prof_quad.pearson_r) < 0.05
assert abs(prof_quad.spearman_rho) < 0.05
assert prof_quad.mutual_info_nats > 0.3
x_norm = rng.normal(0.0, 3.0, size=60000)
prof_exp = compute_dependence_profile(x_norm, np.exp(x_norm), n_bins=8)
assert prof_exp.pearson_r < 0.15
assert prof_exp.spearman_rho > 0.999
x_ties = np.array([1.0, 2.0, 2.0, 4.0, 4.0, 4.0])
y_ties = np.array([10.0, 20.0, 20.0, 30.0, 30.0, 50.0])
rx_exact = np.array([1.0, 2.5, 2.5, 5.0, 5.0, 5.0])
ry_exact = np.array([1.0, 2.5, 2.5, 4.5, 4.5, 6.0])
expected_sp = float(np.corrcoef(rx_exact, ry_exact)[0, 1])
assert spearman_midrank_corr(x_ties, y_ties) == pytest.approx(expected_sp, abs=1e-12)
# 4
def test_berry_esseen_clt_and_wilson_vs_wald_intervals() -> None:
"""Verify Berry-Esseen coverage collapse at n=30 and Wilson vs. Wald boundary safety."""
rows = benchmark_berry_esseen_clt(n_grid=(30, 1000), n_mc=400, seed=42)
lookup = {(r.dist_name, r.sample_size): r for r in rows}
assert lookup[("uniform", 30)].empirical_95_coverage >= 0.92
assert lookup[("rare_bernoulli_p0.01", 30)].empirical_95_coverage < 0.50
assert lookup[("rare_bernoulli_p0.01", 1000)].empirical_95_coverage >= 0.85
assert lookup[("lognormal_sigma1.2", 30)].empirical_95_coverage < 0.90
assert lookup[("lognormal_sigma1.2", 1000)].empirical_95_coverage >= 0.91
w_0_30 = wilson_score_interval(0, 30)
wald_0_30 = wald_interval(0, 30)
assert w_0_30[0] == 0.0 and 0.0 < w_0_30[1] < 0.15
assert wald_0_30 == (0.0, 0.0)
w_1_20 = wilson_score_interval(1, 20)
wald_1_20 = wald_interval(1, 20)
assert 0.0 <= w_1_20[0] < w_1_20[1] <= 1.0
assert wald_1_20[0] < 0.0
# 5
def test_bootstrap_bca_block_and_max_order_breakdown() -> None:
"""Verify BCa skew alignment, AR(1) moving-block SE inflation, and max(X) point mass."""
rng = np.random.default_rng(42)
# BCa vs Basic on right-skewed Exponential(1.0) sample means
bca_cover = 0
basic_cover = 0
bca_hi_list = []
basic_hi_list = []
for i in range(80):
samp = rng.exponential(1.0, size=25)
r_bca = bootstrap_ci(samp, np.mean, method="bca", n_boot=250, seed=100 + i)
r_bas = bootstrap_ci(samp, np.mean, method="basic", n_boot=250, seed=100 + i)
bca_cover += int(r_bca["ci_lower"] <= 1.0 <= r_bca["ci_upper"])
basic_cover += int(r_bas["ci_lower"] <= 1.0 <= r_bas["ci_upper"])
bca_hi_list.append(r_bca["ci_upper"])
basic_hi_list.append(r_bas["ci_upper"])
assert bca_cover >= basic_cover
assert float(np.mean(bca_hi_list)) > float(np.mean(basic_hi_list))
# Autocorrelated AR(1) phi=0.85: moving_block SE > 1.3 * iid percentile SE
n_ar = 1200
eps = rng.normal(0.0, 0.4, size=n_ar)
ar = np.empty(n_ar, dtype=np.float64)
ar[0] = eps[0]
for t in range(1, n_ar):
ar[t] = 0.85 * ar[t - 1] + eps[t]
ar_pos = np.exp(2.0 + ar)
r_iid = bootstrap_ci(ar_pos, lambda a: float(np.quantile(a, 0.95)), method="percentile", n_boot=400, seed=42)
r_blk = bootstrap_ci(ar_pos, lambda a: float(np.quantile(a, 0.95)), method="moving_block", n_boot=400, block_len=24, seed=42)
assert r_blk["se"] > 1.3 * r_iid["se"]
# Extreme order statistic max(X) on Uniform(0,1): P(max* == max) -> 1 - e^-1 ~ 0.632
u_samp = rng.uniform(0.0, 1.0, size=200)
r_max = bootstrap_ci(u_samp, np.max, method="percentile", n_boot=1000, seed=42)
mass_at_max = float(np.mean(r_max["boot_stats"] == r_max["estimate"]))
assert 0.55 <= mass_at_max <= 0.72
# 6
def test_welch_mann_whitney_and_studentized_permutation() -> None:
"""Verify Welch Behrens-Fisher FPR, Mann-Whitney equal-median trap, and permutation p."""
rng = np.random.default_rng(42)
welch_rej = 0
for _ in range(300):
c = rng.normal(0.0, 1.0, size=80)
t = rng.normal(0.0, 4.0, size=20)
if welch_t_test(c, t).p_value <= 0.05:
welch_rej += 1
assert welch_rej / 300.0 <= 0.08
# Equal-median bimodal mixture counterexample (both medians = 0, concordance ~ 0.725)
n_mw = 800
ux = rng.random(n_mw)
x = np.where(ux < 0.5, rng.uniform(-1.0, 0.0, size=n_mw), rng.uniform(0.0, 10.0, size=n_mw))
uy = rng.random(n_mw)
y = np.where(uy < 0.5, rng.uniform(-10.0, 0.0, size=n_mw), rng.uniform(0.0, 1.0, size=n_mw))
assert abs(float(np.median(x))) < 0.25 and abs(float(np.median(y))) < 0.25
mwu = mann_whitney_u_test(x, y)
assert 0.65 < mwu["concordance"] < 0.80
assert mwu["p_value"] < 1e-6
# Studentized permutation p >= 1/(B+1) and Behrens-Fisher Type-I error <= 0.08
perm_rej = 0
n_perm = 199
for idx in range(150):
c = rng.normal(0.0, 1.0, size=60)
t = rng.normal(0.0, 3.0, size=20)
pr = studentized_permutation_test(c, t, n_perm=n_perm, seed=500 + idx)
assert pr["p_value"] >= 1.0 / (n_perm + 1)
if pr["p_value"] <= 0.05:
perm_rej += 1
assert perm_rej / 150.0 <= 0.08
# 7
def test_srm_chisq_guard_and_dirichlet_e_process() -> None:
"""Verify 50.35/49.65 SRM chi2=9.80 detection, Dirichlet e-values, and [0, 0] safety."""
res_035 = srm_chisq_guard([100700, 99300], [0.5, 0.5], alpha=0.002, dirichlet_conc=10000.0)
assert res_035.chi2_stat == pytest.approx(9.80, abs=1e-6)
assert res_035.p_value == pytest.approx(0.0017451, abs=1e-5)
assert res_035.srm_detected is True
assert res_035.e_value_dirichlet is not None and res_035.e_value_dirichlet > 20.0
res_050 = srm_chisq_guard([101000, 99000], [0.5, 0.5], alpha=0.001)
assert res_050.srm_detected is True
assert res_050.e_value_dirichlet is not None and res_050.e_value_dirichlet > 20.0
res_empty = srm_chisq_guard([0, 0], [0.5, 0.5])
assert res_empty.p_value == 1.0
assert res_empty.srm_detected is False
res_bal = srm_chisq_guard([100000, 100000], [0.5, 0.5], alpha=0.05)
assert res_bal.e_value_dirichlet is not None and res_bal.e_value_dirichlet < 20.0
# 8
def test_cuped_lin_ancova2_and_mlrate_crossfit() -> None:
"""Verify d=50 signal VR > 0.70, d=100 noise overfit guard, and heterogeneous Lin ANCOVA2."""
rng = np.random.default_rng(42)
# (a) Signal embeddings (d=50)
n_sig = 800
x_sig = rng.normal(0.0, 1.0, size=(n_sig, 50))
w_sig = rng.random(n_sig) < 0.5
beta_sig = np.linspace(1.0, 0.1, 50)
tau_true = 0.40
y_sig = 1.5 + tau_true * w_sig + x_sig @ beta_sig + rng.normal(0.0, 0.8, size=n_sig)
for mode in ("cuped_pooled", "lin_ancova2", "mlrate_crossfit"):
res = cuped_adjust(y_sig, x_sig, w_sig, mode=mode, seed=42)
assert res.variance_reduction > 0.70
assert abs(res.ate_adj - tau_true) < 3.0 * res.se_adj
# (b) Pure noise embeddings (d=100, N=400): pooled overfits (>15%) while MLRATE stays honest (<5%)
n_noise = 400
x_noise = rng.normal(0.0, 1.0, size=(n_noise, 100))
w_noise = rng.random(n_noise) < 0.5
y_noise = rng.normal(0.0, 1.0, size=n_noise)
res_pool_noise = cuped_adjust(y_noise, x_noise, w_noise, mode="cuped_pooled", seed=42)
res_mlrate_noise = cuped_adjust(y_noise, x_noise, w_noise, mode="mlrate_crossfit", n_folds=5, seed=42)
assert res_pool_noise.variance_reduction > 0.15
assert res_mlrate_noise.variance_reduction < 0.05
# (c) Heterogeneous slopes & unbalanced p=0.25 allocation under Lin ANCOVA2
n_het = 800
x_het = rng.normal(0.0, 1.0, size=n_het)
w_het = rng.random(n_het) < 0.25
y_het = 2.0 + 0.5 * w_het + 1.2 * x_het + 2.5 * w_het * x_het + rng.normal(0.0, 0.7, size=n_het)
res_lin = cuped_adjust(y_het, x_het, w_het, mode="lin_ancova2", seed=42)
assert res_lin.se_adj < res_lin.se_raw
assert abs(res_lin.ate_adj - 0.5) < 3.0 * res_lin.se_adj
# 9
def test_clustered_delta_ratio_fieller_and_lognormal_trap() -> None:
"""Verify >2x clustered ratio SE, zero-var edges, Fieller high-CV bounds, and LogNormal trap."""
rng = np.random.default_rng(42)
n_usr = 1500
sc = np.maximum(1.0, np.round(rng.pareto(1.6, size=n_usr) * 6.0 + 1.0))
st = np.maximum(1.0, np.round(rng.pareto(1.6, size=n_usr) * 6.0 + 1.0))
yc = rng.binomial(sc.astype(int), rng.beta(1.0, 4.0, size=n_usr)).astype(np.float64)
yt = rng.binomial(st.astype(int), rng.beta(1.05, 3.95, size=n_usr)).astype(np.float64)
r_test = delta_method_ratio_test(yc, sc, yt, st)
naive_se = math.sqrt(
r_test.rate_ctrl * (1.0 - r_test.rate_ctrl) / float(np.sum(sc))
+ r_test.rate_trt * (1.0 - r_test.rate_trt) / float(np.sum(st))
)
assert r_test.se > 2.0 * naive_se
r_same = delta_method_ratio_test([2.0, 2.0, 2.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [1.0, 1.0, 1.0])
assert r_same.se == 0.0 and r_same.p_value_z == 1.0
r_diff = delta_method_ratio_test([2.0, 2.0, 2.0], [1.0, 1.0, 1.0], [4.0, 4.0, 4.0], [1.0, 1.0, 1.0])
assert r_diff.se == 0.0 and r_diff.p_value_z == 0.0
# High denominator CV > 0.25 (finite bounded Fieller) & extreme CV > 0.55 (unbounded flag)
den_hi = np.array([0.2, 0.3, 0.5, 0.6, 0.8, 1.0, 1.4, 2.0, 3.0, 5.2], dtype=np.float64)
num_hi = 1.5 * den_hi + np.array([-0.2, 0.1, -0.1, 0.3, -0.2, 0.2, -0.1, 0.3, -0.2, 0.1])
cv_hi = float(np.std(den_hi, ddof=1) / math.sqrt(den_hi.size)) / float(np.mean(den_hi))
assert 0.25 < cv_hi < 0.50
f_lo, f_hi, f_unb = fieller_ratio_ci(num_hi, den_hi, alpha=0.05)
assert not f_unb and f_lo < (float(np.mean(num_hi)) / float(np.mean(den_hi))) < f_hi
den_ext = np.concatenate([np.full(18, 0.1), np.full(2, 10.0)])
num_ext = 2.0 * den_ext
_, _, f_unb_ext = fieller_ratio_ci(num_ext, den_ext, alpha=0.05)
assert f_unb_ext is True
# Small-sample Fieller uses exact Student-t_{n-1} critical value (wider than 1.96 z-interval)
from prob_stats_lab import t_ppf_two_sided
y_sm = np.array([2.2, 2.8, 3.1, 2.5, 3.4], dtype=np.float64)
x_sm = np.array([1.0, 1.3, 1.4, 1.1, 1.5], dtype=np.float64)
f_lo_sm, f_hi_sm, unb_sm = fieller_ratio_ci(y_sm, x_sm, alpha=0.05)
assert not unb_sm
t_crit = t_ppf_two_sided(0.05, float(y_sm.size - 1))
mx, my = float(np.mean(x_sm)), float(np.mean(y_sm))
vx = float(np.var(x_sm, ddof=1) / x_sm.size)
vy = float(np.var(y_sm, ddof=1) / y_sm.size)
vyx = float(np.cov(y_sm, x_sm, ddof=1)[0, 1] / x_sm.size)
t2 = t_crit * t_crit
a_c = mx * mx - t2 * vx
b_c = mx * my - t2 * vyx
c_c = my * my - t2 * vy
disc = math.sqrt(b_c * b_c - a_c * c_c)
assert f_lo_sm == pytest.approx((b_c - disc) / a_c, rel=1e-12)
assert f_hi_sm == pytest.approx((b_c + disc) / a_c, rel=1e-12)
ln_demo = lognormal_inversion_demo(seed=42, n_per_arm=20000)
assert ln_demo["log_diff"] > 0.0
assert ln_demo["arith_diff"] < 0.0
# Duan smearing recovers arithmetic mean of LogNormal regression within 3%
x_reg = rng.uniform(0.0, 1.0, size=8000)
mu_log = 1.0 + 0.8 * x_reg
eps_log = rng.normal(0.0, 0.9, size=8000)
y_reg = np.exp(mu_log + eps_log)
duan_est = duan_smearing_mean(mu_log, eps_log)
true_est = float(np.mean(y_reg))
assert abs(duan_est - true_est) / true_est < 0.03
# 10
def test_msprt_ville_peeking_and_obrien_fleming() -> None:
"""Verify LIL peeking inflation vs. mSPRT safety, overflow immunity, and OBF thresholds."""
bench = benchmark_peeking_vs_msprt(
n_trajectories=300, max_n=1200, tau_sq=0.04, alpha=0.05, seed=42
)
assert bench["continuous_lil_fpr"] > 0.30
assert bench["continuous_msprt_fpr"] <= 0.06
ext = msprt_confidence_sequence(delta_hat=5.0, pooled_var=1e-6, tau_sq=0.04, alpha=0.05)
assert ext.always_valid_p == 0.0
assert math.isfinite(float(ext.log_e_value))
assert math.isinf(float(ext.e_value))
assert ext.reject is True
bounds = obrien_fleming_boundaries([0.25, 0.50, 0.75, 1.0], alpha=0.05)
zs = [b["z_boundary"] for b in bounds]
assert all(zs[i] > zs[i + 1] for i in range(len(zs) - 1))
assert zs[0] > 3.8
assert zs[-1] < 2.1
# 11
def test_multiple_testing_bonferroni_holm_bh_by_and_ebh() -> None:
"""Verify exact m=6 rejections (1, 2, 5), BY <= BH, and correlated e-BH FDR <= 0.06."""
p_vals = [0.001, 0.009, 0.026, 0.032, 0.041, 0.420]
r_bonf = multiple_testing_control(p_vals, alpha=0.05, method="bonferroni")
r_holm = multiple_testing_control(p_vals, alpha=0.05, method="holm")
r_bh = multiple_testing_control(p_vals, alpha=0.05, method="bh")
r_by = multiple_testing_control(p_vals, alpha=0.05, method="by")
assert r_bonf.n_rejected == 1
assert r_holm.n_rejected == 2
assert r_bh.n_rejected == 5
assert r_by.n_rejected <= r_bh.n_rejected
# 300 simulations under correlated arbitrary-dependence e-values
rng = np.random.default_rng(42)
fdps = []
m_hyp, m0 = 20, 15
for _ in range(300):
shared = rng.standard_normal()
z_nulls = 0.7 * shared + math.sqrt(1.0 - 0.49) * rng.standard_normal(m0)
e_nulls = np.exp(z_nulls - 0.5) # E[exp(Z - 0.5)] = 1 under N(0,1)
e_alts = np.exp(rng.normal(4.8, 0.8, size=m_hyp - m0))
e_all = np.concatenate([e_nulls, e_alts])
res = multiple_testing_control(e_all, alpha=0.05, method="ebh")
if res.n_rejected > 0:
v_false = int(np.sum(res.rejected[:m0]))
fdps.append(v_false / float(res.n_rejected))
else:
fdps.append(0.0)
assert float(np.mean(fdps)) <= 0.06
# 12
def test_scp_finite_sample_coverage_and_cqr_heteroscedasticity() -> None:
"""Verify Decimal conformal rank, n_cal=8 inf fallback, n_cal=10 gap, and CQR strata."""
res_8 = split_conformal_calibrate([0.1, 0.4, 0.2, 0.9, 0.5, 0.3, 0.8, 0.6], alpha=0.10)
assert math.isinf(res_8.q_hat) and res_8.finite_sample_fallback_inf is True
res_149 = split_conformal_calibrate(np.linspace(0.0, 1.0, 149), alpha=0.18)
assert res_149.k_rank == 123
rng = np.random.default_rng(42)
naive_covs = []
exact_covs = []
for _ in range(300):
s_cal = rng.uniform(0.0, 1.0, size=10)
s_te = rng.uniform(0.0, 1.0, size=300)
q_naive = float(np.sort(s_cal)[math.ceil(10 * 0.90) - 1])
q_exact = split_conformal_calibrate(s_cal, alpha=0.10).q_hat
naive_covs.append(float(np.mean(s_te <= q_naive)))
exact_covs.append(float(np.mean(s_te <= q_exact)))
assert float(np.mean(naive_covs)) < 0.85
assert 0.88 <= float(np.mean(exact_covs)) <= 0.94
# Heteroscedastic regression: constant SCP < 0.80 on high-noise stratum vs CQR >= 0.85
x_all = rng.uniform(-2.0, 2.0, size=1800)
y_all = np.sin(x_all) + (0.1 + 1.5 * np.abs(x_all)) * rng.standard_normal(1800)
x_tr, y_tr = x_all[:700], y_all[:700]
x_cal, y_cal = x_all[700:1100], y_all[700:1100]
x_te, y_te = x_all[1100:], y_all[1100:]
hi_mask = np.abs(x_te) > 1.35
f_med = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.50, n_iters=350)
q_scp = split_conformal_calibrate(np.abs(y_cal - f_med(x_cal)), alpha=0.10).q_hat
pred_med = f_med(x_te)
scp_hi_cov = float(np.mean(np.abs(y_te[hi_mask] - pred_med[hi_mask]) <= q_scp))
assert scp_hi_cov < 0.80
f_lo = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.05, n_iters=350)
f_hi = fit_linear_spline_quantile_regressor(x_tr, y_tr, tau_q=0.95, n_iters=350)
cqr = cqr_calibrate_and_predict(
f_lo(x_cal), f_hi(x_cal), y_cal, f_lo(x_te), f_hi(x_te), y_te, alpha=0.10, high_noise_mask=hi_mask
)
assert cqr.high_noise_coverage >= 0.85
# 13
def test_raps_saps_aci_drift_and_conformal_factuality() -> None:
"""Verify LAC/APS/RAPS/SAPS sets, ACI drift tracking + regret bound, and Conformal Factuality."""
rng = np.random.default_rng(42)
n_cls = 40
def _noisy_probs(n_obs: int) -> tuple[np.ndarray, np.ndarray]:
y = rng.integers(0, n_cls, size=n_obs)
logits = rng.normal(0.0, 0.35, size=(n_obs, n_cls))
reg = rng.random(n_obs)
for i in range(n_obs):
if reg[i] < 0.78:
logits[i, y[i]] += 5.0
elif reg[i] < 0.91:
logits[i, y[i]] += 3.2
logits[i, (y[i] + 1) % n_cls] += 3.3
else:
logits[i, (y[i] + 1) % n_cls] += 4.5
logits[i, y[i]] += 0.9
logits -= np.max(logits, axis=1, keepdims=True)
exps = np.exp(logits * 0.9)
return exps / np.sum(exps, axis=1, keepdims=True), y
pc, yc = _noisy_probs(800)
pt, yt = _noisy_probs(1000)
r_lac = calibrate_and_predict_sets(pc, yc, pt, yt, alpha=0.10, method="lac", allow_zero_sets=False, seed=42)
r_aps = calibrate_and_predict_sets(pc, yc, pt, yt, alpha=0.10, method="aps", allow_zero_sets=False, seed=42)
r_raps = calibrate_and_predict_sets(pc, yc, pt, yt, alpha=0.10, method="raps", lam_reg=0.05, k_reg=2, allow_zero_sets=False, seed=42)
r_saps = calibrate_and_predict_sets(pc, yc, pt, yt, alpha=0.10, method="saps", lam_reg=0.25, k_reg=2, allow_zero_sets=False, seed=42)
for res_cls in (r_lac, r_aps, r_raps, r_saps):
assert res_cls.empirical_coverage >= 0.86
assert res_cls.empty_set_rate == 0.0
assert r_raps.avg_set_size < r_aps.avg_set_size
assert r_saps.avg_set_size < r_aps.avg_set_size
# ACI post-shift tracking + exact O(1/(gamma*T)) regret bound
pre = np.abs(rng.normal(0.0, 1.0, size=200))
post = np.abs(rng.normal(0.0, 2.8, size=400))
aci = adaptive_conformal_inference(np.concatenate([pre, post]), alpha=0.10, gamma=0.05, cal_window=100)
post_cov = 1.0 - float(np.mean(aci.errors[200:]))
assert 0.83 <= post_cov <= 0.96
assert abs(aci.cumulative_miscoverage - aci.alpha_target) <= aci.coverage_regret_bound + 1e-12
# Conformal Factuality RAG claim pruning
def _rag(n_resp: int) -> tuple[list[np.ndarray], list[np.ndarray]]:
sc_l, lb_l = [], []
for _ in range(n_resp):
m = int(rng.integers(4, 9))
lb = (rng.random(m) < 0.72).astype(np.int64)
if np.sum(lb) == 0:
lb[0] = 1
sc = np.where(lb == 1, rng.beta(6.0, 1.5, size=m), rng.beta(1.4, 5.0, size=m))
sc_l.append(sc)
lb_l.append(lb)
return sc_l, lb_l
sc_c, lb_c = _rag(350)
sc_t, lb_t = _rag(350)
fact = conformal_factuality_prune(sc_c, lb_c, sc_t, lb_t, alpha=0.10)
assert fact["zero_hallucination_rate"] >= 0.85
# 14
def test_cli_demo_script_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
"""Verify CLI execution, workbench_panels JSON schema, and Security-Only AST Deserialization Ban."""
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
json_path = tmp_path / "ch03_workbench_results.json"
proc = subprocess.run(
[sys.executable, str(script_path), "--seed", "42", "--quick", "--output", str(json_path)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
for header in (
"[1] Probability, Conjugate Bayes, Dependence Counterexamples & Berry-Esseen CLT",
"[2] Hypothesis Tests, SRM Guard, Variance Reduction (CUPED/Lin/MLRATE) & Ratio/LogNormal Pitfalls",
"[3] Anytime-Valid Sequential Testing (LIL vs mSPRT, O'Brien-Fleming, e-BH)",
"[4] Distribution-Free Conformal Prediction (SCP, CQR, RAPS/SAPS, ACI, Conformal Factuality)",
):
assert header in proc.stdout
assert json_path.exists()
payload = json.loads(json_path.read_text(encoding="utf-8"))
for key in (
"config",
"workbench_panels",
"distributions_and_bayes",
"inference_and_experimentation",
"conformal",
):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert {k["id"] for k in panels["kpis"]} == {
"kpi_peeking_fpr",
"kpi_srm_guard",
"kpi_mlrate_vr",
"kpi_clustered_ratio_se",
"kpi_cqr_stratum_coverage",
"kpi_aci_drift_recovery",
}
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert len(panels["bars"]) == 4
assert {b["id"] for b in panels["bars"]} == {
"bar_peeking_fpr_comparison",
"bar_cuped_mlrate_vr",
"bar_conformal_coverage_audit",
"bar_classification_set_size",
}
for bar in panels["bars"]:
assert len(bar["items"]) == 4
for item in bar["items"]:
val = float(item["value"])
assert math.isfinite(val) and val > 0.0
assert item["css_class"] in {"is-fast", "is-mid", "is-slow"}
assert len(panels["tables"]) == 4
assert {t["id"] for t in panels["tables"]} == {
"table_berry_esseen_clt",
"table_ab_variance_and_pitfalls",
"table_sequential_and_multiplicity",
"table_conformal_suite",
}
# Security-Only AST Deserialization Ban (Reference Core zero-scipy/sklearn purity is informational).
forbidden_unsafe_imports = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
for folder in ("src", "scripts", "tests"):
for py_file in (LAB_ROOT / folder).rglob("*.py"):
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top_pkg = alias.name.split(".")[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe import {top_pkg} in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
top_pkg = node.module.split(".")[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe from-import {top_pkg} in {py_file}"
)
np.random.gamma là gì?scale = 1/rate.
63.2% tại 0 làm sai hoàn toàn phân phối tiệm cận mũ.
FPR = (0.05*0.9)/(0.05*0.9 + 0.8*0.1) = 36%. Mann–Whitney chỉ kiểm định trung vị nếu giả định dịch chuyển thuần; phép cộng +1 trong (1+#)/(B+1) bảo toàn bất đẳng thức hạng hoán vị hữu hạn.
X riêng từng nhánh triệt tiêu 100% phần hiệu chỉnh; và theo bất đẳng thức Jensen, hiệu trung bình hình học \(\exp(\overline{\ln Y})\) có thể đổi ngược dấu so với trung bình số học thực sự!
mSPRT, Bất đẳng thức Ville & e-BH)
mSPRT (so sánh \(E_t \ge 1/\alpha\)) và thủ tục e-BH giữ nguyên kiểm soát sai số dưới continuous peeking và phụ thuộc tùy ý giữa \(K\) chỉ số?e-BH loại bỏ hoàn toàn hệ số phạt ln K mà vẫn đúng dưới mọi tương quan bất kỳ.
SCP, CQR & ACI)
90%) với cỡ tập hiệu chuẩn nhỏ \(n_{\text{cal}} = 10\), nếu dùng nhầm phân vị thô ceil((1 - alpha) * n_cal) = 9 thay vì ceil((n_cal + 1) * (1 - alpha)) = 10, độ phủ thực tế bằng bao nhiêu? Khi chuyển sang dòng dữ liệu bị dịch chuyển phân phối (shift), công cụ nào bảo toàn độ phủ dài hạn mà không cần tính hoán vị?k=9, n=10 ta chỉ được 9/11 = 81.82% (và ở n=8, k=9 > 8 bắt buộc fallback về q_hat = +inf). ACI triệt tiêu điều kiện hoán vị nhờ cập nhật mức rủi ro trực tuyến.
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 — Suy diễn Liên hợp Gamma–Poisson, Họ Hàm mũ & Độ ổn định Welford / Berry–Esseen 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết tích phân dự báo hậu nghiệm \(\int_0^\infty \frac{\lambda^{\tilde{x}} e^{-\lambda}}{\tilde{x}!} \frac{(\beta')^{\alpha'}}{\Gamma(\alpha')} \lambda^{\alpha'-1} e^{-\beta'\lambda}\,d\lambda\) bằng cách đặt biến tích phân Gamma chuẩn hóa mới với hình dạng \(\alpha'+\tilde{x}\) và rate \(\beta'+1\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Để chứng minh \(\nabla^2 A(\boldsymbol{\eta}) = \operatorname{Cov}(\mathbf{T}(X))\), lấy đạo hàm bậc hai của đẳng thức chuẩn hóa \(\int h(x)\exp(\boldsymbol{\eta}^\top \mathbf{T}(x) - A(\boldsymbol{\eta}))\,dx = 1\) theo bố cục tử số; kiểm chứng WelfordAccumulator trên 1e9 + N(0, 1) qua prob_stats_lab.
Tiêu chí Đáp án & Số đối chứng
Tích phân ra đúng PMF \(\operatorname{NegBin}(\alpha', \frac{\beta'}{\beta'+1})\) có phương sai \(\frac{\alpha'}{\beta'}(1 + \frac{1}{\beta'})\) (lưu ý NumPy dùng scale = 1/beta'). Trong prob_stats_lab, WelfordAccumulator giữ chuẩn phương sai ~0.999 tại dịch chuyển 1e9 trong khi single-pass sụp về -128.0; rare_bernoulli_p0.01 ở n=30 chỉ đạt độ phủ ~24% khớp với cảnh báo Berry–Esseen.
Bài tập 2 — Đảo phương trình Wilson Score, Sụp đổ Bootstrap Cực đại & Bẫy Trung vị Mann–Whitney 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xuất phát từ điều kiện \(\lvert \hat{p} - p_0 \rvert \le z\sqrt{\frac{p_0(1-p_0)}{n}}\), bình phương hai vế và gom theo bậc \(p_0^2, p_0, 1\) để tính biệt thức \(\Delta\) bằng biến đổi đại số chính xác.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với \(\hat{\theta}_n = \max_{i \le n} X_i\), tính xác suất phần tử lớn nhất không xuất hiện lần nào trong \(n\) lần bốc hoàn lại: \((1 - 1/n)^n\). Với Mann–Whitney, tính xác suất \(P(X > Y)\) theo 4 góc phần tư dấu của hỗn hợp đều đối xứng ở 0.
Tiêu chí Đáp án & Số đối chứng
Công thức Wilson thu được là \(\frac{\hat{p} + z^2/(2n) \pm z\sqrt{\hat{p}(1-\hat{p})/n + z^2/(4n^2)}}{1 + z^2/n}\), luôn lọt trong \([0,1]\). Bootstrap cỡ n đặt khối lượng 1 - e^{-1} ~ 63.2% tại 0 nên sai; hỗn hợp hai nửa đều có cùng trung vị 0 nhưng \(P(X>Y) = 0.725\) khiến mann_whitney_u_test bác bỏ gần 100%.
Bài tập 3 — Chứng minh CUPED, Bẫy Căn giữa Nhánh & Khớp chéo 5-Nếp MLRATE + Lin ANCOVA2 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết hiệu chỉnh \(\bar{\tilde{Y}}_1 - \bar{\tilde{Y}}_0 = (\bar{Y}_1 - \bar{Y}_0) - \theta_{\text{cuped}}(\bar{X}_1 - \bar{X}_0)\) dùng chung trung bình gộp \(\bar{X}\); chứng minh điều gì xảy ra nếu thay \(\bar{X}\) bằng \(\bar{X}_w\) riêng từng nhánh.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đạo hàm \(\operatorname{Var}(Y - \theta X)\) để suy ra \(\theta^* = \operatorname{Cov}(Y, X)/\operatorname{Var}(X)\). Dùng cuped_adjust(..., mode='mlrate_crossfit') và 'lin_ancova2' trên cả dữ liệu tín hiệu d=50 và nhiễu trắng d=100, N=400.
Tiêu chí Đáp án & Số đối chứng
Căn giữa riêng từng nhánh làm hiệu \(\bar{\tilde{Y}}_1 - \bar{\tilde{Y}}_0\) triệt tiêu mất tác dụng giảm phương sai. cuped_pooled trên d=100 nhiễu trắng (N=400) thổi phồng VR giả tới 21.8% trong mẫu, trong khi mlrate_crossfit giữ trung thực ở 0.1% và vẫn đạt 96.0% VR (~25x lưu lượng) trên tín hiệu thật.
Bài tập 4 — Bất đẳng thức Ville 4 Bước, Kiểm định mSPRT & Bổ đề e-BH 3 Dòng Dưới Phụ thuộc Tùy ý
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Định nghĩa thời điểm dừng bị chặn \(\tau_T = \min(\inf\{t: M_t \ge 1/\alpha\}, T)\), khai triển \(M_{\tau_T} = M_0 + \sum_{t=1}^T \mathbb{1}\{\tau_T \ge t\}(M_t - M_{t-1})\), rồi dùng Markov và tính liên tục từ dưới khi \(T \to \infty\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Trong e-BH, nhận xét rằng nếu giả thuyết thật \(i\) bị bác bỏ với tổng số bác bỏ \(R = k^*\), tất yếu \(E_i \ge \frac{K}{\alpha R}\), dẫn tới bất đẳng thức điểm mẫu \(\frac{\mathbb{1}\{i\text{ bị bác bỏ}\}}{\max(R, 1)} \le \frac{\alpha E_i}{K}\).
Tiêu chí Đáp án & Số đối chứng
Ville bảo toàn FPR suốt toàn bộ quỹ đạo ở mức <= alpha (3.20% thực nghiệm so với 42.0% khi peeking cố định trên 250 luồng). Chứng minh e-BH chỉ dùng phép cộng kỳ vọng trên mọi phân phối liên kết nên giữ FDR <= alpha mà không tốn hình phạt ln K.
Bài tập 5 — Chứng minh Đối xứng Hạng SCP, Dải Heteroscedastic CQR, ACI Trực tuyến & Cắt tỉa RAG
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh tương đương đa tập \(\{S_{n+1} \le S_{(k)}\} \iff \{S_{n+1} \le U_k\}\) ngay cả khi có đồng hạng (tie), rồi đếm có ít nhất \(k\) và tối đa \(k\) vị trí thỏa mãn khi có tính hoán vị.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng split_conformal_calibrate với Decimal (tránh lỗi 150 * 0.82 = 123.00000000000001), benchmark cqr_calibrate_and_predict, calibrate_and_predict_sets (lac/aps/raps/saps), adaptive_conformal_inference, và conformal_factuality_prune.
Tiêu chí Đáp án & Số đối chứng
Ở n_cal = 10, alpha = 0.10, quantile thô tụt về 80.26% (lý thuyết 9/11 = 81.82%) còn chuẩn xác đạt 89.77%; ở vùng nhiễu cao CQR giữ 90.3% so với 68.8% của SCP; SAPS giảm kích thước tập 40 lớp từ 2.61 (APS) xuống 1.30; ACI phục hồi về 90.0% hậu shift 2.8x; cắt tỉa RAG đạt 88.25% không ảo giác với 97.43% recall.
Bài tập 6 — Kiểm toán Pháp y Production: SRM 0.35%, Chỉ số Tỷ lệ Cụm & Nghịch lý Độ trễ LogNormal
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra số liệu [100700, 99300] so với kỳ vọng 50/50 bằng srm_chisq_guard(..., dirichlet_conc=10000.0) để thấy cả kiểm định chi-bình phương cố định lẫn e-value Dirichlet.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Trên tỷ số phiên/người dùng có độ lệch cụm, dùng delta_method_ratio_test (thặng dư tuyến tính hóa \(Y_i - \hat{R} X_i\)) và fieller_ratio_ci khi \(\operatorname{CV}(\bar{X}) > 0.1\); dùng lognormal_inversion_demo và duan_smearing_mean để vạch trần sai số đổi dấu khi lấy exp(mean(log Y)).
Tiêu chí Đáp án & Số đối chứng
Độ lệch 50.35% / 49.65% cho chi2 = 9.80, p = 0.001745 (e_dir = 23.21), chứng tỏ mất 1,400 log Treatment. Sai số chuẩn tỷ lệ cụm lớn gấp 3.25x so với SE binomial từng phiên (0.01467 vs 0.00451). Và ở ví dụ LogNormal, độ trễ log tăng +10.1% trong khi trung bình số học thực giảm -31.7%, được khôi phục chính xác bởi Duan smearing (15.356 -> 10.491).