Chương 06 — Mô hình Tuyến tính, Hồi quy Logistic, Tối ưu hóa & Kiểm chứng Nghiêm ngặt
Từ Gauss–Markov BLUE, Läuchli QR/SVD vs Normal Equations, Ridge/Lasso Gap-Safe/ElasticNet & Double Descent (lambda_opt < 0) đến Logistic IRLS, Softmax LSE, Giải cứu Phân tách Firth, FTRL-Proximal Q2.13, PR-AUC/MCC/VIF/HC3/Cook, Purged TS, Nested CV & .632+.
Unit ID:
T1-P2-U01
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Truy xuất Giáo trình Gốc (R29,R30,E29:E31): Lesson 4 (Basic ML Algorithms: Linear Regression — 2 buổi, phủ 100% cả 7 mục) & Lesson 5 (Basic ML Algorithms: Logistic Regression & Classification — 1 buổi, phủ 100% cả 5 mục), gắn kết miền Tài chính/Ngân hàng & Marketing Analytics (Ranh giới không chồng lấn: phân loại toàn diện 6 lớp rò rỉ đánh giá#1và hiệu chuẩn hậu nghiệmPlatt/Isotonic/Venn-Abers+ tối ưu ngưỡng ma trận chi phí#2chuyển giao sangch-07-leakage-proof-evaluation-and-calibration.md; kỹ thuật xây dựng đặc trưngWoE& pipeline tự độngR31chuyển giao sangch-08-feature-engineering-and-automated-pipelines.md)
Bài thực hành Song hành (Lab 06):labs/ch06-linear-logistic-and-validation-workbench/(linear_validation_lab)
Tình huống Mở đầu: Bốn Cạm bẫy Sản xuất Khiến Mô hình Tuyến tính và Logistic Sụp đổ Âm thầm#
Các mô hình tuyến tính và hồi quy logistic (linear & logistic models) tiếp tục đóng vai trò xương sống tại tầng chấm điểm tín dụng ngân hàng, dự báo tỷ lệ nhấp quảng cáo (CTR) thời gian thực, mô hình hóa độ co giãn giá/marketing (MMM), và tầng hiệu chuẩn đầu ra của mạng nơ-ron sâu. Tuy vậy, triển khai chúng theo lối sách giáo khoa sơ khai dẫn đến bốn thất bại sản xuất kinh điển:
- Sụp đổ Chỉ số Điều kiện trên Phương trình Chuẩn & Bẫy Không phạt Hệ số chặn: Khi các kênh chi tiêu quảng cáo (
Paid Search,Paid Social) biến động đồng pha trong mùa cao điểm (\(\rho \approx 0.98\)), ma trận thiết kế có chỉ số điều kiện \(\kappa_2(\mathbf{X}) \approx 4.71 \times 10^7\). GiảiOLSbằng Phương trình Chuẩn \((\mathbf{X}^\top\mathbf{X})\boldsymbol{\beta} = \mathbf{X}^\top\mathbf{y}\) bình phương chỉ số điều kiện thành \(\kappa_2(\mathbf{X}^\top\mathbf{X}) \approx 2.22 \times 10^{15} \sim 1/\varepsilon_{\text{mach}}\), phá hủy tới15chữ số thập phânfloat64(sai số tham số nhảy lên1.33e-02so với2.22e-16củaHouseholder QR) và làm đảo dấu độ co giãn giá. Song song đó, đưa hệ số chặn \(\beta_0\) vào tổng phạt \(L_2\) trong bài toán rủi ro nền1.5%kéo xác suất dự báo nền lệch về50%, phá hỏng hoàn toàn quyết định tín dụng. - Nổ Trọng số Phân tách Hiếm (
Quasi-Complete Separation) & Điểm mù Đa cộng tuyếnVIF: Trong thẻ điểm tín dụng (Credit Scorecard), một nhóm nợ quá hạn hiếm có100%tỷ lệ vỡ nợ khiến hàm hợp lý cực đại (MLE) không phạt đẩy \(\|\hat{\boldsymbol{\beta}}\|_2 \to \infty\) (27.15trong workbench khi trị riêng nhỏ nhất của Hessian tụt về1.76e-10), làm gãy bộ giải Newton/IRLS. Ngược lại, đa cộng tuyến giữa các tỷ lệ dư nợ (\(\text{VIF} = 19.23 > 10\)) khiến trọng số rủi ro bị lật dấu trái quy địnhSR 11-7/EU AI Act, còn vài điểm đòn bẩy ngoại lai (\(D_{\text{Cook}} = 1.79\)) bẻ cong độ dốcOLStừ0.64lên1.75. - Ảo ảnh
ROC-AUC = 0.838–0.96Dưới Mất cân bằng1%–4%& BẫyMAPE/SMAPEGần Không: Khi tỷ lệ gian lận thẻ là1.5%–4%, một mô hình tuyến tính đạtROC-AUC = 0.838nhưng tại ngưỡng cảnh báo top-10%,Precisionchỉ đạt19.3%(MCC = 0.258, tức>80%lệnh chặn là khách hàng vô tội!). Trong dự báo nhu cầu SaaS/bán lẻ có ngày bằng0(y_i = 0),MAPEchia cho0trả vềinf, cònSMAPEtưởng đối xứng nhưng lại phạt thiếu (66.7%) nặng hơn hẳn thừa (40.0%). - Rò rỉ Tách tập Chồng lấn, Lời nguyền Người thắng
HPO& Ảo giác.632Bootstrap: ChiaRandom K-Foldtrên chuỗi lợi suất 10 ngày chồng lấn làm hai dòng kề nhau dùng chung90%cửa sổ nhiễu tương lai, thổi phồng \(R^2_{\text{cv}} = +0.328\) trên bước đi ngẫu nhiên không có tín hiệu (trong khiPurgedTimeSeriesSplitphơi bày \(R^2 = -3.874\)). Tương tự, quét lưới siêu tham số \(\lambda\) và đánh giá trên cùng một tậpK-Foldtạo thiên lệch lạc quan+0.368MSE (Flat CV = 9.556vs.Nested CV = 9.923), còn Bootstrap.632cổ điển báo sai số giả0.266khi mô hìnhp > nghi nhớ sạch dữ liệu huấn luyện (\(\overline{\text{err}} = 0\)), buộc phải dùng.632+nâng trọng số OOB lênw = 0.916để khôi phục ước lượng trung thực0.386.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 06 và bài thực hành linear_validation_lab (T1-P2-U01), học viên có năng lực:
- Chứng minh & Ổn định Đại số Tuyến tính Số cho Hồi quy Tuyến tính (Math & Numerical Rigor): Chứng minh định lý Gauss–Markov (
BLUE), các tính chất bất biến và cận đòn bẩy \(\frac{1}{n} \le h_{ii} \le 1\) của ma trận mũ \(\mathbf{H}\); giải thích vì sao Phương trình Chuẩn bình phương \(\kappa_2(\mathbf{X})^2\) trên ma trận Läuchli so vớiHouseholder QR(\(2np^2 - \frac{2}{3}p^3\)),SVD(\(\mathbf{X}^+\)) và bộ giải ngẫu nhiênRandNLA(Blendenpik/ổn định ngược 2024); đồng thời chứng minh vì sao siêu heuristic (metaheuristics) chịu chặn dưới \(\Omega(p)\) trên hàm lồi trơn so vớiL-BFGS,BGD,SGDvàMini-batch. - Thiết kế Chính quy hóa, Bền vững Ngoại lai & Hồi quy Chiều cao (
Regularization & Double Descent): Dẫn xuất nhân tử lọc phổ Ridge \(f_i = \sigma_i^2 / (\sigma_i^2 + \lambda)\) và chứng minh Định lý Hoerl–Kennard; thiết lập điều kiệnKKTvà phép toán ngưỡng mềm \(S(z, \gamma)\) củaLassokèm sàng lọc an toànGap Safe(skglm); chứng minh Định lý Hiệu ứng NhómElasticNetcủa Zou–Hastie; xây dựngHuber IRLSvà hồi quy phân vịPinball; và giải thích hiện tượng Benign Overfitting cùng cực trị \(\gamma = 1\) của Double Descent và trường hợp \(\lambda_{\text{opt}} < 0\) trên hiệp phương sai gai nhọn (Kobak 2020). - Dẫn xuất Hồi quy Logistic, Softmax
LSE, PhạtFirth& Hệ thốngFTRL-Proximal/EBM(GLM & Systems Rigor): Chứng minh tính lồi toàn cục củaLog-Lossqua Hessian \(\mathbf{H} = \mathbf{X}^\top\mathbf{W}\mathbf{X} + \lambda\mathbf{I}_0 \succeq \mathbf{0}\), dẫn xuất bướcIRLSvới đáp ứng làm việc \(\mathbf{z}^{(t)}\), khử tràn số bằngstable_sigmoidvàlog-sum-exp, khắc phục phân tách gần như hoàn toàn bằng \(L_2\)/Firth (tiên nghiệm Jeffreys), triển khaiFTRL-Proximal+ lượng tử hóaQ2.13(tiết kiệm75%RAM) + hiệu chuẩn lấy mẫu âm, và định vị mô hình cộng tính khả diễnGAM/EBM(GA²M+ làm sạchfANOVA) trong chuẩn quản trị rủi ro 2026. - Thẩm định Độ đo & Chẩn đoán Mô hình Nghiêm ngặt (
Metrics & Diagnostics Rigor): Phân tách bẫyMAPE/SMAPEvà \(R^2\) âm; lý giải tính bất biến tỷ lệ nền củaROC-AUCso vớiPR-AUC,PRG-AUC,MCC(nhị phân & đa lớp Gorodkin \(R_K\)),Log-Lossvà phân rã Murphy củaBrier Score; cài đặt trọn bộ chẩn đoánVIF, phần dư Studentized ngoài via Sherman–MorrisonPRESS, kiểm địnhBreusch–Pagan+ sai số chuẩnHC0–HC3, và khoảng cáchCook\(D_i\). - Kiến trúc Chiến lược Tách tập & Kiểm chứng Không Thiên lệch (
Validation Splitting Rigor): Lựa chọn chính xác giữaHoldout,K-Fold,StratifiedKFold,GroupKFold,PurgedTimeSeriesSplit(cửa sổ mở rộng/cuộn +Purge+Embargo+CPCV),Nested CVloại bỏ thiên lệch lạc quanHPO(Cawley–Talbot 2010 & khoảng tin cậyBates et al. 2024), và Bootstrap.632+trên người học quá khớp \(\overline{\text{err}} = 0\); kiểm chứng toàn bộ qua14/14hợp đồngpytestkhông phụ thuộcscipy/sklearn/pickle.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U01, Dòng R29 & R30)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R29–R30) |
Nâng cấp Chuẩn SOTA 2026 (ch-06) |
Mục trong Chương 06 | Mô-đun & Hợp đồng Kiểm thử (linear_validation_lab) |
|---|---|---|---|
| R29.1 Basic LR & Error Function | OLS, định lý Gauss–Markov (BLUE), ma trận mũ \(\mathbf{H}\) (\(\frac{1}{n} \le h_{ii} \le 1\)), Ridge (\(L_2\), phổ \(\sigma_i^2/(\sigma_i^2+\lambda)\), Hoerl–Kennard), Lasso (\(L_1\), KKT, hình học kim cương), ElasticNet (Grouping Effect), Huber & Pinball Quantile, Benign Overfitting / Double Descent & \(\lambda_{\text{opt}} < 0\) |
Trụ cột 1 (§1.1, §1.3) + Mermaid 1 + Widget regularization-geometry-explorer |
linear_models.py (solve_ols_qr, fit_ridge_svd, fit_lasso_cd, fit_elasticnet_cd, fit_huber_irls, fit_quantile_mm, simulate_double_descent_and_negative_ridge), Tests 1, 3, 4 |
| R29.2–3 Optimization Methods & GD Variants | Dạng đóng (Normal Eq \(\kappa^2\) vs. Householder QR \(2np^2-\frac{2}{3}p^3\) vs. SVD vs. Blendenpik/SAP 2024), Bậc nhất (BGD, SGD, Mini-batch, Coordinate Descent + Gap Safe, skglm), Bậc hai (Newton/IRLS, L-BFGS), và chặn dưới \(\Omega(p)\) vạch trần nhược điểm Siêu heuristic (Metaheuristics: Nelder–Mead) trên hàm lồi trơn |
Trụ cột 1 (§1.1–§1.3) + Trụ cột 3 (§3.2) | linear_models.py (solve_ols_normal_eq, solve_ols_qr, solve_ols_svd, lbfgs_minimize, compare_linear_optimizers), Tests 1, 2, 4 |
| R29.4 Evaluation Metrics for Regression | MSE, RMSE, MAE (trung bình vs. trung vị Bayes), MAPE/SMAPE bẫy chia 0 & bất đối xứng, \(R^2\) âm ngoài mẫu, Adjusted \(R^2\), WAPE, Bias %, và tổn thất Pinball bất đối xứng |
Trụ cột 2 (§2.2) + Trụ cột 3 (§3.1 Case 1) | logistic_and_metrics.py (compute_regression_metrics), Test 6 |
| R29.5 Model Diagnostics | Phần dư chuẩn hóa & Studentized ngoài (hằng đẳng thức Sherman–Morrison PRESS), Đa cộng tuyến VIF (\(\frac{1}{1-R_j^2}\) lật dấu), kiểm định Breusch–Pagan (\(\chi^2\)) + Sandwich HC0–HC3, Đòn bẩy \(h_{ii}\) & Khoảng cách Cook \(D_i\) |
Trụ cột 2 (§2.3) + Trụ cột 3 (§3.1 Cases 2, 3; §3.2) | linear_models.py (compute_regression_diagnostics, chi2_survival_prob), Test 5 |
| R29.6 Validation & Splitting Techniques | Holdout, K-Fold, StratifiedKFold, GroupKFold, PurgedTimeSeriesSplit (mở rộng vs. cuộn + Purge & Embargo + CPCV), Nested CV (Winner's Curse Cawley–Talbot & sai số chuẩn Bates et al. 2024), và Bootstrap .632 / .632+ (Efron–Tibshirani giải cứu \(\overline{\text{err}} = 0\)) |
Trụ cột 2 (§2.4) + Mermaid 3 + Widget validation-split-bias-arena |
validation_splitters.py (holdout_split, kfold_splits, stratified_kfold_splits, group_kfold_splits, purged_timeseries_splits, nested_cv_ridge_audit, bootstrap_632_plus), Tests 11, 12, 13 |
| R30.1–3 Logistic Foundation, MLE/GD & Multivariate | Logit link, stable_sigmoid, Log-Loss Bernoulli MLE, chứng minh Hessian \(\mathbf{H} \succeq \mathbf{0}\), IRLS/Newton-Raphson (\(\mathbf{z}^{(t)}\)) vs. BGD/SGD/L-BFGS, Softmax đa lớp log-sum-exp & tính đồng nhất hóa \(L_2\), Phân tách Gần như Hoàn toàn + Firth Jeffreys prior, FTRL-Proximal (Q2.13) & GAM/EBM (GA²M + fANOVA) |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1) + Mermaid 2 | logistic_and_metrics.py (LogisticRegressionWorkbench, SoftmaxMultinomialClassifier, FTRLProximalClassifier, quantize_q2_13, AdditiveSplineGAM), Tests 7, 8, 9 |
| R30.4 Evaluation & Metrics (Confusion, ROC/AUC) | Ma trận nhầm lẫn, Precision/Recall/F_1, ROC-AUC (Mann–Whitney bất biến \(\pi_+\)) vs. PR-AUC (đường nền \(\pi_+\) dưới 1%–5% hiếm), PRG-AUC (Flach–Kull), Log-Loss, Brier Score (phân rã Murphy), và MCC (nhị phân + đa lớp Gorodkin \(R_K\)) |
Trụ cột 2 (§2.2) + Widget logistic-irls-pr-roc-simulator |
logistic_and_metrics.py (compute_roc_auc, compute_pr_and_prg_auc, compute_classification_metrics, compute_multiclass_mcc), Test 10 |
R29.7 & R30.5 Industrial Tips (E29:E31) |
4 tình huống thực tế (Marketing Elasticity, Credit WoE/SR 11-7/EU AI Act, Fraud 1.5%, Google Streaming CTR FTRL/Q2.13), ngân sách RAM/độ trễ <1 ms CPU, 8 Phản mẫu & Bảng ngưỡng chẩn đoán |
Trụ cột 3 (§3.1–§3.3) + Trụ cột 4 | validation_splitters.py (run_full_ch06_benchmarks), scripts/run_lab_demo.py, Test 14 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-06) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (linear_validation_lab) |
|---|---|---|---|---|
| \(n, d, p\) | \(\mathbb{N}_+\) | Số quan sát \(n\), số đặc trưng gốc \(d\), tổng số cột thiết kế \(p = d+1\) (khi có cột \(\mathbf{1}_n\)) | Phân biệt rõ \(d\) đặc trưng với \(p\) tham số có \(\beta_0\) | n_samples, n_features, p |
| \(\mathbf{X}, \tilde{\mathbf{X}}\) | \(\mathbb{R}^{n \times p}, \mathbb{R}^{n \times d}\) | Ma trận thiết kế mở rộng \([\mathbf{1}_n, \mathbf{X}_{\text{raw}}]\) và ma trận đặc trưng đã quy tâm | Không phạt \(\beta_0\): dùng \(\mathbf{I}_0 = \operatorname{diag}(0, \mathbf{1}_d)\) | X, X_centered |
| \(\boldsymbol{\beta}, \beta_0, \mathbf{w}\) | \(\mathbb{R}^p, \mathbb{R}, \mathbb{R}^d\) | Vector tham số đầy đủ \((\beta_0, \mathbf{w}^\top)^\top\); \(\beta_0\) là hệ số chặn tự do | Tách rời hoàn toàn \(\beta_0\) khỏi \(\mathbf{w}\) chịu phạt | intercept, coef |
| \(\kappa_2(\mathbf{X})\) | \([1, \infty)\) | Chỉ số điều kiện phổ \(\sigma_1 / \sigma_{\min}\) (\(\kappa_2(\mathbf{X}^\top\mathbf{X}) = \kappa_2(\mathbf{X})^2\)) | Phân biệt với tỷ số trơn–lồi chặt \(\kappa = L/\mu\) | condition_number_x |
| \(\gamma, \hat{\gamma}_0\) | \((0, \infty), [0, 1]\) | Tỷ lệ quá tham số \(p/n\) (Double Descent) vs. lỗi vô thông tin .632+ |
Loại bỏ va chạm giữa ký hiệu Double Descent & .632+ |
aspect_ratio_gamma, no_info_gamma |
| \(\lambda_1, \lambda_2\) | \(\mathbb{R}_{\ge 0}\) | Hệ số phạt \(L_1\) và \(L_2\) (chuẩn hóa \(\frac{1}{2n}\) trong CD Lasso/EN; \(\frac{1}{2}\) trong Ridge SVD) | Ghi rõ hệ số \(1/(2n)\) hay \(1/2\) tại từng công thức | l1_alpha, l2_alpha |
| \(\pi_+\) | \((0, 1)\) | Tỷ lệ nền lớp dương \(P(Y=1)\) (đường nền ngẫu nhiên của PR-AUC) |
Tách biệt khỏi xác suất dự báo cá thể \(p_i = \sigma(\eta_i)\) | prevalence, y_prob |
| \(\Delta_{\text{purge}}, \Delta_{\text{emb}}\) | \(\mathbb{N}_{\ge 0}\) | Số bước xóa chồng lấn chân trời nhãn (purge) và vùng đệm sau kiểm định (embargo) |
Liên thông với đệm \(\Delta_{\text{gap}} \ge \Delta t_{\text{horizon}}\) ở ch-04 |
label_horizon, embargo |
| \(\alpha_{\text{ftrl}}, \beta_{\text{ftrl}}\) | \(\mathbb{R}_{>0}\) | Tham số tốc độ học & làm mượt trên từng tọa độ trong FTRL-Proximal |
Phân biệt với hệ số chặn \(\beta_0\) và mức phân vị \(\tau\) | alpha, beta |
Trụ cột 1 — Cơ sở Toán học & Đại số Tuyến tính Số cho Mô hình Tuyến tính, Chính quy hóa & Hồi quy Logistic#
1.1 Hồi quy Tuyến tính OLS, Định lý Gauss–Markov (BLUE), Ma trận Mũ \(\mathbf{H}\) & Ổn định Số học#
Xét mô hình tuyến tính \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta}^* + \boldsymbol{\varepsilon}\) với \(\mathbf{X} \in \mathbb{R}^{n \times p}\) (\(n \ge p\)) và vector sai số \(\boldsymbol{\varepsilon} \in \mathbb{R}^n\). Bộ ước lượng Bình phương Tối thiểu Thông thường (OLS — Ordinary Least Squares) cực tiểu hóa Tổng Bình phương Phần dư (RSS / SSE):
Vì \(\nabla_{\boldsymbol{\beta}}^2 S(\boldsymbol{\beta}) = 2\mathbf{X}^\top\mathbf{X} \succeq \mathbf{0}\), điều kiện bậc nhất \(\nabla_{\boldsymbol{\beta}} S(\boldsymbol{\beta}) = -2\mathbf{X}^\top(\mathbf{y} - \mathbf{X}\boldsymbol{\beta}) = \mathbf{0}\) dẫn đến Phương trình Chuẩn (Normal Equations):
Phần dư khớp \(\mathbf{e} := \mathbf{y} - \mathbf{X}\hat{\boldsymbol{\beta}}_{\text{OLS}}\) trực giao với không gian cột \(\mathcal{C}(\mathbf{X})\) (\(\mathbf{X}^\top\mathbf{e} = \mathbf{0}\)).
Định lý 1.1 (Định lý Gauss–Markov — BLUE)#
Giả sử bốn điều kiện Gauss–Markov thỏa mãn (lưu ý không cần giả định sai số tuân theo phân phối Chuẩn):
- Tuyến tính tham số: \(\mathbf{y} = \mathbf{X}\boldsymbol{\beta}^* + \boldsymbol{\varepsilon}\).
- Đầy đủ hạng cột: \(\operatorname{rank}(\mathbf{X}) = p \le n\).
- Ngoại sinh nghiêm ngặt: \(\mathbb{E}[\boldsymbol{\varepsilon} \mid \mathbf{X}] = \mathbf{0}\).
- Sai số cầu (Spherical Errors — phương sai đồng nhất & không tự tương quan): \(\operatorname{Cov}(\boldsymbol{\varepsilon} \mid \mathbf{X}) = \sigma^2 \mathbf{I}_n\) (\(0 < \sigma^2 < \infty\)).
Khi đó \(\hat{\boldsymbol{\beta}}_{\text{OLS}}\) là Bộ ước lượng Tuyến tính Không chệch Tốt nhất (BLUE — Best Linear Unbiased Estimator): với mọi bộ ước lượng tuyến tính không chệch \(\tilde{\boldsymbol{\beta}} = \mathbf{C}\mathbf{y}\) (\(\mathbf{C} \in \mathbb{R}^{p \times n}\)),
Chứng minh: Đặt \(\mathbf{A} := (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\) và \(\mathbf{D} := \mathbf{C} - \mathbf{A}\). Điều kiện không chệch \(\mathbb{E}[\mathbf{C}\mathbf{y} \mid \mathbf{X}] = \mathbf{C}\mathbf{X}\boldsymbol{\beta}^* = \boldsymbol{\beta}^*\) với mọi \(\boldsymbol{\beta}^* \in \mathbb{R}^p\) buộc \(\mathbf{C}\mathbf{X} = \mathbf{I}_p\). Vì \(\mathbf{A}\mathbf{X} = \mathbf{I}_p\), suy ra \(\mathbf{D}\mathbf{X} = \mathbf{0}\), kéo theo các số hạng chéo triệt tiêu: \(\mathbf{D}\mathbf{A}^\top = \mathbf{D}\mathbf{X}(\mathbf{X}^\top\mathbf{X})^{-1} = \mathbf{0}\) và \(\mathbf{A}\mathbf{D}^\top = \mathbf{0}\). Do đó:
vì với mọi \(\mathbf{v} \in \mathbb{R}^p\), \(\mathbf{v}^\top(\sigma^2\mathbf{D}\mathbf{D}^\top)\mathbf{v} = \sigma^2\|\mathbf{D}^\top\mathbf{v}\|_2^2 \ge 0\), dấu bằng xảy ra khi và chỉ khi \(\mathbf{D} = \mathbf{0}\). \(\blacksquare\) (Đồng thời \(s^2 := \frac{\|\mathbf{e}\|_2^2}{n-p}\) là ước lượng không chệch của \(\sigma^2\).)
Ma trận Mũ \(\mathbf{H}\) (Hat Matrix), Phép chiếu Phần dư \(\mathbf{M}\) & Cận Đòn bẩy \(\frac{1}{n} \le h_{ii} \le 1\)#
Đặt \(\mathbf{H} := \mathbf{X}(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top \in \mathbb{R}^{n \times n}\) (\(\hat{\mathbf{y}} = \mathbf{H}\mathbf{y}\)) và \(\mathbf{M} := \mathbf{I}_n - \mathbf{H}\) (\(\mathbf{e} = \mathbf{M}\mathbf{y} = \mathbf{M}\boldsymbol{\varepsilon}\)):
- Đối xứng & Lũy đẳng: \(\mathbf{H}^\top = \mathbf{H}\), \(\mathbf{H}^2 = \mathbf{H}\), \(\mathbf{M}^\top = \mathbf{M}\), \(\mathbf{M}^2 = \mathbf{M}\), \(\mathbf{H}\mathbf{M} = \mathbf{0}\).
- Vết & Tổng đòn bẩy: \(\operatorname{tr}(\mathbf{H}) = \operatorname{tr}\!\big((\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{X}\big) = \operatorname{tr}(\mathbf{I}_p) = p \implies \sum_{i=1}^n h_{ii} = p\), nên đòn bẩy trung bình \(\bar{h} = p/n\).
- Cận Đòn bẩy (Leverage Bounds): Từ \(h_{ii} = (\mathbf{H}^2)_{ii} = \sum_{k=1}^n h_{ik}^2 = h_{ii}^2 + \sum_{k \ne i} h_{ik}^2 \ge h_{ii}^2\), suy ra \(0 \le h_{ii} \le 1\). Khi mô hình có hệ số chặn (\(\mathbf{1}_n \in \mathcal{C}(\mathbf{X})\)), ta có \(\mathbf{H}\mathbf{1}_n = \mathbf{1}_n \implies \sum_{k=1}^n h_{ik} = 1\); áp dụng bất đẳng thức Cauchy–Schwarz thu được:
\[1 = \left(\sum_{k=1}^n h_{ik}\cdot 1\right)^2 \le \left(\sum_{k=1}^n h_{ik}^2\right)n = n\,h_{ii} \implies \frac{1}{n} \le h_{ii} \le 1.\]
Vì sao Phương trình Chuẩn Thất bại Số học So với Householder QR, SVD & RandNLA (Blendenpik/SAP 2024)#
Cho phân rã SVD rút gọn \(\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) với các giá trị kỳ dị \(\sigma_1 \ge \dots \ge \sigma_p > 0\) và chỉ số điều kiện \(\kappa_2(\mathbf{X}) := \sigma_1 / \sigma_p\):
- Phương trình Chuẩn bình phương chỉ số điều kiện: Vì \(\mathbf{X}^\top\mathbf{X} = \mathbf{V}\boldsymbol{\Sigma}^2\mathbf{V}^\top\), chỉ số điều kiện của ma trận Gram tăng vọt thành:
\[\kappa_2(\mathbf{X}^\top\mathbf{X}) = \frac{\sigma_1^2}{\sigma_p^2} = \kappa_2(\mathbf{X})^2.\]Trong chuẩn dấu phẩy động IEEE 754
float64(\(\varepsilon_{\text{mach}} \approx 2.22 \times 10^{-16}\)), ngay khi \(\kappa_2(\mathbf{X}) \gtrsim \varepsilon_{\text{mach}}^{-1/2} \approx 10^8\), bình phương \(\kappa_2(\mathbf{X})^2 \gtrsim 10^{16}\) triệt tiêu toàn bộ chữ số có nghĩa của \(\sigma_p^2\). Ví dụ trên ma trận Läuchli \(\mathbf{X} = \begin{bmatrix} 1 & 1 \\ \delta & 0 \\ 0 & \delta \end{bmatrix}\) với \(\delta = 3 \times 10^{-8}\) (\(\kappa_2(\mathbf{X}) = 4.71 \times 10^7 \implies \kappa_2^2 = 2.22 \times 10^{15}\)),NormalEqvọt sai số tương đối lên1.33e-02(và tại \(\delta = 10^{-8}\), \(\operatorname{fl}(1 + \delta^2) = 1.0\) đánh sập hẳn hạng ma trận về1!). Householder QR(\(2np^2 - \frac{2}{3}p^3\) FLOPs): Biến đổi \(\mathbf{X} = \mathbf{Q}\mathbf{R} = [\mathbf{Q}_1, \mathbf{Q}_2]\begin{bmatrix}\mathbf{R}_1 \\ \mathbf{0}\end{bmatrix}\) bằng \(p\) phép phản xạ trực giao (\(\kappa_2(\mathbf{Q})=1\)), không bao giờ tạo \(\mathbf{X}^\top\mathbf{X}\). Giải hệ tam giác trên \(\mathbf{R}_1\hat{\boldsymbol{\beta}} = \mathbf{Q}_1^\top\mathbf{y}\) bằng thế ngược mất \(p^2\) FLOPs, giữ sai số tuyến tính theo \(\kappa_2(\mathbf{X})\) (đạt2.22e-16trên Läuchli!).SVD& Giả nghịch đảo Moore–Penrose (\(\mathbf{X}^+ = \mathbf{V}\boldsymbol{\Sigma}^+\mathbf{U}^\top\)): Khi \(\mathbf{X}\) khuyết hạng (\(r < p\)) hoặc \(p > n\), lọc bỏ các \(\sigma_i \le \max(n, p)\varepsilon_{\text{mach}}\sigma_1\) và đặt các thành phần trong không gian hạch bằng \(0\) cho nghiệm chuẩn \(\ell_2\) tối thiểu duy nhất \(\hat{\boldsymbol{\beta}}_{\text{MN}} = \sum_{i=1}^r \frac{\mathbf{u}_i^\top\mathbf{y}}{\sigma_i}\mathbf{v}_i\) (chi phí R-SVD \(\approx 2np^2 + 11p^3\) FLOPs; đạt3.51e-16trên Läuchli).- Bộ giải Ngẫu nhiên
RandNLA(Blendenpik,SAP& Điều kiện Ổn định Ngược 2024): Khi \(n \gg p\) quá lớn khiếnQRchạm trần băng thông bộ nhớ, kỹ thuật Phác thảo-và-Tiền điều kiện (Sketch-and-Precondition,SAP) nhưBlendenpik(phác thảo \(\mathbf{S}\mathbf{X} = \mathbf{Q}_s\mathbf{R}\) rồi chạyLSQRtiền điều kiện bằng \(\mathbf{R}^{-1}\)) cắt chi phí xuống \(O(np\log n + p^3)\). Tuy nhiên, Meier, Nakatsukasa, Townsend & Webb (SIAM J. Matrix Anal. Appl. 2024,arXiv:2302.07202) chứng minh phiên bảnSAPkhởi tạo nóng từ nghiệm phác thảo không ổn định ngược (not backward stable) ở điều kiện xấu; ngay sau đó, Epperly, Meier & Nakatsukasa (arXiv:2406.03468,SPIR/FOSSILS) chứng minh chỉ cần bổ sung một bước làm mịn lặp (iterative refinement) trên hệ tiền điều kiện sẽ khôi phục hoàn toàn tính ổn định ngược với chi phí tiệm cận tối ưu!
1.2 Phân loại Bốn Họ Phương pháp Tối ưu hóa (R29) & Chặn dưới Siêu heuristic#
Trên hàm mất mát OLS \(f(\boldsymbol{\beta}) = \frac{1}{2n}\|\mathbf{y} - \mathbf{X}\boldsymbol{\beta}\|_2^2\), \(f\) là hàm \(L\)-trơn (\(L = \sigma_1^2/n\)) và \(\mu\)-lồi chặt (\(\mu = \sigma_p^2/n\)), với tỷ số điều kiện tối ưu hóa \(\kappa := L/\mu = \kappa_2(\mathbf{X})^2\):
| Họ Tối ưu hóa | Đại diện Tiêu biểu | Chi phí Mỗi bước & RAM | Tốc độ Hội tụ Lý thuyết (\(L\)-trơn, \(\mu\)-lồi chặt) | Khi nào Nên dùng / Khi nào Thất bại |
|---|---|---|---|---|
| 1. Dạng đóng (Closed-Form) | Normal Eq, Householder QR, SVD |
\(O(np^2 + p^3)\) tổng; \(O(np)\) RAM | 1 bước chính xác | Chuẩn mặc định khi \(p \lesssim 10^4\); tránh Normal Eq khi \(\kappa_2(\mathbf{X}) > 10^6\). |
| 2. Bậc nhất (First-Order) | BGD, SGD, Mini-batch, Coordinate Descent, SAGA/SVRG |
BGD: \(O(np)\); SGD: \(O(p)\); Mini-batch: \(O(b_{\text{batch}} p)\) |
BGD: \(O(\kappa \ln\frac{1}{\varepsilon})\) (NAG: \(O(\sqrt{\kappa}\ln\frac{1}{\varepsilon})\)); SGD: \(O(\frac{\sigma_g^2}{\mu^2 T})\); SAGA: \(O((n+\kappa)\ln\frac{1}{\varepsilon})\) |
Bắt buộc chuẩn hóa đặc trưng để giảm \(\kappa\); SGD/Mini-batch cho dữ liệu streaming \(n \gg 10^7\). |
| 3. Bậc hai & Tựa Newton | Newton–Raphson / IRLS, L-BFGS, TRON |
Newton: \(O(np^2+p^3)\); L-BFGS: \(O(np + mp)\) |
Newton: Bậc hai cục bộ (\(5\)–\(15\) bước); L-BFGS: Siêu tuyến tính |
Bất biến với \(\kappa\); newton-cholesky thắng thế áp đảo cho GLM bảng \(p \lesssim 5{,}000\); L-BFGS cho \(p\) trung bình–lớn. |
| 4. Siêu heuristic (Metaheuristics) | Nelder–Mead, GA, PSO, Simulated Annealing |
\(O(np)\) mỗi lần đánh giá hàm mục tiêu | Chặn dưới bậc không \(\Omega(p)\) (đến \(\Omega(e^p)\) nếu lưới phủ); Nelder–Mead có thể kẹt tại điểm không dừng dù hàm lồi \(\mathcal{C}^2\) (\(p \ge 2\))! |
Tuyệt đối không dùng cho bài toán lồi trơn (OLS, Ridge, Logistic); chỉ phù hợp hàm tổ hợp rời rạc (L0), không khả vi, hoặc HPO hộp đen (Meta Robyn Nevergrad). |
1.3 Hình học & Giải tích Chính quy hóa, Phạt Đàn hồi, Huber/Pinball & Double Descent#
A. Hồi quy Ridge (\(L_2\)), Nhân tử Lọc phổ & Định lý Hoerl–Kennard#
Giữ hệ số chặn \(\beta_0\) không bị phạt qua \(\mathbf{I}_0 = \operatorname{diag}(0, \mathbf{1}_d)\) đảm bảo tính bất biến tịnh tiến của dự báo (\(\mathbf{y} \mapsto \mathbf{y} + c \implies \hat{\beta}_0 \mapsto \hat{\beta}_0 + c\) giữ nguyên \(\hat{\mathbf{w}}\)):
Sau khi quy tâm \(\tilde{\mathbf{X}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) (hạng \(r\)) và \(\tilde{\mathbf{y}} = \mathbf{y} - \bar{y}\mathbf{1}_n\), hệ số góc và bậc tự do hiệu dụng có dạng phổ kín:
- Tương đương Tiên nghiệm Bayes Gauss: Với khả năng sinh \(\mathbf{y} \mid \mathbf{X}, \boldsymbol{\beta} \sim \mathcal{N}(\mathbf{X}\boldsymbol{\beta}, \sigma^2\mathbf{I}_n)\) và tiên nghiệm \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \tau^2\mathbf{I}_d)\), cực đại hóa hậu nghiệm (
MAP) trùng khít nghiệm Ridge tại \(\lambda = \sigma^2 / \tau^2\). - Định lý Cải thiện MSE (Hoerl & Kennard 1970): Với \(\boldsymbol{\alpha}^* = \mathbf{V}^\top\mathbf{w}^*\), tổng kỳ vọng sai số bình phương tham số tách thành tổng Bình phương Thiên lệch và Phương sai:
\[g(\lambda) := \mathbb{E}\big[\|\hat{\mathbf{w}}(\lambda) - \mathbf{w}^*\|_2^2\big] = \sum_{i=1}^d \frac{\lambda^2(\alpha_i^*)^2 + \sigma^2\sigma_i^2}{(\sigma_i^2 + \lambda)^2} \implies g'(0^+) = -2\sigma^2\sum_{i=1}^d \sigma_i^{-4} < 0.\]Do \(g'(0^+) < 0\) nghiêm ngặt, luôn tồn tại \(\lambda > 0\) cho \(\operatorname{MSE}(\hat{\mathbf{w}}_{\text{ridge}}(\lambda)) < \operatorname{MSE}(\hat{\mathbf{w}}_{\text{OLS}})\)—đặc biệt hiệu quả khi có giá trị kỳ dị \(\sigma_i \ll 1\) làm nổ phương sai OLS.
B. Hồi quy Lasso (\(L_1\)): KKT, Hình học Kim cương, Ngưỡng mềm & Sàng lọc An toàn Gap Safe#
Trên dữ liệu đã quy tâm và chuẩn hóa (\(\mathbf{A} := \tilde{\mathbf{X}}/\sqrt{n}\), \(\mathbf{b} := \tilde{\mathbf{y}}/\sqrt{n}\)), hàm mục tiêu Lasso với hệ số \(1/(2n)\) viết gọn thành:
- Điều kiện
KKT& Hình học Kim cương Tạo thưa: Dùng dưới vi phân \(\partial|w_j| = \{\operatorname{sgn}(w_j)\}\) khi \(w_j \neq 0\) và \([-1, 1]\) khi \(w_j = 0\), nghiệm tối ưu thỏa \(\mathbf{a}_j^\top(\mathbf{b} - \mathbf{A}\hat{\mathbf{w}}) \in \lambda_1 \partial|\hat{w}_j|\). Hình cầu \(L_2\) nhẵn khắp nơi nên đường đồng mức elipRSShầu như không bao giờ tiếp xúc đúng trên trục tọa độ; ngược lại, khối chóp bát diện / hình thoi \(L_1\) sở hữu các đỉnh và cạnh nhọn trên trục tọa độ có nón pháp tuyến mở rộng khắp \([-\lambda_1, \lambda_1]\), khóa cứng \(\hat{w}_j = 0\) hễ \(|\mathbf{a}_j^\top\mathbf{r}| < \lambda_1\). - Hạ tọa độ Chu kỳ (
Coordinate Descent) & Ngưỡng mềm: Giữ cố định \(\mathbf{w}_{-j}\) và đặt phần dư riêng \(\mathbf{r}^{(-j)} = \mathbf{b} - \sum_{k \neq j} w_k \mathbf{a}_k\), phép tối ưu đơn biến cho nghiệm đóng bằng Toán tử Ngưỡng mềm (Soft-Thresholding):\[S(z, \gamma) := \operatorname{sgn}(z)\max(|z| - \gamma, 0), \qquad \hat{w}_j \leftarrow \frac{S\big(\mathbf{a}_j^\top\mathbf{r}^{(-j)},\, \lambda_1\big)}{\|\mathbf{a}_j\|_2^2}.\] - Sàng lọc An toàn Động
Gap Safe(Ndiaye et al., JMLR 2017) &skglm: Từ điểm khả thi đối ngẫu \(\boldsymbol{\theta}_t = \frac{\mathbf{r}_t}{\max(\lambda_1, \|\mathbf{A}^\top\mathbf{r}_t\|_\infty)}\) và khoảng cách đối ngẫu \(G_{\lambda_1} = P_{\lambda_1}(\mathbf{w}_t) - D_{\lambda_1}(\boldsymbol{\theta}_t)\) (\(D_{\lambda_1}(\boldsymbol{\theta}) = \lambda_1\mathbf{b}^\top\boldsymbol{\theta} - \frac{\lambda_1^2}{2}\|\boldsymbol{\theta}\|_2^2\)), bán kính an toàn \(r_{\text{safe}} = \frac{\sqrt{2 G_{\lambda_1}}}{\lambda_1}\) chứng minh chắc chắn 100%: hễ \(|\mathbf{a}_j^\top\boldsymbol{\theta}_t| + \|\mathbf{a}_j\|_2\, r_{\text{safe}} < 1\) thì \(\hat{w}_j^* = 0\), cho phép cắt bỏ tới80%–95%đặc trưng rác ngay trong vòng lặp (nền tảng cho tốc độ gấp10–100xcủaskglmkết hợp tăng tốc Anderson).
C. ElasticNet (\(L_1 + L_2\)) & Chứng minh Định lý Hiệu ứng Nhóm (Zou & Hastie, 2005)#
Kết hợp phạt \(\lambda_1\|\mathbf{w}\|_1 + \frac{\lambda_2}{2}\|\mathbf{w}\|_2^2\) biến hàm mục tiêu thành \(\lambda_2\)-lồi chặt ngay cả khi \(p > n\) (gỡ trần tối đa \(n\) biến chọn được của Lasso), với cập nhật tọa độ \(w_j \leftarrow \frac{S(\mathbf{a}_j^\top\mathbf{r}^{(-j)}, \lambda_1)}{\|\mathbf{a}_j\|_2^2 + \lambda_2}\). Với các cột đã chuẩn hóa chuẩn đơn vị (\(\|\mathbf{x}_{\cdot, k}\|_2 = 1\), tương quan mẫu \(\rho_{ij} = \mathbf{x}_{\cdot, i}^\top\mathbf{x}_{\cdot, j}\)) và \(\hat{w}_i\hat{w}_j > 0\), lấy hiệu hai phương trình KKT tại \(i\) và \(j\) triệt tiêu hoàn toàn số hạng \(\lambda_1\operatorname{sgn}(\hat{w})\):
Nhờ cận này, khi hai biến marketing tương quan cao (\(\rho_{ij} \to 1\)), ElasticNet giữ trọng số của chúng xấp xỉ nhau thay vì chọn ngẫu nhiên một biến và ép biến kia về 0 như Lasso.
D. Hồi quy Bền vững Huber & Hồi quy Phân vị (Quantile / Pinball Regression)#
- Mất mát Huber (\(\delta > 0\), thường chọn \(\delta = 1.345\hat{\sigma}\) cho hiệu quả Gauss
95%):\[L_\delta(u) = \begin{cases} \frac{1}{2}u^2, & |u| \le \delta \\ \delta\big(|u| - \frac{1}{2}\delta\big), & |u| > \delta \end{cases}, \qquad w_i^{\text{IRLS}} = \begin{cases} 1, & |e_i| \le \delta \\ \delta / |e_i|, & |e_i| > \delta \end{cases},\]chặn cứng lực kéo của phần dư ngoại lai \(|\psi_\delta(e_i)| \le \delta\) trong khi vẫn giữ độ mượt \(\mathcal{C}^1\) gần \(0\). - Mất mát Phân vị /
Pinball(\(\tau \in (0, 1)\)):\[\rho_\tau(u) = u\big(\tau - \mathbb{I}[u < 0]\big) = \max\big(\tau u,\, (\tau - 1)u\big).\]Đạo hàm phải của kỳ vọng rủi ro \(\partial_+\mathbb{E}[\rho_\tau(Y - \hat{y})\mid\mathbf{x}] = F_{Y|\mathbf{x}}(\hat{y}) - \tau = 0\) chứng minh nghiệm cực tiểu tối ưu củaPinballchính là phân vị có điều kiện \(Q_\tau(Y \mid \mathbf{x})\)—công cụ cốt lõi cho bất đối xứng tồn kho/thiếu hàng (ch-13) vàConformalized Quantile Regression(ch-03).
E. Benign Overfitting, Double Descent (\(\gamma = p/n\)) & Phạt Ridge Âm (\(\lambda_{\text{opt}} < 0\))#
Khi \(p > n\) và \(\operatorname{rank}(\mathbf{X}) = n\), nghiệm chuẩn \(\ell_2\) tối thiểu không phạt \(\hat{\boldsymbol{\beta}}_{\min} = \mathbf{X}^+\mathbf{y}\) nội suy sạch tập huấn luyện (\(\mathbf{X}\hat{\boldsymbol{\beta}}_{\min} = \mathbf{y}\)):
- Hai Hạng Hiệu dụng Phổ (
Bartlett et al., PNAS 2020): Chia phổ \(\mathbf{\Sigma}\) tại chỉ số \(k^*\) sao cho \(r_{k^*}(\mathbf{\Sigma}) = \frac{\sum_{i>k^*}\lambda_i}{\lambda_{k^*+1}} \ge b n\). Overfitting là lành tính (benign) (\(R(\hat{\boldsymbol{\beta}}_{\min}) \to 0\)) khi không gian tín hiệu thấp chiều (\(k^* = o(n)\)) nhưng đuôi phổ phẳng trải rộng rất nhiều chiều (\(R_{k^*}(\mathbf{\Sigma}) = \frac{(\sum_{i>k^*}\lambda_i)^2}{\sum_{i>k^*}\lambda_i^2} \gg n\)), giúp nhiễu nhãn bị phân tán đồng đều sang vô số hướng trực giao vô hại. - Cực tại \(\gamma = p/n = 1\) (
Hastie et al., Ann. Stat. 2022): Trong chế độ đẳng hướng \(\mathbf{\Sigma} = \mathbf{I}_p\), rủi ro bằng \(\sigma^2\frac{\gamma}{1-\gamma}\) (\(\gamma < 1\)) và \(r^2(1 - \frac{1}{\gamma}) + \frac{\sigma^2}{\gamma-1}\) (\(\gamma > 1\)), bùng nổ thành cực vô hạn tại \(\gamma = 1\) (\(p=n\)) do \(\sigma_{\min}(\mathbf{X}/\sqrt{n}) \to |1-\sqrt{\gamma}| \to 0\), rồi giảm lại ở nhánh phải (\(\gamma > 1\)). Tuning Ridge \(\lambda^* > 0\) triệt tiêu hoàn toàn cực \(\gamma = 1\) này. - Khi \(\lambda_{\text{opt}} < 0\) (
Kobak et al., JMLR 2020): Trong mô hình hiệp phương sai gai nhọn \(\mathbf{\Sigma} = \mathbf{\Sigma}_{\text{sig}} + \sigma_{\text{tail}}^2\mathbf{I}_{p_{\text{tail}}}\) (\(p_{\text{tail}} \gg n\)), ma trận Gram \(\mathbf{X}\mathbf{X}^\top \approx \mathbf{X}_{\text{sig}}\mathbf{X}_{\text{sig}}^\top + \operatorname{tr}(\mathbf{\Sigma}_{\text{tail}})\mathbf{I}_n\) tự tạo một lượng co rút ngầm \(\lambda_{\text{imp}} \approx \operatorname{tr}(\mathbf{\Sigma}_{\text{tail}})\). Nếu \(\lambda_{\text{imp}}\) đã lớn hơn mức tối ưu cho các gai tín hiệu, mọi \(\lambda > 0\) đều co rút quá mức; khi đó \(\lambda_{\text{opt}} < 0\) (nằm trên \((-\sigma_{\min}^2(\mathbf{X}), 0)\)) mới tối thiểu hóa sai số kiểm tra!
1.4 Hồi quy Logistic, IRLS, Softmax Đa lớp LSE & Giải cứu Phân tách Bằng Firth / \(L_2\)#
A. Liên kết Logit, Tính toán An toàn Số & Log-Loss Từ MLE#
Mô hình hóa \(Y_i \mid \mathbf{x}_i \sim \operatorname{Bernoulli}(p_i)\) qua hàm liên kết chính tắc logit \(\eta_i := \mathbf{x}_i^\top\boldsymbol{\beta} = \ln\frac{p_i}{1-p_i}\) cho \(p_i = \sigma(\eta_i) = (1 + e^{-\eta_i})^{-1}\). Để tránh tràn số mũ float64 khi \(|\eta_i| > 709\) và tránh \(\ln(0)\) trong Log-Loss, sử dụng công thức phân nhánh ổn định:
Từ cực đại hóa hợp lý Bernoulli \(\prod_{i=1}^n p_i^{y_i}(1-p_i)^{1-y_i}\) (kèm phạt \(L_2\) bỏ qua \(\beta_0\)), hàm mất mát đối âm Log-Loss chính quy hóa là:
B. Chứng minh Hessian PSD (Lồi Toàn cục) & Dẫn xuất IRLS / Newton–Raphson#
Lấy đạo hàm bậc nhất và bậc hai của \(J(\boldsymbol{\beta})\) với ma trận trọng số đường chéo \(\mathbf{W} := \operatorname{diag}\big(p_1(1-p_1), \dots, p_n(1-p_n)\big)\):
Vì \(p_i \in (0, 1) \implies w_i = p_i(1-p_i) > 0\), với mọi \(\mathbf{v} \in \mathbb{R}^p\):
Do đó \(J(\boldsymbol{\beta})\) lồi toàn cục (mọi cực tiểu địa phương đều là cực tiểu toàn cục; \(L\)-trơn với \(L \le \frac{1}{4}\sigma_1(\mathbf{X})^2 + \lambda\)). Thay \(\mathbf{g}\) và \(\mathbf{H}\) vào bước Newton–Raphson \(\boldsymbol{\beta}^{(t+1)} = \boldsymbol{\beta}^{(t)} - \mathbf{H}^{-1}\mathbf{g}\) và nhóm hạng tử cho phương trình Bình phương Tối thiểu Tái trọng số Lặp (IRLS):
trong đó \(\mathbf{z}^{(t)}\) là đáp ứng làm việc (working response). IRLS đạt hội tụ bậc hai chỉ trong ~5–12 vòng lặp (vượt trội hẳn so với hội tụ tuyến tính của BGD/SGD khi \(p \lesssim 5{,}000\)).
C. Hồi quy Softmax Đa lớp, Tính Đồng nhất hóa & Log-Sum-Exp#
Cho \(K\) lớp với ma trận tham số \(\mathbf{B} = [\boldsymbol{\beta}_1, \dots, \boldsymbol{\beta}_K] \in \mathbb{R}^{p \times K}\) và logit \(\eta_{ik} = \mathbf{x}_i^\top\boldsymbol{\beta}_k\):
- Ổn định
Log-Sum-Exp(LSE): Đặt \(m_i = \max_{1 \le c \le K}\eta_{ic}\), ta có \(\operatorname{LSE}(\boldsymbol{\eta}_i) = m_i + \ln\sum_{c=1}^K e^{\eta_{ic} - m_i}\), suy ra \(\ln p_{ik} = \eta_{ik} - \operatorname{LSE}(\boldsymbol{\eta}_i)\) và gradient \(\nabla_{\boldsymbol{\beta}_k} J = \mathbf{X}^\top(\mathbf{p}_{\cdot, k} - \mathbf{y}_{\cdot, k}) + \lambda\mathbf{I}_0\boldsymbol{\beta}_k\). - Thừa tham số \(K\) vs. \(K-1\): Nếu không phạt, phép tịnh tiến \(\boldsymbol{\beta}_k \mapsto \boldsymbol{\beta}_k - \boldsymbol{\psi}\) không làm đổi xác suất softmax, sinh không gian hạch \(p\) chiều. Cố định lớp chuẩn \(\boldsymbol{\beta}_K \equiv \mathbf{0}\) đưa về \(K-1\) lớp nhưng phá đối xứng; ngược lại, phạt \(L_2\) đối xứng (\(\lambda > 0\)) trên cả \(K\) cột buộc tự động ràng buộc tổng bằng không \(\sum_{k=1}^K \hat{\boldsymbol{\beta}}_{k, 1:d} = \mathbf{0}\), khôi phục tính duy nhất chặt chẽ.
D. Phân tách Gần như Hoàn toàn (Albert & Anderson, 1984) & Giải pháp Firth / \(L_2\)#
Khi tồn tại siêu phẳng phân tách hoàn toàn hoặc gần như hoàn toàn (quasi-complete separation: \((2y_i - 1)\mathbf{v}^\top\mathbf{x}_i \ge 0\) với ít nhất một điểm \(> 0\), phổ biến khi một danh mục hiếm chỉ chứa toàn nhãn 1 hoặc 0), \(\mathbf{v}^\top\nabla\text{NLL}(\boldsymbol{\beta}) < 0\) tại mọi điểm hữu hạn, đẩy \(\|\hat{\boldsymbol{\beta}}_{\text{MLE}}\|_2 \to +\infty\) và làm ma trận thông tin Fisher \(\mathbf{X}^\top\mathbf{W}\mathbf{X}\) suy biến (\(\lambda_{\min} \to 0\)).
- Phạt Ridge \(L_2\) (\(\lambda > 0\)): Tạo tính cưỡng bức \(J(\boldsymbol{\beta}) \to +\infty\) khi \(\|\boldsymbol{\beta}_{1:d}\|_2 \to \infty\), giữ nghiệm hữu hạn và ổn định hiệu chuẩn.
- Hợp lý Phạt Firth (
Firth, Biometrika 1993): Cộng tiên nghiệm bất biến Jeffreys \(\ell^*(\boldsymbol{\beta}) = \ell(\boldsymbol{\beta}) + \frac{1}{2}\ln\det(\mathbf{X}^\top\mathbf{W}\mathbf{X})\) tạo hàng rào logarit chặn \(\det(\mathbf{X}^\top\mathbf{W}\mathbf{X}) \to 0\). Với đòn bẩy có trọng số \(h_{ii} = w_i\mathbf{x}_i^\top(\mathbf{X}^\top\mathbf{W}\mathbf{X})^{-1}\mathbf{x}_i\), phương trình điểm số hiệu chỉnh:\[U_j^*(\boldsymbol{\beta}) = \sum_{i=1}^n \Big[\big(y_i + \tfrac{h_{ii}}{2}\big) - p_i(1 + h_{ii})\Big]x_{ij} = 0\]vừa triệt tiêu thiên lệch tiệm cận bậc \(O(n^{-1})\) trên mẫu nhỏ, vừa đảm bảo nghiệm luôn hữu hạn và hội tụ ngay cả dưới phân tách hoàn toàn!
Trụ cột 2 — Kiến trúc Hệ thống Học Tuyến tính/Logistic Sản xuất, Độ đo, Chẩn đoán & Chiến lược Tách tập#
2.1 Kiến trúc Huấn luyện & Phục vụ SOTA 2024–2026: FTRL-Proximal (Q2.13), newton-cholesky & EBM/GAM#
-
Học Trực tuyến Quy mô Tỷ Đặc trưng — Google
FTRL-Proximal(McMahan et al., KDD 2013): Trong đấu giá quảng cáo thời gian thực (<10 msSLA),SGDvới \(L_1\) dao động quanh0.0và tốn RAM khổng lồ để lưu hàng tỷ trọng số nhiễu gần0.FTRL-Proximalchỉ duy trì đúng hai số tích lũy trên mỗi đặc trưng xuất hiện \((z_i, n_i)\) với tốc độ học thích ứng \(\eta_{t,i} = \frac{\alpha_{\text{ftrl}}}{\beta_{\text{ftrl}} + \sqrt{n_i}}\) và quy tắc cập nhật đóng thưa tuyệt đối:\[n_i^{\text{new}} = n_i + g_{t,i}^2, \quad \sigma_i = \frac{\sqrt{n_i^{\text{new}}} - \sqrt{n_i}}{\alpha_{\text{ftrl}}}, \quad z_i \leftarrow z_i + g_{t,i} - \sigma_i w_{t,i},\]\[w_{t+1,i} = \begin{cases} 0, & |z_i| \le \lambda_1 \\ -\left(\dfrac{\beta_{\text{ftrl}} + \sqrt{n_i^{\text{new}}}}{\alpha_{\text{ftrl}}} + \lambda_2\right)^{-1}\big(z_i - \operatorname{sgn}(z_i)\lambda_1\big), & |z_i| > \lambda_1 \end{cases}.\]Ba tối ưu kỹ thuật giúp Google giảm chi phí hạ tầng đột biến:
- Lượng tử hóa
Q2.13làm tròn ngẫu nhiên: Vì phạt \(L_1+L_2\) giữ hầu hết \(|w_i| < 2\), lưu trọng số bằng số dấu phẩy tĩnh 16-bit (1dấu +2nguyên +13thập phân, độ phân giải \(2^{-13}\)) dùng nhiễu đều \(R \sim \mathcal{U}[0,1)\): \(v_q = 2^{-13}\lfloor 2^{13}v + R \rfloor\) giữ sai số lượng tử hóa không thiên lệch (\(\mathbb{E}[v_q]=v\)) và cắt75%RAM so vớifloat64(50%so vớifloat32) với độ lệchLog-Lossgần bằng0! - Lọc nạp Bloom đếm (Counting Bloom Admission): Chỉ cấp phát cặp \((z_i, n_i)\) cho đặc trưng xuất hiện \(\ge k\) lần để chặn từ khóa gõ nhầm làm nổ RAM.
- Lấy mẫu âm + Hiệu chuẩn Log-Odds: Giữ
100%lượt nhấp (\(y=1\)) và chỉ lấy mẫu \(r \in (0, 1]\) các lượt không nhấp (\(y=0\)), sau đó cộng đúng hằng số phân tích \(\ln(r)\) vào logit lúc suy luận: \(\operatorname{logit}(p_{\text{cal}}) = \operatorname{logit}(p_{\text{sub}}) + \ln(r)\). (Mở rộng 2024: Khi cần bất định xác suất trên luồng trực tuyến cho bandit/định giá khởi đầu lạnh,Online LaplacehoặcBONG— Jones, Chang & Murphy, NeurIPS 2024 — cập nhật ma trận hiệp phương sai hậu nghiệm \(\mathbf{\Sigma}_t\) theo bước gradient tự nhiên để điều chỉnh độ dốc sigmoid theo \(\big(1 + \frac{\pi}{8}\mathbf{x}_t^\top\mathbf{\Sigma}_t\mathbf{x}_t\big)^{-1/2}\).)
- Lượng tử hóa
-
Chuẩn Bảng Dữ liệu Giải thích được 2026 —
GAM& Explainable Boosting Machines (EBM,InterpretML): Khi dữ liệu bảng tín dụng hoặc y tế chứa ngưỡng phi tuyến (ví dụ hình chữ U của biến rủi ro \(x_1^2\)), hồi quy logistic tuyến tính bỏ sót tín hiệu nghiêm trọng. Mô hình Cộng tính Tổng quát (GAM) vàEBM(GA²M, Lou et al. 2013; Nori et al. 2019–2026) mở rộng dự báo thành:\[g\big(\mathbb{E}[Y \mid \mathbf{x}]\big) = \beta_0 + \sum_{j=1}^d f_j(x_j) + \sum_{(j,k)\in\mathcal{I}} f_{jk}(x_j, x_k).\]- Cơ chế
EBM: Boosting vòng tròn (round-robin) trên từng đặc trưng một với tốc độ học cực nhỏ (\(\eta \sim 0.01\)) lồng trong bagging ngoài (ngăn cây tham lam cướp tín hiệu giữa các biến tương quan, đồng thời cung cấp khoảng tin cậy cho từng hàm hình dạng \(f_j\)), cộng thuật toánFASTquét tương tác 2 chiều trên biểu đồ tần suất \(O(b^2)\), rồi nén toàn bộ cây thành bảng tra cứu mảng1D/2Dsuy luận ở mức micro-giây! - Làm sạch
fANOVA(Lengerich et al., AISTATS 2020): Vì có thể dời bất kỳ hàm \(h(x_j)\) nào giữa \(f_j\) và \(f_{jk}\) mà không đổi tổng dự báo, thuật toán Mass-Moving Purification áp đặt trực giao biên \(\mathbb{E}_{X_j}[f_{jk}(X_j, x_k) \mid x_k] = 0\) giúp các biểu đồ đóng góp \(f_j(x_j)\) có tính nhận dạng duy nhất trước kiểm toánSR 11-7vàEU AI Act!
- Cơ chế
2.2 Độ đo Đánh giá Nghiêm ngặt: Bẫy MAPE/SMAPE & ROC-AUC vs. PR-AUC, MCC, Brier#
A. Bẫy Độ đo Hồi quy (Đặc biệt trên Dữ liệu Cầu Gần Không)#
MSE/RMSEvs.MAE:MSEđược tối ưu bởi kỳ vọng có điều kiện \(\mathbb{E}[Y \mid \mathbf{x}]\);MAE\(= 2\rho_{0.5}\) được tối ưu bởi trung vị \(\operatorname{Med}(Y \mid \mathbf{x})\)—khác biệt lớn trên dữ liệu lệch phải (LTV, chi tiêu).- Bẫy Chết người của
MAPE&SMAPE:MAPE\(= \frac{100\%}{n}\sum\frac{|y_i - \hat{y}_i|}{|y_i|}\) chia cho0(inf) bất cứ khi nào có ngày không đơn hàng (\(y_i = 0\)), đồng thời bị chặn trên ở100%khi dự báo thấp (\(\hat{y}_i = 0\)) nhưng không giới hạn trên khi dự báo vượt, ép mô hình tối ưu hóa theoMAPEthiên lệch dự báo thiếu một cách có hệ thống.SMAPE\(= \frac{100\%}{n}\sum\frac{|y_i - \hat{y}_i|}{(|y_i| + |\hat{y}_i|)/2}\) không hề đối xứng: khi \(y_i = 0, \hat{y}_i > 0\), mọi sai số đều bị kẹp cứng ở200%bất kể \(\hat{y}_i = 0.1\) hay \(50{,}000\); còn tại \(y_i = 100\), dự báo thấp-50(\(\hat{y}_i = 50\)) chịu lỗi66.7%trong khi dự báo cao+50(\(\hat{y}_i = 150\)) chỉ chịu40.0%! Hãy thay thế bằngWAPE(\(\frac{\sum |y_i - \hat{y}_i|}{\sum |y_i|}\)),Bias %,MASE, hoặcPinball Loss\(\rho_\tau\).
- \(R^2\) Âm Ngoài mẫu & Giới hạn Adjusted-\(R^2\): Trên tập huấn luyện có hệ số chặn,
OLSđảm bảo \(R^2 \in [0, 1]\); nhưng trên tập kiểm tra ngoài mẫu, trực giao phần dư không còn giữ nữa nên \(R^2 = 1 - \frac{\text{SSE}_{\text{test}}}{\text{SST}_{\text{test}}} \in (-\infty, 1]\) có thể âm sâu nếu mô hình dự báo tệ hơn trung bình mẫu \(\bar{y}_{\text{test}}\).Adj-R^2\(= 1 - (1-R^2)\frac{n-1}{n-p}\) chỉ hợp lệ choOLStrong mẫu, vô nghĩa vớiRidge/Lassohoặc khi \(p \ge n\).
B. Phân loại Mất cân bằng Nghiêm trọng (\(\pi_+ \in [1\%, 5\%]\)): ROC-AUC vs. PR-AUC, PRG-AUC, MCC & Brier#
Với tỷ lệ dương nền \(\pi_+ = \frac{P}{P+N}\):
- Đẳng thức Liên kết
ROC–PR& Sụp đổPrecision(Davis & Goadrich 2006;Saito & Rehmsmeier 2015):ROC-AUCtương đương thống kê hạng Mann–Whitney \(U / (n_+ n_-) = P(S_+ > S_-) + \frac{1}{2}P(S_+ = S_-)\), điều kiện hóa tách biệt trên \(Y=1\) (TPR) và \(Y=0\) (FPR), nênROC-AUCbất biến hoàn toàn với tỷ lệ nền \(\pi_+\) và mù trước hiệu chuẩn xác suất. Ngược lại, qua định lý Bayes:\[\text{Precision}(\tau) = \frac{\pi_+ \cdot \text{TPR}(\tau)}{\pi_+ \cdot \text{TPR}(\tau) + (1 - \pi_+)\cdot \text{FPR}(\tau)}.\]Khi \(\pi_+ = 0.01\) (1%gian lận), mẫu số \((1 - \pi_+)\cdot \text{FPR}\) nhân phóng đại báo động giả lên99xlần so với số lượng gian lận thật! Trong không gianPR, mô hình ngẫu nhiên có đường nền bằng đúng \(\pi_+\) (không phải0.50!), và cần tínhPR-AUCbằng Average Precision theo bậc thang (tránh nội suy tuyến tính hình thang thổi phồng đường cong hyperbol). Để khôi phục tính hợp lệ của nội suy tuyến tính và đưa đường nền ngẫu nhiên về0ở mọi \(\pi_+\), Flach & Kull (NeurIPS 2015) đề xuấtPRG-AUCtrên tọa độ \(\text{prec}_G = 1 - \frac{\pi_+}{1-\pi_+}\frac{\text{FP}}{\text{TP}}\) và \(\text{rec}_G = 1 - \frac{\pi_+}{1-\pi_+}\frac{\text{FN}}{\text{TP}}\). - Hệ số Tương quan Matthews (
MCC, Chicco & Jurman 2020/2023) & Gorodkin \(R_K\):\[\text{MCC} = \frac{\text{TP}\cdot\text{TN} - \text{FP}\cdot\text{FN}}{\sqrt{(\text{TP}+\text{FP})(\text{TP}+\text{FN})(\text{TN}+\text{FP})(\text{TN}+\text{FN})}} \in [-1, +1].\]Khác với Accuracy (đạt98.5%dù đoán toàn0) và \(F_1\) (bỏ qua \(\text{TN}\) và biến đổi khi tráo nhãn \(0 \leftrightarrow 1\)),MCCbằng chính tương quan Pearson \(\phi(Y, \hat{Y})\), đối xứng tuyệt đối, cho0với mọi mô hình hằng số/ngẫu nhiên, và chỉ cao khi cả 4 ô ma trận nhầm lẫn cùng tốt (mở rộng đa lớp \(K\) qua công thức Gorodkin \(R_K\)). - Quy tắc Điểm Chuẩn Nghiêm ngặt (
Log-Loss& Phân rã Murphy củaBrier Score):Log-LossvàBrier Score\(\text{BS} = \frac{1}{n}\sum(\hat{p}_i - y_i)^2\) đạt cực tiểu duy nhất tại xác suất hậu nghiệm thật. Khi gộp vào các hộp xác suất \(B_b\) (\(p_b, \bar{y}_b\)), Murphy (1973) phân tách chính xácBrier Scorethành:\[\text{BS}_{\text{binned}} = \underbrace{\frac{1}{n}\sum_{b=1}^M n_b(p_b - \bar{y}_b)^2}_{\text{Reliability (Hiệu chuẩn } \downarrow\text{)}} - \underbrace{\frac{1}{n}\sum_{b=1}^M n_b(\bar{y}_b - \bar{y})^2}_{\text{Resolution (Độ phân giải } \uparrow\text{)}} + \underbrace{\bar{y}(1 - \bar{y})}_{\text{Uncertainty}}.\](Xemch-07để học sâu vềECE,Platt Scaling,Isotonic,Venn-Abersvà tối ưu ngưỡng \(\tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\).)
2.3 Chẩn đoán Mô hình (Model Diagnostics): Phần dư Studentized, VIF, Breusch–Pagan + HC3 & Khoảng cách Cook#
- Phần dư Chuẩn hóa & Studentized Ngoài via Hằng đẳng thức Xóa 1 dòng Sherman–Morrison:
Vì \(\operatorname{Cov}(\mathbf{e} \mid \mathbf{X}) = \sigma^2(\mathbf{I}_n - \mathbf{H})\), phần dư thô có phương sai không đồng nhất \(\sigma^2(1 - h_{ii})\). Đặt phần dư chuẩn hóa nội bộ \(r_i = \frac{e_i}{s\sqrt{1 - h_{ii}}}\). Áp dụng công thức đảo hạng 1 Sherman–Morrison cho \(\mathbf{X}_{(-i)}^\top\mathbf{X}_{(-i)} = \mathbf{X}^\top\mathbf{X} - \mathbf{x}_i\mathbf{x}_i^\top\):
\[\hat{\boldsymbol{\beta}} - \hat{\boldsymbol{\beta}}_{(-i)} = \frac{(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{x}_i e_i}{1 - h_{ii}} \implies e_{(-i)} := y_i - \mathbf{x}_i^\top\hat{\boldsymbol{\beta}}_{(-i)} = \frac{e_i}{1 - h_{ii}} \quad \Big(\text{PRESS} = \sum_{i=1}^n e_{(-i)}^2\Big),\]và phần dư Studentized ngoài tuân theo phân phối \(t_{n-p-1}\) chuẩn xác dưới giả định Gauss:\[t_i = \frac{e_i}{s_{(-i)}\sqrt{1 - h_{ii}}} = r_i\sqrt{\frac{n - p - 1}{n - p - r_i^2}} \qquad \Big(s_{(-i)}^2 = s^2\frac{n-p-r_i^2}{n-p-1}\Big).\]
- Hệ số Phóng đại Phương sai (
VIF— Variance Inflation Factor): Trên ma trận tương quan các biến dự báo \(\mathbf{R}_{XX}\), áp dụng phép đảo khối Schur cho thấy phần tử chéo nghịch đảo chính là:\[\text{VIF}_j := \big[(\mathbf{R}_{XX})^{-1}\big]_{jj} = \frac{1}{1 - R_j^2}, \qquad \operatorname{Var}(\hat{\beta}_j \mid \mathbf{X}) = \frac{\sigma^2}{\text{SST}_j}\,\text{VIF}_j,\]với \(R_j^2\) là \(R^2\) khi hồi quy \(X_j\) theo \(d-1\) biến còn lại.VIF >= 10(cảnh báo từ>= 5) phá hỏng ước lượng tham số riêng lẻ và hay làm lật dấu hệ số, mặc dù dự báo \(\hat{y}\) trong phân phối vẫn giữ phương sai tổng \(\sigma^2 p\) (nhưng sẽ vỡ khi tương quan giữa các đặc trưng đổi chiều ngoài sản xuất!). - Kiểm định Phương sai Thay đổi
Breusch–Pagan& Sai số Chuẩn SandwichHC3:- Kiểm định
Breusch–Pagan/ Koenker: Hồi quy bình phương phần dư \(e_i^2\) theo \(\mathbf{X}\); thống kê nhân tử Lagrange \(\text{LM} = n R_{\text{aux}}^2 \xrightarrow{d} \chi^2_d\) bác bỏ giả định phương sai đồng nhất khi \(p < 0.05\). -
Ước lượng Hiệp phương sai Bền vững Sandwich
HC0–HC3: Dưới \(\operatorname{Cov}(\boldsymbol{\varepsilon} \mid \mathbf{X}) = \operatorname{diag}(\sigma_1^2,\dots,\sigma_n^2)\), thay \(s^2(\mathbf{X}^\top\mathbf{X})^{-1}\) sai lệch bằng ma trận kẹp \((\mathbf{X}^\top\mathbf{X})^{-1}\big(\sum_{i=1}^n \hat{\omega}_i \mathbf{x}_i\mathbf{x}_i^\top\big)(\mathbf{X}^\top\mathbf{X})^{-1}\), trong đó:HC0: \(e_i^2\);HC1: \(\frac{n}{n-p}e_i^2\);HC2: \(\frac{e_i^2}{1-h_{ii}}\); và chuẩn khuyến nghị mặc định trên mẫu hữu hạnHC3(MacKinnon & White 1985; Long & Ervin 2000): \(\hat{\omega}_i = \frac{e_i^2}{(1 - h_{ii})^2} = e_{(-i)}^2\), chống tụt sai số chuẩn tại các điểm đòn bẩy cao. 4. Đòn bẩy \(h_{ii}\) & Khoảng cáchCook(\(D_i\)): Đo trực tiếp độ dịch chuyển tổng thể trên toàn bộ vector dự báo \(\hat{\mathbf{y}}\) khi xóa quan sát \(i\):\[D_i := \frac{\|\hat{\mathbf{y}} - \hat{\mathbf{y}}_{(-i)}\|_2^2}{p s^2} = \frac{e_i^2}{p s^2}\cdot\frac{h_{ii}}{(1 - h_{ii})^2} = \frac{r_i^2}{p}\cdot\frac{h_{ii}}{1 - h_{ii}}.\]Ngưỡng kiểm tra thực tế: \(h_{ii} > 2p/n\) cho đòn bẩy cao và \(D_i > 4/n\) (hoặc \(D_i > 1.0\) báo động đỏ) cho điểm ngoại lai có ảnh hưởng bẻ cong độ dốc mô hình.
- Kiểm định
2.4 Chiến lược Tách tập & Kiểm chứng Thống kê (Validation Splitting Strategies)#
- Từ
HoldoutđếnStratifiedKFold&GroupKFold:Holdoutđơn lẻ chịu phương sai cao trên tập nhỏ;K-Foldchia \(K\) nếp rời nhau;StratifiedKFoldbắt buộc phải dùng khi \(\pi_+ \in [1\%, 5\%]\) để bảo toàn số ca dương trong mọi nếp;GroupKFoldbắt buộc khi dữ liệu có thực thể lặp lại (patient_id,account_id) để đảm bảo \(\mathcal{G}(\mathcal{D}_{\text{tr}}) \cap \mathcal{G}(\mathcal{D}_{\text{val}}) = \emptyset\). PurgedTimeSeriesSplit(Mở rộng vs. Cuộn +Purge+Embargo) &CPCV(López de Prado 2018;Cerqueira 2020):- Cửa sổ mở rộng (
Expanding) vs. Cửa sổ cuộn (Rolling): Cửa sổ mở rộng tận dụng toàn bộ lịch sử khi cơ chế dữ liệu dừng; cửa sổ cuộn giới hạn độ dàiWgần nhất để thích ứng khi thị trường có chuyển dịch chế độ (regime shift). Cerqueira et al. (2020) chứng minh chỉ nên dùngBlocked CVkhi chuỗi thực sự dừng; hễ chuỗi không dừng bắt buộc phải đánh giá tuần tự theo chiều thời gian (prequential). Purge&Embargo: Nếu nhãn tại \(t_i\) phụ thuộc chân trời tương lai \([t_i, t_i + H]\) (ví dụ lợi suất 10 ngày hoặc vỡ nợ 90 ngày), mọi hàng huấn luyện có cửa sổ nhãn chạm vào tập kiểm định đều phải bịPurge(xóa bỏ); đồng thời đặt vùng đệmEmbargongay sau khối kiểm định để triệt tiêu rò rỉ tự tương quan chuỗi. Kết hợp mọi tổ hợp \(k\) khối từ \(N\) khối tạo nênCPCVvới \(\phi(N, k) = \frac{k}{N}\binom{N}{k}\) đường kiểm thử lịch sử độc lập.
- Cửa sổ mở rộng (
-
Nested CV— Định lượng Thiên lệch Lạc quanHPO(Cawley & Talbot 2010;Bates, Hastie & Tibshirani, JASA 2024): Tìm siêu tham số tối ưu \(\hat{\lambda} = \arg\min_{\lambda \in \Lambda}\widehat{\text{Err}}_{\text{CV}}(\lambda)\) rồi báo cáo chính điểm thấp nhất đó vướng phải Lời nguyền Người thắng (Winner's Curse Selection Bias) theo bất đẳng thức Jensen: \(\mathbb{E}[\min_\lambda \widehat{\text{Err}}(\lambda)] \le \min_\lambda \mathbb{E}[\widehat{\text{Err}}(\lambda)]\).Nested CV: Chạy vòng lặp trong \(K_{\text{in}}\) để chọn \(\hat{\lambda}^{(k)}\) hoàn toàn bên trong từng tập huấn luyện ngoài, rồi đánh giá trên nếp ngoài chưa từng đụng tới (lặp \(K_{\text{out}} \cdot K_{\text{in}} \cdot |\Lambda|\) lần).- Hiệu chỉnh Nhanh
Tibshirani & Tibshirani (2009): \(\widehat{\text{Bias}}_{\text{TT}} = \frac{1}{K}\sum_{k=1}^K \big(\hat{e}_k(\hat{\lambda}) - \hat{e}_k(\hat{\lambda}_k)\big) \ge 0\). - Định lý Khoảng tin cậy CV (
Bates, Hastie & Tibshirani, JASA 2024): Tác giả chứng minh \(K\)-Fold CV thực chất ước lượng sai số trung bình trên các tập huấn luyện ngẫu nhiên thay vì sai số có điều kiện của đúng mô hình vừa khớp, và các khoảng tin cậy chuẩn \(\pm z \hat{\sigma}/\sqrt{n}\) phủ thiếu nghiêm trọng (chỉ đạt~60–75%thay vì95%) vì các nếp huấn luyện chồng lấn \((K-2)/K\) gây tương quan dương giữa lỗi các nếp; ước lượng phương sai lồng nhauNCVkhôi phục độ phủ về chuẩn~95%. 4. Efron & Tibshirani.632vs..632+Bootstrap (JASA, 1997): Mỗi mẫu bootstrap cỡ \(n\) chứa trung bình \(1 - (1 - \frac{1}{n})^n \approx 63.2\%\) phần tử duy nhất và để lại36.8%mẫu ngoài túi (OOB), cho sai số \(\widehat{\text{Err}}^{(1)}\). Bộ ước lượng.632(\(0.368\,\overline{\text{err}} + 0.632\,\widehat{\text{Err}}^{(1)}\)) sụp đổ khi mô hình quá khớp/nội suy ép lỗi huấn luyện \(\overline{\text{err}} = 0\) trên nhiễu thuần (báo nhầm0.632 * 0.5 = 0.316!)..632+tính tỷ lệ lỗi vô thông tin \(\hat{\gamma}_0 = \frac{1}{n^2}\sum_{i,j} L(y_i, \hat{f}(\mathbf{x}_j))\), tỷ lệ quá khớp tương đối \(\hat{R}\), và trọng số thích ứng \(\hat{w} \in [0.632, 1.0]\):\[\hat{R} = \operatorname{clip}\!\left(\frac{\min(\widehat{\text{Err}}^{(1)}, \hat{\gamma}_0) - \overline{\text{err}}}{\hat{\gamma}_0 - \overline{\text{err}}},\; 0,\; 1\right), \quad \hat{w} = \frac{0.632}{1 - 0.368\,\hat{R}}, \quad \widehat{\text{Err}}^{(.632+)} = (1-\hat{w})\,\overline{\text{err}} + \hat{w}\,\widehat{\text{Err}}^{(1)}.\]Khi \(\overline{\text{err}} = 0\) và mô hình chỉ đoán mò ngoài mẫu (\(\hat{R} \to 1\)), \(\hat{w} \to 1.0\) loại bỏ sạch thiên lệch lạc quan từ tập huấn luyện!
Trụ cột 3 — Hệ Sinh thái 2026, Bốn Tình huống Công nghiệp Thực tế & Cẩm nang Chống Phản mẫu#
3.1 Bốn Tình huống Công nghiệp Định lượng (R29–R30, E29:E31)#
- Độ co giãn Marketing (
MMM—Meta Robyn/Google MeridianPattern): Khi chi tiêuSearchvàSocialđồng pha \(\rho \approx 0.98\),Normal Eqnổ sai số tham số, cònLassođơn thuần chọn ngẫu nhiên một kênh (|w1 - w2| = 0.130). Chuyển sangHouseholder QR/SVD+ElasticNetgiữ cặp kênh sát nhau (|w1 - w2| = 0.009,w = (1.52, 1.53)) tương tự nguyên lýRidgetrongMeta Robyn; đồng thời thayMAPE/SMAPEtrên ngày doanh thu0bằngWAPE+Pinball Loss. - Thẻ điểm Tín dụng Ngân hàng (
WoEScorecard,SR 11-7&EU AI Act): Yêu cầu giải trình từ chối tín dụng buộc dùng Hồi quy LogisticWoE(Factor = PDO / ln 2) hoặcEBMcó ràng buộc đơn điệu thay cho hộp đen. Hai kiểm tra sống còn của kiểm toánMRM: giữVIF < 5chống đảo dấu trọng số rủi ro và bật phạtFirth/L2chặn nổ chuẩn||beta|| -> 27.15trên nhóm nợ quá hạn hiếm có100%vỡ nợ. - Phát hiện Gian lận Mất cân bằng
1.5%–4%(Stripe RadarPattern): Trong bài toán tỷ lệ nền hiếm, mô hìnhIRLSđạtROC-AUC = 0.838nhưngPrecisiontại ngưỡng top-10%tụt xuống chỉ19.3%(MCC = 0.258, tức~80%cảnh báo chặn nhầm khách hàng sạch). Khi nguy cơ có cấu trúc phi tuyến (\(x_1^2\)), thay mô hình tuyến tính bằngAdditiveSplineGAMkéoPR-AUCtừ0.283vọt lên0.680vàMCClên0.555(Brier = 0.0218); song song khóa đòn bẩy bằngCook's D_i <= 4/nhoặcHuberđể ngăn vài giao dịch doanh nghiệp khổng lồ làm lệch độ dốc hiệu chuẩn. - Đấu giá CTR Thời gian thực (
Google FTRL-Proximal) & Kiểm định Hồi quy Tài chính:FTRL-Proximalgiữ72.8%trọng số bằng đúng0.0và nénQ2.13tiết kiệm75%RAM với sai lệchLog-Losschỉ1.20e-06dưới ngân sách<10 ms; cònPurgedTimeSeriesSplit+Nested CV+.632+loại bỏ hoàn toàn lợi nhuận ảo trên nhãn chồng lấn và tìm lướiHPO.
3.2 Ngân sách Hạ tầng, 8 Phản mẫu Công nghiệp & Cẩm nang Ngưỡng Chẩn đoán#
| Bộ giải / Mô hình | Thời gian Huấn luyện | Bộ nhớ Huấn luyện | Độ trễ Suy luận (p99 CPU 1 dòng) |
Điểm Ngọt Triển khai (2026) |
|---|---|---|---|---|
Householder QR / SVD |
\(O(2np^2 - \frac{2}{3}p^3)\) / \(O(np^2 + p^3)\) | \(O(np)\) (float64) |
<0.05 ms (\(O(d)\) tích vô hướng) |
Chuẩn hồi quy bảng chính xác \(p \le 10^4\), an toàn đa cộng tuyến & \(p > n\) (SVD). |
IRLS / newton-cholesky |
\(O(T(np^2+p^3))\), \(T \in [5, 12]\) | \(O(p^2)\) Hessian | <0.1 ms |
Mặc định 2026 cho Logistic bảng \(p \lesssim 5{,}000\); bắt buộc bật L2/Firth khi có phân tách. |
L-BFGS / SAGA |
\(O(T(np+mp))\) / \(O((n+\kappa)\ln\frac{1}{\varepsilon})\) | \(O(mp)\) / \(O(n)\) | <0.1 ms |
L-BFGS cho đa lớp / \(p\) trung bình; SAGA cho \(n\) lớn kèm phạt \(L_1\). |
FTRL-Proximal (Q2.13) |
\(O(n \cdot k_{\text{active}})\) 1 lượt stream | \(O(3 \cdot d_{\text{admitted}})\) | <1 ms dot-product (<10 ms SLA) |
Luồng CTR tỷ chiều; nén Q2.13 giảm 75% RAM so với float64. |
EBM / Additive GAM |
\(O(T_{\text{cyc}} \cdot p \cdot b \cdot n)\) | \(O(p\cdot b + |\mathcal{I}|b^2)\) | <0.2 ms (tra cứu mảng 1D/2D) |
Chuẩn "hộp kính" thay thế hồi quy tuyến tính khi có ngưỡng phi tuyến & yêu cầu giải trình EU AI Act. |
Bảng Ngưỡng Chẩn đoán & Bảy + Một Phản mẫu Bắt buộc Chặn#
| Chỉ báo / Phản mẫu | Ngưỡng Xanh | Cảnh báo / Sửa lỗi Bắt buộc | Phản mẫu Ngăn chặn |
|---|---|---|---|
| Chỉ số Điều kiện \(\kappa_2(\mathbf{X})\) | \(< 10^2\) (sau chuẩn hóa) | \(\ge 10^6 \implies\) cấm Normal Eq (\(\kappa^2 \ge 10^{12}\)), dùng QR/SVD + Ridge |
Giải \((\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\) trên kênh đồng pha |
Đa cộng tuyến VIF_j |
\(< 5.0\) | \(\ge 10.0 \implies\) gộp biến hoặc ElasticNet/Ridge |
Giữ biến trùng lặp làm đảo dấu hệ số scorecard |
Breusch–Pagan & HC3 |
\(p_{\text{BP}} \ge 0.05\) | \(p_{\text{BP}} < 0.05 \implies\) thay SE_OLS bằng HC3 |
Báo khoảng tin cậy giả hẹp dưới sai số hình quạt |
Đòn bẩy \(h_{ii}\) & Cook's D_i |
\(D_i \le \frac{4}{n},\; h_{ii} \le \frac{2p}{n}\) | \(D_i > \frac{4}{n}\) (đặc biệt \(> 1.0\)) \(\implies\) kiểm toán / Huber |
Để vài điểm ngoại lai bẻ cong độ dốc hiệu chuẩn |
| Hệ số chặn & Chuẩn hóa | Không phạt \(\beta_0\); chuẩn hóa bên trong từng nếp | Phạt \(\beta_0\) hoặc quên chuẩn hóa phá 1% calibration & GD |
Gắn cột \(\mathbf{1}\) chung vào \(\lambda\|\mathbf{w}\|^2\) |
| Phân tách Logistic | \(\|\hat{\boldsymbol{\beta}}\|_2 < 6\), \(H\) xác định dương | \(\|\hat{\boldsymbol{\beta}}\|_2 > 10\) hoặc \(\lambda_{\min}(H) < 10^{-8} \implies\) Firth / L2 |
Chạy MLE không phạt trên danh mục cực hiếm |
Mất cân bằng & Cầu bằng 0 |
Đánh giá PR-AUC, MCC, WAPE, Pinball |
Cấm Accuracy/ROC-AUC đơn lẻ ở \(\pi_+ < 5\%\) và MAPE ở \(y=0\) |
Tự hào ROC-AUC 0.84 khi Precision chỉ 19% |
| Tách tập & Chọn mô hình | PurgedTS / GroupKFold / Nested CV / .632+ |
Chênh lệch Flat CV vs Nested CV \(> 0\) hoặc \(\overline{\text{err}} \approx 0\) |
Chia ngẫu nhiên nhãn chồng lấn; tinh chỉnh \(\lambda\) ngoài lồng |
3.3 Đoạn mã Thực thi Tham chiếu Hệ sinh thái 2026 (QR vs NormalEq, Ridge Path, Firth & PurgedKFold)#
(Ghi chú rạch ròi: Mã dưới đây minh họa trực tiếp API chuẩn sản xuất NumPy + scikit-learn có thể chạy ngay trong .venv; còn gói lab Trụ cột 4 cài đặt toàn bộ thuật toán từ đầu bằng Python stdlib + NumPy + Pandas + Pydantic v2 và được khóa bảo mật deserialization qua AST scan.)
from __future__ import annotations
import numpy as np
from sklearn.linear_model import LogisticRegression, Ridge
def demo_lauchli_qr_vs_normal_eq(delta: float = 3e-8) -> dict[str, float]:
"""Compare relative parameter error of Normal Equations vs Householder QR on Lauchli matrix."""
X = np.array([[1.0, 1.0], [delta, 0.0], [0.0, delta]], dtype=np.float64)
beta_true = np.array([1.0, 1.0], dtype=np.float64)
y = X @ beta_true + np.array([0.0, delta, -delta], dtype=np.float64) * 1e-6
beta_ref, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
# Normal Equations squares kappa(X) -> kappa(X)^2 and loses precision
beta_ne = np.linalg.solve(X.T @ X, X.T @ y)
# Householder QR avoids forming X^T X
Q, R = np.linalg.qr(X, mode="reduced")
beta_qr = np.linalg.solve(R, Q.T @ y)
ref_norm = float(np.linalg.norm(beta_ref))
return {
"kappa_X": float(np.linalg.cond(X)),
"normal_eq_rel_err": float(np.linalg.norm(beta_ne - beta_ref) / ref_norm),
"qr_rel_err": float(np.linalg.norm(beta_qr - beta_ref) / ref_norm),
}
def demo_ridge_path_and_firth_separation(seed: int = 42) -> dict[str, float]:
"""Demonstrate Ridge regularization path and Jeffreys/Firth rescue under separation."""
rng = np.random.default_rng(seed)
X_reg = rng.normal(0.0, 1.0, size=(200, 6))
X_reg[:, 1] = 0.98 * X_reg[:, 0] + rng.normal(0.0, 0.05, size=200)
y_reg = 2.0 * X_reg[:, 0] - 1.5 * X_reg[:, 2] + rng.normal(0.0, 0.5, size=200)
ridge_norms = {
alpha: float(np.linalg.norm(Ridge(alpha=alpha, fit_intercept=True).fit(X_reg, y_reg).coef_))
for alpha in (0.1, 1.0, 25.0)
}
# Quasi-complete separation: rare bucket (first 12 rows) has 100% positives
x_cont = rng.normal(0.0, 1.0, size=180)
rare_flag = np.zeros(180, dtype=np.float64)
rare_flag[:12] = 1.0
p_sep = 1.0 / (1.0 + np.exp(-(-1.0 + 0.9 * x_cont)))
y_sep = (rng.uniform(size=180) < p_sep).astype(np.float64)
y_sep[:12] = 1.0
X_sep = np.column_stack([np.ones(180), x_cont, rare_flag])
# Unpenalized/weakly regularized MLE vs Firth penalized Newton score equation
mle_weak = LogisticRegression(C=1e6, solver="newton-cholesky", max_iter=200).fit(X_sep[:, 1:], y_sep)
beta_firth = np.zeros(3, dtype=np.float64)
for _ in range(30):
eta = np.clip(X_sep @ beta_firth, -20.0, 20.0)
p = 1.0 / (1.0 + np.exp(-eta))
w = np.maximum(p * (1.0 - p), 1e-8)
fisher = (X_sep.T * w) @ X_sep + 1e-8 * np.eye(3)
h_diag = np.sum((X_sep @ np.linalg.inv(fisher)) * X_sep, axis=1) * w
score_firth = X_sep.T @ ((y_sep + 0.5 * h_diag) - p * (1.0 + h_diag))
step = np.linalg.solve(fisher, score_firth)
beta_firth += step
if float(np.max(np.abs(step))) < 1e-8:
break
return {
"ridge_norm_01": ridge_norms[0.1],
"ridge_norm_25": ridge_norms[25.0],
"mle_norm_sep": float(np.linalg.norm(mle_weak.coef_)),
"firth_norm_sep": float(np.linalg.norm(beta_firth[1:])),
}
def purged_kfold_split(
n_samples: int,
n_splits: int = 4,
label_horizon: int = 6,
embargo: int = 0,
) -> list[tuple[np.ndarray, np.ndarray]]:
"""Generate Purged K-Fold splits enforcing post-val label horizon purge even at embargo=0."""
blocks = np.array_split(np.arange(n_samples, dtype=np.int64), n_splits)
pre_purge = max(label_horizon - 1, 0)
post_purge = max(embargo, 0) + pre_purge
folds: list[tuple[np.ndarray, np.ndarray]] = []
for val_idx in blocks:
v_start, v_end = int(val_idx[0]), int(val_idx[-1]) + 1
tr_pre = np.arange(0, max(0, v_start - pre_purge), dtype=np.int64)
tr_post = np.arange(min(n_samples, v_end + post_purge), n_samples, dtype=np.int64)
folds.append((np.concatenate([tr_pre, tr_post]), val_idx))
return folds
if __name__ == "__main__":
print("Lauchli:", demo_lauchli_qr_vs_normal_eq())
print("Ridge/Firth:", demo_ridge_path_and_firth_separation())
tr0, va0 = purged_kfold_split(120, n_splits=4, label_horizon=6, embargo=0)[0]
assert int(np.min(tr0[tr0 > va0[-1]])) == int(va0[-1]) + 6
print("PurgedKFold Fold-0 post_train_start:", int(np.min(tr0[tr0 > va0[-1]])), "(expected", int(va0[-1]) + 6, ")")
Trụ cột 4 — Thực hành Lab 06 (linear_validation_lab) & Kiểm định 14 Hợp đồng pytest#
Bài thực hành đồng hành tại labs/ch06-linear-logistic-and-validation-workbench/ hiện thực hóa toàn bộ lý thuyết từ Trụ cột 1–3 thành gói Python kiểm chứng độc lập linear_validation_lab cài đặt từ đầu bằng Python stdlib + NumPy + Pandas + Pydantic v2 (quản lý phụ thuộc với uv.lock, kèm kiểm soát AST bảo mật deserialization cấm tuyệt đối pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal).
4.1 Kiến trúc Gói linear_validation_lab#
labs/ch06-linear-logistic-and-validation-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch06_workbench_results.json
├── src/
│ └── linear_validation_lab/
│ ├── __init__.py
│ ├── linear_models.py
│ ├── logistic_and_metrics.py
│ └── validation_splitters.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_linear_validation_lab.py
4.2 Đồng bộ Kết quả Thực nghiệm CLI (artifacts/ch06_workbench_results.json)#
Chạy một lệnh duy nhất từ thư mục gốc của Lab:
python scripts/run_lab_demo.py --seed 42 --quick --output artifacts/ch06_workbench_results.json
Báo cáo artifacts/ch06_workbench_results.json xuất trọn bộ workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% các giá trị đo kiểm thực tế dưới đây:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm Chính xác (--seed 42 --quick) |
Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_qr_vs_normal_eq_error (Läuchli \(\delta = 3\times 10^{-8}\)) |
1.33e-02 vs. 2.22e-16 (SVD = 3.51e-16) |
critical — \(\kappa_2(\mathbf{X}) = 4.71\times 10^7\) bình phương thành \(\kappa_2^2 = 2.22\times 10^{15}\); L-BFGS đạt 4.64e-10 trong 13 bước vs. Nelder–Mead 4.89e-02 (1200 evals). |
kpi_elasticnet_grouping_and_pinball (Marketing \(\rho \approx 0.98\)) |
0.009 vs. 0.130 (|w1 - w2| ElasticNet vs. Lasso) |
ok — Gap Safe sàng lọc 8/10 cột 0 (duality gap 1.7e-08); VIF = 19.23, BP p = 6.46e-02, HC3/OLS = 2.06x, Cook_max = 1.79 (Huber = 1.59 vs. OLS = 1.75). |
kpi_separation_firth_vs_mle (Phân tách gần như hoàn toàn) |
27.1 -> 5.57 (Firth, L2 = 3.23) |
warn — MLE không phạt vọt chuẩn 27.15 (min eig Hessian 1.76e-10), Firth & L2 giữ nghiệm hữu hạn hội tụ hoàn toàn; Double Descent nổ đỉnh 8.624 tại \(\gamma = 1.05\), còn spiked Ridge tối ưu tại \(\lambda^* = -110.0\) (MSE = 0.715). |
kpi_imbalance_roc_vs_pr_mcc (Gian lận hiếm) |
ROC 0.838 | PR 0.283 (Precision = 19.3%, MCC = 0.258) |
warn — AdditiveSplineGAM bắt hiệu ứng chữ U nâng lên PR-AUC = 0.680 (ROC = 0.957, MCC = 0.555, Brier = 0.0218); Softmax 3 lớp đạt Acc = 88.1%, Gorodkin MCC = 0.818. |
kpi_ftrl_sparsity_and_q213 (Streaming CTR + Q2.13) |
72.8% Zero | -75% RAM (Q2.13) |
ok — FTRL-Proximal giữ 68/250 trọng số khác không (ROC-AUC = 0.825), Q2.13 lệch Log-Loss chỉ 1.20e-06 (0.00000 làm tròn 5 chữ số) so với float64. |
kpi_nested_cv_and_632plus_bias (Kiểm toán Nested CV & .632+) |
Opt +0.368 | .632+ 0.386 (Test = 7.903) |
ok — Flat CV = 9.556 vs. Nested CV = 9.923 (TT bias = +0.465), chuỗi 10d Random K-Fold R^2 = +0.328 vs. Purged TS = -3.874 (45 purged, 20 embargoed); .632 = 0.266 bị lừa bởi \(\overline{\text{err}} = 0\) trong khi .632+ đẩy \(\hat{w} = 0.916\) (\(\hat{R} = 0.843\)) lên 0.386. |
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_linear_validation_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_ols_normal_eq_vs_qr_svd_ill_conditioned_lauchli_and_collinear |
Kiểm chứng Pydantic extra="forbid", \(\kappa(\mathbf{X}) > 10^7\) bình phương thành \(\kappa^2\), Normal Eq rel_err > 1e-3 trong khi QR/SVD < 1e-6, và khóa coef.setflags(write=False). |
| 2 | test_linear_optimizer_comparison_bgd_sgd_minibatch_lbfgs_vs_nelder_mead |
L-BFGS đạt loss_gap < 1e-8, BGD < 1e-6, Mini-batch < 0.02, và Nelder–Mead tụt hậu \(>100\times\) về sai số mất mát lẫn sai số tham số. |
| 3 | test_ridge_svd_filter_factors_df_and_double_descent_negative_ridge |
Kiểm chứng \(1 < \operatorname{df}(\lambda_{\text{large}}) < \operatorname{df}(\lambda_{\text{small}}) < p\), tính bất biến tịnh tiến của \(\beta_0\) không bị phạt, cực Double Descent quanh \(\gamma \approx 1\), và \(\lambda^* < 0\) trên mô hình gai nhọn. |
| 4 | test_lasso_gap_safe_cd_elasticnet_grouping_and_huber_quantile_pinball |
Khẳng định ngưỡng mềm chính xác, Gap Safe sàng lọc \(\ge 5\) cột 0 với duality gap \(< 10^{-6}\), ElasticNet thu hẹp cặp kênh tương quan < 0.35, Huber thắng OLS khi có 10% ngoại lai +80, và Quantile (0.10/0.90) bao phủ đúng tỷ lệ mẫu. |
| 5 | test_ols_diagnostics_hat_sherman_morrison_vif_bp_hc3_and_cooks_d |
Khẳng định \(\sum h_{ii} = p\), \(h_{ii} \ge 1/n\), VIF > 10 trên cặp cộng tuyến, BP p < 0.01, chi2_survival_prob(3.8415, 1) <= 0.06, HC3 > SE_OLS, và Cook's D_0 khớp chính xác 100% tính toán LOO thô (rel_tol=1e-9). |
| 6 | test_regression_metrics_and_mape_smape_zero_asymmetry_traps |
Chứng minh mape_raw == inf khi có y=0, SMAPE phạt thiếu nặng hơn thừa (smape_under > smape_over) trong khi WAPE cân bằng, và \(R^2_{\text{test}} < 0\) khi dự báo kém hơn trung bình. |
| 7 | test_logistic_irls_lbfgs_gradient_descent_and_softmax_lse_convergence |
Kiểm chứng stable_sigmoid(+/-1000) không tràn số, IRLS (H_min_eig > 0), L-BFGS, BGD hội tụ về cùng nghiệm (atol <= 5e-3), và Softmax LSE tổng xác suất 1.0 + ràng buộc tổng trọng số lớp bằng 0.0. |
| 8 | test_logistic_quasi_complete_separation_and_firth_l2_remedy |
Chứng minh MLE không phạt nổ chuẩn > 10.0 dưới phân tách gần như hoàn toàn, trong khi L2 và Firth giữ < 6.0 và hội tụ ổn định. |
| 9 | test_ftrl_proximal_exact_sparsity_q2_13_quantization_and_subsampling_offset |
Khẳng định >= 70% trọng số bằng đúng 0.0, Q2.13 lệch Log-Loss < 0.01, lưới \(2^{-13}\) chuẩn xác với làm tròn ngẫu nhiên không thiên lệch, và hiệu chuẩn bù \(\ln(r)\) khôi phục tỷ lệ nền thật. |
| 10 | test_classification_imbalance_roc_vs_pr_prg_mcc_and_brier_murphy |
Chứng minh trên tập hiếm ROC-AUC > 0.75 nhưng PR-AUC < 0.45, Precision < 0.25, MCC < 0.40; kiểm chứng đẳng thức Murphy brier_binned == reliability - resolution + uncertainty (atol=1e-12); MCC == 0 cho dự báo hằng số và Gorodkin == 1.0. |
| 11 | test_validation_splitters_stratified_group_and_purged_embargo_time_series |
Kiểm chứng StratifiedKFold bảo toàn đúng 2 ca dương/nếp, GroupKFold giao nhóm bằng rỗng, PurgedTimeSeriesSplit (mở rộng, cuộn, purged_kfold) thỏa max(train) + horizon <= min(val), và xóa sạch rò rỉ \(R^2\) ảo trên chuỗi 10 ngày chồng lấn. |
| 12 | test_nested_cv_hpo_winners_curse_bias_and_fold_coverage |
Khẳng định flat_cv_mse < nested_cv_mse (winners_curse_optimism > 0) và ước lượng hiệu chỉnh chọn lọc tt_bias_correction >= 0. |
| 13 | test_bootstrap_632_plus_rescues_zero_train_error_overfitting |
Trên mô hình p > n nội suy nhiễu (\(\overline{\text{err}} = 0.0\)), chứng minh .632 tụt ảo < 0.38 trong khi .632+ đẩy \(\hat{R} > 0.70\), \(\hat{w} > 0.85\) và nâng sai số lên \(> \text{err}_{.632} + 0.08\). |
| 14 | test_cli_demo_script_workbench_json_and_zero_forbidden_imports |
Chạy run_lab_demo.py (returncode == 0), kiểm tra cấu trúc JSON workbench_panels (6 KPI, 4 bar, 4 bảng) và quét AST bảo mật deserialization toàn bộ tệp .py khẳng định 0 import không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bộ Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Golub, G. H., & Van Loan, C. F. (2013); Meier, M., Nakatsukasa, Y., Townsend, A., & Webb, M. (SIAM J. Matrix Anal. Appl. 2024,
arXiv:2302.07202); Epperly, E. N., Meier, M., & Nakatsukasa, Y. (arXiv:2406.03468). Matrix Computations (4th ed.); Are Sketch-and-Precondition Least Squares Solvers Always Backward Stable?; & Fast Randomized Least-Squares Solvers Can Just Be Used Reliably (SPIR/FOSSILS).
Vì sao quan trọng: Thiết lập ranh giới ổn định số giữa Phương trình Chuẩn (\(\kappa^2\)),Householder QR,SVD, chứng minh điểm mất ổn định ngược củaSAPkhởi tạo nóng và cách một bước làm mịn lặp khôi phục hoàn toàn tính ổn định ngược. - Hoerl, A. E., & Kennard, R. W. (1970); Zou, H., & Hastie, T. (2005); Ndiaye, E., et al. (2017); Bertrand, Q., et al. (
skglm, NeurIPS 2022).
Vì sao quan trọng: Đặt nền tảng chứng minh cải thiện MSE củaRidge, Định lý Hiệu ứng NhómElasticNet, và sàng lọc an toànGap Safetăng tốc thuật toán thưa gấp nhiều bậc độ lớn. - Bartlett, P. L., et al. (PNAS 2020); Hastie, T., et al. (Ann. Stat. 2022); Kobak, D., et al. (JMLR 2020); Tsigler, A., & Bartlett, P. L. (JMLR 2023).
Vì sao quan trọng: Giải mã lý thuyết Benign Overfitting (\(r_k, R_k\)), cực trị \(\gamma = p/n = 1\) của Double Descent, và điều kiện cho \(\lambda_{\text{opt}} < 0\) trong dữ liệu chiều cao. - Albert, A., & Anderson, J. A. (1984); Firth, D. (Biometrika 1993); McMahan, H. B., et al. (KDD 2013); Jones, M., et al. (
BONG, NeurIPS 2024).
Vì sao quan trọng: Hoàn thiện giải phẫu phân tách hồi quy logistic, tiên nghiệm Jeffreys cho mẫu hiếm, kiến trúc streamingFTRL-Proximal(Q2.13) quy mô tỷ đặc trưng, và cập nhật độ bất định Bayes trực tuyến. - Nori, H., et al. (
InterpretMLEBM, 2019–2026); Lengerich, B., et al. (fANOVAPurification, AISTATS 2020).
Vì sao quan trọng: Đưa mô hình cộng tính hộp kính lên ngang hàng vớiGBDTvề độ chính xác trong ngân hàng/y tế đồng thời bảo toàn tính khả giải thích duy nhất. - Saito, T., & Rehmsmeier, M. (2015); Flach, P., & Kull, M. (
PRG, NeurIPS 2015); Chicco, D., & Jurman, G. (MCC, 2020–2023); Cawley, G. C., & Talbot, N. L. C. (JMLR 2010); Efron, B., & Tibshirani, R. (JASA 1997); López de Prado, M. (2018); Bates, S., Hastie, T., & Tibshirani, R. (JASA 2024).
Vì sao quan trọng: Xây dựng bộ quy chuẩn đánh giá mất cân bằng (PR-AUC,PRG,MCC) và lý thuyết thống kê hiện đại cho tách tập chống rò rỉ (Purged/CPCV),Nested CV(kèm sai số chuẩn tương quan nếp) và Bootstrap.632+.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Chứng minh \(\kappa_2(\mathbf{X}^\top\mathbf{X}) = \kappa_2(\mathbf{X})^2\) và giải thích vì sao trên ma trận Läuchli \(\delta = 3\times 10^{-8}\), Phương trình Chuẩn mất sạch độ chính xác (
1.33e-02) cònQR/SVDgiữ~1e-16. - Q2: Tại sao
ElasticNetgiữ được cặp biến tương quan (0.009vs.Lasso 0.130), cơ chế nào giúpGap Safesàng lọc8/10biến0mà không sai nghiệm, và vì sao \(\lambda_{\text{opt}}\) trong Ridge có thể nhận giá trị âm ở chế độ \(p \gg n\)? - Q3: Chứng minh Hessian hồi quy logistic \(\mathbf{H} = \mathbf{X}^\top\mathbf{W}\mathbf{X} + \lambda\mathbf{I}_0 \succeq \mathbf{0}\), giải thích cơ chế phân tách làm \(\lambda_{\min}(H) \to 0\) (
||beta|| = 27.15), và cách tiên nghiệm Jeffreys củaFirthgiữ nghiệm hữu hạn. - Q4: Giải thích công thức cập nhật thưa tuyệt đối trong
FTRL-Proximal, cơ chế làm tròn ngẫu nhiên không thiên lệchQ2.13cắt75%RAM, và hiệu chuẩn cộng \(\ln(r)\) khi lấy mẫu âm. - Q5: Vì sao
MAPEđổ vỡ tại \(y = 0\), vì saoSMAPEvẫn bất đối xứng giữa dự báo thiếu (66.7%) và thừa (40.0%), và vì sao trên gian lận1.5%–4%chỉ sốROC-AUC = 0.838lại che giấuPrecision = 19.3%? - Q6: Sử dụng đẳng thức xóa 1 dòng Sherman–Morrison, giải thích mối liên hệ giữa phần dư
PRESS, sai số chuẩnHC3(2.06x), và Khoảng cáchCook\(D_i\); đồng thời phân biệt tác động củaVIF = 19.23lên tham số vs. dự báo. - Q7: Giải thích cơ chế
Random K-Foldthổi phồng \(R^2 = +0.328\) trên bước đi ngẫu nhiên 10 ngày chồng lấn và cơ chế kết hợpPurge+Embargo+GroupKFoldđể cô lập rò rỉ. - Q8: Phân biệt thiên lệch chọn lọc Winner's Curse trong
Flat CV(9.556vs.Nested CV 9.923), định lý phủ thiếu khoảng tin cậy CV củaBates et al. (2024), và cơ chế đẩy \(\hat{w} \to 0.916\) của Bootstrap.632+khi \(\overline{\text{err}} = 0\).
5.3 Sáu Bài tập Thực hành & Chứng minh Tính điểm (Ex1–Ex6)#
- Bài tập 1 (
15%): Chứng minh bất đẳng thức Gauss–Markov và bình phương chỉ số điều kiện \(\kappa_2(\mathbf{X})^2\); kiểm chứng thực nghiệm Läuchli (Normal Eqvs.QR/SVD) và bảng đuaL-BFGS,BGD,SGD,Mini-batch,Nelder–Meadquacompare_linear_optimizers. - Bài tập 2 (
20%): Suy diễn ngưỡng mềmLasso, đối ngẫuGap Safevà Định lý NhómElasticNet; chạyfit_lasso_cd,fit_elasticnet_cdvàsimulate_double_descent_and_negative_ridgeghi nhận cực \(\gamma \approx 1\) cùng \(\lambda^* = -110.0\). - Bài tập 3 (
15%): Chứng minhVIF_j = [(R_XX)^-1]_jjvàCook's D_ivia Sherman–Morrison; đối chiếucompute_regression_diagnostics,fit_huber_irls,fit_quantile_mm(..., tau=0.90)và bẫyMAPE/SMAPEtrêncompute_regression_metrics. - Bài tập 4 (
15%): Dẫn xuất đáp ứng làm việcIRLSvà phương trình điểm sốFirth; kiểm chứng nổ chuẩn27.15 -> 5.57trên dữ liệu phân tách và kiểm tra tổng trọng số0.0trongSoftmaxMultinomialClassifier(LSE). - Bài tập 5 (
15%): Dẫn xuất Bayes Precision theo \(\pi_+\) và phân rã Murphy choBrier Score; so sánhIRLSvs.AdditiveSplineGAMtrên gian lận hiếm (PR-AUC 0.283 -> 0.680) và chạyFTRLProximalClassifier+quantize_q2_13. - Bài tập 6 (
20%): Cài đặt và kiểm toánpurged_timeseries_splits,group_kfold_splits,nested_cv_ridge_auditvàbootstrap_632_plustrên tập nội suy nhiễu \(p > n\), đối chiếu trọn vẹn14/14ca kiểm thửpytest.
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 (Gauss–Markov, \(\frac{1}{n} \le h_{ii} \le 1\), Hoerl–Kennard, Grouping Effect, lồi toàn cục Logistic + IRLS, Sherman–Morrison PRESS/Cook, Murphy Brier, .632+); gói linear_validation_lab đạt 14/14 pytest với 0 import cấm (Test 14); đồng bộ chuẩn xác các ngưỡng VIF, HC3, Firth, PR-AUC/MCC, FTRL Q2.13, Purged TS, Nested CV. |
| Senior Standard | 75–89% | Triển khai chạy thông suốt 14/14 pytest thuần NumPy/Pandas/Pydantic, nhưng còn thiếu chiều sâu khi giải thích bẫy phủ thiếu khoảng tin cậy Bates et al. (2024), điều kiện \(\lambda_{\text{opt}} < 0\) hoặc đối ngẫu Gap Safe. |
| Needs Remediation | < 75% | Dùng Normal Eq trên dữ liệu đa cộng tuyến; phạt cả hệ số chặn \(\beta_0\); đánh giá gian lận 1%–4% chỉ bằng Accuracy/ROC-AUC; bỏ sót Purge/Embargo hoặc Nested CV khi chọn siêu tham số; hoặc rò rỉ import scipy/sklearn/pickle trong lab. |
Optimizer Relative Param Error vs QR Exact Baseline (OLS d=18)
1.5% Rare-Event Classification: ROC-AUC Illusion vs PR-AUC, MCC & Precision
Log-Loss & PR-AUC: Linear IRLS vs Spline GAM vs Streaming FTRL Q2.13
Validation Rigor: Flat vs Nested MSE & .632 vs .632+ Overfit Error
Linear Solvers, Conditioning, Regularization & Zero-Demand Metrics
| experiment | method | primary_metric | secondary_metric | verdict |
|---|---|---|---|---|
| lauchli_kappa_4.7e7 | Normal Equations | rel_err=1.331e-02 | kappa^2=2.22e+15 | PRECISION_LOSS |
| lauchli_kappa_4.7e7 | Householder QR | rel_err=2.220e-16 | kappa=4.71e+07 | STABLE_EXACT |
| lauchli_kappa_4.7e7 | SVD Pseudoinverse | rel_err=3.511e-16 | kappa=4.71e+07 | RANK_SAFE |
| collinear_marketing | Lasso (Gap Safe) | pair_gap=0.130 | screened=8/10 | DROPS_TWIN |
| collinear_marketing | ElasticNet | pair_gap=0.009 | w=(1.52,1.53) | GROUP_STABLE |
| spiked_cov_p_gt_n | Kobak Negative Ridge | lam*=-110.0 | mse=0.715 | NEGATIVE_OPT |
| zero_demand_trap | MAPE vs SMAPE vs WAPE | mape_nz=155.0% | smape=111.3% | wape=151.2% | AVOID_MAPE |
OLS Model Diagnostics: VIF, Heteroscedasticity (BP & HC3), Leverage & Outliers
| diagnostic | observed_value | reference_or_baseline | impact_on_inference | action |
|---|---|---|---|---|
| max_vif_collinear | 19.228 | < 5.0 green (<10 ceiling) | inflates Var(beta_j) | MERGE_OR_RIDGE |
| breusch_pagan_lm | LM=7.24 | p=6.46e-02 | OLS SEs invalid | USE_HC3_SANDWICH |
| hc3_vs_ols_se_ratio | 2.06x | 1.00x homoscedastic | guards high-leverage variance | HC3_DEFAULT |
| cooks_d_and_huber | D_max=1.79 | h_max=0.149 | influential=11 | OLS=1.75 vs Huber=1.59 | HUBER_OR_QUARANTINE |
Logistic IRLS, Separation, Softmax LSE, Imbalance Metrics & Streaming FTRL
| task | model_or_regime | metric_1 | metric_2 | status |
|---|---|---|---|---|
| quasi_separation | Unpenalized IRLS | ||beta||=27.15 | H_min_eig=1.76e-10 | DIVERGES |
| quasi_separation | Firth / L2 Penalized | ||beta||_F=5.57 | ||beta||_L2=3.23 | FINITE_SAFE |
| fraud_1.5pct_alert | Logistic IRLS (top 10%) | ROC=0.838 | PR=0.283 | Prec=19.3% | MCC=0.258 | PR_MCC_REQUIRED |
| fraud_1.5pct_nl | Additive Spline GAM | PR=0.680 | MCC=0.555 | Brier=0.0218 | GLASSBOX_GAIN |
| softmax_3class | Multinomial LSE | acc=88.1% | Gorodkin_MCC=0.818 | IDENTIFIABLE |
| streaming_ctr | FTRL-Proximal Q2.13 | zeros=72.8% | delta_LL=0.00000 (-75% RAM) | PROD_DEPLOY |
Validation Splitting Rigor: Random Leakage vs Purged TS, Nested CV & .632+
| validation_regime | naive_or_biased | rigorous_estimator | bias_or_gap | verdict |
|---|---|---|---|---|
| overlapping_10d_ts | Random K-Fold R2=+0.328 | Purged TS R2=-3.874 | purged=45 | emb=20 | LEAK_ELIMINATED |
| nested_cv_hpo | Flat CV MSE=9.556 | Nested CV MSE=9.923 | optimism=+0.368 (Test=7.903) | WINNERS_CURSE |
| bates_2024_ci_se | Naive sample SE=1.591 | Outer fold SE=1.934 | TT_bias=+0.465 | CORR_ADJUSTED |
| boot_p_gt_n_noise | .632 Err=0.266 (app=0.000) | .632+ Err=0.386 | R=0.843 | w=0.916 | OVERFIT_RESCUED |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/ch06-linear-logistic-and-validation-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "linear-validation-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for Linear Models, Regularization, Logistic IRLS/FTRL Optimization, Diagnostics, Imbalance Metrics, and Validation Splitting Rigor (T1-P2-U01)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.4",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
"""Public API exports for Lab 06 (`linear_validation_lab`, Unit T1-P2-U01)."""
from linear_validation_lab.linear_models import (
LinearFitResult,
LinearModelConfig,
RegressionDiagnostics,
chi2_survival_prob,
compare_linear_optimizers,
compute_regression_diagnostics,
fit_elasticnet_cd,
fit_huber_irls,
fit_lasso_cd,
fit_quantile_mm,
fit_ridge_svd,
lbfgs_minimize,
simulate_double_descent_and_negative_ridge,
soft_threshold,
solve_ols_normal_eq,
solve_ols_qr,
solve_ols_svd,
)
from linear_validation_lab.logistic_and_metrics import (
AdditiveSplineGAM,
FTRLProximalClassifier,
LogisticConfig,
LogisticFitResult,
LogisticRegressionWorkbench,
SoftmaxMultinomialClassifier,
compute_classification_metrics,
compute_multiclass_mcc,
compute_pr_and_prg_auc,
compute_regression_metrics,
compute_roc_auc,
logsumexp,
quantize_q2_13,
stable_sigmoid,
)
from linear_validation_lab.validation_splitters import (
SplitFold,
bootstrap_632_plus,
group_kfold_splits,
holdout_split,
kfold_splits,
nested_cv_ridge_audit,
purged_timeseries_splits,
run_full_ch06_benchmarks,
stratified_kfold_splits,
)
__all__ = [
"AdditiveSplineGAM",
"FTRLProximalClassifier",
"LinearFitResult",
"LinearModelConfig",
"LogisticConfig",
"LogisticFitResult",
"LogisticRegressionWorkbench",
"RegressionDiagnostics",
"SoftmaxMultinomialClassifier",
"SplitFold",
"bootstrap_632_plus",
"chi2_survival_prob",
"compare_linear_optimizers",
"compute_classification_metrics",
"compute_multiclass_mcc",
"compute_pr_and_prg_auc",
"compute_regression_diagnostics",
"compute_regression_metrics",
"compute_roc_auc",
"fit_elasticnet_cd",
"fit_huber_irls",
"fit_lasso_cd",
"fit_quantile_mm",
"fit_ridge_svd",
"group_kfold_splits",
"holdout_split",
"kfold_splits",
"lbfgs_minimize",
"logsumexp",
"nested_cv_ridge_audit",
"purged_timeseries_splits",
"quantize_q2_13",
"run_full_ch06_benchmarks",
"simulate_double_descent_and_negative_ridge",
"soft_threshold",
"solve_ols_normal_eq",
"solve_ols_qr",
"solve_ols_svd",
"stable_sigmoid",
"stratified_kfold_splits",
]
"""Linear models, regularization paths, optimization variants, and regression diagnostics."""
from __future__ import annotations
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
class LinearModelConfig(BaseModel):
"""Typed boundary configuration for linear and regularized linear estimators."""
model_config = ConfigDict(frozen=True, extra="forbid")
solver: Literal[
"qr",
"svd",
"normal_eq",
"ridge_svd",
"lasso_cd",
"elasticnet_cd",
"huber_irls",
"quantile_mm",
"bgd",
"sgd",
"minibatch",
"lbfgs",
"nelder_mead",
] = "qr"
l1_alpha: float = Field(default=0.0, ge=0.0)
l2_alpha: float = Field(default=0.0)
fit_intercept: bool = True
standardize: bool = True
huber_delta: float = Field(default=1.345, gt=0.0)
quantile_tau: float = Field(default=0.5, gt=0.0, lt=1.0)
max_iter: int = Field(default=1000, ge=1)
tol: float = Field(default=1e-7, gt=0.0)
learning_rate: float = Field(default=0.05, gt=0.0)
batch_size: int = Field(default=32, ge=1)
seed: int = 42
@dataclass(frozen=True, slots=True)
class LinearFitResult:
"""Immutable fitted linear model state with numerical diagnostics."""
intercept: float
coef: np.ndarray
solver: str
condition_number_x: float
condition_number_xtx: float
effective_df: float
n_iter: int
converged: bool
screened_count: int
duality_gap: float
singular_fallback: bool
loss_history: tuple[float, ...]
def __post_init__(self) -> None:
coef_arr = np.array(self.coef, dtype=np.float64, copy=True)
coef_arr.setflags(write=False)
object.__setattr__(self, "coef", coef_arr)
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predict continuous targets from feature matrix X."""
x_arr = np.asarray(X, dtype=np.float64)
return self.intercept + x_arr @ self.coef
@dataclass(frozen=True, slots=True)
class RegressionDiagnostics:
"""Complete OLS regression diagnostics (Hat, Studentized, VIF, BP, HC0-HC3, Cook's D)."""
leverage: np.ndarray
residuals: np.ndarray
standardized_residuals: np.ndarray
studentized_residuals: np.ndarray
cooks_distance: np.ndarray
vif: np.ndarray
breusch_pagan_lm: float
breusch_pagan_pvalue: float
se_ols: np.ndarray
se_hc0: np.ndarray
se_hc1: np.ndarray
se_hc2: np.ndarray
se_hc3: np.ndarray
high_leverage_indices: tuple[int, ...]
influential_indices: tuple[int, ...]
def chi2_survival_prob(stat: float, df: int) -> float:
"""Compute exact upper-tail chi-square probability Q(df/2, stat/2) without SciPy."""
if df <= 0:
raise ValueError("Degrees of freedom must be positive.")
if stat <= 0.0:
return 1.0
a = 0.5 * float(df)
x = 0.5 * float(stat)
log_gamma_a = math.lgamma(a)
if x < a + 1.0:
ap = a
term = 1.0 / a
summ = term
for _ in range(500):
ap += 1.0
term *= x / ap
summ += term
if abs(term) < abs(summ) * 1e-14:
break
lower_reg = summ * math.exp(-x + a * math.log(x) - log_gamma_a)
return float(max(0.0, min(1.0, 1.0 - lower_reg)))
b = x + 1.0 - a
c = 1.0 / 1e-30
d = 1.0 / b if abs(b) > 1e-30 else 1e30
h = d
for i in range(1, 500):
an = -float(i) * (float(i) - a)
b += 2.0
d = an * d + b
if abs(d) < 1e-30:
d = 1e-30
c = b + an / c
if abs(c) < 1e-30:
c = 1e-30
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-14:
break
upper_reg = math.exp(-x + a * math.log(x) - log_gamma_a) * h
return float(max(0.0, min(1.0, upper_reg)))
def lbfgs_minimize(
value_and_grad: Callable[[np.ndarray], tuple[float, np.ndarray]],
x0: np.ndarray,
max_iter: int = 120,
memory: int = 10,
tol: float = 1e-7,
) -> tuple[np.ndarray, int, bool, tuple[float, ...]]:
"""Minimize a smooth objective via two-loop L-BFGS with Armijo backtracking."""
x = np.array(x0, dtype=np.float64, copy=True)
s_hist: list[np.ndarray] = []
y_hist: list[np.ndarray] = []
rho_hist: list[float] = []
loss, grad = value_and_grad(x)
losses = [float(loss)]
converged = False
for step_idx in range(1, max_iter + 1):
if float(np.max(np.abs(grad))) <= tol:
converged = True
break
q = grad.copy()
alphas: list[float] = []
for s_k, y_k, rho_k in reversed(list(zip(s_hist, y_hist, rho_hist))):
a_k = rho_k * float(np.dot(s_k, q))
alphas.append(a_k)
q -= a_k * y_k
if y_hist:
gamma = float(np.dot(s_hist[-1], y_hist[-1])) / max(
float(np.dot(y_hist[-1], y_hist[-1])), 1e-24
)
r = gamma * q
else:
r = q
for (s_k, y_k, rho_k), a_k in zip(zip(s_hist, y_hist, rho_hist), reversed(alphas)):
b_k = rho_k * float(np.dot(y_k, r))
r += s_k * (a_k - b_k)
direction = -r
slope = float(np.dot(grad, direction))
if slope >= 0.0:
direction = -grad
slope = float(np.dot(grad, direction))
step_size = 1.0
accepted = False
new_x = x
new_loss = loss
new_grad = grad
for _ in range(30):
cand_x = x + step_size * direction
cand_loss, cand_grad = value_and_grad(cand_x)
if math.isfinite(cand_loss) and cand_loss <= loss + 1e-4 * step_size * slope:
new_x, new_loss, new_grad = cand_x, cand_loss, cand_grad
accepted = True
break
step_size *= 0.5
if not accepted:
break
s_k = new_x - x
y_k = new_grad - grad
sy = float(np.dot(s_k, y_k))
if sy > 1e-12 * float(np.linalg.norm(s_k) * np.linalg.norm(y_k)):
if len(s_hist) == memory:
s_hist.pop(0)
y_hist.pop(0)
rho_hist.pop(0)
s_hist.append(s_k)
y_hist.append(y_k)
rho_hist.append(1.0 / sy)
x, loss, grad = new_x, new_loss, new_grad
losses.append(float(loss))
if float(np.max(np.abs(grad))) <= tol or float(np.linalg.norm(s_k)) <= tol * 1e-3:
converged = True
return x, step_idx, converged, tuple(losses)
return x, len(losses) - 1, converged, tuple(losses)
def _solve_upper_triangular(R: np.ndarray, rhs: np.ndarray) -> np.ndarray:
"""Solve upper-triangular R @ x = rhs via backward substitution."""
p = R.shape[0]
out = np.zeros(p, dtype=np.float64)
for i in range(p - 1, -1, -1):
rem = float(rhs[i] - np.dot(R[i, i + 1 :], out[i + 1 :]))
diag = float(R[i, i])
if abs(diag) < 1e-15:
raise np.linalg.LinAlgError(f"Zero diagonal in R at index {i}.")
out[i] = rem / diag
return out
def _design_with_intercept(X: np.ndarray, fit_intercept: bool) -> np.ndarray:
x_arr = np.asarray(X, dtype=np.float64)
if not fit_intercept:
return x_arr
return np.column_stack([np.ones(x_arr.shape[0], dtype=np.float64), x_arr])
def _prepare_standardized_centered(
X: np.ndarray,
y: np.ndarray,
fit_intercept: bool,
standardize: bool,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, float, np.ndarray]:
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
if fit_intercept:
x_mean = np.mean(x_arr, axis=0)
y_mean = float(np.mean(y_arr))
x_c = x_arr - x_mean
y_c = y_arr - y_mean
else:
x_mean = np.zeros(x_arr.shape[1], dtype=np.float64)
y_mean = 0.0
x_c = x_arr.copy()
y_c = y_arr.copy()
if standardize:
x_scale = np.std(x_c, axis=0)
x_scale = np.where(x_scale > 1e-12, x_scale, 1.0)
x_s = x_c / x_scale
else:
x_scale = np.ones(x_arr.shape[1], dtype=np.float64)
x_s = x_c
return x_s, y_c, x_mean, y_mean, x_scale
def _cond_numbers(X_aug: np.ndarray) -> tuple[float, float]:
svals = np.linalg.svd(X_aug, compute_uv=False)
if svals.size == 0 or svals[-1] <= 1e-15:
return float("inf"), float("inf")
kx = float(svals[0] / svals[-1])
return kx, float(kx * kx)
def solve_ols_normal_eq(
X: np.ndarray,
y: np.ndarray,
fit_intercept: bool = True,
) -> LinearFitResult:
"""Solve OLS explicitly via Normal Equations (X^T X) beta = X^T y (squares condition number)."""
X_aug = _design_with_intercept(X, fit_intercept)
y_arr = np.asarray(y, dtype=np.float64)
kx, kxtx = _cond_numbers(X_aug)
gram = X_aug.T @ X_aug
rhs = X_aug.T @ y_arr
singular_fallback = False
try:
beta = np.linalg.solve(gram, rhs)
except np.linalg.LinAlgError:
singular_fallback = True
beta = np.linalg.lstsq(gram, rhs, rcond=None)[0]
intercept = float(beta[0]) if fit_intercept else 0.0
coef = beta[1:] if fit_intercept else beta
rss = 0.5 * float(np.mean((y_arr - X_aug @ beta) ** 2))
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="normal_eq",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(X_aug.shape[1]),
n_iter=1,
converged=not singular_fallback,
screened_count=0,
duality_gap=0.0,
singular_fallback=singular_fallback,
loss_history=(rss,),
)
def solve_ols_qr(
X: np.ndarray,
y: np.ndarray,
fit_intercept: bool = True,
) -> LinearFitResult:
"""Solve OLS via Householder QR decomposition and upper-triangular back-substitution."""
X_aug = _design_with_intercept(X, fit_intercept)
y_arr = np.asarray(y, dtype=np.float64)
kx, kxtx = _cond_numbers(X_aug)
Q, R = np.linalg.qr(X_aug, mode="reduced")
beta = _solve_upper_triangular(R, Q.T @ y_arr)
intercept = float(beta[0]) if fit_intercept else 0.0
coef = beta[1:] if fit_intercept else beta
rss = 0.5 * float(np.mean((y_arr - X_aug @ beta) ** 2))
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="qr",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(X_aug.shape[1]),
n_iter=1,
converged=True,
screened_count=0,
duality_gap=0.0,
singular_fallback=False,
loss_history=(rss,),
)
def solve_ols_svd(
X: np.ndarray,
y: np.ndarray,
fit_intercept: bool = True,
rcond: float | None = None,
) -> LinearFitResult:
"""Solve OLS (or minimum-norm under p > n) via SVD pseudoinverse X^+ = V Sigma^+ U^T."""
X_aug = _design_with_intercept(X, fit_intercept)
y_arr = np.asarray(y, dtype=np.float64)
kx, kxtx = _cond_numbers(X_aug)
U, svals, Vt = np.linalg.svd(X_aug, full_matrices=False)
cutoff = (
max(X_aug.shape) * float(np.finfo(np.float64).eps) * float(svals[0])
if rcond is None and svals.size > 0
else (0.0 if rcond is None else rcond * float(svals[0]))
)
inv_s = np.where(svals > cutoff, 1.0 / np.maximum(svals, 1e-300), 0.0)
beta = Vt.T @ (inv_s * (U.T @ y_arr))
rank = int(np.sum(svals > cutoff))
intercept = float(beta[0]) if fit_intercept else 0.0
coef = beta[1:] if fit_intercept else beta
rss = 0.5 * float(np.mean((y_arr - X_aug @ beta) ** 2))
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="svd",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(rank),
n_iter=1,
converged=True,
screened_count=0,
duality_gap=0.0,
singular_fallback=False,
loss_history=(rss,),
)
def fit_ridge_svd(
X: np.ndarray,
y: np.ndarray,
l2_alpha: float = 1.0,
fit_intercept: bool = True,
standardize: bool = True,
) -> LinearFitResult:
"""Fit Ridge regression via SVD spectral filter factors (supports negative lambda above -s_min^2)."""
x_s, y_c, x_mean, y_mean, x_scale = _prepare_standardized_centered(
X, y, fit_intercept=fit_intercept, standardize=standardize
)
kx, kxtx = _cond_numbers(_design_with_intercept(x_s, fit_intercept))
U, svals, Vt = np.linalg.svd(x_s, full_matrices=False)
s2 = svals**2
denom = s2 + float(l2_alpha)
if np.any(denom <= 1e-14):
raise ValueError(
f"Ridge denominator s_i^2 + lambda must remain positive (min={float(np.min(denom)):.3e})."
)
filter_factors = s2 / denom
w_s = Vt.T @ ((svals / denom) * (U.T @ y_c))
coef = w_s / x_scale
intercept = float(y_mean - np.dot(x_mean, coef)) if fit_intercept else 0.0
eff_df = float(np.sum(filter_factors) + (1.0 if fit_intercept else 0.0))
preds = intercept + np.asarray(X, dtype=np.float64) @ coef
loss = 0.5 * float(np.mean((np.asarray(y, dtype=np.float64) - preds) ** 2))
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="ridge_svd",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=eff_df,
n_iter=1,
converged=True,
screened_count=0,
duality_gap=0.0,
singular_fallback=False,
loss_history=(loss,),
)
def soft_threshold(z: float, gamma: float) -> float:
"""Exact L1 proximal soft-thresholding operator S(z, gamma) = sign(z) * max(|z| - gamma, 0)."""
if z > gamma:
return float(z - gamma)
if z < -gamma:
return float(z + gamma)
return 0.0
def fit_lasso_cd(
X: np.ndarray,
y: np.ndarray,
l1_alpha: float = 0.1,
fit_intercept: bool = True,
standardize: bool = True,
use_gap_safe: bool = True,
max_iter: int = 3000,
tol: float = 1e-8,
) -> LinearFitResult:
"""Fit Lasso via cyclic Coordinate Descent with optional Gap Safe variable screening."""
return fit_elasticnet_cd(
X=X,
y=y,
l1_alpha=l1_alpha,
l2_alpha=0.0,
fit_intercept=fit_intercept,
standardize=standardize,
use_gap_safe=use_gap_safe,
max_iter=max_iter,
tol=tol,
)
def fit_elasticnet_cd(
X: np.ndarray,
y: np.ndarray,
l1_alpha: float = 0.1,
l2_alpha: float = 0.1,
fit_intercept: bool = True,
standardize: bool = True,
use_gap_safe: bool = True,
max_iter: int = 3000,
tol: float = 1e-8,
) -> LinearFitResult:
"""Fit ElasticNet (1/(2n)||y-Xw||^2 + l1||w||_1 + (l2/2)||w||_2^2) via Coordinate Descent."""
x_s, y_c, x_mean, y_mean, x_scale = _prepare_standardized_centered(
X, y, fit_intercept=fit_intercept, standardize=standardize
)
n, d = x_s.shape
kx, kxtx = _cond_numbers(_design_with_intercept(x_s, fit_intercept))
# Rescale by 1/sqrt(n) so 1/(2n)||y - Xw||^2 == 1/2 ||b - Aw||^2
inv_sqrt_n = 1.0 / math.sqrt(float(n))
A = x_s * inv_sqrt_n
b = y_c * inv_sqrt_n
col_norm_sq = np.sum(A * A, axis=0)
col_norm = np.sqrt(col_norm_sq)
w = np.zeros(d, dtype=np.float64)
r = b.copy()
active = np.ones(d, dtype=bool)
losses: list[float] = []
duality_gap = float("inf")
converged = False
for it in range(1, max_iter + 1):
if l1_alpha > 0.0 and l2_alpha == 0.0 and use_gap_safe and (it == 1 or it % 5 == 0):
at_r_inf = float(np.max(np.abs(A.T @ r))) if d > 0 else 0.0
scale_d = max(float(l1_alpha), at_r_inf, 1e-15)
theta = r / scale_d
primal = 0.5 * float(np.dot(r, r)) + float(l1_alpha * np.sum(np.abs(w)))
dual = float(l1_alpha * np.dot(b, theta)) - 0.5 * (float(l1_alpha) ** 2) * float(
np.dot(theta, theta)
)
duality_gap = max(0.0, primal - dual)
safe_r = math.sqrt(2.0 * duality_gap) / float(l1_alpha)
if it > 1 and duality_gap <= tol:
converged = True
losses.append(primal)
break
scores = np.abs(A.T @ theta) + col_norm * safe_r
newly_screened = active & (scores < 1.0 - 1e-12)
if np.any(newly_screened):
w[newly_screened] = 0.0
active[newly_screened] = False
r = b - A @ w
max_delta = 0.0
for j in np.flatnonzero(active):
denom = float(col_norm_sq[j]) + float(l2_alpha)
if denom <= 1e-15:
continue
w_old = float(w[j])
z_j = float(np.dot(A[:, j], r)) + float(col_norm_sq[j]) * w_old
w_new = soft_threshold(z_j, float(l1_alpha)) / denom
delta = w_new - w_old
if delta != 0.0:
w[j] = w_new
r -= delta * A[:, j]
max_delta = max(max_delta, abs(delta))
primal_now = (
0.5 * float(np.dot(r, r))
+ float(l1_alpha * np.sum(np.abs(w)))
+ 0.5 * float(l2_alpha * np.dot(w, w))
)
losses.append(primal_now)
if max_delta <= tol:
# Verify KKT optimality on all coordinates if screening disabled some
if np.all(active):
converged = True
break
grad_all = A.T @ r
violated = (np.abs(grad_all) > float(l1_alpha) + 1e-7) & (~active)
if not np.any(violated):
converged = True
break
active[violated] = True
if l1_alpha > 0.0 and l2_alpha == 0.0:
at_r_inf = float(np.max(np.abs(A.T @ r))) if d > 0 else 0.0
theta = r / max(float(l1_alpha), at_r_inf, 1e-15)
primal = 0.5 * float(np.dot(r, r)) + float(l1_alpha * np.sum(np.abs(w)))
dual = float(l1_alpha * np.dot(b, theta)) - 0.5 * (float(l1_alpha) ** 2) * float(
np.dot(theta, theta)
)
duality_gap = max(0.0, primal - dual)
else:
duality_gap = 0.0
coef = w / x_scale
intercept = float(y_mean - np.dot(x_mean, coef)) if fit_intercept else 0.0
solver_name = "lasso_cd" if l2_alpha == 0.0 else "elasticnet_cd"
return LinearFitResult(
intercept=intercept,
coef=coef,
solver=solver_name,
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(np.sum(np.abs(coef) > 1e-10) + (1 if fit_intercept else 0)),
n_iter=len(losses),
converged=converged,
screened_count=int(np.sum(~active)),
duality_gap=float(duality_gap),
singular_fallback=False,
loss_history=tuple(losses),
)
def fit_huber_irls(
X: np.ndarray,
y: np.ndarray,
delta: float = 1.345,
l2_alpha: float = 1e-8,
fit_intercept: bool = True,
max_iter: int = 80,
tol: float = 1e-7,
) -> LinearFitResult:
"""Fit robust Huber regression via Iteratively Reweighted Least Squares (IRLS)."""
X_aug = _design_with_intercept(X, fit_intercept)
y_arr = np.asarray(y, dtype=np.float64)
_n, p = X_aug.shape
kx, kxtx = _cond_numbers(X_aug)
I0 = np.eye(p, dtype=np.float64)
if fit_intercept:
I0[0, 0] = 0.0
beta = np.linalg.lstsq(X_aug, y_arr, rcond=None)[0]
losses: list[float] = []
converged = False
for _ in range(max_iter):
res = y_arr - X_aug @ beta
abs_r = np.abs(res)
huber_vals = np.where(abs_r <= delta, 0.5 * res * res, delta * (abs_r - 0.5 * delta))
losses.append(float(np.mean(huber_vals)))
weights = np.where(abs_r <= delta, 1.0, delta / np.maximum(abs_r, 1e-12))
Xw = X_aug.T * weights
beta_new = np.linalg.solve(Xw @ X_aug + float(l2_alpha) * I0, Xw @ y_arr)
diff = float(np.max(np.abs(beta_new - beta)))
beta = beta_new
if diff <= tol:
converged = True
break
intercept = float(beta[0]) if fit_intercept else 0.0
coef = beta[1:] if fit_intercept else beta
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="huber_irls",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(p),
n_iter=len(losses),
converged=converged,
screened_count=0,
duality_gap=0.0,
singular_fallback=False,
loss_history=tuple(losses),
)
def fit_quantile_mm(
X: np.ndarray,
y: np.ndarray,
tau: float = 0.5,
l2_alpha: float = 1e-8,
fit_intercept: bool = True,
max_iter: int = 200,
tol: float = 1e-6,
eps_smooth: float = 1e-6,
) -> LinearFitResult:
"""Fit Quantile / Pinball regression via Majorize-Minimize IRLS (Schlossmacher / Hunter-Lange)."""
if not 0.0 < tau < 1.0:
raise ValueError("tau must lie strictly in (0, 1).")
X_aug = _design_with_intercept(X, fit_intercept)
y_arr = np.asarray(y, dtype=np.float64)
_, p = X_aug.shape
kx, kxtx = _cond_numbers(X_aug)
I0 = np.eye(p, dtype=np.float64)
if fit_intercept:
I0[0, 0] = 0.0
beta = np.linalg.lstsq(X_aug, y_arr, rcond=None)[0]
losses: list[float] = []
converged = False
for _ in range(max_iter):
u = y_arr - X_aug @ beta
pinball = np.where(u >= 0.0, tau * u, (tau - 1.0) * u)
losses.append(float(np.mean(pinball)))
denom = np.maximum(np.abs(u), eps_smooth)
weights = np.where(u >= 0.0, tau / denom, (1.0 - tau) / denom)
# Asymmetric quadratic MM surrogate: exact subgradient fixed point
Xw = X_aug.T * weights
beta_new = np.linalg.solve(Xw @ X_aug + float(l2_alpha) * I0, Xw @ y_arr)
if float(np.max(np.abs(beta_new - beta))) <= tol:
beta = beta_new
converged = True
break
beta = beta_new
intercept = float(beta[0]) if fit_intercept else 0.0
coef = beta[1:] if fit_intercept else beta
return LinearFitResult(
intercept=intercept,
coef=coef,
solver="quantile_mm",
condition_number_x=kx,
condition_number_xtx=kxtx,
effective_df=float(p),
n_iter=len(losses),
converged=converged,
screened_count=0,
duality_gap=0.0,
singular_fallback=False,
loss_history=tuple(losses),
)
def _nelder_mead_minimize(
fn: Callable[[np.ndarray], float],
x0: np.ndarray,
max_evals: int = 1200,
) -> tuple[np.ndarray, int, float]:
"""Minimal Nelder-Mead simplex search demonstrating zeroth-order scaling bounds."""
p = x0.size
simplex = np.tile(x0, (p + 1, 1))
for i in range(p):
simplex[i + 1, i] += 0.25 if abs(x0[i]) < 1e-6 else 0.1 * abs(x0[i])
vals = np.array([fn(pt) for pt in simplex], dtype=np.float64)
evals = p + 1
while evals < max_evals:
order = np.argsort(vals)
simplex = simplex[order]
vals = vals[order]
if float(np.max(np.abs(vals - vals[0]))) < 1e-10:
break
centroid = np.mean(simplex[:-1], axis=0)
xr = centroid + 1.0 * (centroid - simplex[-1])
vr = fn(xr)
evals += 1
if vals[0] <= vr < vals[-2]:
simplex[-1], vals[-1] = xr, vr
elif vr < vals[0]:
xe = centroid + 2.0 * (xr - centroid)
ve = fn(xe)
evals += 1
if ve < vr:
simplex[-1], vals[-1] = xe, ve
else:
simplex[-1], vals[-1] = xr, vr
else:
xc = centroid + 0.5 * (simplex[-1] - centroid)
vc = fn(xc)
evals += 1
if vc < vals[-1]:
simplex[-1], vals[-1] = xc, vc
else:
for i in range(1, p + 1):
simplex[i] = simplex[0] + 0.5 * (simplex[i] - simplex[0])
vals[i] = fn(simplex[i])
evals += 1
best_idx = int(np.argmin(vals))
return simplex[best_idx], evals, float(vals[best_idx])
def compare_linear_optimizers(
X: np.ndarray,
y: np.ndarray,
max_iter: int = 300,
batch_size: int = 32,
seed: int = 42,
) -> dict[str, dict[str, float]]:
"""Compare QR, L-BFGS, Batch GD, Mini-batch SGD, SGD, and Nelder-Mead on OLS loss."""
x_s, y_c, x_mean, y_mean, x_scale = _prepare_standardized_centered(
X, y, fit_intercept=True, standardize=True
)
n, d = x_s.shape
qr_ref = solve_ols_qr(x_s, y_c, fit_intercept=False)
w_star = qr_ref.coef
opt_loss = 0.5 * float(np.mean((y_c - x_s @ w_star) ** 2))
# Lipchitz bound L = lambda_max(X^T X / n) for safe stable step size
svals = np.linalg.svd(x_s, compute_uv=False)
lipschitz = float((svals[0] ** 2) / n) if svals.size else 1.0
lr_bgd = 1.0 / max(lipschitz, 1e-8)
def _val_grad(w: np.ndarray) -> tuple[float, np.ndarray]:
err = x_s @ w - y_c
loss = 0.5 * float(np.mean(err * err))
grad = (x_s.T @ err) / float(n)
return loss, grad
# 1. Batch GD
w_bgd = np.zeros(d, dtype=np.float64)
bgd_steps = 0
for step in range(1, max_iter + 1):
_, g = _val_grad(w_bgd)
w_bgd -= lr_bgd * g
bgd_steps = step
if float(np.linalg.norm(g)) < 1e-7:
break
bgd_loss = _val_grad(w_bgd)[0]
# 2. Mini-batch & 3. Pure SGD with decaying schedule
rng = np.random.default_rng(seed)
def _run_stochastic(bs: int, epochs: int) -> tuple[float, np.ndarray]:
w = np.zeros(d, dtype=np.float64)
t_step = 0
for _ in range(epochs):
perm = rng.permutation(n)
for start in range(0, n, bs):
t_step += 1
idx = perm[start : start + bs]
xb, yb = x_s[idx], y_c[idx]
grad = (xb.T @ (xb @ w - yb)) / float(len(idx))
lr_t = min(0.5 * lr_bgd, 0.25 / (1.0 + 0.02 * t_step))
w -= lr_t * grad
return _val_grad(w)[0], w
mb_loss, w_mb = _run_stochastic(min(batch_size, n), epochs=max(20, max_iter // 10))
sgd_loss, w_sgd = _run_stochastic(1, epochs=max(20, max_iter // 10))
# 4. L-BFGS
w_lbfgs, lbfgs_steps, _, _ = lbfgs_minimize(
_val_grad, np.zeros(d, dtype=np.float64), max_iter=max_iter, tol=1e-8
)
lbfgs_loss = _val_grad(w_lbfgs)[0]
# 5. Nelder-Mead metaheuristic capped at 1200 evals
w_nm, nm_evals, nm_loss = _nelder_mead_minimize(
lambda w: _val_grad(w)[0], np.zeros(d, dtype=np.float64), max_evals=1200
)
def _rel_err(w: np.ndarray) -> float:
denom = max(float(np.linalg.norm(w_star)), 1e-12)
return float(np.linalg.norm(w - w_star) / denom)
_ = (x_mean, y_mean, x_scale)
return {
"qr": {"loss_gap": 0.0, "param_rel_err": 0.0, "steps": 1.0},
"lbfgs": {"loss_gap": max(0.0, lbfgs_loss - opt_loss), "param_rel_err": _rel_err(w_lbfgs), "steps": float(lbfgs_steps)},
"bgd": {"loss_gap": max(0.0, bgd_loss - opt_loss), "param_rel_err": _rel_err(w_bgd), "steps": float(bgd_steps)},
"minibatch": {"loss_gap": max(0.0, mb_loss - opt_loss), "param_rel_err": _rel_err(w_mb), "steps": float(max(20, max_iter // 10))},
"sgd": {"loss_gap": max(0.0, sgd_loss - opt_loss), "param_rel_err": _rel_err(w_sgd), "steps": float(max(20, max_iter // 10))},
"nelder_mead": {"loss_gap": max(0.0, nm_loss - opt_loss), "param_rel_err": _rel_err(w_nm), "steps": float(nm_evals)},
}
def compute_regression_diagnostics(
X: np.ndarray,
y: np.ndarray,
fit_intercept: bool = True,
) -> RegressionDiagnostics:
"""Compute Hat leverages, Studentized residuals, VIF, Breusch-Pagan, HC0-HC3 SEs, and Cook's D."""
x_raw = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = x_raw.shape
X_aug = _design_with_intercept(x_raw, fit_intercept)
p = X_aug.shape[1]
if n <= p + 1:
raise ValueError("Need n > p + 1 observations for externally Studentized diagnostics.")
ols = solve_ols_qr(x_raw, y_arr, fit_intercept=fit_intercept)
beta = np.concatenate([[ols.intercept], ols.coef]) if fit_intercept else ols.coef
residuals = y_arr - X_aug @ beta
# Hat diagonal via thin QR: H = Q Q^T => h_ii = sum_j Q_{ij}^2
Q, R = np.linalg.qr(X_aug, mode="reduced")
h_ii = np.clip(np.sum(Q * Q, axis=1), 0.0, 1.0 - 1e-12)
sse = float(np.dot(residuals, residuals))
s2 = sse / float(n - p)
one_minus_h = np.maximum(1.0 - h_ii, 1e-12)
std_res = residuals / np.sqrt(max(s2, 1e-18) * one_minus_h)
num_t = np.maximum(float(n - p - 1), 1.0)
den_t = np.maximum(float(n - p) - std_res * std_res, 1e-12)
stud_res = std_res * np.sqrt(num_t / den_t)
cooks_d = ((residuals * residuals) / (float(p) * max(s2, 1e-18))) * (
h_ii / (one_minus_h * one_minus_h)
)
# VIF via inverse correlation matrix on centered standardized predictors
x_c = x_raw - np.mean(x_raw, axis=0)
sd = np.std(x_c, axis=0)
x_z = x_c / np.where(sd > 1e-12, sd, 1.0)
corr_mat = (x_z.T @ x_z) / float(n)
try:
vif_vals = np.diag(np.linalg.inv(corr_mat))
except np.linalg.LinAlgError:
vif_vals = np.diag(np.linalg.pinv(corr_mat))
# Koenker/Breusch-Pagan test: regress e^2 on predictors
e2 = residuals * residuals
e2_hat = X_aug @ np.linalg.lstsq(X_aug, e2, rcond=None)[0]
sst_e2 = float(np.sum((e2 - np.mean(e2)) ** 2))
r2_aux = 1.0 - float(np.sum((e2 - e2_hat) ** 2)) / max(sst_e2, 1e-18)
r2_aux = max(0.0, min(1.0, r2_aux))
bp_lm = float(n) * r2_aux
bp_pval = chi2_survival_prob(bp_lm, df=max(d, 1))
# Bread (X^T X)^-1 = R^-1 R^-T
R_inv = np.linalg.solve(R, np.eye(p, dtype=np.float64))
xtx_inv = R_inv @ R_inv.T
se_ols = np.sqrt(np.maximum(np.diag(s2 * xtx_inv), 0.0))
def _hc_se(scale_vec: np.ndarray) -> np.ndarray:
meat = (X_aug.T * scale_vec) @ X_aug
vcov = xtx_inv @ meat @ xtx_inv
return np.sqrt(np.maximum(np.diag(vcov), 0.0))
se_hc0 = _hc_se(e2)
se_hc1 = _hc_se((float(n) / float(n - p)) * e2)
se_hc2 = _hc_se(e2 / one_minus_h)
se_hc3 = _hc_se(e2 / (one_minus_h * one_minus_h))
lev_thresh = 2.0 * float(p) / float(n)
cook_thresh = 4.0 / float(n)
high_lev = tuple(int(i) for i in np.flatnonzero(h_ii > lev_thresh))
influential = tuple(int(i) for i in np.flatnonzero(cooks_d > cook_thresh))
return RegressionDiagnostics(
leverage=h_ii,
residuals=residuals,
standardized_residuals=std_res,
studentized_residuals=stud_res,
cooks_distance=cooks_d,
vif=vif_vals,
breusch_pagan_lm=float(bp_lm),
breusch_pagan_pvalue=float(bp_pval),
se_ols=se_ols,
se_hc0=se_hc0,
se_hc1=se_hc1,
se_hc2=se_hc2,
se_hc3=se_hc3,
high_leverage_indices=high_lev,
influential_indices=influential,
)
def simulate_double_descent_and_negative_ridge(
seed: int = 42,
quick: bool = True,
) -> dict[str, object]:
"""Reproduce Hastie et al. (2022) gamma=1 pole & Kobak et al. (2020) optimal lambda < 0."""
rng = np.random.default_rng(seed)
n_train = 60 if quick else 100
n_test = 400 if quick else 800
trials = 10 if quick else 20
gammas = [0.3, 0.7, 0.95, 1.05, 1.5, 2.5]
sigma = 0.5
gamma_curve: list[dict[str, float]] = []
for gamma in gammas:
p = max(2, round(gamma * n_train))
mses: list[float] = []
for _ in range(trials):
beta_true = rng.normal(0.0, 1.0 / math.sqrt(float(p)), size=p)
X_tr = rng.normal(0.0, 1.0, size=(n_train, p))
y_tr = X_tr @ beta_true + rng.normal(0.0, sigma, size=n_train)
X_te = rng.normal(0.0, 1.0, size=(n_test, p))
y_te = X_te @ beta_true + rng.normal(0.0, sigma, size=n_test)
fit = solve_ols_svd(X_tr, y_tr, fit_intercept=False)
mses.append(float(np.mean((y_te - fit.predict(X_te)) ** 2)))
gamma_curve.append({"gamma": float(gamma), "p": float(p), "test_mse": float(np.mean(mses))})
# Kobak et al. (2020) spiked covariance: strong 2D signal + isotropic high-dim tail
n_sp = 60 if quick else 80
p_tail = 400 if quick else 550
cov_diag = np.concatenate([[85.0, 65.0], np.full(p_tail, 1.0)])
sqrt_cov = np.sqrt(cov_diag)
beta_sp = np.zeros(2 + p_tail, dtype=np.float64)
beta_sp[:2] = [1.4, -1.1]
lambdas = [-110.0, -70.0, -35.0, 0.0, 50.0, 180.0]
neg_ridge_curve: list[dict[str, float]] = []
agg_mses = {lam: [] for lam in lambdas}
for _ in range(trials):
X_tr = rng.normal(0.0, 1.0, size=(n_sp, 2 + p_tail)) * sqrt_cov
y_tr = X_tr @ beta_sp + rng.normal(0.0, 0.25, size=n_sp)
X_te = rng.normal(0.0, 1.0, size=(n_test, 2 + p_tail)) * sqrt_cov
y_te = X_te @ beta_sp + rng.normal(0.0, 0.25, size=n_test)
svals = np.linalg.svd(X_tr, compute_uv=False)
min_s2 = float(svals[-1] ** 2)
for lam in lambdas:
if min_s2 + lam <= 1e-6:
continue
fit = fit_ridge_svd(X_tr, y_tr, l2_alpha=lam, fit_intercept=False, standardize=False)
agg_mses[lam].append(float(np.mean((y_te - fit.predict(X_te)) ** 2)))
for lam in lambdas:
if agg_mses[lam]:
neg_ridge_curve.append({"l2_alpha": float(lam), "test_mse": float(np.mean(agg_mses[lam]))})
best_pt = min(neg_ridge_curve, key=lambda r: r["test_mse"])
return {
"double_descent_curve": gamma_curve,
"negative_ridge_curve": neg_ridge_curve,
"best_spiked_lambda": float(best_pt["l2_alpha"]),
"best_spiked_mse": float(best_pt["test_mse"]),
}
"""Logistic/Softmax solvers (IRLS, Firth, L-BFGS, GD, FTRL-Proximal, GAM) and evaluation metrics."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from linear_validation_lab.linear_models import lbfgs_minimize
def stable_sigmoid(z: np.ndarray | float) -> np.ndarray | float:
"""Overflow-safe sigmoid mapping R -> (0, 1) cleanly across positive and negative regimes."""
arr = np.asarray(z, dtype=np.float64)
pos = arr >= 0.0
out = np.empty_like(arr, dtype=np.float64)
out[pos] = 1.0 / (1.0 + np.exp(-np.clip(arr[pos], 0.0, 500.0)))
exp_neg = np.exp(np.clip(arr[~pos], -500.0, 0.0))
out[~pos] = exp_neg / (1.0 + exp_neg)
if np.ndim(z) == 0:
return float(out.item())
return out
def logsumexp(logits: np.ndarray, axis: int = -1) -> np.ndarray:
"""Numerically stable log(sum(exp(logits))) along given axis."""
arr = np.asarray(logits, dtype=np.float64)
m = np.max(arr, axis=axis, keepdims=True)
res = m + np.log(np.sum(np.exp(arr - m), axis=axis, keepdims=True))
return np.squeeze(res, axis=axis)
def _binary_logloss_from_logits(logits: np.ndarray, y: np.ndarray) -> np.ndarray:
"""Stable elementwise binary cross-entropy: max(z, 0) - y*z + log(1 + exp(-|z|))."""
return np.maximum(logits, 0.0) - y * logits + np.log1p(np.exp(-np.abs(logits)))
class LogisticConfig(BaseModel):
"""Typed boundary configuration for binary logistic regression solvers."""
model_config = ConfigDict(frozen=True, extra="forbid")
solver: Literal["irls", "firth", "lbfgs", "bgd", "sgd", "minibatch"] = "irls"
l2_alpha: float = Field(default=1.0, ge=0.0)
fit_intercept: bool = True
standardize: bool = False
max_iter: int = Field(default=80, ge=1)
tol: float = Field(default=1e-7, gt=0.0)
learning_rate: float = Field(default=0.1, gt=0.0)
batch_size: int = Field(default=32, ge=1)
seed: int = 42
@dataclass(frozen=True, slots=True)
class LogisticFitResult:
"""Immutable binary logistic model state with optimization and Hessian metrics."""
intercept: float
coef: np.ndarray
solver: str
n_iter: int
converged: bool
param_l2_norm: float
hessian_min_eig: float
loss_history: tuple[float, ...]
mean_vec: np.ndarray
scale_vec: np.ndarray
def __post_init__(self) -> None:
for attr in ("coef", "mean_vec", "scale_vec"):
arr = np.array(getattr(self, attr), dtype=np.float64, copy=True)
arr.setflags(write=False)
object.__setattr__(self, attr, arr)
def predict_logits(self, X: np.ndarray) -> np.ndarray:
"""Compute linear predictor eta = b + X_scaled @ w."""
x_arr = (np.asarray(X, dtype=np.float64) - self.mean_vec) / self.scale_vec
return self.intercept + x_arr @ self.coef
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Predict calibrated positive-class probabilities P(Y=1|X)."""
return np.asarray(stable_sigmoid(self.predict_logits(X)), dtype=np.float64)
class LogisticRegressionWorkbench:
"""Unified binary logistic estimator supporting IRLS, Firth, L-BFGS, BGD, SGD, and Mini-batch."""
def __init__(self, config: LogisticConfig | None = None) -> None:
self.config = config or LogisticConfig()
self.state_: LogisticFitResult | None = None
def fit(self, X: np.ndarray, y: np.ndarray) -> LogisticFitResult:
"""Fit binary logistic regression using the configured optimization algorithm."""
x_raw = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n, d = x_raw.shape
cfg = self.config
if cfg.standardize:
mean_v = np.mean(x_raw, axis=0)
sd_v = np.std(x_raw, axis=0)
scale_v = np.where(sd_v > 1e-12, sd_v, 1.0)
x_s = (x_raw - mean_v) / scale_v
else:
mean_v = np.zeros(d, dtype=np.float64)
scale_v = np.ones(d, dtype=np.float64)
x_s = x_raw
X_aug = np.column_stack([np.ones(n, dtype=np.float64), x_s]) if cfg.fit_intercept else x_s
p = X_aug.shape[1]
I0 = np.eye(p, dtype=np.float64)
if cfg.fit_intercept:
I0[0, 0] = 0.0
theta = np.zeros(p, dtype=np.float64)
losses: list[float] = []
converged = False
def _obj_and_grad(th: np.ndarray) -> tuple[float, np.ndarray]:
eta = X_aug @ th
probs = np.asarray(stable_sigmoid(eta), dtype=np.float64)
pen = 0.5 * cfg.l2_alpha * float(np.dot(th, I0 @ th))
loss_val = float(np.sum(_binary_logloss_from_logits(eta, y_arr))) + pen
grad = X_aug.T @ (probs - y_arr) + cfg.l2_alpha * (I0 @ th)
return loss_val, grad
if cfg.solver == "irls":
for _ in range(cfg.max_iter):
eta = X_aug @ theta
probs = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w_diag = np.maximum(probs * (1.0 - probs), 1e-10)
cur_loss = float(np.sum(_binary_logloss_from_logits(eta, y_arr))) + 0.5 * cfg.l2_alpha * float(
np.dot(theta, I0 @ theta)
)
losses.append(cur_loss)
# IRLS WLS formulation: (X^T W X + lam I0) theta_new = X^T W z
z_work = eta + (y_arr - probs) / w_diag
Xw = X_aug.T * w_diag
H = Xw @ X_aug + cfg.l2_alpha * I0 + 1e-10 * np.eye(p)
grad = X_aug.T @ (probs - y_arr) + cfg.l2_alpha * (I0 @ theta)
# Direct Newton step (mathematically identical to WLS on z_work) with damping safeguard
step = np.linalg.solve(H, grad)
step_scale = 1.0
for _ in range(15):
cand = theta - step_scale * step
cand_loss, _ = _obj_and_grad(cand)
if cand_loss <= cur_loss + 1e-9:
theta = cand
break
step_scale *= 0.5
else:
# Fallback exact WLS check
theta_wls = np.linalg.solve(H, Xw @ z_work)
theta = theta_wls
if float(np.max(np.abs(step_scale * step))) <= cfg.tol:
converged = True
break
elif cfg.solver == "firth":
# Firth (1993) Jeffreys prior penalized logistic score: (y + h/2) - p(1 + h)
for _ in range(cfg.max_iter):
eta = X_aug @ theta
probs = np.asarray(stable_sigmoid(eta), dtype=np.float64)
w_diag = np.maximum(probs * (1.0 - probs), 1e-10)
fisher = (X_aug.T * w_diag) @ X_aug + 1e-9 * np.eye(p)
fisher_inv = np.linalg.inv(fisher)
# Weighted hat diagonal h_ii = w_i * x_i^T I^{-1} x_i
h_ii = w_diag * np.sum((X_aug @ fisher_inv) * X_aug, axis=1)
sign_det, logdet = np.linalg.slogdet(fisher)
firth_obj = float(np.sum(_binary_logloss_from_logits(eta, y_arr))) - (
0.5 * float(logdet) if sign_det > 0 else 0.0
)
losses.append(firth_obj)
# Modified score U* = X^T [(y + h/2) - p(1 + h)] => gradient of negative Firth LL is -U*
u_star = X_aug.T @ ((y_arr + 0.5 * h_ii) - probs * (1.0 + h_ii))
step = fisher_inv @ u_star
max_step = float(np.max(np.abs(step)))
if max_step > 2.5:
step *= 2.5 / max_step
theta_new = theta + step
if float(np.max(np.abs(theta_new - theta))) <= cfg.tol:
theta = theta_new
converged = True
break
theta = theta_new
elif cfg.solver == "lbfgs":
# Scale objective by 1/n for smooth L-BFGS curvature
def _scaled_obj(th: np.ndarray) -> tuple[float, np.ndarray]:
l_val, g_val = _obj_and_grad(th)
return l_val / float(n), g_val / float(n)
theta, _, converged, losses_tuple = lbfgs_minimize(
_scaled_obj, theta, max_iter=cfg.max_iter, tol=cfg.tol
)
losses = list(losses_tuple)
else:
# First-order variants: BGD, SGD, Mini-batch GD on mean objective
rng = np.random.default_rng(cfg.seed)
bs = n if cfg.solver == "bgd" else (1 if cfg.solver == "sgd" else min(cfg.batch_size, n))
t_step = 0
for epoch in range(cfg.max_iter):
if cfg.solver == "bgd":
eta = X_aug @ theta
probs = np.asarray(stable_sigmoid(eta), dtype=np.float64)
loss_val = (
float(np.mean(_binary_logloss_from_logits(eta, y_arr)))
+ (0.5 * cfg.l2_alpha / float(n)) * float(np.dot(theta, I0 @ theta))
)
losses.append(loss_val)
grad = (X_aug.T @ (probs - y_arr)) / float(n) + (cfg.l2_alpha / float(n)) * (I0 @ theta)
theta -= cfg.learning_rate * grad
if float(np.max(np.abs(grad))) <= cfg.tol:
converged = True
break
else:
perm = rng.permutation(n)
for start in range(0, n, bs):
t_step += 1
idx = perm[start : start + bs]
xb, yb = X_aug[idx], y_arr[idx]
pb = np.asarray(stable_sigmoid(xb @ theta), dtype=np.float64)
grad = (xb.T @ (pb - yb)) / float(len(idx)) + (cfg.l2_alpha / float(n)) * (I0 @ theta)
lr_t = cfg.learning_rate / (1.0 + 0.005 * float(t_step))
theta -= lr_t * grad
losses.append(float(np.mean(_binary_logloss_from_logits(X_aug @ theta, y_arr))))
if epoch > 5 and abs(losses[-1] - losses[-2]) <= cfg.tol:
converged = True
break
eta_final = X_aug @ theta
p_final = np.asarray(stable_sigmoid(eta_final), dtype=np.float64)
w_final = np.maximum(p_final * (1.0 - p_final), 1e-12)
H_final = (X_aug.T * w_final) @ X_aug + cfg.l2_alpha * I0
min_eig = float(np.min(np.linalg.eigvalsh(H_final)))
intercept = float(theta[0]) if cfg.fit_intercept else 0.0
coef = theta[1:] if cfg.fit_intercept else theta
res = LogisticFitResult(
intercept=intercept,
coef=coef,
solver=cfg.solver,
n_iter=len(losses),
converged=converged,
param_l2_norm=float(np.linalg.norm(theta)),
hessian_min_eig=min_eig,
loss_history=tuple(losses),
mean_vec=mean_v,
scale_vec=scale_v,
)
self.state_ = res
return res
class SoftmaxMultinomialClassifier:
"""L2-regularized Multinomial Softmax Regression with log-sum-exp numerical stability."""
def __init__(self, l2_alpha: float = 1.0, max_iter: int = 150, tol: float = 1e-7) -> None:
self.l2_alpha = float(l2_alpha)
self.max_iter = int(max_iter)
self.tol = float(tol)
self.weights_: np.ndarray | None = None # shape (d, K)
self.intercept_: np.ndarray | None = None # shape (K,)
self.n_classes_: int = 0
self.n_iter_: int = 0
def fit(self, X: np.ndarray, y: np.ndarray) -> SoftmaxMultinomialClassifier:
"""Fit K-class Softmax classifier using L-BFGS over stable log-sum-exp cross-entropy."""
x_arr = np.asarray(X, dtype=np.float64)
y_int = np.asarray(y, dtype=np.int64)
n, d = x_arr.shape
k_cls = int(np.max(y_int)) + 1
self.n_classes_ = k_cls
X_aug = np.column_stack([np.ones(n, dtype=np.float64), x_arr])
p = d + 1
Y_onehot = np.zeros((n, k_cls), dtype=np.float64)
Y_onehot[np.arange(n), y_int] = 1.0
def _val_grad(flat_B: np.ndarray) -> tuple[float, np.ndarray]:
B = flat_B.reshape(p, k_cls)
logits = X_aug @ B
lse = logsumexp(logits, axis=1)
probs = np.exp(logits - lse[:, None])
nll = float(np.mean(lse - np.sum(Y_onehot * logits, axis=1)))
B_reg = B.copy()
B_reg[0, :] = 0.0 # Unpenalized class intercepts
loss = nll + (0.5 * self.l2_alpha / float(n)) * float(np.sum(B_reg * B_reg))
grad = (X_aug.T @ (probs - Y_onehot)) / float(n) + (self.l2_alpha / float(n)) * B_reg
return loss, grad.ravel()
b_opt, steps, _, _ = lbfgs_minimize(
_val_grad, np.zeros(p * k_cls, dtype=np.float64), max_iter=self.max_iter, tol=self.tol
)
B_opt = b_opt.reshape(p, k_cls)
self.intercept_ = B_opt[0, :].copy()
self.weights_ = B_opt[1:, :].copy()
self.intercept_.setflags(write=False)
self.weights_.setflags(write=False)
self.n_iter_ = steps
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Predict normalized K-class probability matrix via stable log-sum-exp."""
if self.weights_ is None or self.intercept_ is None:
raise RuntimeError("SoftmaxMultinomialClassifier must be fit before calling predict_proba.")
logits = np.asarray(X, dtype=np.float64) @ self.weights_ + self.intercept_
lse = logsumexp(logits, axis=1)
return np.exp(logits - lse[:, None])
def quantize_q2_13(
weights: np.ndarray,
seed: int = 42,
stochastic_rounding: bool = True,
) -> np.ndarray:
"""Quantize weights to Q2.13 fixed-point resolution (2^-13) with unbiased stochastic rounding."""
w = np.asarray(weights, dtype=np.float64)
clipped = np.clip(w, -4.0, 4.0 - 2.0 ** -13)
scale = float(2 ** 13)
if stochastic_rounding:
rng = np.random.default_rng(seed)
noise = rng.uniform(0.0, 1.0, size=clipped.shape)
return np.floor(clipped * scale + noise) / scale
return np.round(clipped * scale) / scale
class FTRLProximalClassifier:
"""Google McMahan et al. (2013) per-coordinate FTRL-Proximal online logistic classifier."""
def __init__(
self,
n_features: int,
alpha: float = 0.15,
beta: float = 1.0,
l1_alpha: float = 1.0,
l2_alpha: float = 1.0,
negative_subsample_rate: float = 1.0,
seed: int = 42,
) -> None:
self.n_features = int(n_features)
self.alpha = float(alpha)
self.beta = float(beta)
self.l1_alpha = float(l1_alpha)
self.l2_alpha = float(l2_alpha)
self.negative_subsample_rate = float(negative_subsample_rate)
self.rng = np.random.default_rng(seed)
self.z = np.zeros(self.n_features, dtype=np.float64)
self.n_sq = np.zeros(self.n_features, dtype=np.float64)
self.z_bias = 0.0
self.n_bias = 0.0
def current_weights(self) -> tuple[float, np.ndarray]:
"""Recover exact sparse weights w_i (exact 0 whenever |z_i| <= l1_alpha)."""
w_bias = (
-self.z_bias / ((self.beta + math.sqrt(self.n_bias)) / self.alpha)
if abs(self.z_bias) > 1e-15
else 0.0
)
abs_z = np.abs(self.z)
active = abs_z > self.l1_alpha
denom = (self.beta + np.sqrt(self.n_sq)) / self.alpha + self.l2_alpha
w = np.zeros(self.n_features, dtype=np.float64)
w[active] = -(self.z[active] - np.sign(self.z[active]) * self.l1_alpha) / denom[active]
return float(w_bias), w
def stream_fit_prequential(self, X: np.ndarray, y: np.ndarray) -> dict[str, float]:
"""Single-pass streaming training with progressive prequential Log-Loss tracking."""
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
preq_losses: list[float] = []
r_sub = self.negative_subsample_rate
log_r = math.log(r_sub) if 0.0 < r_sub < 1.0 else 0.0
kept_rows = 0
for i in range(x_arr.shape[0]):
xi = x_arr[i]
yi = float(y_arr[i])
w_b, w_vec = self.current_weights()
eta = w_b + float(np.dot(xi, w_vec))
# Prior calibration offset when negatives are subsampled during training
eta_cal = eta + log_r
preq_losses.append(float(_binary_logloss_from_logits(np.array([eta_cal]), np.array([yi]))[0]))
if yi == 0.0 and r_sub < 1.0 and float(self.rng.uniform()) > r_sub:
continue
kept_rows += 1
p_sub = float(stable_sigmoid(eta))
g0 = p_sub - yi
sigma0 = (math.sqrt(self.n_bias + g0 * g0) - math.sqrt(self.n_bias)) / self.alpha
self.z_bias += g0 - sigma0 * w_b
self.n_bias += g0 * g0
nz = np.flatnonzero(xi != 0.0)
if nz.size > 0:
g = g0 * xi[nz]
n_old = self.n_sq[nz]
n_new = n_old + g * g
sigma = (np.sqrt(n_new) - np.sqrt(n_old)) / self.alpha
self.z[nz] += g - sigma * w_vec[nz]
self.n_sq[nz] = n_new
_, w_final = self.current_weights()
zero_frac = float(np.mean(w_final == 0.0))
return {
"prequential_log_loss": float(np.mean(preq_losses)),
"zero_weight_fraction": zero_frac,
"nonzero_weights": float(np.sum(w_final != 0.0)),
"kept_fraction": float(kept_rows / max(x_arr.shape[0], 1)),
}
def predict_proba(
self,
X: np.ndarray,
weights_override: np.ndarray | None = None,
) -> np.ndarray:
"""Predict calibrated probabilities applying exact negative-subsampling log-odds offset."""
w_b, w_vec = self.current_weights()
if weights_override is not None:
w_vec = np.asarray(weights_override, dtype=np.float64)
eta = w_b + np.asarray(X, dtype=np.float64) @ w_vec
if 0.0 < self.negative_subsample_rate < 1.0:
eta = eta + math.log(self.negative_subsample_rate)
return np.asarray(stable_sigmoid(eta), dtype=np.float64)
class AdditiveSplineGAM:
"""Interpretable glass-box Generalized Additive Model (GAM) via quantile spline basis + IRLS."""
def __init__(self, n_knots: int = 5, l2_alpha: float = 5.0) -> None:
self.n_knots = int(n_knots)
self.l2_alpha = float(l2_alpha)
self.knots_: list[np.ndarray] = []
self.logistic_: LogisticRegressionWorkbench | None = None
def _expand_basis(self, X: np.ndarray) -> np.ndarray:
x_arr = np.asarray(X, dtype=np.float64)
cols: list[np.ndarray] = []
for j in range(x_arr.shape[1]):
xj = x_arr[:, j]
cols.append(xj)
for k in self.knots_[j]:
cols.append(np.maximum(0.0, xj - float(k)))
return np.column_stack(cols)
def fit(self, X: np.ndarray, y: np.ndarray) -> AdditiveSplineGAM:
"""Fit additive spline logistic GAM cleanly on training fold knots."""
x_arr = np.asarray(X, dtype=np.float64)
qs = np.linspace(0.15, 0.85, self.n_knots)
self.knots_ = [np.quantile(x_arr[:, j], qs) for j in range(x_arr.shape[1])]
X_basis = self._expand_basis(x_arr)
cfg = LogisticConfig(solver="irls", l2_alpha=self.l2_alpha, standardize=True, max_iter=60)
self.logistic_ = LogisticRegressionWorkbench(cfg)
self.logistic_.fit(X_basis, y)
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Predict additive GAM probabilities."""
if self.logistic_ is None or self.logistic_.state_ is None:
raise RuntimeError("AdditiveSplineGAM must be fit before calling predict_proba.")
return self.logistic_.state_.predict_proba(self._expand_basis(X))
def compute_regression_metrics(
y_true: np.ndarray,
y_pred: np.ndarray,
n_predictors: int = 1,
quantile_tau: float = 0.5,
) -> dict[str, float]:
"""Compute rigorous regression metrics including MAPE/SMAPE zero-guards, R2/Adj-R2, WAPE, Pinball."""
yt = np.asarray(y_true, dtype=np.float64)
yp = np.asarray(y_pred, dtype=np.float64)
n = int(yt.size)
err = yp - yt
abs_err = np.abs(err)
mse = float(np.mean(err * err))
rmse = math.sqrt(mse)
mae = float(np.mean(abs_err))
nz_mask = np.abs(yt) > 1e-12
zero_count = int(np.sum(~nz_mask))
mape_nz = float(100.0 * np.mean(abs_err[nz_mask] / np.abs(yt[nz_mask]))) if np.any(nz_mask) else float("inf")
mape_raw = float("inf") if zero_count > 0 else mape_nz
denom_smape = 0.5 * (np.abs(yt) + np.abs(yp))
with np.errstate(divide="ignore", invalid="ignore"):
smape_vals = np.where(denom_smape > 1e-12, 100.0 * abs_err / denom_smape, 0.0)
smape = float(np.mean(smape_vals))
sum_abs_y = float(np.sum(np.abs(yt)))
wape = float(100.0 * np.sum(abs_err) / sum_abs_y) if sum_abs_y > 1e-12 else float("inf")
sum_y = float(np.sum(yt))
bias_pct = float(100.0 * np.sum(yp - yt) / sum_y) if abs(sum_y) > 1e-12 else 0.0
sst = float(np.sum((yt - np.mean(yt)) ** 2))
sse = float(np.sum(err * err))
r2 = 1.0 - sse / sst if sst > 1e-15 else 0.0
adj_r2 = (
1.0 - (1.0 - r2) * float(n - 1) / float(max(n - n_predictors - 1, 1))
if n > n_predictors + 1
else float("nan")
)
u = yt - yp
pinball = float(np.mean(np.where(u >= 0.0, quantile_tau * u, (quantile_tau - 1.0) * u)))
return {
"mse": mse,
"rmse": rmse,
"mae": mae,
"mape_raw": mape_raw,
"mape_nonzero": mape_nz,
"zero_target_count": float(zero_count),
"smape": smape,
"wape": wape,
"bias_pct": bias_pct,
"r2": float(r2),
"adj_r2": float(adj_r2),
"pinball_loss": pinball,
}
def compute_roc_auc(y_true: np.ndarray, y_score: np.ndarray) -> float:
"""Exact tie-aware Mann-Whitney U ROC-AUC in O(n log n)."""
yt = np.asarray(y_true, dtype=np.int64)
ys = np.asarray(y_score, dtype=np.float64)
n_pos = int(np.sum(yt == 1))
n_neg = int(np.sum(yt == 0))
if n_pos == 0 or n_neg == 0:
return 0.5
order = np.argsort(ys, kind="mergesort")
sorted_s = ys[order]
sorted_y = yt[order]
ranks = np.empty(ys.size, dtype=np.float64)
i = 0
while i < ys.size:
j = i + 1
while j < ys.size and sorted_s[j] == sorted_s[i]:
j += 1
avg_rank = 0.5 * (float(i + 1) + float(j))
ranks[i:j] = avg_rank
i = j
pos_rank_sum = float(np.sum(ranks[sorted_y == 1]))
u_stat = pos_rank_sum - 0.5 * float(n_pos * (n_pos + 1))
return float(u_stat / float(n_pos * n_neg))
def compute_pr_and_prg_auc(y_true: np.ndarray, y_score: np.ndarray) -> tuple[float, float]:
"""Compute exact stepwise Average Precision (PR-AUC) and Flach-Kull Precision-Recall-Gain AUC."""
yt = np.asarray(y_true, dtype=np.int64)
ys = np.asarray(y_score, dtype=np.float64)
n = int(yt.size)
n_pos = int(np.sum(yt == 1))
if n_pos == 0 or n_pos == n:
return float(n_pos / max(n, 1)), 0.0
pi_pos = float(n_pos) / float(n)
order = np.argsort(-ys, kind="mergesort")
s_sorted = ys[order]
y_sorted = yt[order]
# Collapse ties at distinct score thresholds
tp_cum = np.cumsum(y_sorted)
total_cum = np.arange(1, n + 1, dtype=np.float64)
distinct_idx = np.r_[np.flatnonzero(np.diff(s_sorted) != 0.0), n - 1]
tps = tp_cum[distinct_idx].astype(np.float64)
totals = total_cum[distinct_idx]
fps = totals - tps
fns = float(n_pos) - tps
recalls = tps / float(n_pos)
precisions = tps / np.maximum(totals, 1.0)
rec_prev = np.r_[0.0, recalls[:-1]]
pr_auc = float(np.sum((recalls - rec_prev) * precisions))
# Flach & Kull (2015) Precision-Recall-Gain (clipped to [0, 1] unit square)
ratio = pi_pos / max(1.0 - pi_pos, 1e-12)
with np.errstate(divide="ignore", invalid="ignore"):
prec_g = np.where(tps > 0.0, 1.0 - ratio * (fps / tps), 0.0)
rec_g = np.where(tps > 0.0, 1.0 - ratio * (fns / tps), 0.0)
prec_g = np.clip(prec_g, 0.0, 1.0)
rec_g = np.clip(rec_g, 0.0, 1.0)
# Append (0, 1) and (1, 0) gain endpoints and integrate monotonically sorted by rec_g
order_g = np.argsort(rec_g, kind="mergesort")
rg = np.r_[0.0, rec_g[order_g], 1.0]
pg = np.r_[1.0, prec_g[order_g], 0.0]
prg_auc = float(np.trapezoid(pg, rg) if hasattr(np, "trapezoid") else np.trapz(pg, rg))
return pr_auc, float(max(0.0, min(1.0, prg_auc)))
def compute_multiclass_mcc(y_true: np.ndarray, y_pred: np.ndarray, n_classes: int | None = None) -> float:
"""Compute Gorodkin (2004) K-category Matthews Correlation Coefficient R_K."""
yt = np.asarray(y_true, dtype=np.int64)
yp = np.asarray(y_pred, dtype=np.int64)
k = int(n_classes) if n_classes is not None else int(max(np.max(yt), np.max(yp)) + 1)
C = np.zeros((k, k), dtype=np.float64)
for t_i, p_i in zip(yt, yp):
C[t_i, p_i] += 1.0
n = float(np.sum(C))
t_k = np.sum(C, axis=1)
p_k = np.sum(C, axis=0)
c_diag = float(np.trace(C))
num = n * c_diag - float(np.dot(t_k, p_k))
den = math.sqrt(max(n * n - float(np.dot(p_k, p_k)), 0.0) * max(n * n - float(np.dot(t_k, t_k)), 0.0))
return float(num / den) if den > 1e-15 else 0.0
def compute_classification_metrics(
y_true: np.ndarray,
y_prob: np.ndarray,
threshold: float = 0.5,
n_brier_bins: int = 10,
) -> dict[str, float]:
"""Compute confusion matrix, ROC-AUC, stepwise PR-AUC, PRG-AUC, MCC, Log-Loss & Murphy Brier."""
yt = np.asarray(y_true, dtype=np.int64)
yp = np.clip(np.asarray(y_prob, dtype=np.float64), 1e-15, 1.0 - 1e-15)
y_hat = (yp >= float(threshold)).astype(np.int64)
tp = int(np.sum((yt == 1) & (y_hat == 1)))
fp = int(np.sum((yt == 0) & (y_hat == 1)))
fn = int(np.sum((yt == 1) & (y_hat == 0)))
tn = int(np.sum((yt == 0) & (y_hat == 0)))
n = max(tp + fp + fn + tn, 1)
accuracy = float(tp + tn) / float(n)
precision = float(tp) / float(tp + fp) if (tp + fp) > 0 else 0.0
recall = float(tp) / float(tp + fn) if (tp + fn) > 0 else 0.0
f1 = (2.0 * precision * recall / (precision + recall)) if (precision + recall) > 0.0 else 0.0
mcc_den = math.sqrt(float((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)))
mcc = float(tp * tn - fp * fn) / mcc_den if mcc_den > 0.0 else 0.0
roc_auc = compute_roc_auc(yt, yp)
pr_auc, prg_auc = compute_pr_and_prg_auc(yt, yp)
log_loss = float(-np.mean(yt * np.log(yp) + (1.0 - yt) * np.log(1.0 - yp)))
brier = float(np.mean((yp - yt) ** 2))
# Exact Murphy (1973) Brier decomposition over binned probabilities
edges = np.linspace(0.0, 1.0, n_brier_bins + 1)
bin_ids = np.clip(np.digitize(yp, edges[1:-1], right=False), 0, n_brier_bins - 1)
y_bar = float(np.mean(yt))
reliability = 0.0
resolution = 0.0
yp_binned = np.empty_like(yp)
for b in range(n_brier_bins):
mask = bin_ids == b
nb = int(np.sum(mask))
if nb == 0:
continue
p_b = float(np.mean(yp[mask]))
y_b = float(np.mean(yt[mask]))
yp_binned[mask] = p_b
reliability += (float(nb) / float(n)) * ((p_b - y_b) ** 2)
resolution += (float(nb) / float(n)) * ((y_b - y_bar) ** 2)
uncertainty = y_bar * (1.0 - y_bar)
brier_binned = float(np.mean((yp_binned - yt) ** 2))
return {
"tp": float(tp),
"fp": float(fp),
"fn": float(fn),
"tn": float(tn),
"prevalence": float(y_bar),
"accuracy": accuracy,
"precision": precision,
"recall": recall,
"f1": f1,
"mcc": mcc,
"roc_auc": roc_auc,
"pr_auc": pr_auc,
"prg_auc": prg_auc,
"log_loss": log_loss,
"brier_score": brier,
"brier_binned": brier_binned,
"brier_reliability": float(reliability),
"brier_resolution": float(resolution),
"brier_uncertainty": float(uncertainty),
}
"""Validation splitting strategies, Nested CV optimism audit, .632+ Bootstrap, and Lab 06 benchmarks."""
from __future__ import annotations
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from linear_validation_lab.linear_models import (
compare_linear_optimizers,
compute_regression_diagnostics,
fit_elasticnet_cd,
fit_huber_irls,
fit_lasso_cd,
fit_quantile_mm,
fit_ridge_svd,
simulate_double_descent_and_negative_ridge,
solve_ols_normal_eq,
solve_ols_qr,
solve_ols_svd,
)
from linear_validation_lab.logistic_and_metrics import (
AdditiveSplineGAM,
FTRLProximalClassifier,
LogisticConfig,
LogisticRegressionWorkbench,
SoftmaxMultinomialClassifier,
compute_classification_metrics,
compute_multiclass_mcc,
compute_regression_metrics,
quantize_q2_13,
stable_sigmoid,
)
@dataclass(frozen=True, slots=True)
class SplitFold:
"""Immutable train/validation fold index pair with purge and embargo accounting."""
fold_id: int
train_indices: np.ndarray
val_indices: np.ndarray
purged_count: int = 0
embargoed_count: int = 0
def __post_init__(self) -> None:
for attr in ("train_indices", "val_indices"):
arr = np.array(getattr(self, attr), dtype=np.int64, copy=True)
arr.setflags(write=False)
object.__setattr__(self, attr, arr)
def holdout_split(
n_samples: int,
test_ratio: float = 0.2,
stratify_y: np.ndarray | None = None,
seed: int = 42,
) -> tuple[np.ndarray, np.ndarray]:
"""Deterministic single Holdout split (with optional class stratification)."""
if not 0.0 < test_ratio < 1.0:
raise ValueError("test_ratio must lie strictly in (0, 1).")
rng = np.random.default_rng(seed)
if stratify_y is None:
perm = rng.permutation(n_samples)
n_test = max(1, round(n_samples * test_ratio))
return np.sort(perm[n_test:]), np.sort(perm[:n_test])
y_arr = np.asarray(stratify_y)
train_parts: list[np.ndarray] = []
test_parts: list[np.ndarray] = []
for cls_val in np.unique(y_arr):
cls_idx = np.flatnonzero(y_arr == cls_val)
rng.shuffle(cls_idx)
n_cls_test = max(1, round(len(cls_idx) * test_ratio)) if len(cls_idx) > 1 else 0
test_parts.append(cls_idx[:n_cls_test])
train_parts.append(cls_idx[n_cls_test:])
return np.sort(np.concatenate(train_parts)), np.sort(np.concatenate(test_parts))
def kfold_splits(
n_samples: int,
n_splits: int = 5,
shuffle: bool = True,
seed: int = 42,
) -> list[SplitFold]:
"""Standard K-Fold index generator."""
if n_splits < 2 or n_splits > n_samples:
raise ValueError("n_splits must satisfy 2 <= n_splits <= n_samples.")
indices = np.arange(n_samples, dtype=np.int64)
if shuffle:
np.random.default_rng(seed).shuffle(indices)
folds = np.array_split(indices, n_splits)
out: list[SplitFold] = []
for k in range(n_splits):
val_idx = np.sort(folds[k])
tr_idx = np.sort(np.concatenate([folds[j] for j in range(n_splits) if j != k]))
out.append(SplitFold(fold_id=k, train_indices=tr_idx, val_indices=val_idx))
return out
def stratified_kfold_splits(
y: np.ndarray,
n_splits: int = 5,
shuffle: bool = True,
seed: int = 42,
) -> list[SplitFold]:
"""Stratified K-Fold preserving minority class prevalence across all folds."""
y_arr = np.asarray(y)
n = int(y_arr.size)
if n_splits < 2 or n_splits > n:
raise ValueError("Invalid n_splits for dataset length.")
rng = np.random.default_rng(seed)
fold_buckets: list[list[int]] = [[] for _ in range(n_splits)]
for cls_val in np.unique(y_arr):
cls_idx = np.flatnonzero(y_arr == cls_val).copy()
if shuffle:
rng.shuffle(cls_idx)
for pos, idx in enumerate(cls_idx):
fold_buckets[pos % n_splits].append(int(idx))
all_idx = np.arange(n, dtype=np.int64)
out: list[SplitFold] = []
for k in range(n_splits):
val_idx = np.sort(np.array(fold_buckets[k], dtype=np.int64))
mask = np.ones(n, dtype=bool)
mask[val_idx] = False
tr_idx = all_idx[mask]
out.append(SplitFold(fold_id=k, train_indices=tr_idx, val_indices=val_idx))
return out
def group_kfold_splits(groups: np.ndarray | list[Any], n_splits: int = 5) -> list[SplitFold]:
"""Balanced GroupKFold enforcing zero entity overlap between train and validation folds."""
grp_arr = np.asarray(groups)
unique_grps, inv, counts = np.unique(grp_arr, return_inverse=True, return_counts=True)
if unique_grps.size < n_splits:
raise ValueError("Number of unique groups must be >= n_splits.")
order = np.argsort(-counts, kind="mergesort")
fold_sizes = np.zeros(n_splits, dtype=np.int64)
grp_to_fold = np.empty(unique_grps.size, dtype=np.int64)
for g_idx in order:
target_fold = int(np.argmin(fold_sizes))
grp_to_fold[g_idx] = target_fold
fold_sizes[target_fold] += int(counts[g_idx])
sample_folds = grp_to_fold[inv]
all_idx = np.arange(grp_arr.size, dtype=np.int64)
out: list[SplitFold] = []
for k in range(n_splits):
val_mask = sample_folds == k
out.append(
SplitFold(
fold_id=k,
train_indices=all_idx[~val_mask],
val_indices=all_idx[val_mask],
)
)
return out
def purged_timeseries_splits(
n_samples: int,
n_splits: int = 5,
label_horizon: int = 1,
embargo: int = 0,
mode: Literal["expanding", "rolling", "purged_kfold"] = "expanding",
max_train_size: int | None = None,
) -> list[SplitFold]:
"""Chronological expanding/rolling splits or blocked PurgedKFold with horizon purge + embargo."""
if n_splits < 2:
raise ValueError("n_splits must be >= 2.")
out: list[SplitFold] = []
if mode == "purged_kfold":
blocks = np.array_split(np.arange(n_samples, dtype=np.int64), n_splits)
pre_purge = max(label_horizon - 1, 0)
post_purge = max(embargo, 0) + pre_purge
for k in range(n_splits):
val_idx = blocks[k]
v_start = int(val_idx[0])
v_end = int(val_idx[-1]) + 1
purge_start = max(0, v_start - pre_purge)
post_purge_end = min(n_samples, v_end + pre_purge)
embargo_end = min(n_samples, v_end + post_purge)
pre_train = np.arange(0, purge_start, dtype=np.int64)
post_train = np.arange(embargo_end, n_samples, dtype=np.int64)
tr_idx = np.concatenate([pre_train, post_train])
purged_cnt = (v_start - purge_start) + (post_purge_end - v_end)
embargo_cnt = embargo_end - post_purge_end
out.append(
SplitFold(
fold_id=k,
train_indices=tr_idx,
val_indices=val_idx,
purged_count=purged_cnt,
embargoed_count=embargo_cnt,
)
)
return out
# Walk-forward expanding or rolling window
block_size = n_samples // (n_splits + 1)
if block_size < 2:
raise ValueError("n_samples too small for requested n_splits walk-forward blocks.")
for k in range(n_splits):
val_start = (k + 1) * block_size
val_end = n_samples if k == n_splits - 1 else (k + 2) * block_size
purge_gap = max(label_horizon - 1, 0) + max(embargo, 0)
train_end = max(0, val_start - purge_gap)
train_start = 0
if mode == "rolling":
win = max_train_size if max_train_size is not None else block_size
train_start = max(0, train_end - win)
tr_idx = np.arange(train_start, train_end, dtype=np.int64)
val_idx = np.arange(val_start, val_end, dtype=np.int64)
out.append(
SplitFold(
fold_id=k,
train_indices=tr_idx,
val_indices=val_idx,
purged_count=min(val_start, max(label_horizon - 1, 0)),
embargoed_count=min(max(val_start - max(label_horizon - 1, 0), 0), max(embargo, 0)),
)
)
return out
def nested_cv_ridge_audit(
X: np.ndarray,
y: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
lambdas: np.ndarray | list[float],
outer_splits: int = 5,
inner_splits: int = 5,
seed: int = 42,
) -> dict[str, Any]:
"""Quantify HPO winner's curse optimism: Flat CV vs Nested CV vs Untouched Holdout Test."""
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
lam_grid = [float(l) for l in lambdas]
n = x_arr.shape[0]
outer_folds = kfold_splits(n, n_splits=outer_splits, shuffle=True, seed=seed)
def _cv_mse_grid(x_sub: np.ndarray, y_sub: np.ndarray, folds: list[SplitFold]) -> np.ndarray:
fold_mses = np.empty((len(folds), len(lam_grid)), dtype=np.float64)
for fi, fold in enumerate(folds):
x_tr, y_tr = x_sub[fold.train_indices], y_sub[fold.train_indices]
x_va, y_va = x_sub[fold.val_indices], y_sub[fold.val_indices]
for li, lam in enumerate(lam_grid):
fit = fit_ridge_svd(x_tr, y_tr, l2_alpha=lam, fit_intercept=True, standardize=True)
fold_mses[fi, li] = float(np.mean((y_va - fit.predict(x_va)) ** 2))
return fold_mses
# 1. Flat CV across full (X, y)
flat_fold_mses = _cv_mse_grid(x_arr, y_arr, outer_folds)
flat_mean_mses = np.mean(flat_fold_mses, axis=0)
best_flat_idx = int(np.argmin(flat_mean_mses))
best_flat_lam = lam_grid[best_flat_idx]
flat_cv_mse = float(flat_mean_mses[best_flat_idx])
# Tibshirani & Tibshirani (2009) analytical selection bias estimate
tt_bias = float(np.mean(flat_fold_mses[:, best_flat_idx] - np.min(flat_fold_mses, axis=1)))
# 2. Nested CV outer unbiased evaluation of the HPO procedure
nested_outer_errs: list[float] = []
nested_sample_errs = np.empty(n, dtype=np.float64)
selected_outer_lambdas: list[float] = []
for k, out_fold in enumerate(outer_folds):
x_otr, y_otr = x_arr[out_fold.train_indices], y_arr[out_fold.train_indices]
x_ova, y_ova = x_arr[out_fold.val_indices], y_arr[out_fold.val_indices]
in_folds = kfold_splits(x_otr.shape[0], n_splits=inner_splits, shuffle=True, seed=seed + 100 + k)
inner_mses = _cv_mse_grid(x_otr, y_otr, in_folds)
best_in_lam = lam_grid[int(np.argmin(np.mean(inner_mses, axis=0)))]
selected_outer_lambdas.append(best_in_lam)
fit_out = fit_ridge_svd(x_otr, y_otr, l2_alpha=best_in_lam, fit_intercept=True, standardize=True)
sq_errs = (y_ova - fit_out.predict(x_ova)) ** 2
nested_sample_errs[out_fold.val_indices] = sq_errs
nested_outer_errs.append(float(np.mean(sq_errs)))
nested_cv_mse = float(np.mean(nested_outer_errs))
# Untouched external test set evaluation of flat winner
final_fit = fit_ridge_svd(x_arr, y_arr, l2_alpha=best_flat_lam, fit_intercept=True, standardize=True)
true_test_mse = float(np.mean((np.asarray(y_test, dtype=np.float64) - final_fit.predict(X_test)) ** 2))
# Bates et al. (2024) naive SE vs outer fold SE comparison
naive_se = float(np.std(nested_sample_errs, ddof=1) / math.sqrt(float(n)))
outer_fold_se = float(np.std(nested_outer_errs, ddof=1) / math.sqrt(float(outer_splits)))
return {
"best_flat_lambda": float(best_flat_lam),
"flat_cv_mse": flat_cv_mse,
"nested_cv_mse": nested_cv_mse,
"true_test_mse": true_test_mse,
"winners_curse_optimism": float(nested_cv_mse - flat_cv_mse),
"tt_bias_correction": tt_bias,
"tt_corrected_mse": float(flat_cv_mse + tt_bias),
"selected_outer_lambdas": selected_outer_lambdas,
"naive_sample_se": naive_se,
"outer_fold_se": outer_fold_se,
}
def bootstrap_632_plus(
X: np.ndarray,
y: np.ndarray,
fit_predict_fn: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray],
loss_type: Literal["zero_one", "mse"] = "zero_one",
n_bootstraps: int = 80,
seed: int = 42,
) -> dict[str, float]:
"""Compute Efron-Tibshirani .632 and .632+ bootstrap estimators handling zero-train-error overfitting."""
x_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64)
n = x_arr.shape[0]
rng = np.random.default_rng(seed)
def _point_losses(yt: np.ndarray, yp: np.ndarray) -> np.ndarray:
if loss_type == "zero_one":
return (yt != yp).astype(np.float64)
return (yt - yp) ** 2
# Apparent training error on full dataset
full_preds = np.asarray(fit_predict_fn(x_arr, y_arr, x_arr))
apparent_err = float(np.mean(_point_losses(y_arr, full_preds)))
# Leave-one-out bootstrap error Err^(1)
oob_sums = np.zeros(n, dtype=np.float64)
oob_counts = np.zeros(n, dtype=np.int64)
in_bag_fractions: list[float] = []
for _ in range(n_bootstraps):
boot_idx = rng.integers(0, n, size=n)
in_bag = np.zeros(n, dtype=bool)
in_bag[boot_idx] = True
in_bag_fractions.append(float(np.mean(in_bag)))
oob_idx = np.flatnonzero(~in_bag)
if oob_idx.size == 0:
continue
preds_oob = np.asarray(fit_predict_fn(x_arr[boot_idx], y_arr[boot_idx], x_arr[oob_idx]))
losses_oob = _point_losses(y_arr[oob_idx], preds_oob)
oob_sums[oob_idx] += losses_oob
oob_counts[oob_idx] += 1
valid = oob_counts > 0
oob_err = float(np.mean(oob_sums[valid] / oob_counts[valid])) if np.any(valid) else apparent_err
# No-information error rate gamma_0 over all n x n pairs
if loss_type == "zero_one":
classes = np.unique(np.concatenate([y_arr, full_preds]))
gamma_0 = 0.0
for c in classes:
p_c = float(np.mean(y_arr == c))
q_c = float(np.mean(full_preds == c))
gamma_0 += p_c * (1.0 - q_c)
else:
# 1/n^2 sum_{i,j} (y_i - f_hat(x_j))^2 == Var(y) + Var(f_hat) + (mean(y) - mean(f_hat))^2
gamma_0 = float(
np.var(y_arr) + np.var(full_preds) + (float(np.mean(y_arr)) - float(np.mean(full_preds))) ** 2
)
err_632 = 0.368 * apparent_err + 0.632 * oob_err
if oob_err > apparent_err and gamma_0 > apparent_err + 1e-12:
r_overfit = min(1.0, max(0.0, (min(oob_err, gamma_0) - apparent_err) / (gamma_0 - apparent_err)))
else:
r_overfit = 0.0
weight_w = 0.632 / (1.0 - 0.368 * r_overfit)
err_632_plus = (1.0 - weight_w) * apparent_err + weight_w * oob_err
return {
"apparent_err": apparent_err,
"oob_err": oob_err,
"no_info_gamma": float(gamma_0),
"overfit_rate_R": float(r_overfit),
"weight_w": float(weight_w),
"err_632": float(err_632),
"err_632_plus": float(err_632_plus),
"mean_unique_in_bag_fraction": float(np.mean(in_bag_fractions)),
}
def run_full_ch06_benchmarks(quick: bool = True, seed: int = 42) -> dict[str, Any]:
"""Execute end-to-end numerical, optimization, diagnostic, imbalance, and validation benchmarks."""
ss = np.random.SeedSequence(seed)
c_seeds = [int(s.generate_state(1, dtype=np.uint32)[0]) for s in ss.spawn(5)]
rng1 = np.random.default_rng(c_seeds[0])
rng2 = np.random.default_rng(c_seeds[1])
rng3 = np.random.default_rng(c_seeds[2])
rng4 = np.random.default_rng(c_seeds[3])
# ------------------------------------------------------------------
# [1] Numerical Conditioning, Regularization, Huber/Pinball & Diagnostics
# ------------------------------------------------------------------
delta_lauchli = 3.0e-8
X_lauchli = np.array([[1.0, 1.0], [delta_lauchli, 0.0], [0.0, delta_lauchli]], dtype=np.float64)
beta_lauchli = np.array([1.0, -1.0], dtype=np.float64)
y_lauchli = X_lauchli @ beta_lauchli
ols_neq = solve_ols_normal_eq(X_lauchli, y_lauchli, fit_intercept=False)
ols_qr = solve_ols_qr(X_lauchli, y_lauchli, fit_intercept=False)
ols_svd = solve_ols_svd(X_lauchli, y_lauchli, fit_intercept=False)
norm_b = float(np.linalg.norm(beta_lauchli))
lauchli_audit = {
"condition_number_x": ols_qr.condition_number_x,
"condition_number_xtx": ols_qr.condition_number_xtx,
"normal_eq_rel_err": float(np.linalg.norm(ols_neq.coef - beta_lauchli) / norm_b),
"qr_rel_err": float(np.linalg.norm(ols_qr.coef - beta_lauchli) / norm_b),
"svd_rel_err": float(np.linalg.norm(ols_svd.coef - beta_lauchli) / norm_b),
"normal_eq_singular_fallback": ols_neq.singular_fallback,
}
# Optimizer shootout on d=18 design (exposes Nelder-Mead curse of dimensionality)
X_opt = rng1.normal(0.0, 1.0, size=(320, 18))
w_opt_true = np.zeros(18, dtype=np.float64)
w_opt_true[:10] = [2.5, -1.8, 1.2, 0.0, 0.9, -0.7, 0.6, 0.5, -0.4, 0.3]
y_opt = 3.0 + X_opt @ w_opt_true + rng1.normal(0.0, 0.5, size=320)
opt_comp = compare_linear_optimizers(X_opt, y_opt, max_iter=250, seed=c_seeds[0])
# Collinear Marketing Channels (rho ~ 0.98) + Lasso vs ElasticNet grouping + Gap Safe
n_mkt = 300
base_mkt = rng1.normal(0.0, 1.0, size=n_mkt)
search_spend = base_mkt + rng1.normal(0.0, 0.14, size=n_mkt)
social_spend = base_mkt + rng1.normal(0.0, 0.14, size=n_mkt)
noise_cols = rng1.normal(0.0, 1.0, size=(n_mkt, 8))
X_mkt = np.column_stack([search_spend, social_spend, noise_cols])
y_mkt = 10.0 + 2.0 * search_spend + 2.0 * social_spend + rng1.normal(0.0, 0.6, size=n_mkt)
lasso_mkt = fit_lasso_cd(X_mkt, y_mkt, l1_alpha=0.35, use_gap_safe=True)
enet_mkt = fit_elasticnet_cd(X_mkt, y_mkt, l1_alpha=0.25, l2_alpha=0.45)
ridge_mkt = fit_ridge_svd(X_mkt, y_mkt, l2_alpha=15.0)
marketing_reg = {
"lasso_search_social": [float(lasso_mkt.coef[0]), float(lasso_mkt.coef[1])],
"lasso_pair_gap": float(abs(lasso_mkt.coef[0] - lasso_mkt.coef[1])),
"lasso_screened_cols": lasso_mkt.screened_count,
"lasso_duality_gap": lasso_mkt.duality_gap,
"elasticnet_search_social": [float(enet_mkt.coef[0]), float(enet_mkt.coef[1])],
"elasticnet_pair_gap": float(abs(enet_mkt.coef[0] - enet_mkt.coef[1])),
"ridge_df": ridge_mkt.effective_df,
}
# Diagnostics (VIF, BP heteroscedasticity, HC3 vs OLS SE, Leverage & Cook's D) + Huber/Quantile + MAPE trap
n_diag = 220
x1 = rng1.normal(0.0, 1.0, size=n_diag)
x2 = 0.95 * x1 + rng1.normal(0.0, 0.25, size=n_diag)
x3 = rng1.normal(0.0, 1.0, size=n_diag)
X_diag = np.column_stack([x1, x2, x3])
# Monotonically fan-shaped heteroscedastic errors in x1 + 2 extreme leverage outliers
hetero_sd = 0.25 + 1.8 * np.maximum(0.0, x1 + 1.5)
y_diag = 2.0 + 1.5 * x1 + 1.5 * x2 - 1.0 * x3 + rng1.normal(0.0, 1.0, size=n_diag) * hetero_sd
X_diag[0] = [5.5, 5.2, 4.0]
y_diag[0] = 55.0
X_diag[1] = [-5.2, -4.9, -3.5]
y_diag[1] = -48.0
diag = compute_regression_diagnostics(X_diag, y_diag)
ols_clean = solve_ols_qr(X_diag[2:], y_diag[2:])
ols_poison = solve_ols_qr(X_diag, y_diag)
huber_fit = fit_huber_irls(X_diag, y_diag, delta=1.345)
q90_fit = fit_quantile_mm(X_diag, y_diag, tau=0.90)
# Zero-demand MAPE/SMAPE asymmetry demonstration
y_zero_dem = np.array([0.0, 0.0, 1.0, 10.0, 20.0, 20.0])
y_zero_pred = np.array([0.1, 50.0, 6.0, 12.0, 10.0, 30.0])
reg_trap = compute_regression_metrics(y_zero_dem, y_zero_pred, n_predictors=1, quantile_tau=0.90)
dd_res = simulate_double_descent_and_negative_ridge(seed=c_seeds[0], quick=quick)
# ------------------------------------------------------------------
# [2] Logistic IRLS, Separation/Firth, Softmax LSE, Imbalance & FTRL Q2.13
# ------------------------------------------------------------------
# Quasi-complete separation in rare credit delinquency bucket
n_sep = 240
z_score = rng2.normal(0.0, 1.0, size=n_sep)
rare_delinq = np.zeros(n_sep, dtype=np.float64)
rare_delinq[:16] = 1.0
logits_sep = -1.2 + 1.1 * z_score + 6.0 * rare_delinq
y_sep = (rng2.uniform(size=n_sep) < np.asarray(stable_sigmoid(logits_sep))).astype(np.float64)
y_sep[:16] = 1.0 # Force 100% default inside rare bucket -> quasi-complete separation!
X_sep = np.column_stack([z_score, rare_delinq])
mle_sep = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=0.0, max_iter=30)).fit(X_sep, y_sep)
l2_sep = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=1.0, max_iter=30)).fit(X_sep, y_sep)
firth_sep = LogisticRegressionWorkbench(LogisticConfig(solver="firth", l2_alpha=0.0, max_iter=35)).fit(X_sep, y_sep)
# Severe ~1.5% Fraud / Default imbalance dataset (with nonlinear risk U-curve for GAM comparison)
n_imb = 3000 if quick else 5000
X_imb_tr = rng2.normal(0.0, 1.0, size=(n_imb, 5))
X_imb_te = rng2.normal(0.0, 1.0, size=(n_imb, 5))
eta_tr = -6.1 + 2.2 * X_imb_tr[:, 0] + 1.1 * (X_imb_tr[:, 1] ** 2 - 1.0) - 1.4 * X_imb_tr[:, 2]
eta_te = -6.1 + 2.2 * X_imb_te[:, 0] + 1.1 * (X_imb_te[:, 1] ** 2 - 1.0) - 1.4 * X_imb_te[:, 2]
y_imb_tr = (rng2.uniform(size=n_imb) < np.asarray(stable_sigmoid(eta_tr))).astype(np.int64)
y_imb_te = (rng2.uniform(size=n_imb) < np.asarray(stable_sigmoid(eta_te))).astype(np.int64)
irls_imb = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=1.0, max_iter=40)).fit(
X_imb_tr, y_imb_tr
)
lbfgs_imb = LogisticRegressionWorkbench(LogisticConfig(solver="lbfgs", l2_alpha=1.0, max_iter=100)).fit(
X_imb_tr, y_imb_tr
)
gam_imb = AdditiveSplineGAM(n_knots=5, l2_alpha=4.0).fit(X_imb_tr, y_imb_tr)
p_irls = irls_imb.predict_proba(X_imb_te)
p_gam = gam_imb.predict_proba(X_imb_te)
# Show precision collapse at top 10% score alert threshold vs tuned threshold
alert_thresh = float(np.quantile(p_irls, 0.90))
m_imb_alert = compute_classification_metrics(y_imb_te, p_irls, threshold=alert_thresh)
m_imb_05 = compute_classification_metrics(y_imb_te, p_irls, threshold=0.20)
m_gam = compute_classification_metrics(y_imb_te, p_gam, threshold=0.20)
# 3-class Softmax LSE test
X_sm_tr = rng2.normal(0.0, 1.0, size=(360, 4))
W_sm = np.array([[1.8, -1.5, 0.1], [-1.2, 1.6, 0.2], [0.5, 0.4, -1.7], [0.2, -0.3, 0.9]])
logits_sm = X_sm_tr @ W_sm
y_sm_tr = np.argmax(logits_sm + rng2.gumbel(0.0, 0.5, size=logits_sm.shape), axis=1)
sm_clf = SoftmaxMultinomialClassifier(l2_alpha=1.0).fit(X_sm_tr, y_sm_tr)
sm_probs = sm_clf.predict_proba(X_sm_tr)
sm_pred = np.argmax(sm_probs, axis=1)
sm_mcc = compute_multiclass_mcc(y_sm_tr, sm_pred, n_classes=3)
# FTRL-Proximal sparse streaming CTR + Q2.13 quantization (frequent 15 signals + 235 sparse tail IDs)
n_ftrl, d_ftrl = (3200 if quick else 5000), 250
X_ctr = np.zeros((n_ftrl, d_ftrl), dtype=np.float64)
X_ctr[:, :15] = (rng3.uniform(size=(n_ftrl, 15)) < 0.22).astype(np.float64)
for row_i in range(n_ftrl):
tail_cols = rng3.choice(np.arange(15, d_ftrl), size=6, replace=False)
X_ctr[row_i, tail_cols] = 1.0
w_ctr_true = np.zeros(d_ftrl, dtype=np.float64)
w_ctr_true[:15] = rng3.normal(0.0, 1.25, size=15)
y_ctr = (rng3.uniform(size=n_ftrl) < np.asarray(stable_sigmoid(-2.35 + X_ctr @ w_ctr_true))).astype(np.float64)
split_ctr = int(0.8 * n_ftrl)
ftrl = FTRLProximalClassifier(
n_features=d_ftrl, alpha=0.35, beta=1.0, l1_alpha=2.0, l2_alpha=1.0, negative_subsample_rate=0.25, seed=c_seeds[2]
)
ftrl_stream = ftrl.stream_fit_prequential(X_ctr[:split_ctr], y_ctr[:split_ctr])
_, w_ftrl = ftrl.current_weights()
w_q213 = quantize_q2_13(w_ftrl, seed=c_seeds[2], stochastic_rounding=True)
p_f64 = ftrl.predict_proba(X_ctr[split_ctr:])
p_q16 = ftrl.predict_proba(X_ctr[split_ctr:], weights_override=w_q213)
m_f64 = compute_classification_metrics(y_ctr[split_ctr:], p_f64, threshold=0.20)
m_q16 = compute_classification_metrics(y_ctr[split_ctr:], p_q16, threshold=0.20)
# ------------------------------------------------------------------
# [3] Validation Splitting Rigor: Purged TS, Nested CV, .632+ Bootstrap
# ------------------------------------------------------------------
# Overlapping 10-day forward return horizon on pure random walk shocks (zero true OOS alpha!)
n_ts = 360
shocks = rng4.normal(0.0, 1.0, size=n_ts + 25)
# Target y_t = sum_{s=t+1}^{t+10} shocks[s] (overlapping 10-step horizon)
y_ts_full = np.array([float(np.sum(shocks[t + 1 : t + 11])) for t in range(n_ts)], dtype=np.float64)
# Smooth low-frequency Fourier basis (6 predictors): interpolates overlapping noise in K-Fold
t_norm = np.linspace(0.0, 1.0, n_ts)
fourier_cols = [np.sin(2.0 * math.pi * k * t_norm) for k in range(1, 5)] + [
np.cos(2.0 * math.pi * k * t_norm) for k in range(1, 5)
]
X_ts = np.column_stack(fourier_cols)
# Compare naive random K-Fold vs Purged Expanding TS split on overlapping returns
naive_folds = kfold_splits(n_ts, n_splits=5, shuffle=True, seed=c_seeds[3])
purged_folds = purged_timeseries_splits(n_ts, n_splits=5, label_horizon=10, embargo=4, mode="expanding")
def _eval_r2(folds: list[SplitFold]) -> float:
r2s: list[float] = []
for f in folds:
fit = fit_ridge_svd(X_ts[f.train_indices], y_ts_full[f.train_indices], l2_alpha=2.0)
preds = fit.predict(X_ts[f.val_indices])
sst = float(np.sum((y_ts_full[f.val_indices] - np.mean(y_ts_full[f.val_indices])) ** 2))
sse = float(np.sum((y_ts_full[f.val_indices] - preds) ** 2))
r2s.append(1.0 - sse / max(sst, 1e-12))
return float(np.mean(r2s))
# Nested CV HPO winner's curse audit (small-n noisy high-dim Ridge sweep)
n_hpo, d_hpo = 85, 65
w_hpo_true = np.zeros(d_hpo, dtype=np.float64)
w_hpo_true[:5] = [0.7, -0.6, 0.5, -0.4, 0.3]
X_hpo_dev = rng4.normal(0.0, 1.0, size=(n_hpo, d_hpo))
y_hpo_dev = X_hpo_dev @ w_hpo_true + rng4.normal(0.0, 2.6, size=n_hpo)
X_hpo_te = rng4.normal(0.0, 1.0, size=(600, d_hpo))
y_hpo_te = X_hpo_te @ w_hpo_true + rng4.normal(0.0, 2.6, size=600)
lam_grid = np.geomspace(0.05, 500.0, 22)
nested_audit = nested_cv_ridge_audit(
X_hpo_dev, y_hpo_dev, X_hpo_te, y_hpo_te, lambdas=lam_grid, outer_splits=5, inner_splits=4, seed=c_seeds[3]
)
# Bootstrap .632 vs .632+ on interpolating p > n pure-noise balanced classifier (apparent_err == 0.0!)
n_boot_s, d_boot_s = 70, 130
X_noise_b = rng4.normal(0.0, 1.0, size=(n_boot_s, d_boot_s))
y_noise_b = np.array([0, 1] * (n_boot_s // 2), dtype=np.int64)
rng4.shuffle(y_noise_b)
def _interpolating_min_norm_clf(x_tr: np.ndarray, y_tr: np.ndarray, x_ev: np.ndarray) -> np.ndarray:
y_signed = 2.0 * y_tr.astype(np.float64) - 1.0
fit = solve_ols_svd(x_tr, y_signed, fit_intercept=False)
return (fit.predict(x_ev) >= 0.0).astype(np.int64)
boot_res = bootstrap_632_plus(
X_noise_b, y_noise_b, _interpolating_min_norm_clf, loss_type="zero_one", n_bootstraps=60 if quick else 150, seed=c_seeds[3]
)
return {
"linear_and_diagnostics": {
"lauchli": lauchli_audit,
"optimizer_shootout": opt_comp,
"marketing_regularization": marketing_reg,
"diagnostics": {
"max_vif": float(np.max(diag.vif)),
"vif_list": [float(v) for v in diag.vif],
"breusch_pagan_lm": diag.breusch_pagan_lm,
"breusch_pagan_pvalue": diag.breusch_pagan_pvalue,
"max_hc3_to_ols_se_ratio": float(np.max(diag.se_hc3 / np.maximum(diag.se_ols, 1e-12))),
"max_leverage": float(np.max(diag.leverage)),
"max_cooks_d": float(np.max(diag.cooks_distance)),
"influential_count": len(diag.influential_indices),
"ols_clean_coef_0": float(ols_clean.coef[0]),
"ols_poison_coef_0": float(ols_poison.coef[0]),
"huber_poison_coef_0": float(huber_fit.coef[0]),
"q90_coef_0": float(q90_fit.coef[0]),
},
"zero_demand_metric_trap": reg_trap,
"double_descent_and_negative_ridge": dd_res,
},
"logistic_and_imbalance": {
"separation": {
"mle_l2_norm": mle_sep.param_l2_norm,
"mle_min_hessian_eig": mle_sep.hessian_min_eig,
"l2_norm": l2_sep.param_l2_norm,
"firth_norm": firth_sep.param_l2_norm,
"firth_converged": firth_sep.converged,
},
"imbalance_1_5pct": {
"prevalence": m_imb_alert["prevalence"],
"irls_at_top10_alert": m_imb_alert,
"irls_at_t020": m_imb_05,
"lbfgs_n_iter": lbfgs_imb.n_iter,
"gam_at_t020": m_gam,
},
"softmax_multiclass": {
"n_iter": sm_clf.n_iter_,
"accuracy": float(np.mean(sm_pred == y_sm_tr)),
"gorodkin_mcc": sm_mcc,
},
"ftrl_streaming_ctr": {
"stream_stats": ftrl_stream,
"float64_metrics": m_f64,
"q2_13_metrics": m_q16,
"q2_13_logloss_delta": float(abs(m_q16["log_loss"] - m_f64["log_loss"])),
"ram_savings_vs_f64_pct": 75.0,
},
},
"validation_rigor": {
"overlapping_ts": {
"naive_random_kfold_r2": _eval_r2(naive_folds),
"purged_expanding_ts_r2": _eval_r2(purged_folds),
"total_purged_rows": sum(f.purged_count for f in purged_folds),
"total_embargoed_rows": sum(f.embargoed_count for f in purged_folds),
},
"nested_cv_audit": nested_audit,
"bootstrap_632_plus_interpolating_noise": boot_res,
},
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 06 (linear_validation_lab)."""
from __future__ import annotations
import argparse
import json
import math
import sys
from pathlib import Path
from typing import Any
import numpy as np
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import linear_validation_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 linear_validation_lab.validation_splitters import run_full_ch06_benchmarks
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy scalars/arrays and non-finite floats into strict JSON-safe primitives."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar(val: float, floor: float = 0.001) -> float:
"""Guarantee strictly positive finite bar values for dashboard width rendering."""
if not math.isfinite(val):
return floor
return float(max(floor, abs(val)))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Linear, Logistic & Validation Workbench."""
parser = argparse.ArgumentParser(
description="Run Lab 06: Linear Solvers, Regularization, Logistic IRLS/FTRL & Validation Rigor."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true", help="Run fast CI/demo sample budgets.")
parser.add_argument(
"--output",
"--json-out",
dest="output",
type=str,
default=None,
help="Output JSON path (e.g., artifacts/ch06_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
lin = bench["linear_and_diagnostics"]
logi = bench["logistic_and_imbalance"]
val = bench["validation_rigor"]
lau = lin["lauchli"]
opt = lin["optimizer_shootout"]
mkt = lin["marketing_regularization"]
diag = lin["diagnostics"]
dd = lin["double_descent_and_negative_ridge"]
ztrap = lin["zero_demand_metric_trap"]
sep = logi["separation"]
imb_top = logi["imbalance_1_5pct"]["irls_at_top10_alert"]
imb_20 = logi["imbalance_1_5pct"]["irls_at_t020"]
gam_20 = logi["imbalance_1_5pct"]["gam_at_t020"]
sm = logi["softmax_multiclass"]
ftrl = logi["ftrl_streaming_ctr"]
ots = val["overlapping_ts"]
ncv = val["nested_cv_audit"]
boot = val["bootstrap_632_plus_interpolating_noise"]
kpis = [
{
"id": "kpi_qr_vs_normal_eq_error",
"label": "Lauchli Conditioning (Normal Eq vs QR)",
"value": f"{lau['normal_eq_rel_err']:.2e} vs {lau['qr_rel_err']:.2e}",
"unit": "Rel Err",
"status": "critical",
"detail": (
f"kappa(X)={lau['condition_number_x']:.2e} squares to kappa(X^T X)={lau['condition_number_xtx']:.2e}; "
f"SVD err={lau['svd_rel_err']:.2e}."
),
},
{
"id": "kpi_elasticnet_grouping_and_pinball",
"label": "Marketing ElasticNet Spread vs Lasso",
"value": f"{mkt['elasticnet_pair_gap']:.3f} vs {mkt['lasso_pair_gap']:.3f}",
"unit": "|w1 - w2|",
"status": "ok",
"detail": (
f"Gap-Safe screened {mkt['lasso_screened_cols']} zero cols (gap={mkt['lasso_duality_gap']:.1e}); "
f"Huber slope={diag['huber_poison_coef_0']:.2f} vs OLS poisoned={diag['ols_poison_coef_0']:.2f}."
),
},
{
"id": "kpi_separation_firth_vs_mle",
"label": "Separation Blow-Up (Unpenalized vs Firth)",
"value": f"{sep['mle_l2_norm']:.1f} -> {sep['firth_norm']:.2f}",
"unit": "||beta||_2",
"status": "warn",
"detail": (
f"Quasi-complete separation pushes MLE ||beta||->inf (min eig={sep['mle_min_hessian_eig']:.2e}); "
f"Firth & L2 ({sep['l2_norm']:.2f}) stay finite."
),
},
{
"id": "kpi_imbalance_roc_vs_pr_mcc",
"label": "Imbalanced Fraud (1.5%): ROC vs PR / MCC",
"value": f"ROC {imb_top['roc_auc']:.3f} | PR {imb_top['pr_auc']:.3f}",
"unit": f"Prec {imb_top['precision']*100:.1f}%",
"status": "warn",
"detail": (
f"Top-10% alert yields Precision={imb_top['precision']*100:.1f}% & MCC={imb_top['mcc']:.3f}; "
f"GAM PR-AUC={gam_20['pr_auc']:.3f} vs IRLS={imb_20['pr_auc']:.3f}."
),
},
{
"id": "kpi_ftrl_sparsity_and_q213",
"label": "Streaming FTRL Sparsity & Q2.13 RAM Cut",
"value": f"{ftrl['stream_stats']['zero_weight_fraction']*100:.1f}% Zero | -75% RAM",
"unit": "Q2.13",
"status": "ok",
"detail": (
f"Exact L1 zeros={ftrl['stream_stats']['zero_weight_fraction']*100:.1f}%; "
f"Q2.13 Log-Loss delta={ftrl['q2_13_logloss_delta']:.5f} vs float64."
),
},
{
"id": "kpi_nested_cv_and_632plus_bias",
"label": "Nested CV & .632+ Overfit Rescue",
"value": f"Opt +{ncv['winners_curse_optimism']:.3f} | .632+ {boot['err_632_plus']:.3f}",
"unit": "Err Audit",
"status": "ok",
"detail": (
f"Flat CV={ncv['flat_cv_mse']:.3f} vs Nested={ncv['nested_cv_mse']:.3f} (Test={ncv['true_test_mse']:.3f}); "
f".632={boot['err_632']:.3f} fooled by err_train=0 while .632+ w={boot['weight_w']:.2f}."
),
},
]
bars = [
{
"id": "bar_solver_stability_and_cd",
"title": "Optimizer Relative Param Error vs QR Exact Baseline (OLS d=18)",
"metric_label": "Rel Err",
"items": [
{"label": "lbfgs_quasi_newton", "value": _pos_bar(opt["lbfgs"]["param_rel_err"], 1e-6), "display": f"{opt['lbfgs']['param_rel_err']:.2e} ({int(opt['lbfgs']['steps'])}st)", "css_class": "is-fast"},
{"label": "batch_gd", "value": _pos_bar(opt["bgd"]["param_rel_err"], 1e-6), "display": f"{opt['bgd']['param_rel_err']:.2e} ({int(opt['bgd']['steps'])}st)", "css_class": "is-fast"},
{"label": "minibatch_sgd", "value": _pos_bar(opt["minibatch"]["param_rel_err"], 1e-6), "display": f"{opt['minibatch']['param_rel_err']:.4f}", "css_class": "is-mid"},
{"label": "nelder_mead_1200", "value": _pos_bar(opt["nelder_mead"]["param_rel_err"], 1e-6), "display": f"{opt['nelder_mead']['param_rel_err']:.4f} (1200ev)", "css_class": "is-slow"},
],
},
{
"id": "bar_imbalance_metrics_reality",
"title": "1.5% Rare-Event Classification: ROC-AUC Illusion vs PR-AUC, MCC & Precision",
"metric_label": "Metric Value",
"items": [
{"label": "roc_auc_masked", "value": _pos_bar(imb_top["roc_auc"]), "display": f"{imb_top['roc_auc']:.3f}", "css_class": "is-slow"},
{"label": "pr_auc_stepwise", "value": _pos_bar(imb_top["pr_auc"]), "display": f"{imb_top['pr_auc']:.3f}", "css_class": "is-fast"},
{"label": "mcc_top10_alert", "value": _pos_bar(imb_top["mcc"]), "display": f"{imb_top['mcc']:.3f}", "css_class": "is-mid"},
{"label": "precision_top10_alert", "value": _pos_bar(imb_top["precision"]), "display": f"{imb_top['precision']*100:.1f}%", "css_class": "is-mid"},
],
},
{
"id": "bar_ftrl_and_gam_performance",
"title": "Log-Loss & PR-AUC: Linear IRLS vs Spline GAM vs Streaming FTRL Q2.13",
"metric_label": "Score",
"items": [
{"label": "gam_spline_pr_auc", "value": _pos_bar(gam_20["pr_auc"]), "display": f"PR {gam_20['pr_auc']:.3f}", "css_class": "is-fast"},
{"label": "irls_linear_pr_auc", "value": _pos_bar(imb_20["pr_auc"]), "display": f"PR {imb_20['pr_auc']:.3f}", "css_class": "is-mid"},
{"label": "ftrl_f64_roc_auc", "value": _pos_bar(ftrl["float64_metrics"]["roc_auc"]), "display": f"AUC {ftrl['float64_metrics']['roc_auc']:.3f}", "css_class": "is-fast"},
{"label": "ftrl_q213_roc_auc", "value": _pos_bar(ftrl["q2_13_metrics"]["roc_auc"]), "display": f"AUC {ftrl['q2_13_metrics']['roc_auc']:.3f}", "css_class": "is-fast"},
],
},
{
"id": "bar_validation_optimism_audit",
"title": "Validation Rigor: Flat vs Nested MSE & .632 vs .632+ Overfit Error",
"metric_label": "Error",
"items": [
{"label": "flat_hpo_cv_mse", "value": _pos_bar(ncv["flat_cv_mse"]), "display": f"{ncv['flat_cv_mse']:.3f} (opt)", "css_class": "is-slow"},
{"label": "nested_cv_mse", "value": _pos_bar(ncv["nested_cv_mse"]), "display": f"{ncv['nested_cv_mse']:.3f} (honest)", "css_class": "is-fast"},
{"label": "boot_632_fooled", "value": _pos_bar(boot["err_632"]), "display": f"{boot['err_632']:.3f} (err0)", "css_class": "is-slow"},
{"label": "boot_632_plus_rescued", "value": _pos_bar(boot["err_632_plus"]), "display": f"{boot['err_632_plus']:.3f} (w={boot['weight_w']:.2f})", "css_class": "is-fast"},
],
},
]
tables = [
{
"id": "table_linear_solvers_and_regularization",
"title": "Linear Solvers, Conditioning, Regularization & Zero-Demand Metrics",
"columns": ["experiment", "method", "primary_metric", "secondary_metric", "verdict"],
"rows": [
["lauchli_kappa_4.7e7", "Normal Equations", f"rel_err={lau['normal_eq_rel_err']:.3e}", f"kappa^2={lau['condition_number_xtx']:.2e}", "PRECISION_LOSS"],
["lauchli_kappa_4.7e7", "Householder QR", f"rel_err={lau['qr_rel_err']:.3e}", f"kappa={lau['condition_number_x']:.2e}", "STABLE_EXACT"],
["lauchli_kappa_4.7e7", "SVD Pseudoinverse", f"rel_err={lau['svd_rel_err']:.3e}", f"kappa={lau['condition_number_x']:.2e}", "RANK_SAFE"],
["collinear_marketing", "Lasso (Gap Safe)", f"pair_gap={mkt['lasso_pair_gap']:.3f}", f"screened={mkt['lasso_screened_cols']}/10", "DROPS_TWIN"],
["collinear_marketing", "ElasticNet", f"pair_gap={mkt['elasticnet_pair_gap']:.3f}", f"w=({mkt['elasticnet_search_social'][0]:.2f},{mkt['elasticnet_search_social'][1]:.2f})", "GROUP_STABLE"],
["spiked_cov_p_gt_n", "Kobak Negative Ridge", f"lam*={dd['best_spiked_lambda']:.1f}", f"mse={dd['best_spiked_mse']:.3f}", "NEGATIVE_OPT"],
["zero_demand_trap", "MAPE vs SMAPE vs WAPE", f"mape_nz={ztrap['mape_nonzero']:.1f}%", f"smape={ztrap['smape']:.1f}% | wape={ztrap['wape']:.1f}%", "AVOID_MAPE"],
],
},
{
"id": "table_diagnostics_and_cooks_audit",
"title": "OLS Model Diagnostics: VIF, Heteroscedasticity (BP & HC3), Leverage & Outliers",
"columns": ["diagnostic", "observed_value", "reference_or_baseline", "impact_on_inference", "action"],
"rows": [
["max_vif_collinear", round(diag["max_vif"], 3), "< 5.0 green (<10 ceiling)", "inflates Var(beta_j)", "MERGE_OR_RIDGE"],
["breusch_pagan_lm", f"LM={diag['breusch_pagan_lm']:.2f}", f"p={diag['breusch_pagan_pvalue']:.2e}", "OLS SEs invalid", "USE_HC3_SANDWICH"],
["hc3_vs_ols_se_ratio", f"{diag['max_hc3_to_ols_se_ratio']:.2f}x", "1.00x homoscedastic", "guards high-leverage variance", "HC3_DEFAULT"],
["cooks_d_and_huber", f"D_max={diag['max_cooks_d']:.2f} | h_max={diag['max_leverage']:.3f}", f"influential={diag['influential_count']}", f"OLS={diag['ols_poison_coef_0']:.2f} vs Huber={diag['huber_poison_coef_0']:.2f}", "HUBER_OR_QUARANTINE"],
],
},
{
"id": "table_logistic_firth_ftrl_and_metrics",
"title": "Logistic IRLS, Separation, Softmax LSE, Imbalance Metrics & Streaming FTRL",
"columns": ["task", "model_or_regime", "metric_1", "metric_2", "status"],
"rows": [
["quasi_separation", "Unpenalized IRLS", f"||beta||={sep['mle_l2_norm']:.2f}", f"H_min_eig={sep['mle_min_hessian_eig']:.2e}", "DIVERGES"],
["quasi_separation", "Firth / L2 Penalized", f"||beta||_F={sep['firth_norm']:.2f}", f"||beta||_L2={sep['l2_norm']:.2f}", "FINITE_SAFE"],
["fraud_1.5pct_alert", "Logistic IRLS (top 10%)", f"ROC={imb_top['roc_auc']:.3f} | PR={imb_top['pr_auc']:.3f}", f"Prec={imb_top['precision']*100:.1f}% | MCC={imb_top['mcc']:.3f}", "PR_MCC_REQUIRED"],
["fraud_1.5pct_nl", "Additive Spline GAM", f"PR={gam_20['pr_auc']:.3f} | MCC={gam_20['mcc']:.3f}", f"Brier={gam_20['brier_score']:.4f}", "GLASSBOX_GAIN"],
["softmax_3class", "Multinomial LSE", f"acc={sm['accuracy']*100:.1f}%", f"Gorodkin_MCC={sm['gorodkin_mcc']:.3f}", "IDENTIFIABLE"],
["streaming_ctr", "FTRL-Proximal Q2.13", f"zeros={ftrl['stream_stats']['zero_weight_fraction']*100:.1f}%", f"delta_LL={ftrl['q2_13_logloss_delta']:.5f} (-75% RAM)", "PROD_DEPLOY"],
],
},
{
"id": "table_validation_split_rigor",
"title": "Validation Splitting Rigor: Random Leakage vs Purged TS, Nested CV & .632+",
"columns": ["validation_regime", "naive_or_biased", "rigorous_estimator", "bias_or_gap", "verdict"],
"rows": [
["overlapping_10d_ts", f"Random K-Fold R2={ots['naive_random_kfold_r2']:+.3f}", f"Purged TS R2={ots['purged_expanding_ts_r2']:+.3f}", f"purged={ots['total_purged_rows']} | emb={ots['total_embargoed_rows']}", "LEAK_ELIMINATED"],
["nested_cv_hpo", f"Flat CV MSE={ncv['flat_cv_mse']:.3f}", f"Nested CV MSE={ncv['nested_cv_mse']:.3f}", f"optimism=+{ncv['winners_curse_optimism']:.3f} (Test={ncv['true_test_mse']:.3f})", "WINNERS_CURSE"],
["bates_2024_ci_se", f"Naive sample SE={ncv['naive_sample_se']:.3f}", f"Outer fold SE={ncv['outer_fold_se']:.3f}", f"TT_bias=+{ncv['tt_bias_correction']:.3f}", "CORR_ADJUSTED"],
["boot_p_gt_n_noise", f".632 Err={boot['err_632']:.3f} (app={boot['apparent_err']:.3f})", f".632+ Err={boot['err_632_plus']:.3f}", f"R={boot['overfit_rate_R']:.3f} | w={boot['weight_w']:.3f}", "OVERFIT_RESCUED"],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
"""Run CLI demo, print 4 summary blocks, and optionally save workbench JSON."""
args = parse_args(argv)
bench = run_full_ch06_benchmarks(quick=args.quick, seed=args.seed)
panels = _build_workbench_panels(bench)
lin = bench["linear_and_diagnostics"]
logi = bench["logistic_and_imbalance"]
val = bench["validation_rigor"]
print("[1] Numerical Conditioning, Regularization & OLS Diagnostics")
print(
f" Lauchli (kappa={lin['lauchli']['condition_number_x']:.2e}): "
f"NormalEq rel_err={lin['lauchli']['normal_eq_rel_err']:.2e} vs "
f"QR={lin['lauchli']['qr_rel_err']:.2e} vs SVD={lin['lauchli']['svd_rel_err']:.2e}"
)
print(
f" Marketing Grouping: Lasso |w1-w2|={lin['marketing_regularization']['lasso_pair_gap']:.3f} "
f"(screened={lin['marketing_regularization']['lasso_screened_cols']}) vs "
f"ElasticNet |w1-w2|={lin['marketing_regularization']['elasticnet_pair_gap']:.3f}"
)
print(
f" Diagnostics: max_VIF={lin['diagnostics']['max_vif']:.2f}, "
f"BP_p={lin['diagnostics']['breusch_pagan_pvalue']:.2e}, "
f"HC3/OLS={lin['diagnostics']['max_hc3_to_ols_se_ratio']:.2f}x, "
f"Cook_max={lin['diagnostics']['max_cooks_d']:.2f}"
)
print("[2] Logistic IRLS, Quasi-Complete Separation (Firth/L2) & Softmax LSE")
print(
f" Separation ||beta||_2: Unpenalized MLE={logi['separation']['mle_l2_norm']:.2f} "
f"vs L2={logi['separation']['l2_norm']:.2f} vs Firth={logi['separation']['firth_norm']:.2f}"
)
print(
f" Softmax 3-Class: Acc={logi['softmax_multiclass']['accuracy']*100:.1f}%, "
f"Gorodkin MCC={logi['softmax_multiclass']['gorodkin_mcc']:.3f}"
)
print("[3] Severe 1.5% Imbalance (PR-AUC, MCC, GAM) & Streaming FTRL-Proximal Q2.13")
top10 = logi["imbalance_1_5pct"]["irls_at_top10_alert"]
print(
f" 1.5% Fraud Top-10% Alert: ROC-AUC={top10['roc_auc']:.3f}, "
f"PR-AUC={top10['pr_auc']:.3f}, Precision={top10['precision']*100:.1f}%, MCC={top10['mcc']:.3f}"
)
ftrl = logi["ftrl_streaming_ctr"]
print(
f" FTRL-Proximal: Exact Zeros={ftrl['stream_stats']['zero_weight_fraction']*100:.1f}%, "
f"Q2.13 delta_LogLoss={ftrl['q2_13_logloss_delta']:.5f} (75% RAM cut)"
)
print("[4] Validation Splitting Rigor (Purged TS, Nested CV & .632+ Bootstrap)")
ots = val["overlapping_ts"]
ncv = val["nested_cv_audit"]
boot = val["bootstrap_632_plus_interpolating_noise"]
print(
f" Overlapping 10d TS: Random K-Fold R2={ots['naive_random_kfold_r2']:+.3f} vs "
f"Purged Expanding R2={ots['purged_expanding_ts_r2']:+.3f}"
)
print(
f" Nested CV HPO Audit: Flat CV MSE={ncv['flat_cv_mse']:.3f} vs "
f"Nested CV={ncv['nested_cv_mse']:.3f} vs Test={ncv['true_test_mse']:.3f}"
)
print(
f" Bootstrap p>n Noise (app={boot['apparent_err']:.3f}): "
f".632={boot['err_632']:.3f} vs .632+={boot['err_632_plus']:.3f} (R={boot['overfit_rate_R']:.3f}, w={boot['weight_w']:.3f})"
)
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
payload = _sanitize_json_value(
{
"config": {"seed": args.seed, "quick": args.quick, "output": args.output},
"workbench_panels": panels,
**bench,
}
)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
print(f"Saved JSON results -> {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Automated 14-test contract verification suite for Lab 06 (`linear_validation_lab`)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
from linear_validation_lab import (
FTRLProximalClassifier,
LinearModelConfig,
LogisticConfig,
LogisticRegressionWorkbench,
SoftmaxMultinomialClassifier,
bootstrap_632_plus,
chi2_survival_prob,
compare_linear_optimizers,
compute_classification_metrics,
compute_multiclass_mcc,
compute_regression_diagnostics,
compute_regression_metrics,
fit_elasticnet_cd,
fit_huber_irls,
fit_lasso_cd,
fit_quantile_mm,
fit_ridge_svd,
group_kfold_splits,
holdout_split,
purged_timeseries_splits,
quantize_q2_13,
run_full_ch06_benchmarks,
simulate_double_descent_and_negative_ridge,
soft_threshold,
solve_ols_normal_eq,
solve_ols_qr,
solve_ols_svd,
stable_sigmoid,
stratified_kfold_splits,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
# ---------------------------------------------------------------------------
# Test 1: Normal Eq vs Householder QR vs SVD on ill-conditioned Lauchli matrix
# ---------------------------------------------------------------------------
def test_ols_normal_eq_vs_qr_svd_ill_conditioned_lauchli_and_collinear() -> None:
with pytest.raises(ValidationError):
LinearModelConfig(unknown_flag=True) # extra="forbid"
delta = 3.0e-8
X = np.array([[1.0, 1.0], [delta, 0.0], [0.0, delta]], dtype=np.float64)
beta_true = np.array([1.0, -1.0], dtype=np.float64)
y = X @ beta_true
neq = solve_ols_normal_eq(X, y, fit_intercept=False)
qr = solve_ols_qr(X, y, fit_intercept=False)
svd = solve_ols_svd(X, y, fit_intercept=False)
assert qr.condition_number_x > 1.0e7
assert math.isclose(qr.condition_number_xtx, qr.condition_number_x ** 2, rel_tol=1e-9)
err_neq = float(np.linalg.norm(neq.coef - beta_true) / np.linalg.norm(beta_true))
err_qr = float(np.linalg.norm(qr.coef - beta_true) / np.linalg.norm(beta_true))
err_svd = float(np.linalg.norm(svd.coef - beta_true) / np.linalg.norm(beta_true))
assert err_neq > 1.0e-3
assert err_qr < 1.0e-6
assert err_svd < 1.0e-6
with pytest.raises(ValueError):
qr.coef[0] = 999.0 # read-only buffer
# ---------------------------------------------------------------------------
# Test 2: Optimizer comparison (QR, L-BFGS, BGD, Mini-batch, SGD, Nelder-Mead)
# ---------------------------------------------------------------------------
def test_linear_optimizer_comparison_bgd_sgd_minibatch_lbfgs_vs_nelder_mead() -> None:
rng = np.random.default_rng(42)
X = rng.normal(0.0, 1.0, size=(250, 10))
w_true = np.array([2.0, -1.5, 1.0, 0.0, 0.7, -0.5, 0.0, 0.3, 0.0, -0.2])
y = 4.0 + X @ w_true + rng.normal(0.0, 0.4, size=250)
res = compare_linear_optimizers(X, y, max_iter=250, batch_size=32, seed=42)
assert res["lbfgs"]["loss_gap"] < 1e-8
assert res["bgd"]["loss_gap"] < 1e-6
assert res["minibatch"]["loss_gap"] < 0.02
assert res["nelder_mead"]["loss_gap"] > res["lbfgs"]["loss_gap"] * 100.0
assert res["nelder_mead"]["param_rel_err"] > res["lbfgs"]["param_rel_err"]
# ---------------------------------------------------------------------------
# Test 3: Ridge SVD spectral filters, df(lambda), double descent & lambda < 0
# ---------------------------------------------------------------------------
def test_ridge_svd_filter_factors_df_and_double_descent_negative_ridge() -> None:
rng = np.random.default_rng(42)
X = rng.normal(0.0, 1.0, size=(120, 6))
y = 2.0 + X @ np.array([1.5, -1.0, 0.5, 0.0, 0.0, 0.0]) + rng.normal(0.0, 0.5, size=120)
r_small = fit_ridge_svd(X, y, l2_alpha=0.1)
r_large = fit_ridge_svd(X, y, l2_alpha=50.0)
assert 1.0 < r_large.effective_df < r_small.effective_df < 7.0
# Verify intercept is unpenalized under constant y shift
r_shift = fit_ridge_svd(X, y + 100.0, l2_alpha=50.0)
assert np.allclose(r_shift.coef, r_large.coef, atol=1e-12)
assert math.isclose(r_shift.intercept - r_large.intercept, 100.0, abs_tol=1e-12)
dd = simulate_double_descent_and_negative_ridge(seed=42, quick=True)
pole_pt = max(dd["double_descent_curve"], key=lambda r: r["test_mse"])
assert 0.85 <= pole_pt["gamma"] <= 1.15
assert dd["best_spiked_lambda"] < 0.0
# ---------------------------------------------------------------------------
# Test 4: Lasso Gap Safe CD, ElasticNet grouping, Huber IRLS & Quantile Pinball
# ---------------------------------------------------------------------------
def test_lasso_gap_safe_cd_elasticnet_grouping_and_huber_quantile_pinball() -> None:
assert soft_threshold(2.5, 1.0) == 1.5
assert soft_threshold(-0.4, 1.0) == 0.0
rng = np.random.default_rng(42)
n = 300
base = rng.normal(0.0, 1.0, size=n)
x1 = base + rng.normal(0.0, 0.05, size=n)
x2 = base + rng.normal(0.0, 0.05, size=n)
X = np.column_stack([x1, x2, rng.normal(0.0, 1.0, size=(n, 8))])
y = 5.0 + 2.0 * x1 + 2.0 * x2 + rng.normal(0.0, 0.5, size=n)
lasso = fit_lasso_cd(X, y, l1_alpha=0.45, use_gap_safe=True, tol=1e-9)
enet = fit_elasticnet_cd(X, y, l1_alpha=0.25, l2_alpha=0.5, tol=1e-9)
assert lasso.duality_gap < 1e-6
assert lasso.screened_count >= 5
assert np.allclose(lasso.coef[2:], 0.0, atol=1e-6)
assert abs(enet.coef[0] - enet.coef[1]) < 0.35
# Heavy outlier contamination: Huber beats OLS; Quantile tau=0.90 sits above tau=0.10
x_1d = rng.uniform(0.0, 10.0, size=(120, 1))
y_clean = 2.0 + 3.0 * x_1d[:, 0] + rng.normal(0.0, 1.0, size=120)
y_out = y_clean.copy()
y_out[:12] += 80.0
ols_o = solve_ols_qr(x_1d, y_out)
hub_o = fit_huber_irls(x_1d, y_out, delta=1.345)
assert abs(hub_o.coef[0] - 3.0) < abs(ols_o.coef[0] - 3.0)
q10 = fit_quantile_mm(x_1d, y_clean, tau=0.10)
q90 = fit_quantile_mm(x_1d, y_clean, tau=0.90)
frac_below_q90 = float(np.mean(y_clean <= q90.predict(x_1d)))
frac_below_q10 = float(np.mean(y_clean <= q10.predict(x_1d)))
assert 0.82 <= frac_below_q90 <= 0.96
assert 0.04 <= frac_below_q10 <= 0.18
# ---------------------------------------------------------------------------
# Test 5: Hat matrix, Sherman-Morrison Studentized t_i, VIF, BP+HC3, Cook's D
# ---------------------------------------------------------------------------
def test_ols_diagnostics_hat_sherman_morrison_vif_bp_hc3_and_cooks_d() -> None:
rng = np.random.default_rng(42)
n = 150
x1 = rng.normal(0.0, 1.0, size=n)
x2 = 0.96 * x1 + rng.normal(0.0, 0.2, size=n)
x3 = rng.normal(0.0, 1.0, size=n)
X = np.column_stack([x1, x2, x3])
y = 1.0 + 2.0 * x1 + 1.0 * x2 - 0.5 * x3 + rng.normal(0.0, 1.0, size=n) * (0.2 + 2.0 * np.abs(x1))
X[0] = [5.5, 5.2, 4.0]
y[0] = 45.0
diag = compute_regression_diagnostics(X, y)
p = 4 # intercept + 3 predictors
assert math.isclose(float(np.sum(diag.leverage)), float(p), abs_tol=1e-10)
assert float(np.min(diag.leverage)) >= (1.0 / float(n)) - 1e-10
assert diag.vif[0] > 10.0 and diag.vif[1] > 10.0 and diag.vif[2] < 2.0
assert diag.breusch_pagan_pvalue < 0.01
assert 0.0 <= chi2_survival_prob(3.8414588, df=1) <= 0.06
assert np.max(diag.se_hc3) > np.max(diag.se_ols)
assert 0 in diag.influential_indices
# Verify Sherman-Morrison LOO prediction shift matches exact brute-force LOO on row 0
ols_full = solve_ols_qr(X, y)
ols_loo = solve_ols_qr(X[1:], y[1:])
pred_diff_sq = float(np.sum((ols_full.predict(X) - ols_loo.predict(X)) ** 2))
s2 = float(np.sum(diag.residuals ** 2)) / float(n - p)
exact_cook_0 = pred_diff_sq / (float(p) * s2)
assert math.isclose(diag.cooks_distance[0], exact_cook_0, rel_tol=1e-9)
# ---------------------------------------------------------------------------
# Test 6: Regression metrics and MAPE / SMAPE zero & asymmetry traps
# ---------------------------------------------------------------------------
def test_regression_metrics_and_mape_smape_zero_asymmetry_traps() -> None:
y_true = np.array([0.0, 100.0, 100.0])
y_under = np.array([0.0, 50.0, 50.0])
y_over = np.array([0.0, 150.0, 150.0])
m_under = compute_regression_metrics(y_true, y_under, n_predictors=1)
m_over = compute_regression_metrics(y_true, y_over, n_predictors=1)
assert math.isinf(m_under["mape_raw"])
assert m_under["zero_target_count"] == 1.0
assert m_under["smape"] > m_over["smape"] # Asymmetry: under-forecast penalized harsher!
assert math.isclose(m_under["wape"], m_over["wape"], abs_tol=1e-12)
# Negative out-of-sample R^2 when predictions are worse than mean baseline
m_bad = compute_regression_metrics(np.array([1.0, 2.0, 3.0]), np.array([10.0, -5.0, 12.0]))
assert m_bad["r2"] < 0.0
# ---------------------------------------------------------------------------
# Test 7: Logistic IRLS, L-BFGS, GD convergence & Softmax LSE identifiability
# ---------------------------------------------------------------------------
def test_logistic_irls_lbfgs_gradient_descent_and_softmax_lse_convergence() -> None:
assert math.isclose(float(stable_sigmoid(1000.0)), 1.0, abs_tol=1e-12)
assert math.isclose(float(stable_sigmoid(-1000.0)), 0.0, abs_tol=1e-12)
rng = np.random.default_rng(42)
X = rng.normal(0.0, 1.0, size=(300, 4))
y = (rng.uniform(size=300) < np.asarray(stable_sigmoid(-0.8 + X @ np.array([1.2, -0.9, 0.6, 0.0])))).astype(
np.float64
)
f_irls = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=1.0)).fit(X, y)
f_lbfgs = LogisticRegressionWorkbench(LogisticConfig(solver="lbfgs", l2_alpha=1.0, max_iter=150)).fit(X, y)
f_bgd = LogisticRegressionWorkbench(
LogisticConfig(solver="bgd", l2_alpha=1.0, learning_rate=0.5, max_iter=500, tol=1e-6)
).fit(X, y)
assert f_irls.converged and f_irls.hessian_min_eig > 0.0
assert np.allclose(f_irls.coef, f_lbfgs.coef, atol=1e-4)
assert np.allclose(f_irls.coef, f_bgd.coef, atol=5e-3)
# 3-class Softmax LSE zero-sum L2 gauge constraint across slopes
W_sm = np.array([[1.5, -1.2, 0.1], [-0.8, 1.4, -0.2], [0.2, -0.3, 1.6], [0.5, 0.4, -0.9]])
logits_sm = X @ W_sm
y_sm = np.argmax(logits_sm + rng.gumbel(0.0, 0.4, size=logits_sm.shape), axis=1)
sm = SoftmaxMultinomialClassifier(l2_alpha=2.0).fit(X, y_sm)
probs = sm.predict_proba(X)
assert np.allclose(np.sum(probs, axis=1), 1.0, atol=1e-12)
assert np.allclose(np.sum(sm.weights_, axis=1), 0.0, atol=1e-4)
# ---------------------------------------------------------------------------
# Test 8: Quasi-complete separation MLE blow-up vs Firth & L2 remedy
# ---------------------------------------------------------------------------
def test_logistic_quasi_complete_separation_and_firth_l2_remedy() -> None:
rng = np.random.default_rng(42)
n = 200
x1 = rng.normal(0.0, 1.0, size=n)
rare = np.zeros(n, dtype=np.float64)
rare[:15] = 1.0
y = (rng.uniform(size=n) < np.asarray(stable_sigmoid(-1.0 + 1.0 * x1))).astype(np.float64)
y[:15] = 1.0 # Rare group has 100% positives -> quasi-complete separation
X = np.column_stack([x1, rare])
mle = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=0.0, max_iter=30)).fit(X, y)
l2 = LogisticRegressionWorkbench(LogisticConfig(solver="irls", l2_alpha=1.0, max_iter=30)).fit(X, y)
firth = LogisticRegressionWorkbench(LogisticConfig(solver="firth", l2_alpha=0.0, max_iter=35)).fit(X, y)
assert mle.param_l2_norm > 10.0
assert l2.param_l2_norm < 6.0 and l2.converged
assert firth.param_l2_norm < 6.0 and firth.converged
# ---------------------------------------------------------------------------
# Test 9: FTRL-Proximal exact L1 sparsity, Q2.13 quantization & log-odds offset
# ---------------------------------------------------------------------------
def test_ftrl_proximal_exact_sparsity_q2_13_quantization_and_subsampling_offset() -> None:
bench = run_full_ch06_benchmarks(quick=True, seed=42)
ftrl_res = bench["logistic_and_imbalance"]["ftrl_streaming_ctr"]
assert ftrl_res["stream_stats"]["zero_weight_fraction"] >= 0.70
assert ftrl_res["q2_13_logloss_delta"] < 0.01
# Verify Q2.13 stochastic rounding is unbiased in expectation & exact 2^-13 grid
rng = np.random.default_rng(42)
w = rng.uniform(-1.5, 1.5, size=200)
q = quantize_q2_13(w, seed=42, stochastic_rounding=True)
assert np.allclose(q * 8192.0, np.round(q * 8192.0), atol=1e-12)
assert np.max(np.abs(q - w)) <= (2.0 ** -13) + 1e-12
# Negative subsampling calibration: base rate with r=0.2 recovers true mean rate
n = 1200
X_const = np.zeros((n, 2), dtype=np.float64)
y_rare = (rng.uniform(size=n) < 0.08).astype(np.float64)
clf = FTRLProximalClassifier(n_features=2, alpha=0.5, l1_alpha=0.0, l2_alpha=0.1, negative_subsample_rate=0.2, seed=42)
clf.stream_fit_prequential(X_const, y_rare)
p_mean = float(np.mean(clf.predict_proba(X_const[:10])))
assert abs(p_mean - float(np.mean(y_rare))) < 0.05
# ---------------------------------------------------------------------------
# Test 10: Severe imbalance ROC-AUC vs PR-AUC, PRG, MCC, Gorodkin & Murphy Brier
# ---------------------------------------------------------------------------
def test_classification_imbalance_roc_vs_pr_prg_mcc_and_brier_murphy() -> None:
bench = run_full_ch06_benchmarks(quick=True, seed=42)
imb = bench["logistic_and_imbalance"]["imbalance_1_5pct"]
top = imb["irls_at_top10_alert"]
assert top["prevalence"] < 0.05
assert top["roc_auc"] > 0.75
assert top["pr_auc"] < 0.45
assert top["precision"] < 0.25
assert top["mcc"] < 0.40
# Verify exact Murphy (1973) Brier decomposition identity on binned probabilities
assert math.isclose(
top["brier_binned"],
top["brier_reliability"] - top["brier_resolution"] + top["brier_uncertainty"],
abs_tol=1e-12,
)
# Random constant prediction gets MCC == 0
m_const = compute_classification_metrics(np.array([0, 0, 0, 1]), np.array([0.1, 0.1, 0.1, 0.1]), threshold=0.5)
assert m_const["mcc"] == 0.0
assert math.isclose(compute_multiclass_mcc(np.array([0, 1, 2]), np.array([0, 1, 2]), 3), 1.0, abs_tol=1e-12)
# ---------------------------------------------------------------------------
# Test 11: StratifiedKFold, GroupKFold & PurgedTimeSeriesSplit / PurgedKFold
# ---------------------------------------------------------------------------
def test_validation_splitters_stratified_group_and_purged_embargo_time_series() -> None:
y_imb = np.array([1] * 10 + [0] * 190)
tr_h, te_h = holdout_split(200, test_ratio=0.2, stratify_y=y_imb, seed=42)
assert np.intersect1d(tr_h, te_h).size == 0
assert int(np.sum(y_imb[te_h])) == 2
skf = stratified_kfold_splits(y_imb, n_splits=5, seed=42)
assert all(int(np.sum(y_imb[f.val_indices])) == 2 for f in skf)
groups = np.repeat(np.arange(20), 5)
gkf = group_kfold_splits(groups, n_splits=5)
for f in gkf:
assert np.intersect1d(groups[f.train_indices], groups[f.val_indices]).size == 0
pts_exp = purged_timeseries_splits(120, n_splits=4, label_horizon=6, embargo=2, mode="expanding")
pts_roll = purged_timeseries_splits(120, n_splits=4, label_horizon=6, embargo=2, mode="rolling", max_train_size=24)
pts_pkf = purged_timeseries_splits(120, n_splits=4, label_horizon=6, embargo=2, mode="purged_kfold")
pts_pkf_zero_emb = purged_timeseries_splits(120, n_splits=4, label_horizon=6, embargo=0, mode="purged_kfold")
for f in pts_exp:
assert int(np.max(f.train_indices)) + 6 <= int(np.min(f.val_indices))
assert len(pts_roll[-1].train_indices) <= 24
assert all(f.purged_count > 0 or f.embargoed_count > 0 for f in pts_pkf)
# Regression check: even when embargo=0, post-validation horizon (label_horizon - 1 = 5) MUST be purged
f0 = pts_pkf_zero_emb[0]
v0_end = int(np.max(f0.val_indices)) + 1
assert f0.purged_count == 5
assert f0.embargoed_count == 0
assert int(np.min(f0.train_indices[f0.train_indices >= v0_end])) == v0_end + 5
f1 = pts_pkf_zero_emb[1]
assert f1.purged_count == 10 # 5 pre-val + 5 post-val purged when interior fold
# Verify naive random K-Fold leaks overlapping 10d random-walk target while Purged TS stops it
bench = run_full_ch06_benchmarks(quick=True, seed=42)
ots = bench["validation_rigor"]["overlapping_ts"]
assert ots["naive_random_kfold_r2"] > 0.30
assert ots["purged_expanding_ts_r2"] < 0.10
# ---------------------------------------------------------------------------
# Test 12: Nested CV HPO winner's curse bias & Bates et al. (2024) fold SE
# ---------------------------------------------------------------------------
def test_nested_cv_hpo_winners_curse_bias_and_fold_coverage() -> None:
bench = run_full_ch06_benchmarks(quick=True, seed=42)
ncv = bench["validation_rigor"]["nested_cv_audit"]
assert ncv["flat_cv_mse"] < ncv["nested_cv_mse"]
assert ncv["winners_curse_optimism"] > 0.0
assert ncv["tt_bias_correction"] >= 0.0
assert abs(ncv["nested_cv_mse"] - ncv["true_test_mse"]) < abs(ncv["flat_cv_mse"] - ncv["true_test_mse"]) + 1.0
# ---------------------------------------------------------------------------
# Test 13: Efron-Tibshirani .632+ Bootstrap rescues zero-train-error overfitting
# ---------------------------------------------------------------------------
def test_bootstrap_632_plus_rescues_zero_train_error_overfitting() -> None:
rng = np.random.default_rng(42)
X_noise = rng.normal(0.0, 1.0, size=(60, 110))
y_noise = rng.integers(0, 2, size=60, dtype=np.int64)
def _interp(x_tr: np.ndarray, y_tr: np.ndarray, x_ev: np.ndarray) -> np.ndarray:
fit = solve_ols_svd(x_tr, 2.0 * y_tr.astype(np.float64) - 1.0, fit_intercept=False)
return (fit.predict(x_ev) >= 0.0).astype(np.int64)
res = bootstrap_632_plus(X_noise, y_noise, _interp, loss_type="zero_one", n_bootstraps=50, seed=42)
assert res["apparent_err"] == 0.0
assert res["err_632"] < 0.38
assert res["overfit_rate_R"] > 0.70
assert res["weight_w"] > 0.85
assert res["err_632_plus"] > res["err_632"] + 0.08
# ---------------------------------------------------------------------------
# Test 14: CLI demo execution, workbench_panels JSON schema & AST import guard
# ---------------------------------------------------------------------------
def test_cli_demo_script_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch06_workbench_results.json"
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
proc = subprocess.run(
[sys.executable, str(script_path), "--seed", "42", "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
for hdr in (
"[1] Numerical Conditioning",
"[2] Logistic IRLS",
"[3] Severe 1.5% Imbalance",
"[4] Validation Splitting Rigor",
):
assert hdr in proc.stdout
payload = json.loads(out_json.read_text(encoding="utf-8"))
for key in (
"config",
"workbench_panels",
"linear_and_diagnostics",
"logistic_and_imbalance",
"validation_rigor",
):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert isinstance(kpi["value"], str) and kpi["value"]
assert len(panels["bars"]) == 4
for bar in panels["bars"]:
assert len(bar["items"]) == 4
for item in bar["items"]:
assert item["css_class"] in {"is-fast", "is-mid", "is-slow"}
assert isinstance(item["value"], (int, float)) and math.isfinite(item["value"]) and item["value"] > 0.0
assert len(panels["tables"]) == 4
for tbl in panels["tables"]:
assert len(tbl["columns"]) >= 4
assert len(tbl["rows"]) >= 3
# Security-Only AST deserialization scan across src/, scripts/, and tests/
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
py_files = (
sorted((LAB_ROOT / "src").rglob("*.py"))
+ sorted((LAB_ROOT / "scripts").rglob("*.py"))
+ sorted((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 6
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, f"Unsafe deserialization import '{alias.name}' in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module is not None:
root_mod = node.module.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, f"Unsafe deserialization from-import '{node.module}' in {py_file}"
Householder QR và SVD vẫn giữ sai số tương đối \(\sim 10^{-16}\)?NormalEq vọt sai số lên 1.33e-02 trong khi QR đạt 2.22e-16 và SVD đạt 3.51e-16.
Gap Safe, ElasticNet Grouping & Double Descent
IRLS, Softmax LSE & Bẫy Phân tách
100% vỡ nợ gây hiện tượng Phân tách Gần như Hoàn toàn (Quasi-Complete Separation). Điều gì xảy ra với MLE không phạt và cách khắc phục chuẩn mực là gì?MLE hữu hạn chỉ tồn tại khi dữ liệu có vùng chồng lấn. IRLS dùng bước Newton hội tụ bậc hai khi có vùng chồng lấn hoặc khi thêm phạt \(L_2\) / Firth (Firth 1993: cộng \(\frac{1}{2}\ln\det(\mathbf{X}^\top\mathbf{W}\mathbf{X})\) làm rào cản logarit chặn phân kỳ).
FTRL-Proximal & Lượng tử hóa Q2.13 (Google CTR)
FTRL-Proximal kết hợp lượng tử hóa Q2.13 làm tròn ngẫu nhiên và hiệu chuẩn lấy mẫu âm lại vượt trội SGD + L-BFGS trong hệ thống dự báo CTR quảng cáo quy mô tỷ đặc trưng?|z_i| <= lambda_1 triệt tiêu dao động quanh 0 của SGD, Q2.13 với nhiễu đều \(R \sim \mathcal{U}[0,1)\) giữ sai số lượng tử hóa kỳ vọng bằng 0, và bù logit(p) + ln(r) phục hồi xác suất nền thật.
MAPE/SMAPE) & Mất cân bằng Phân loại (ROC vs. PR-AUC / MCC)
0 (y = 0) và bài toán gian lận thẻ tỷ lệ nền hiếm (~1.5%–4%)?ROC-AUC bất biến với \(\pi_+\), che giấu bùng nổ FP từ pool âm khổng lồ (Saito & Rehmsmeier 2015). PR-AUC có đường nền bằng \(\pi_+\) và MCC đòi hỏi cả 4 ô ma trận nhầm lẫn cùng tốt (Chicco & Jurman 2020).
VIF, Breusch–Pagan + HC3 & Khoảng cách Cook
heteroscedasticity), và 2 điểm đòn bẩy ngoại lai cực trị, bộ công cụ chẩn đoán nào phản ánh ĐÚNG rủi ro?Cook nhân tố hóa bình phương phần dư với \(\frac{h_{ii}}{(1-h_{ii})^2}\), còn HC3 chia cho \((1-h_{ii})^2\) mô phỏng sai số xóa 1 dòng Sherman–Morrison PRESS.
PurgedTimeSeriesSplit) & Nhóm (GroupKFold)
Random K-Fold lại báo \(R^2_{\text{cv}} = +0.328\) trong khi PurgedTimeSeriesSplit (label_horizon=10, embargo=4) báo \(R^2 = -3.874\). Cơ chế nào giải thích điều này?Purge, cộng thêm vùng đệm Embargo sau khối kiểm định để ngăn rò rỉ tự tương quan.
Nested CV (Winner's Curse) & Bootstrap .632+ Khi \(\overline{\text{err}} = 0\)
lambda ở cỡ mẫu nhỏ (n = 85, d = 65) và bộ phân loại p > n nội suy 100% nhiễu trắng (\(\overline{\text{err}} = 0.000\)), kết quả thực nghiệm nào ĐÚNG?HPO và đánh giá trên cùng nếp tạo thiên lệch chọn lọc (Winner's Curse). Efron & Tibshirani (1997) thiết kế .632+ dùng tỷ lệ quá khớp tương đối \(\hat{R}\) để đẩy \(\hat{w} \to 1.0\) khi \(\overline{\text{err}} \to 0\).
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Điều kiện Läuchli (Normal Eq vs. QR/SVD) & Đua Tốc độ Tối ưu hóa 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết phân rã SVD \(\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) để suy ra \(\kappa_2(\mathbf{X}^\top\mathbf{X}) = (\sigma_1/\sigma_{\min})^2\), rồi kiểm tra giới hạn chính xác float64 (\(\epsilon_{\text{mach}} \approx 2.22\times 10^{-16}\)) trên ma trận Läuchli \(\delta = 3\times 10^{-8}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi solve_ols_normal_eq, solve_ols_qr, solve_ols_svd và compare_linear_optimizers trên d = 18 để đối chiếu L-BFGS, BGD, SGD, Mini-batch và Nelder–Mead.
Tiêu chí Đáp án & Số đối chứng
Với \(\kappa(\mathbf{X}) = 4.71\times 10^7\), NormalEq nhân đôi thành 2.22e+15 khiến sai số tương đối nhảy lên 1.33e-02, còn QR = 2.22e-16 và SVD = 3.51e-16. Ở d = 18, L-BFGS đạt 4.64e-10 chỉ sau 13 bước trong khi Nelder–Mead dừng ở 4.89e-02 sau 1,200 lần đánh giá.
Bài tập 2 — KKT Ngưỡng mềm Lasso (Gap Safe), Hiệu ứng Nhóm ElasticNet & Ridge Âm p > n
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Từ dưới vi phân KKT \(0 \in -\mathbf{a}_j^\top\mathbf{r}^{(-j)} + \|\mathbf{a}_j\|_2^2 w_j + \lambda\partial|w_j|\), dẫn xuất toán tử \(S(z, \gamma)\) và chứng minh bất đẳng thức nhóm Zou–Hastie \(|\hat{w}_i - \hat{w}_j| \le \frac{\|\mathbf{y}\|_2}{\lambda_2}\sqrt{2(1-\rho_{ij})}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy fit_lasso_cd(..., use_gap_safe=True) vs. fit_elasticnet_cd trên hai kênh marketing tương quan cao, đồng thời gọi simulate_double_descent_and_negative_ridge để quan sát cực \(\gamma \approx 1\) và \(\lambda_{\text{opt}} < 0\).
Tiêu chí Đáp án & Số đối chứng
Gap Safe sàng lọc an toàn 8/10 cột 0 đạt duality gap 1.65e-08. ElasticNet giữ độ lệch hai kênh còn 0.009 (w=(1.52, 1.53)) so với 0.130 ở Lasso. Double Descent đạt đỉnh MSE = 8.624 tại \(\gamma = 1.05\), còn mô hình gai nhọn đạt cực tiểu tại \(\lambda^* = -110.0\) (MSE = 0.715 vs. 1.376 tại 0).
Bài tập 3 — Chẩn đoán VIF, Breusch–Pagan + HC3, Cook's D, Huber/Pinball & Bẫy MAPE/SMAPE
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng phép đảo khối Schur để chứng minh \([(\mathbf{R}_{XX})^{-1}]_{jj} = 1/(1-R_j^2)\) và dùng Sherman–Morrison chứng minh \(e_{(-i)} = e_i/(1-h_{ii})\) cùng công thức Cook's D_i và HC3.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm nghiệm compute_regression_diagnostics, fit_huber_irls, fit_quantile_mm(..., tau=0.90) và compute_regression_metrics trên ví dụ có y = 0 và dự báo đối xứng +/-50.
Tiêu chí Đáp án & Số đối chứng
Thực nghiệm cho max_VIF = 19.23, BP LM = 7.24 (p = 6.46e-02), HC3/OLS SE = 2.06x, Cook_max = 1.79 (11 điểm ảnh hưởng) kéo OLS = 1.75 trong khi Huber = 1.59. Với y = 0, mape_raw = inf và SMAPE phạt thiếu nặng hơn thừa (66.7% vs. 40.0%).
Bài tập 4 — Đạo hàm Hessian IRLS, Softmax LSE & Giải cứu Phân tách Bằng Firth/L2
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh \(\mathbf{v}^\top\mathbf{X}^\top\mathbf{W}\mathbf{X}\mathbf{v} \ge 0\) với \(w_i = p_i(1-p_i)\), dẫn xuất đáp ứng làm việc \(\mathbf{z}^{(t)} = \boldsymbol{\eta}^{(t)} + (\mathbf{W}^{(t)})^{-1}(\mathbf{y}-\mathbf{p}^{(t)})\), và thiết lập phương trình điểm số Firth \((y_i + h_{ii}/2) - p_i(1+h_{ii})\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy LogisticRegressionWorkbench với solver='irls' (l2=0 vs. l2=1) và solver='firth' trên dữ liệu nhóm nợ quá hạn hiếm vỡ nợ 100%, kèm SoftmaxMultinomialClassifier 3 lớp.
Tiêu chí Đáp án & Số đối chứng
Trên tập phân tách gần như hoàn toàn, MLE không phạt vọt chuẩn ||beta||_2 = 27.15 với trị riêng Hessian cực tiểu 1.76e-10, trong khi L2 giữ 3.23 và Firth giữ 5.57 hội tụ hoàn toàn. Softmax LSE đạt Acc = 88.1%, Gorodkin MCC = 0.818 và tổng trọng số theo lớp bằng 0.
Bài tập 5 — Đánh giá Mất cân bằng (ROC vs. PR-AUC, MCC, GAM) & Streaming FTRL-Proximal Q2.13
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Suy diễn công thức Bayes \(\text{Precision} = \frac{\pi_+\text{TPR}}{\pi_+\text{TPR} + (1-\pi_+)\text{FPR}}\), giải thích đường nền PR-AUC = pi_+, và triển khai phân rã Murphy cho Brier Score.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu LogisticRegressionWorkbench vs. AdditiveSplineGAM trên dữ liệu gian lận ~4% có hiệu ứng chữ U, và chạy FTRLProximalClassifier + quantize_q2_13 với lấy mẫu âm r = 0.25.
Tiêu chí Đáp án & Số đối chứng
IRLS tuyến tính đạt ROC-AUC = 0.838 nhưng Precision top-10% chỉ 19.3% (PR-AUC = 0.283, MCC = 0.258); AdditiveSplineGAM nắm bắt độ cong chữ U nâng lên ROC = 0.957, PR-AUC = 0.680, MCC = 0.555. FTRL-Proximal ép 72.8% trọng số về 0 và Q2.13 lệch Log-Loss chỉ 1.2e-06 (-75% RAM).
Bài tập 6 — PurgedTimeSeriesSplit, GroupKFold, Nested CV Winner's Curse & .632+ Bootstrap
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết điều kiện cách ly thời gian có label_horizon và embargo, công thức hiệu chỉnh thiên lệch chọn lọc Tibshirani–Tibshirani, và bộ ba biểu thức \((\hat{\gamma}_0, \hat{R}, \hat{w})\) của .632+.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi purged_timeseries_splits, group_kfold_splits, nested_cv_ridge_audit, và bootstrap_632_plus trên bộ phân loại p > n nội suy nhiễu trắng (apparent_err = 0).
Tiêu chí Đáp án & Số đối chứng
Chuỗi chồng lấn 10 ngày cho thấy Random K-Fold rò rỉ R^2 = +0.328 trong khi Purged TS lột trần -3.874 (45 purged, 20 embargoed). Nested CV phát hiện lạc quan +0.368 (9.923 vs. Flat 9.556), và .632+ đẩy trọng số từ 0.632 lên w = 0.916 sửa lỗi 0.266 -> 0.386.