Chương 09 — Máy Vector Hỗ trợ (SVM), Đối ngẫu KKT & Phương pháp Nhân Mở rộng (RFF, Nyström, NTK & Linear Attention)
Từ Ng–Jordan (n=12 vs n=320), Hình học Lề Lớn & Pegasos, Đối ngẫu Lagrangian & Platt SMO (gap 3.97e-04), Bẫy co giãn gamma RBF (50.6% -> 79.4%) & Tường Gram 80 GB đến Bochner/ORF/QMC, Nyström (0.046 vs 0.565), E-Com Platt Calibration & FAVOR+.
Unit ID:
T1-P2-U04
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 (R32,E32:E35): Lesson 7 (Basic ML Algorithms: Support Vector Machine (SVM) — 1 buổi, phủ trọn vẹn 100% cả 7 mục:Generative vs. discriminative classification,Linear SVM: large margin intuition & support vectors,Objective function: hinge loss, regularization & optimization,Hard & soft margin classifications,Kernel methods,Nonlinear SVM: polynomial & gaussian,Industrial tips), gắn kết miền Thương mại Điện tử (Ecommerce— Personalization: Recommender Systems Across the User Journey) (Ranh giới không chồng lấn: chuẩn mực tách tập chống rò rỉ kế thừa từch-04; tối ưu hóa tuyến tính/hội tụ kế thừa từch-06; kỹ thuật chuẩn hóa/đặc trưng trong nếp kế thừa từch-08; toàn bộ thuật toán hiệu chuẩn hậu nghiệmPlatt/Isotonic PAVA/Venn-Abers& ngưỡng chi phí Bayes chuyển giao chuyên sâu sangch-07; cây quyết địnhGBDT& truy xuấtANNtiếp nối tạich-10&ch-11)
Bài thực hành Song hành (Lab 09):labs/ch09-svm-and-kernels-workbench/(svm_kernels_lab)
Tình huống Mở đầu: Bốn Thất bại Sản xuất Khi Đưa SVM và Nhân Phi tuyến Ra Thực địa#
Máy Vector Hỗ trợ (Support Vector Machines — SVM) và Lý thuyết Không gian Hilbert Nhân Tái tạo (Reproducing Kernel Hilbert Spaces — RKHS) là cầu nối toán học tinh tế nhất giữa tối ưu lồi cổ điển và học sâu hiện đại (Neural Tangent Kernel và Linearized Softmax Attention). Tuy nhiên, việc áp dụng SVM theo công thức sách giáo khoa sơ khai dẫn đến bốn thất bại sản xuất kinh điển:
- Thảm họa Tỷ lệ Đặc trưng & Đảo Ghi nhớ
(C, gamma): Trên dữ liệu phiên mua sắm E-Commerce pha trộncart_value_usd([10, 5000]) với9tỷ lệ hành vi ([0, 1]), cột tiền tệ chiếm tới99.9998%khoảng cách Euclid bình phương \(\|\mathbf{x}_i - \mathbf{x}_j\|_2^2\). Không chuẩn hóa khiếngamma='auto'kéo toàn bộ phần tử ngoài chéo của nhânRBFxuống0.00(ma trận Gram suy biến thành \(\mathbf{K} \to \mathbf{I}_n\), độ chính xác kiểm tra sụp còn50.6%), còngamma='scale'làm \(\gamma_{\text{scale}}\) tụt về1.11e-05xóa sạch cả9biến tỷ lệ (57.2%). Khi khắc phục bằnglog1p + StandardScalernội nếp với \(\gamma_{\text{med}} = 0.0537\), độ chính xác vọt lên79.4%; ngược lại, đẩy \((C=1000, \gamma=10)\) tạo ra các "đảo ghi nhớ" cô lập100.0%vector hỗ trợ (train 100.0%nhưngtest 55.6%). - Bức tường Bộ nhớ \(O(n^2)\) & Định lý Không thưa
Steinwart(\(n_{\text{SV}} = \Omega(n)\)): Ma trận Gramfloat64kích thước \(n \times n\) tiêu tốn800 MBở \(n=10^4\), nhưng nhảy vọt lên80 GBở \(n=10^5\) và8 TBở \(n=10^6\), gây tràn bộ nhớ ngay tức khắc. Tệ hơn, Định lý Steinwart (2003) chứng minh khi dữ liệu có nhiễu không tách rời (rủi ro Bayes \(R^* > 0\)), tỷ lệ vector hỗ trợ không hề thưa mà tiệm cận \(2R^*\) (10.4% -> 31.5% -> 47.7%trong workbench khi \(R^*\) tăng lên17.9%), biến suy luận đối ngẫu \(O(n_{\text{SV}} \cdot d)\) thành thảm họa trễ trên lưu lượng E-Commerce (2.615 msngay cả ở mẫu thử nhỏ, phình thành300–800 msở \(n = 150{,}000\)). - Điểm mù Mặt cầu Đơn vị trên Văn bản Thưa & Đổ vỡ Tùy chọn Mặc định
SVR/OC-SVM: Trên vectorTF-IDFchuẩn hóa \(L_2\) chiều cao (\(d = 400\text{–}50{,}000\)), mọi cặp văn bản gần như trực giao trên mặt cầu đơn vị vớimedian ||x_i - x_j||^2 = 2.00, khiến nhânRBFvừa lãng phí độ phức tạp \(O(n^2)\) vừa sụp dướiLinear DCD(100.0%), trong khi gọiStandardScaler(with_mean=True)lên ma trận CSR phình RAM từ192 MBlên80 GB. Tương tự, dùng mặc địnhepsilon=0.05trong \(\epsilon\)-SVR giữ tới96.7%mẫu làm vector hỗ trợ thay vì hiệu chuẩn theoMAD(eps=2.58nén còn11.1%SV và hạMAEgấp19.6xso vớiOLStrước gai+380..+520 USD/MWh). - Lề Thô Không Hiệu chuẩn & Độ trễ Attention Bậc hai \(O(L^2)\): Vì mất mát bản lề (hinge loss) có đạo hàm bằng
0ngoài biên \(\pm 1\), điểm quyết định thô \(f(\mathbf{x})\) co cụm quanh \(\pm 1\) và không phải xác suất hậu nghiệm (ECE = 0.085, cần cầu nối hiệu chuẩnPlatt/Venn-Aberscủach-07trước khi nhân kỳ vọng GMV). Ở tầng kiến trúc 2024–2026, nhân tử hóaSoftmax Attentionbằng đặc trưng ngẫu nhiên dương trực giaoFAVOR+biến \(O(L^2)\) thành \(O(L)\) với tăng tốc3.32xtại \(L = 2048\).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 09 và bài thực hành svm_kernels_lab (T1-P2-U04), học viên có năng lực:
- Phân tích Đối xứng Sinh vs. Phân biệt & Hình học Lề Cực đại (
R32.1–R32.3): Chứng minh dạng log-odds tuyến tính củaGaussian Naive Bayes(GNB) vàLDA; giải thích Định lý Giao điểm Ng–Jordan (2001) (\(O(\log d)\) vs. \(O(d)\)); chứng minh phép chuẩn hóa lề hàm \(\min_i \hat{\gamma}_i = 1\) biến cực đại hóa \(\gamma_{\text{geom}} = 1/\|\mathbf{w}\|_2\) thành \(\min \frac{1}{2}\|\mathbf{w}\|_2^2\); dẫn xuất tương đương giữaSoft-Margin Primalvà rủi ro bản lề chính quy hóa \(L_2\) (\(\lambda = \frac{1}{nC}\)), lý do không phạt hệ số chặn \(b\), thuật toánPegasos(bóng \(1/\sqrt{\lambda}\), tốc độ \(O(1/(\lambda \varepsilon_{\text{opt}}))\)) vàDCD(LIBLINEAR). - Làm chủ Đối ngẫu Lagrange, Điều kiện
KKT& Giải thuậtPlatt SMO(R32.4): Thực hiện trọn vẹn phép biến đổi sơ cấp \(\to\) đối ngẫu QP; phân hoạch chính xác toàn bộ dữ liệu thành3lớpKKT(\(\alpha_i = 0\) Non-SV, \(0 < \alpha_i < C\) Free SV, \(\alpha_i = C\) Bounded SV); dẫn xuất trọn bộ cập nhật giải tích 2 biến củaPlatt SMOdưới quy ước+b(cận hộp \([L, H]\), độ cong \(\eta_{\text{SMO}}\), nhánh biên \(\eta_{\text{SMO}} \le 0\), cập nhật \(b_1, b_2\) và khoảng dừng Keerthi). - Nắm vững Không gian
RKHS, Định lý Mercer/Biểu diễn & Các Họ Nhân (R32.5–R32.6): Kiểm chứng điều kiện nửa xác định dươngPSD(phát hiện nhânsigmoidkhôngPSD); chứng minh Định lý Biểu diễn (Representer Theorem) bằng phép chiếu trực giao; khai triển tường minh đơn thức nhân Đa thức (\(d_{\text{poly}}=2\)), chuỗi Taylor vô hạn chiều củaRBF(\(\gamma_{\text{rbf}} \to 0\) tuyến tính vs. \(\gamma_{\text{rbf}} \to \infty\) đảo gai), các nhân miền chuyên biệt (String k-spectrum,HIK, \(\chi^2\)), cùng mở rộng \(\epsilon\)-SVR, \(\nu\)-OCSVM / SVDD, Đa lớpOvR/OvOvà cầu nốiPlatt Scaling(ch-07). - Phá vỡ Bức tường \(O(n^2)\) Bằng
RFF(ORF/QMC),Nyström& Cầu nối SOTA 2024–2026: Chứng minh Định lý Steinwart (2003) (\(n_{\text{SV}}/n \to 2R^*\)); dẫn xuấtRFFqua Định lý Bochner choRBF(\(\mathcal{N}(\mathbf{0}, 2\gamma_{\text{rbf}}\mathbf{I}_d)\)) vàLaplace(Cauchy); chứng minh bất đẳng thức phương sai Sutherland–Schneider (2015) (Paired Sin/Cos<Random-Phase Cos),ORF(Haar QR) &Halton QMC; triển khaiNyströmvới gập trọng số \(O(md)\) và so sánh phổ Yang et al. (2012); liên kết sangFalkon,NTK(chế độ lười vs. giàuKTA), vàFAVOR+/Hedgehog/BASED/LoLCATs. - Triển khai Thực chiến
R32.7& Miền E-Commerce (E32:E35): Làm chủ5mẹo công nghiệp,4kịch bản sản xuất thực tế,8phản mẫu chống sụp đổ, và vượt qua toàn bộ14/14hợp đồngpytestthuầnNumPy + Pandas + Pydantic v2(tuyệt đối0import cấm).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U04, Dòng R32 & E32:E35)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R32 & E32:E35) |
Nâng cấp Chuẩn SOTA 2026 (ch-09) |
Mục trong Chương 09 | Mô-đun & Hợp đồng Kiểm thử (svm_kernels_lab) |
|---|---|---|---|
| R32.1 Generative vs. Discriminative Classification | Log-odds tuyến tính GNB & LDA vs. LogReg / SVM; Định lý Giao điểm Ng–Jordan (2001) \(O(\log d)\) vs. \(O(d)\) & Hiệu quả Efron |
Trụ cột 1 (§1.1) + Mermaid 1 + Widget svm-margin-kkt-explorer |
primal_and_dual_svm.py (GaussianNaiveBayesClassifier, ShrinkageLDAClassifier, simulate_ng_jordan_crossover), Test 1 |
| R32.2 Linear SVM: Large Margin & Support Vectors | Khoảng cách hình học có dấu \(\gamma_{\text{geom}} = 1/\|\mathbf{w}\|_2\), chuẩn hóa chính tắc \(\min_i \hat{\gamma}_i = 1\), cận VC \(O(R^2/\gamma_{\text{geom}}^2)\) | Trụ cột 1 (§1.2) + Widget svm-margin-kkt-explorer |
primal_and_dual_svm.py (LinearSVMPrimal), Test 2 |
| R32.3 Objective: Hinge Loss, Regularization & Optimization | Tương đương bản lề vs. ERM \(\lambda = 1/(nC)\), bất biến không phạt \(b\), Pegasos (\(L_2\) ball \(1/\sqrt{\lambda}\), \(O(1/(\lambda\varepsilon_{\text{opt}}))\)) vs. DCD (LIBLINEAR) |
Trụ cột 1 (§1.3) + Mermaid 1 | primal_and_dual_svm.py (LinearSVMPrimal, _optimal_1d_hinge_bias), Test 2 |
| R32.4 Hard & Soft Margin Classifications | Biến chùng \(\xi_i \ge 0\), đối ngẫu Lagrange QP (Slater), Phân hoạch 3 nhóm KKT, & bước giải tích Platt SMO ([L, H], \(\eta_{\text{SMO}} \le 0\), \(b_1/b_2\)) |
Trụ cột 1 (§1.4) + Mermaid 2 | primal_and_dual_svm.py (KernelSMOSolver, smo_two_variable_step), Test 3 |
| R32.5–6 Kernel Methods & Nonlinear SVM (Poly & Gaussian) | Gram PSD, Mercer, Định lý Biểu diễn, Poly (\(d_{\text{poly}}=2\)), RBF (\(\gamma_{\text{rbf}}\) & đảo gai), String/HIK/\(\chi^2\), \(\epsilon\)-SVR, \(\nu\)-OCSVM/SVDD, OvR/OvO, cầu Platt (ch-07) |
Trụ cột 1 (§1.5–§1.6) + Mermaid 2 + Widget kernel-trick-rbf-poly-arena |
primal_and_dual_svm.py (EpsilonSVR, OneClassSVMSolver, SVDDSolver, MulticlassSVM, PlattCalibrator), kernels_and_approximations.py (audit_kernel_psd, explicit_poly2_feature_map, string_spectrum_kernel), Tests 4, 6, 7, 8 |
| Scalability & SOTA 2024–2026 Kernel Approximations | Bức tường \(O(n^2)\) (80 GB @ 100k), Steinwart (\(n_{\text{SV}} = \Omega(n)\)), Bochner RFF (Paired/ORF/QMC), Nyström (Yang et al.), Falkon/NTK/FAVOR+/Hedgehog/BASED/LoLCATs |
Trụ cột 2 (§2.1–§2.4) + Mermaid 3 + Widget rff-nystrom-scalability-explorer |
kernels_and_approximations.py (RandomPhaseCosRFF, PairedSinCosRFF, OrthogonalRandomFeatures, HaltonQMCRFF, NystromFeatures, run_ntk_and_kta_bridge, run_softmax_attention_kernel_bridge), Tests 9, 10, 11, 12 |
R32.7 Industrial Tips & E32:E35 Ecommerce Personalization |
Bẫy tỷ lệ RBF, đảo (C, gamma), mất cân bằng & hiệu chuẩn, E-Commerce Personalization (E32:E35), văn bản thưa TF-IDF, 8 Phản mẫu & Benchmark CLI |
Trụ cột 3 (§3.1–§3.3) + Trụ cột 4 | kernels_and_approximations.py (run_scaling_and_island_diagnostics, run_ecommerce_and_sparse_cases, run_full_ch09_benchmarks), scripts/run_lab_demo.py, Tests 5, 13, 14 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-09) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (svm_kernels_lab) |
|---|---|---|---|---|
| \(n, d, D\) | \(\mathbb{N}_+\) | Cỡ mẫu huấn luyện \(n\), chiều đặc trưng thô \(d\), chiều không gian nâng/xấp xỉ \(D\) (\(D = 2m_{\text{freq}}\) ở Paired RFF) | Không dùng \(d\) cho bậc đa thức | n_samples, n_features, n_components |
| \(d_{\text{poly}}, r\) | \(\mathbb{N}_+, \mathbb{R}_{\ge 0}\) | Bậc đa thức \(d_{\text{poly}}\) và hệ số bù \(r\) trong \((\gamma_{\text{poly}}\langle\mathbf{x},\mathbf{z}\rangle + r)^{d_{\text{poly}}}\) | Tách biệt hoàn toàn khỏi chiều \(d\) | degree, coef0 |
| \(y_i\) | \(\{-1, +1\}\) hoặc \(\mathbb{R}\) | Nhãn có dấu SVM \(y_i \in \{-1, +1\}\) (hoặc biến mục tiêu liên tục trong \(\epsilon\)-SVR) | Phân biệt với nhãn Bernoulli \(\{0, 1\}\) ở ch-06/ch-07 |
y_signed, y |
| \(\mathbf{w}, b\) | \(\mathbb{R}^d, \mathbb{R}\) | Vector pháp tuyến \(\mathbf{w}\) và hệ số chặn không bị phạt \(b\) (\(f(\mathbf{x}) = \langle\mathbf{w}, \phi(\mathbf{x})\rangle + b\)) | Khóa quy ước +b (LIBSVM/sklearn), cảnh báo dấu -b_Platt (1998) |
coef_, intercept_ |
| \(\hat{\gamma}_i, \gamma_{\text{geom}}\) | \(\mathbb{R}, \mathbb{R}_{>0}\) | Lề hàm \(y_i(\mathbf{w}^\top\mathbf{x}_i + b)\) và lề hình học chuẩn hóa \(1/\|\mathbf{w}\|_2\) | Không viết \(\gamma\) trần cho lề; tách khỏi \(\gamma_{\text{rbf}}\) | functional_margin, geometric_margin_ |
| \(\gamma_{\text{rbf}}, \sigma_{\text{rbf}}\) | \(\mathbb{R}_{>0}\) | Băng thông nghịch đảo RBF \(\gamma_{\text{rbf}} = 1/(2\sigma_{\text{rbf}}^2)\) |
Tách khỏi lề hình học & hằng số nối \(\gamma_c\) | gamma |
| \(C, \lambda\) | \(\mathbb{R}_{>0}\) | Hệ số phạt chùng \(C\) (\(C\sum\xi_i\)) và trọng số chính quy \(L_2\) \(\lambda = \frac{1}{nC}\) | Ghi rõ đẳng thức \(\lambda = 1/(nC)\) | c_reg, lam_ |
| \(\alpha_i, \alpha_i^*, \mu_i\) | \(\mathbb{R}_{\ge 0}\) | Nhân tử Lagrange đối ngẫu (\(0 \le \alpha_i \le C\) SVC; \((\alpha_i, \alpha_i^*)\) SVR; \(\mu_i = C-\alpha_i\)) | Tách khỏi hệ số hiệu chuẩn \(A_{\text{Platt}}\) | alphas_, alpha_diff_ |
| \(\eta_{\text{SMO}}, \eta_t\) | \(\mathbb{R}, \mathbb{R}_{>0}\) | Độ cong 2 biến SMO (\(K_{11}+K_{22}-2K_{12}\)) vs. bước học Pegasos (\(1/(\lambda t)\)) |
Luôn gắn chỉ số dưới phân biệt | eta, step_size |
| \(\epsilon_{\text{tube}}, \varepsilon_{\text{tol}}, \varepsilon_{\text{opt}}\) | \(\mathbb{R}_{\ge 0}, \mathbb{R}_{>0}\) | Nửa bề rộng ống \(\epsilon\)-SVR vs. ngưỡng dừng KKT SMO vs. khoảng dừng tối ưu Pegasos |
Không dùng \(\epsilon\) trần cho hai vai trò cạnh nhau | epsilon_tube, tol |
| \(\nu, \rho, R_{\text{sph}}\) | \((0, 1], \mathbb{R}, \mathbb{R}_{\ge 0}\) | Tham số OC-SVM/SVDD (\(\frac{m_{\text{out}}}{n} \le \nu \le \frac{n_{\text{SV}}}{n}\)), bù gốc \(\rho\), bán kính siêu cầu \(R_{\text{sph}}\) |
Tách khỏi bán kính dữ liệu \(R = \max_i \|\mathbf{x}_i\|_2\) | nu, rho_, radius_sq_ |
| \(\mathbf{K}, K_{\text{cls}}\) | \(\mathbb{R}^{n\times n}, \mathbb{N}_{\ge 2}\) | Ma trận Gram PSD đối xứng (\(K_{ij} = K(\mathbf{x}_i, \mathbf{x}_j)\)) vs. số lớp phân loại \(K_{\text{cls}}\) |
Tránh va chạm giữa tên nhân \(K\) và số lớp | K, n_classes |
Trụ cột 1 — Cơ sở Toán học: Sinh vs. Phân biệt, Lề Cực đại, Đối ngẫu KKT/SMO & RKHS#
1.1 Phân loại Sinh vs. Phân biệt & Định lý Giao điểm Ng–Jordan (2001) (R32.1)#
Xét bài toán phân loại nhị phân trên tập quan sát i.i.d. \(\{(\mathbf{x}_i, y_i)\}_{i=1}^n\) (\(\mathbf{x}_i \in \mathbb{R}^d\), \(y_i \in \{-1, +1\}\)). Có ba hệ hình thiết kế ranh giới quyết định:
-
Bộ phân loại Sinh (Generative Classifiers —
GNB,LDA): Ước lượng riêng tiên nghiệm lớp \(\pi_y = \mathbb{P}(Y=y)\) và mật độ có điều kiện \(p(\mathbf{x} \mid Y=y)\) để mô hình hóa phân phối đồng thời \(p(\mathbf{x}, y) = p(y)\,p(\mathbf{x} \mid y)\), rồi dùng quy tắc Bayes suy ra log-odds hậu nghiệm:\[\ln\frac{P(Y=+1 \mid \mathbf{x})}{P(Y=-1 \mid \mathbf{x})} = \ln\frac{p(\mathbf{x} \mid Y=+1)}{p(\mathbf{x} \mid Y=-1)} + \ln\frac{\pi_+}{\pi_-}.\]- Gaussian Naive Bayes (
GNB): Giả sử các đặc trưng độc lập có điều kiện \(p(\mathbf{x}\mid Y=y) = \prod_{j=1}^d \mathcal{N}(x_j \mid \mu_{y,j}, \sigma_{y,j}^2)\). Khi dùng chung phương sai từng tọa độ (\(\sigma_{+1,j}^2 = \sigma_{-1,j}^2 = \sigma_j^2\)), số hạng bậc hai \(x_j^2\) triệt tiêu hoàn toàn, thu gọn log-odds về hàm tuyến tính chính xác:\[w_{\text{GNB}, j} = \frac{\mu_{+1,j} - \mu_{-1,j}}{\sigma_j^2}, \qquad b_{\text{GNB}} = \sum_{j=1}^d \frac{\mu_{-1,j}^2 - \mu_{+1,j}^2}{2\sigma_j^2} + \ln\frac{\pi_+}{\pi_-}.\] - Linear Discriminant Analysis (
LDA): Mô hình hóa \(\mathbf{x} \mid Y=y \sim \mathcal{N}(\boldsymbol{\mu}_y, \boldsymbol{\Sigma})\) với ma trận hiệp phương sai đầy đủ dùng chung \(\boldsymbol{\Sigma} \succ \mathbf{0}\) (\(O(d^2)\) tham số). Khai triển dạng toàn phương cũng triệt tiêu \(\mathbf{x}^\top\boldsymbol{\Sigma}^{-1}\mathbf{x}\) và sinh ra đúng họ siêu phẳng \(P(Y=+1\mid\mathbf{x}) = \sigma(\mathbf{w}_{\text{LDA}}^\top\mathbf{x} + b_{\text{LDA}})\) với \(\mathbf{w}_{\text{LDA}} = \boldsymbol{\Sigma}^{-1}(\boldsymbol{\mu}_+ - \boldsymbol{\mu}_-)\). 2. Bộ phân loại Phân biệt Xác suất (Probabilistic Discriminative —Logistic Regression,ch-06): Bỏ qua \(p(\mathbf{x})\), tham số hóa trực tiếp \(P(Y=+1\mid\mathbf{x}) = \sigma(\mathbf{w}^\top\mathbf{x} + b)\) bằng cực đại hóa hợp lý có điều kiện (Log-Loss). 3. Bộ phân loại Phân biệt Lề trực tiếp (Direct Margin Discriminant —Linear SVM): Áp dụng Nguyên lý Vapnik (không giải bài toán ước lượng mật độ tổng quát hơn mức cần thiết khi mục tiêu chỉ là phân hoạch ranh giới), tối ưu trực tiếp siêu phẳng \(f(\mathbf{x}) = \mathbf{w}^\top\mathbf{x} + b\) cực đại hóa khoảng cách hình học giữa hai lớp.
- Gaussian Naive Bayes (
Định lý 1.1 (Ng & Jordan, NIPS 2001 — Tiệm cận vs. Độ phức tạp Mẫu \(O(\log d)\) vs. \(O(d)\))#
So sánh cặp Sinh–Phân biệt chia sẻ cùng họ log-odds tuyến tính (GNB vs. Logistic Regression / Linear SVM):
- Chế độ Tiệm cận (\(n \to \infty\)): Nếu giả định sinh sai lệch (misspecified — chẳng hạn các đặc trưng có tương quan khối \(\rho = 0.72\) phá vỡ giả định độc lập của
GNB),GNBcộng dồn trọng số dư thừa làm sai lệch hướng phân tách, khiến lỗi tiệm cận thỏa \(\varepsilon(h_{\text{Dis}, \infty}) \le \varepsilon(h_{\text{Gen}, \infty})\). (Ngược lại, theo Định lý Hiệu quả Efron 1975, chỉ khi phân phối chuẩn đồng nhất thực sự đúng thìLDAmới cùng giới hạn Bayes vớiLogRegvà có phương sai thấp hơn ~30–50%.) - Chế độ Cỡ mẫu Hữu hạn (\(O(\log d)\) vs. \(O(d)\)): Vì tập siêu phẳng tuyến tính trong \(\mathbb{R}^d\) có chiều Vapnik–Chervonenkis \(\operatorname{VC} = d + 1\), bộ học phân biệt không chính quy chặt cần \(n = \Omega(d)\) mẫu để hội tụ. Trái lại,
GNBước lượng rời \(d\) cặp tham số 1D \((\hat{\mu}_{y,j}, \hat{\sigma}_j^2)\); theo bất đẳng thức Hoeffding kết hợp chặn hợp qua \(d\) tọa độ:\[\mathbb{P}\!\left(\max_{1 \le j \le d} |\hat{\theta}_j - \theta_j| > \tau\right) \le 2d\,\exp(-2nc\,\tau^2) \le \delta \quad \Longleftarrow \quad n = O\!\left(\frac{\ln(d/\delta)}{\tau^2}\right) = O(\log d)!\]Trong bài toán thực nghiệmd = 36(12 kênh tín hiệu tương quan \(\rho = 0.72\) kèm 24 kênh nhiễu phương sai lớn) củasvm_kernels_lab, ở \(n = 12\),GNBtự chuẩn hóa từng phương sai trục chỉ sai14.6%trong khiLinear SVMchưa đủ mẫu lọc nhiễu sai41.9%(LDA 41.6%); nhưng đến \(n = 320\),Linear DCDhọc triệt tiêu hoàn toàn nhiễu và tương quan, lật ngược tỷ số xuống1.1%(LDA 0.8%) so với trần thiên lệch1.8%củaGNB!
1.2 Hình học Lề Cực đại & Phép Chuẩn hóa Chính tắc (R32.2)#
Xét siêu phẳng \(\mathcal{H} := \{\mathbf{x} \in \mathbb{R}^d : \mathbf{w}^\top\mathbf{x} + b = 0\}\) (\(\mathbf{w} \neq \mathbf{0}\)) phân chia hai lớp \(y_i \in \{-1, +1\}\). Chiếu trực giao \(\mathbf{x}_i\) xuống điểm \(\mathbf{x}_\perp \in \mathcal{H}\) dọc theo vector pháp tuyến đơn vị \(\mathbf{w}/\|\mathbf{w}\|_2\):
Do đó, lề hình học (geometric margin) — khoảng cách Euclid có dấu từ \(\mathbf{x}_i\) tới siêu phẳng — là:
trong đó \(\hat{\gamma}_i := y_i(\mathbf{w}^\top\mathbf{x}_i + b)\) là lề hàm (functional margin).
- Bất biến Thước đo & Chuẩn hóa Chính tắc: Nhân \((\mathbf{w}, b) \mapsto (\kappa \mathbf{w}, \kappa b)\) (\(\kappa > 0\)) giữ nguyên \(\mathcal{H}\) và mọi \(\gamma_{\text{geom}, i}\), nhưng kéo \(\hat{\gamma}_i \mapsto \kappa \hat{\gamma}_i\). Để bài toán cực đại hóa lề tập \(\gamma_{\text{geom}} := \min_i \gamma_{\text{geom}, i}\) xác định duy nhất, ta cố định thước đo bằng siêu phẳng chính tắc sao cho các điểm gần nhất nằm đúng trên \(\hat{\gamma}_i = 1\):
\[\min_{i=1,\dots,n} y_i(\mathbf{w}^\top\mathbf{x}_i + b) = 1 \quad \Longrightarrow \quad \gamma_{\text{geom}} = \frac{1}{\|\mathbf{w}\|_2},\qquad \operatorname{Width}(\mathcal{H}_+, \mathcal{H}_-) = \frac{2}{\|\mathbf{w}\|_2}.\]
- Tương đương \(\max \frac{2}{\|\mathbf{w}\|_2} \iff \min \frac{1}{2}\|\mathbf{w}\|_2^2\): Cực đại hóa \(\frac{2}{\|\mathbf{w}\|_2}\) tương đương cực tiểu hóa \(\|\mathbf{w}\|_2\). Vì hàm \(g(z) = \frac{1}{2}z^2\) tăng ngặt trên \((0, \infty)\) (\(g'(z) = z > 0\)), bài toán Hard-Margin SVM bảo toàn chính xác cực tiểu toàn cục dưới dạng quy hoạch toàn phương lồi chặt khả vi:
\[\min_{\mathbf{w} \in \mathbb{R}^d,\, b \in \mathbb{R}} \; \frac{1}{2}\|\mathbf{w}\|_2^2 \qquad \text{s.t.} \quad y_i(\mathbf{w}^\top\mathbf{x}_i + b) \ge 1 \quad (\forall i=1,\dots,n).\]
- Bảo đảm Tổng quát hóa Độc lập với Chiều (Vapnik 1995): Nếu dữ liệu nằm trong quả cầu \(\|\mathbf{x}_i\|_2 \le R\), họ siêu phẳng có lề hình học tối thiểu \(\gamma_{\text{geom}}\) sở hữu chiều VC bị chặn bởi \(\operatorname{VC} \le \min(\lceil R^2/\gamma_{\text{geom}}^2 \rceil, d) + 1 = \min(\lceil R^2\|\mathbf{w}\|_2^2 \rceil, d) + 1\) — lý giải vì sao cực tiểu hóa \(\|\mathbf{w}\|_2^2\) ngăn quá khớp ngay cả khi \(D = \infty\) trong
RKHS!
1.3 Lề Cứng vs. Lề Mềm, Mất mát Bản lề, Pegasos & DCD (R32.3–R32.4)#
Khi dữ liệu có nhiễu chồng lấn hoặc không tách rời tuyến tính, Hard Margin trở nên vô nghiệm. Soft-Margin SVM (Cortes & Vapnik, 1995) thêm biến chùng không âm \(\xi_i \ge 0\) đo mức độ vi phạm biên:
- \(\xi_i = 0\): điểm nằm ngoài hoặc trên dải lề (\(y_i f(\mathbf{x}_i) \ge 1\)).
- \(0 < \xi_i < 1\): nằm trong dải lề nhưng vẫn phân loại đúng.
- \(\xi_i \ge 1\): nằm trên siêu phẳng hoặc bị phân loại sai (\(\sum_i \xi_i\) chặn trên số lỗi \(0\text{–}1\)).
Tương đương Tuyệt đối với Rủi ro Mất mát Bản lề (Hinge Loss) & Bất biến Không phạt \(b\)#
Với mọi \((\mathbf{w}, b)\) cố định và \(C > 0\), tối ưu hóa theo \(\xi_i\) tách rời từng mẫu thành nghiệm duy nhất \(\xi_i^* = \max(0, 1 - y_i(\mathbf{w}^\top\mathbf{x}_i + b)) =: \ell_{\text{hinge}}(y_i f(\mathbf{x}_i))\). Chia toàn bộ hàm mục tiêu cho hằng số dương \(nC > 0\) cho thấy Soft-Margin SVM đồng nhất nghiệm với bài toán chính quy hóa \(L_2\):
- Vì sao tuyệt đối KHÔNG phạt hệ số chặn \(b\): Đưa \(\frac{\lambda}{2}b^2\) vào tổng phạt phá hủy tính bất biến tịnh tiến (\(\mathbf{x}_i \mapsto \mathbf{x}_i + \mathbf{t}\) phải giữ nguyên \(\mathbf{w}^*\) và dịch đúng \(b^* \mapsto b^* - \mathbf{w}^{*\top}\mathbf{t}\)), kéo siêu phẳng lệch về gốc \(\mathbf{0}\) khi cụm dữ liệu nằm xa gốc hoặc lớp mất cân bằng. (Trong
svm_kernels_lab, quy tâm nội bộ rồi hoàn dịch \(b\) bảo toàn chuẩn tịnh tiến dưới sai số1e-3ngay cả khi cộng hằng số+500.)
Thuật toán Sơ cấp Pegasos (Shalev-Shwartz et al., 2011) vs. Hạ Tọa độ Đối ngẫu DCD (LIBLINEAR, Hsieh et al., 2008)#
- Chứng minh Bất đẳng thức Quả cầu
Pegasos(\(\|\mathbf{w}^*\|_2 \le 1/\sqrt{\lambda}\)): Theo đối ngẫu mạnh của bài toán chia \(\lambda\) (\(C_{\text{eq}} = \frac{1}{\lambda n}\)), tại nghiệm tối ưu \(\frac{1}{2}\|\mathbf{w}^*\|_2^2 + \frac{1}{\lambda n}\sum_i \xi_i^* = \sum_i \alpha_i^* - \frac{1}{2}\|\mathbf{w}^*\|_2^2\). Vì \(\xi_i^* \ge 0\) và \(0 \le \alpha_i^* \le \frac{1}{\lambda n}\), suy ra ngay:\[\|\mathbf{w}^*\|_2^2 = \sum_{i=1}^n \alpha_i^* - \frac{1}{\lambda n}\sum_{i=1}^n \xi_i^* \le n \cdot \frac{1}{\lambda n} = \frac{1}{\lambda} \implies \|\mathbf{w}^*\|_2 \le \frac{1}{\sqrt{\lambda}}.\] - Quy tắc Cập nhật & Hội tụ Độc lập Cỡ mẫu \(O(1/(\lambda \varepsilon_{\text{opt}}))\): Tại bước \(t\),
Pegasosbốc lô nhỏ \(A_t\) cỡ \(k\), lọc tập vi phạm \(A_t^+ = \{i \in A_t : y_i f_t(\mathbf{x}_i) < 1\}\), dùng bước \(\eta_t = \frac{1}{\lambda t}\) cập nhật \(\mathbf{w}_{t+1/2} = (1 - \frac{1}{t})\mathbf{w}_t + \frac{1}{\lambda t k}\sum_{i \in A_t^+} y_i\mathbf{x}_i\) rồi chiếu lên quả cầu \(\mathcal{B}(0, 1/\sqrt{\lambda})\):\[\mathbf{w}_{t+1} = \min\!\left(1,\; \frac{1/\sqrt{\lambda}}{\|\mathbf{w}_{t+1/2}\|_2}\right)\mathbf{w}_{t+1/2}.\]Nhờ tính lồi chặt \(\lambda\), trung bình đuôi đạt sai số tối ưu \(\varepsilon_{\text{opt}}\) sau \(T = O\!\left(\frac{R^2}{\lambda \varepsilon_{\text{opt}}}\right)\) bước — hoàn toàn độc lập với cỡ mẫu \(n\)! - Đối chiếu với
DCD(LIBLINEAR): Khi cần độ chính xác tối ưu chặt (\(\varepsilon_{\text{opt}} \ll 10^{-4}\)) trên dữ liệu thưa hoặc vừa phải,DCDlưu trực tiếp \(\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i\) trong \(O(d)\) RAM và cập nhật từng tọa độ \(\alpha_i \leftarrow \operatorname{clip}(\alpha_i - \frac{G_i}{\|\mathbf{x}_i\|_2^2 + D_{ii}}, 0, U)\) đạt tốc độ hội tụ tuyến tính \(O(n\bar{s}\log(1/\varepsilon_{\text{opt}}))\) (với \(D_{ii}=0, U=C\) cho \(L_1\)-hinge; \(D_{ii}=\frac{1}{2C}, U=\infty\) cho \(L_2\)-squared hinge). Trong thực nghiệm lab (n=120, C=2),Pegasos(42.7247, \(\|\mathbf{w}\|_2 = 3.942 \le 15.492\)) vàDCD(42.7222) bám sát tối ưuSMO(42.6916) dưới0.08%.
1.4 Dẫn xuất Đối ngẫu Lagrange, Phân hoạch KKT & Giải thuật Platt SMO (R32.4)#
Viết bài toán sơ cấp trong không gian ánh xạ \(\phi(\mathbf{x}_i)\) với các bất đẳng thức chuẩn \(1 - \xi_i - y_i(\mathbf{w}^\top\phi(\mathbf{x}_i) + b) \le 0\) và \(-\xi_i \le 0\). Vì tập nghiệm khả thi nghiêm ngặt luôn tồn tại (\(\mathbf{w}=\mathbf{0}, b=0, \xi_i=2\)), Điều kiện Slater thỏa mãn vô điều kiện (\(C > 0\)), bảo đảm đối ngẫu mạnh (\(p^* = d^*\)).
- Hàm Lagrange & Điều kiện Dừng KKT: Gán nhân tử \(\alpha_i \ge 0\) và \(\mu_i \ge 0\):
\[\mathcal{L}(\mathbf{w}, b, \boldsymbol{\xi}, \boldsymbol{\alpha}, \boldsymbol{\mu}) = \frac{1}{2}\|\mathbf{w}\|_2^2 + C\sum_{i=1}^n \xi_i + \sum_{i=1}^n \alpha_i\Big[1 - \xi_i - y_i\big(\mathbf{w}^\top\phi(\mathbf{x}_i) + b\big)\Big] - \sum_{i=1}^n \mu_i \xi_i.\]Triệt tiêu đạo hàm theo các biến sơ cấp \((\mathbf{w}, b, \boldsymbol{\xi})\):\[\nabla_{\mathbf{w}}\mathcal{L} = \mathbf{0} \implies \mathbf{w} = \sum_{i=1}^n \alpha_i y_i \phi(\mathbf{x}_i), \qquad \frac{\partial \mathcal{L}}{\partial b} = 0 \implies \sum_{i=1}^n \alpha_i y_i = 0, \qquad \frac{\partial \mathcal{L}}{\partial \xi_i} = 0 \implies 0 \le \alpha_i \le C \;(\mu_i = C - \alpha_i).\]
- Bài toán Quy hoạch Toàn phương Đối ngẫu (
Dual QP): Thay ngược các đẳng thức trên vào \(\mathcal{L}\) (số hạng \(\mathbf{w}\) triệt tiêu thành \(-\frac{1}{2}\|\mathbf{w}\|_2^2\), hệ số của \(b\) và \(\xi_i\) bằng0), đặt \(K(\mathbf{x}_i, \mathbf{x}_j) := \langle \phi(\mathbf{x}_i), \phi(\mathbf{x}_j)\rangle\):\[\max_{\boldsymbol{\alpha} \in \mathbb{R}^n} \; W(\boldsymbol{\alpha}) = \sum_{i=1}^n \alpha_i - \frac{1}{2}\sum_{i=1}^n\sum_{j=1}^n \alpha_i \alpha_j y_i y_j K(\mathbf{x}_i, \mathbf{x}_j) \qquad \text{s.t.} \quad 0 \le \alpha_i \le C \; (\forall i),\qquad \sum_{i=1}^n \alpha_i y_i = 0.\]Điểm mấu chốt: toàn bộ dữ liệu chỉ xuất hiện qua tích vô hướng \(K(\mathbf{x}_i, \mathbf{x}_j)\) cả trong huấn luyện lẫn dự báo \(f(\mathbf{x}) = \sum_{i \in \text{SV}} \alpha_i y_i K(\mathbf{x}_i, \mathbf{x}) + b\)!
Phân hoạch 3 Nhóm theo Điều kiện Bù KKT (Complementary Slackness)#
Hai phương trình bù \(\alpha_i^*\big[1 - \xi_i^* - y_i f(\mathbf{x}_i)\big] = 0\) và \((C - \alpha_i^*)\xi_i^* = 0\) chia toàn bộ \(n\) mẫu thành đúng 3 chế độ (đã kiểm chứng đạt duality_gap = 3.97e-04, Non-SV = 93, Free SV = 5, Bounded SV = 22 trong Test 3):
- Nhóm (a) Non-SV (\(\alpha_i^* = 0\)): \(\mu_i^* = C > 0 \implies \xi_i^* = 0 \implies y_i f(\mathbf{x}_i) \ge 1\). Trọng số bằng
0tuyệt đối. - Nhóm (b) Free Margin SV (\(0 < \alpha_i^* < C\)): \(\mu_i^* > 0 \implies \xi_i^* = 0\) và ràng buộc lề hoạt động chặt: \(y_i f(\mathbf{x}_i) = 1\). Các điểm này nằm đúng trên biên \(\mathcal{H}_\pm\) và cho phép khôi phục chính xác hệ số chặn \(b^* = \frac{1}{|\mathcal{S}_{\text{free}}|}\sum_{i \in \mathcal{S}_{\text{free}}}\big(y_i - \sum_{j \in \text{SV}} \alpha_j^* y_j K_{ji}\big)\).
- Nhóm (c) Bounded / Margin-Error SV (\(\alpha_i^* = C\)): \(\mu_i^* = 0 \implies \xi_i^* = 1 - y_i f(\mathbf{x}_i) \ge 0 \implies y_i f(\mathbf{x}_i) \le 1\) (nằm bên trong dải lề hoặc bị phân loại sai, lực kéo bị chặn trần tại \(C\)).
Giải tích Bước 2 Biến Platt SMO (Sequential Minimal Optimization, 1998 — Quy ước +b)#
Cảnh báo Quy ước Dấu: Platt (1998) viết \(f_{\text{Platt}}(\mathbf{x}) = \mathbf{w}^\top\phi(\mathbf{x}) - b_{\text{Platt}}\), còn
LIBSVM/scikit-learnvà chương này dùng \(+b\) (\(f(\mathbf{x}) = \mathbf{w}^\top\phi(\mathbf{x}) + b\)). Mọi công thức dưới đây nhất quán hoàn toàn theo quy ước \(+b\).
Vì ràng buộc \(\sum_i \alpha_i y_i = 0\) không cho phép thay đổi đơn lẻ một biến, SMO tối ưu đồng thời 2 nhân tử \((\alpha_1, \alpha_2)\) dọc đoạn \(\alpha_1 + s\alpha_2 = \alpha_1^{\text{old}} + s\alpha_2^{\text{old}}\) (với \(s := y_1 y_2 \in \{-1, +1\}\)):
- Cận Hộp \([L, H]\) chính xác (hỗ trợ cả trọng số lớp \(C_1, C_2\) bất đối xứng):
- Nếu \(y_1 = y_2\) (\(s=+1\)): \(L = \max(0,\, \alpha_1^{\text{old}} + \alpha_2^{\text{old}} - C_1)\), \(H = \min(C_2,\, \alpha_1^{\text{old}} + \alpha_2^{\text{old}})\).
- Nếu \(y_1 \neq y_2\) (\(s=-1\)): \(L = \max(0,\, \alpha_2^{\text{old}} - \alpha_1^{\text{old}})\), \(H = \min(C_2,\, C_1 + \alpha_2^{\text{old}} - \alpha_1^{\text{old}})\).
-
Độ cong 1D \(\eta_{\text{SMO}}\) & Nhánh Suy biến \(\eta_{\text{SMO}} \le 0\): Đặt sai số \(E_i := f^{\text{old}}(\mathbf{x}_i) - y_i\) và phần dư bất biến \(F_i := \sum_j \alpha_j y_j K_{ij} - y_i\) (chú ý \(E_1 - E_2 \equiv F_1 - F_2\) vì \(b\) triệt tiêu). Đặt:
\[\eta_{\text{SMO}} := K_{11} + K_{22} - 2K_{12} = \|\phi(\mathbf{x}_1) - \phi(\mathbf{x}_2)\|_{\mathcal{H}}^2.\]- Nếu \(\eta_{\text{SMO}} > 0\) (lõm ngặt): \(\alpha_2^{\text{new,unc}} = \alpha_2^{\text{old}} + \frac{y_2(E_1 - E_2)}{\eta_{\text{SMO}}}\), rồi cắt vào \([L, H]\): \(\alpha_2^{\text{new}} = \min(H, \max(L, \alpha_2^{\text{new,unc}}))\).
- Nếu \(\eta_{\text{SMO}} \le 0\) (hai điểm trùng nhau hoặc nhân không
PSD): Cực đại bắt buộc nằm ở hai đầu mút; tính hàm \(\tilde{\psi}(\alpha_2) = (y_2(E_1 - E_2) + \eta_{\text{SMO}}\alpha_2^{\text{old}})\alpha_2 - \frac{1}{2}\eta_{\text{SMO}}\alpha_2^2\) tại \(L\) và \(H\) để chọn biên lớn hơn. 3. Cập nhật \(\alpha_1^{\text{new}}\), Ngưỡng \(b_1, b_2\) & Điều kiện Dừng Keerthi:\[\alpha_1^{\text{new}} = \alpha_1^{\text{old}} + s\big(\alpha_2^{\text{old}} - \alpha_2^{\text{new}}\big),\]\[b_1^{\text{new}} = b^{\text{old}} - E_1 - y_1\Delta\alpha_1 K_{11} - y_2\Delta\alpha_2 K_{12},\qquad b_2^{\text{new}} = b^{\text{old}} - E_2 - y_1\Delta\alpha_1 K_{12} - y_2\Delta\alpha_2 K_{22},\]chọn \(b_1^{\text{new}}\) nếu \(0 < \alpha_1^{\text{new}} < C_1\), \(b_2^{\text{new}}\) nếu \(0 < \alpha_2^{\text{new}} < C_2\), hoặc \(\frac{1}{2}(b_1^{\text{new}} + b_2^{\text{new}})\) nếu cả hai chạm biên. Với chỉ số Keerthi \(b_{\text{low}} = \max_{j \in I_{\text{low}}} F_j\) và \(b_{\text{up}} = \min_{i \in I_{\text{up}}} F_i\), thuật toán dừng đạt chuẩn \(\varepsilon_{\text{tol}}\) khi \(b_{\text{low}} \le b_{\text{up}} + 2\varepsilon_{\text{tol}}\) (WSS3chọn cặp tối đa hóa \((F_j - F_i)^2 / \eta_{\text{SMO}}\)).
1.5 Không gian Hilbert Nhân Tái tạo (RKHS), Định lý Mercer, Định lý Biểu diễn & Các Họ Nhân (R32.5–R32.6)#
-
Điều kiện
PSD& Định lý Mercer (1909): Hàm đối xứng \(K: \mathcal{X} \times \mathcal{X} \to \mathbb{R}\) là nhân hợp lệ khi và chỉ khi với mọi tập hữu hạn \(\{\mathbf{x}_1, \dots, \mathbf{x}_m\}\), ma trận Gram \(\mathbf{K} = [K(\mathbf{x}_i, \mathbf{x}_j)]\) là nửa xác định dương (PSD): \(\mathbf{v}^\top \mathbf{K} \mathbf{v} \ge 0\;\forall \mathbf{v}\). Theo Định lý Moore–Aronszajn, \(K\) cảm sinh duy nhất một không gianRKHS\(\mathcal{H}_K\) thỏa tính chất tái tạo \(\langle f, K(\mathbf{x}, \cdot) \rangle_{\mathcal{H}_K} = f(\mathbf{x})\). Theo Định lý Mercer, trên tập compact \(\mathcal{X}\), \(K\) phân rã phổ qua hàm riêng trực chuẩn \(\{\psi_k\}\) với trị riêng \(\lambda_k \ge 0\):\[K(\mathbf{x}, \mathbf{z}) = \sum_{k=1}^\infty \lambda_k\,\psi_k(\mathbf{x})\psi_k(\mathbf{z}) \implies \phi(\mathbf{x}) = \big(\sqrt{\lambda_k}\psi_k(\mathbf{x})\big)_{k=1}^\infty,\quad \|f\|_{\mathcal{H}_K}^2 = \sum_{k:\lambda_k>0} \frac{\langle f, \psi_k \rangle_{L_2}^2}{\lambda_k}.\]Trong kiểm toán phổ
audit_kernel_psdcủa lab, 7 họ nhân chuẩn (linear,poly,rbf,laplace,hik,chi2_add,chi2_exp) đều đạt \(\lambda_{\min} \ge -5.29\times 10^{-14}\) (PASS), còn nhânsigmoid\(\tanh(\gamma\langle\mathbf{x},\mathbf{z}\rangle + r)\) cho \(\lambda_{\min} = -0.235\) (FAIL — Không PSD). -
Định lý Biểu diễn (Representer Theorem — Schölkopf, Herbrich & Smola, 2001): Xét bài toán tổng quát \(\min_{f \in \mathcal{H}_K} L(\{(\mathbf{x}_i, y_i, f(\mathbf{x}_i))\}_{i=1}^n) + \Omega(\|f\|_{\mathcal{H}_K})\) với \(\Omega\) tăng ngặt. Mọi nghiệm cực tiểu \(f^* \in \mathcal{H}_K\) đều có dạng khai triển hữu hạn \(f^*(\mathbf{x}) = \sum_{i=1}^n c_i K(\mathbf{x}_i, \mathbf{x})\)!
- Chứng minh: Đặt \(\mathcal{H}_\parallel = \operatorname{span}\{K(\mathbf{x}_1,\cdot),\dots,K(\mathbf{x}_n,\cdot)\}\) và phân tách trực giao \(f = f_\parallel + f_\perp\) (\(f_\perp \in \mathcal{H}_\parallel^\perp\)). Nhờ tính tái tạo tại mọi mẫu huấn luyện, \(f(\mathbf{x}_j) = \langle f_\parallel + f_\perp, K(\mathbf{x}_j,\cdot)\rangle = f_\parallel(\mathbf{x}_j) + 0 = f_\parallel(\mathbf{x}_j)\) nên phần mất mát \(L\) giữ nguyên; nhưng theo định lý Pythagoras \(\|f\|_{\mathcal{H}_K}^2 = \|f_\parallel\|_{\mathcal{H}_K}^2 + \|f_\perp\|_{\mathcal{H}_K}^2\), mọi \(f_\perp \neq 0\) đều làm \(\Omega(\|f\|_{\mathcal{H}_K})\) tăng ngặt. Vậy \(f_\perp^* = 0 \implies f^* = f_\parallel^*\). \(\blacksquare\)
-
Bảng Khai triển Không gian Đặc trưng của Các Họ Nhân Chủ chốt:
| Họ Nhân | Biểu thức \(K(\mathbf{x}, \mathbf{z})\) | Ánh xạ Đặc trưng \(\phi(\mathbf{x})\) & Độ phức tạp | Hiện tượng Hình học & Bẫy Vận hành |
|---|---|---|---|
Đa thức (Polynomial) |
\((\gamma_{\text{poly}}\langle\mathbf{x}, \mathbf{z}\rangle + r)^{d_{\text{poly}}}\) | Hạng \(D = \binom{d+d_{\text{poly}}}{d_{\text{poly}}}\). Với \(d_{\text{poly}}=2\): \(\phi(\mathbf{x}) = \big(r, \sqrt{2\gamma_{\text{poly}} r}\,x_j, \gamma_{\text{poly}} x_j^2, \sqrt{2}\gamma_{\text{poly}} x_j x_k\big)^\top\) | Tính được \(K\) trong \(O(d)\) thay vì \(O(d^{d_{\text{poly}}})\); nhưng dễ nổ số học \(10^{22}\) nếu đặc trưng chưa chuẩn hóa hoặc \(d_{\text{poly}}\) lớn. |
Gaussian (RBF) |
\(\exp(-\gamma_{\text{rbf}}\|\mathbf{x}-\mathbf{z}\|_2^2)\) (\(\gamma_{\text{rbf}} = \frac{1}{2\sigma_{\text{rbf}}^2}\)) | Vô hạn chiều (\(\ell_2\)): \(\phi_{\boldsymbol{\alpha}}(\mathbf{x}) = e^{-\gamma_{\text{rbf}}\|\mathbf{x}\|_2^2}\sqrt{\frac{(2\gamma_{\text{rbf}})^{|\boldsymbol{\alpha}|}}{\prod \alpha_j!}}\prod_j x_j^{\alpha_j}\), \(\|\phi(\mathbf{x})\|_2 = 1\) | \(\gamma_{\text{rbf}} \to 0^+\) tiến về nhân tuyến tính (thiếu khớp); \(\gamma_{\text{rbf}} \to \infty\) kéo \(\mathbf{K} \to \mathbf{I}_n\), tạo đảo gai quá khớp quanh từng điểm. |
Chuỗi (String k-spectrum) |
\(\sum_{u \in \Sigma^k} \operatorname{count}(u, s)\operatorname{count}(u, t)\) | Vector tần suất \(k\)-mer trong \(\mathbb{Z}_{\ge 0}^{|\Sigma|^k}\), tính trong \(O(k(|s|+|t|))\) qua trie | PSD tuyệt đối cho chuỗi DNA, log phiên E-Commerce, tên SKU mà không cần tách từ điển thủ công. |
Giao Biểu đồ (HIK) & \(\chi^2\) |
\(K_{\text{HI}} = \sum_j \min(x_j, z_j)\); \(K_{\chi^2}^{\text{add}} = \sum_j \frac{2x_jz_j}{x_j+z_j}\); \(K_{\chi^2}^{\text{exp}} = e^{-\gamma_{\text{rbf}} d_{\chi^2}^2}\) | \(\min(a,b) = \int_0^\infty \mathbb{I}[a\ge u]\mathbb{I}[b\ge u]du\) trong \(L_2([0,\infty))\); \(\chi^2\) là nhân phân phối CND theo Schoenberg |
Cực kỳ tự nhiên cho biểu đồ tần suất hạng mục, vector ảnh BoVW, phân bổ chi tiêu người dùng không âm. |
1.6 Các Mở rộng Trọng yếu: \(\epsilon\)-SVR, \(\nu\)-OCSVM / SVDD, Đa lớp & Cầu nối Hiệu chuẩn ch-07#
- Hồi quy Vector Hỗ trợ \(\epsilon\)-SVR (Vapnik 1995): Thay mất mát bình phương bằng ống không nhạy \(\ell_\epsilon(y_i, f(\mathbf{x}_i)) = \max(0, |y_i - f(\mathbf{x}_i)| - \epsilon_{\text{tube}})\) với cặp biến chùng \((\xi_i, \xi_i^*) \ge 0\) và nhân tử \((\alpha_i, \alpha_i^*) \in [0, C]^2\):
\[\max_{\boldsymbol{\alpha}, \boldsymbol{\alpha}^* \in [0, C]^n} \; -\frac{1}{2}\sum_{i,j}(\alpha_i - \alpha_i^*)(\alpha_j - \alpha_j^*)K_{ij} - \epsilon_{\text{tube}}\sum_i (\alpha_i + \alpha_i^*) + \sum_i y_i(\alpha_i - \alpha_i^*) \quad \text{s.t. } \sum_i(\alpha_i - \alpha_i^*) = 0.\]Khi \(\epsilon_{\text{tube}} > 0\), bù KKT ép \(\alpha_i \alpha_i^* = 0\); mọi điểm nằm gọn trong ống \(|y_i - f(\mathbf{x}_i)| < \epsilon_{\text{tube}}\) bị triệt tiêu (\(\alpha_i = \alpha_i^* = 0\)) tạo độ thưa mô hình, còn điểm ngoại lai bị kẹp lực kéo tối đa tại \(|\alpha_i - \alpha_i^*| \le C\). Trong lab (
+380..+520 USD/MWhgai giá),MAD-calibrated \(\epsilon\)-SVR (\(\epsilon_{\text{tube}} = 2.58\)) hạMAExuống0.76so vớiOLS14.97(19.6xbền vững) với chỉ11.1%vector hỗ trợ! - Phát hiện Bất thường Một lớp (\(\nu\)-OCSVM vs.
SVDD):- Schölkopf \(\nu\)-OCSVM (2001): Tách dữ liệu bình thường khỏi gốc tọa độ \(\mathcal{H}\): \(\min \frac{1}{2}\|\mathbf{w}\|_2^2 + \frac{1}{\nu n}\sum_i \xi_i - \rho\) s.t. \(\langle \mathbf{w}, \phi(\mathbf{x}_i)\rangle \ge \rho - \xi_i\). Bài toán đối ngẫu \(\min_{\boldsymbol{\alpha}} \frac{1}{2}\boldsymbol{\alpha}^\top \mathbf{K}\boldsymbol{\alpha}\) dưới ràng buộc \(0 \le \alpha_i \le \frac{1}{\nu n}, \sum_i \alpha_i = 1\) chứng minh tính chất kép \(\nu\): \(\frac{m_{\text{outliers}}}{n} \le \nu \le \frac{n_{\text{SV}}}{n}\) (
0.079 <= 0.120 <= 0.211trongTest 7). - Tax & Duin
SVDD(2004): Bao dữ liệu vào siêu cầu bán kính nhỏ nhất \(R_{\text{sph}}^2\) tâm \(\mathbf{a}\) (\(\max \sum_i \alpha_i K_{ii} - \boldsymbol{\alpha}^\top \mathbf{K}\boldsymbol{\alpha}\)). Khi \(K(\mathbf{x}_i, \mathbf{x}_i) \equiv 1\) (như nhânRBF), \(\sum \alpha_i K_{ii} = 1\) là hằng số khiếnSVDDtrùng khít tuyệt đối với \(\nu\)-OCSVM (max|alpha_oc - alpha_svdd| = 7.21e-15,agreement = 100.0%).
- Schölkopf \(\nu\)-OCSVM (2001): Tách dữ liệu bình thường khỏi gốc tọa độ \(\mathcal{H}\): \(\min \frac{1}{2}\|\mathbf{w}\|_2^2 + \frac{1}{\nu n}\sum_i \xi_i - \rho\) s.t. \(\langle \mathbf{w}, \phi(\mathbf{x}_i)\rangle \ge \rho - \xi_i\). Bài toán đối ngẫu \(\min_{\boldsymbol{\alpha}} \frac{1}{2}\boldsymbol{\alpha}^\top \mathbf{K}\boldsymbol{\alpha}\) dưới ràng buộc \(0 \le \alpha_i \le \frac{1}{\nu n}, \sum_i \alpha_i = 1\) chứng minh tính chất kép \(\nu\): \(\frac{m_{\text{outliers}}}{n} \le \nu \le \frac{n_{\text{SV}}}{n}\) (
- Phân loại Đa lớp (
OvRvs.OvO): Với \(K_{\text{cls}} \ge 3\) lớp và độ phức tạpSMOthực nghiệm \(O(m^{\alpha_{\text{smo}}})\) (\(\alpha_{\text{smo}} \approx 2.2\)),OvOhuấn luyện \(\binom{K_{\text{cls}}}{2}\) bài toán cân bằng cỡ \(\frac{2n}{K_{\text{cls}}}\), cho tổng thời gian \(O(K_{\text{cls}}^{2-\alpha_{\text{smo}}} n^{\alpha_{\text{smo}}})\) — nhanh hơnOvR(\(O(K_{\text{cls}} n^{\alpha_{\text{smo}}})\)) khi dùng nhân phi tuyến (53.1 msvs.63.7 msở \(K_{\text{cls}}=4\)), đồng thời chia sẻ bộ nhớ SV qua lại. - Cầu nối Hiệu chuẩn
Platt Scalingsangch-07: Lề thô \(f(\mathbf{x})\) của SVM không phải xác suất vì mất mát bản lề đẩy các điểm phân loại đúng co cụm ở \(\pm 1\) và các biến trọng số lớpclass_weightlàm dịch tâm \(f(\mathbf{x})=0\). Chương này chỉ giữ trách nhiệm trích xuất lề ngoài nếp (OOF) hoặc trên tập rời \(\mathcal{D}_{\text{cal}}\) và chuyển giao toàn bộ Newton 2DPlatt(\(\hat{q} = \frac{1}{1+\exp(A_{\text{Platt}}f + B_{\text{Platt}})}\) với mục tiêu làm mượt Laplace) cùngPAVA Isotonic/Cross Venn-Abersvềch-07§2.2.
Trụ cột 2 — Nút thắt Mở rộng \(O(n^2)\)–\(O(n^3)\), Xấp xỉ Nhân (RFF, ORF, QMC, Nyström) & Cầu nối SOTA 2024–2026#
2.1 Bức tường Bộ nhớ Gram \(8n^2\) & Định lý Không thưa Steinwart (2003)#
| Cỡ mẫu \(n\) | Số phần tử Gram \(n^2\) | RAM float64 (\(8n^2\)) |
RAM float32 (\(4n^2\)) |
Khả năng Huấn luyện & Phục vụ Thực tế |
|---|---|---|---|---|
| \(n = 10{,}000\) | \(10^8\) | 800.0 MB |
400.0 MB |
Vừa khít máy trạm / L3-DRAM; SMO chạy mượt trong vài trăm ms. |
| \(n = 100{,}000\) | \(10^{10}\) | 80.0 GB |
40.0 GB |
Vượt ngưỡng workstation 16–64 GB; cache LIBSVM (200 MB = chỉ 250 hàng!) thrash liên tục (\(O(n^{2.3}\text{–}n^3)\)). |
| \(n = 1{,}000{,}000\) | \(10^{12}\) | 8.0 TB |
4.0 TB |
Bất khả thi trên một nút đơn; bắt buộc chuyển sang RFF, Nyström hoặc Falkon đa GPU. |
Về mặt lý thuyết Roofline, tính từng hàng nhân RBF chỉ đạt cường độ số học \(\approx 0.375\text{ FLOP/byte}\) (nghẽn băng thông DRAM trừ khi gom khối GEMM). Quan trọng hơn, Ingo Steinwart (JMLR, 2003) chứng minh rằng với mọi nhân phổ quát (universal kernel như RBF) và lịch chính quy hóa nhất quán Bayes (\(\lambda_n \to 0, \lambda_n n \to \infty\)):
Mọi bài toán thực tế có độ bất định nhãn (\(R^* > 0\)) đều sinh số vector hỗ trợ tăng tuyến tính \(n_{\text{SV}} = \Omega(n)\) (kiểm chứng trên 260 mẫu lab: \(R^*=0.0007 \to 10.4\%\) SV; \(R^*=0.0808 \to 31.5\%\) SV; \(R^*=0.1788 \to \mathbf{47.7\%}\) SV so với \(2R^* = 35.8\%\)). Điều này khóa chặt độ trễ suy luận chính xác ở mức \(O(n_{\text{SV}} \cdot d) = O(n d)\) — không thể đạt < 1 ms trên dữ liệu lớn!
2.2 Đặc trưng Fourier Ngẫu nhiên (RFF, Rahimi & Recht 2007), Phương sai Cặp, ORF & QMC#
-
Định lý Bochner (1933) & Mật độ Phổ Chính xác: Mọi hàm nhân liên tục bất biến tịnh tiến \(k(\mathbf{x}, \mathbf{y}) = \psi(\mathbf{x}-\mathbf{y})\) (chuẩn hóa \(k(\mathbf{0}) = 1\)) là nửa xác định dương khi và chỉ khi nó là biến đổi Fourier của một phân phối xác suất duy nhất \(p(\boldsymbol{\omega})\) trên \(\mathbb{R}^d\):
\[k(\mathbf{x} - \mathbf{y}) = \int_{\mathbb{R}^d} e^{i\boldsymbol{\omega}^\top(\mathbf{x}-\mathbf{y})} p(\boldsymbol{\omega})\, d\boldsymbol{\omega} = \mathbb{E}_{\boldsymbol{\omega} \sim p}\!\Big[\cos\big(\boldsymbol{\omega}^\top(\mathbf{x} - \mathbf{y})\big)\Big].\]- Nhân Gaussian (
RBF) \(k(\boldsymbol{\Delta}) = \exp(-\gamma_{\text{rbf}}\|\boldsymbol{\Delta}\|_2^2)\): Tích phân nghịch đảo theo từng tọa độ \(\frac{1}{2\pi}\int e^{-\gamma_{\text{rbf}}\Delta_j^2 - i\omega_j\Delta_j}d\Delta_j = \frac{1}{\sqrt{4\pi\gamma_{\text{rbf}}}} e^{-\omega_j^2/(4\gamma_{\text{rbf}})}\) cho mật độ phổ chính xác \(\boldsymbol{\omega} \sim \mathcal{N}(\mathbf{0},\; 2\gamma_{\text{rbf}}\mathbf{I}_d)\). - Nhân Laplace (\(L_1\)) \(k(\boldsymbol{\Delta}) = \exp(-\gamma\|\boldsymbol{\Delta}\|_1)\): Tích phân hai phía \(\frac{1}{2\pi}(\frac{1}{\gamma + i\omega_j} + \frac{1}{\gamma - i\omega_j}) = \frac{1}{\pi}\frac{\gamma}{\gamma^2 + \omega_j^2}\) cho tích độc lập \(d\) phân phối \(\operatorname{Cauchy}(0, \gamma)\).
- Nhân Gaussian (
-
Chứng minh Không chệch của Hai Ánh xạ
RFFTường minh (\(D_{\text{out}}\) chiều): Lấy mẫu i.i.d. các hàng tần số \(\boldsymbol{\omega}_r \sim p(\boldsymbol{\omega})\):- (a) Random-Phase Cosine (
Rahimi & Recht 2007): Vẽ pha \(b_r \sim \mathcal{U}[0, 2\pi)\) và đặt \(\mathbf{z}_{\text{cos}}(\mathbf{x}) = \sqrt{\frac{2}{D_{\text{out}}}}\cos(\mathbf{W}\mathbf{x} + \mathbf{b})\). Nhờ đồng nhất thức \(2\cos(u)\cos(v) = \cos(u-v) + \cos(u+v)\) và \(\mathbb{E}_{b_r}[\cos(\theta + 2b_r)] = 0\):\[\mathbb{E}_{\mathbf{W},\mathbf{b}}\big[\mathbf{z}_{\text{cos}}(\mathbf{x})^\top \mathbf{z}_{\text{cos}}(\mathbf{y})\big] = \frac{1}{D_{\text{out}}}\sum_{r=1}^{D_{\text{out}}} \mathbb{E}_{\boldsymbol{\omega}_r}\big[\cos(\boldsymbol{\omega}_r^\top(\mathbf{x}-\mathbf{y}))\big] = k(\mathbf{x}, \mathbf{y}).\] - (b) Paired Sin/Cos (
Sutherland & Schneider 2015): Dùng \(m = D_{\text{out}}/2\) tần số và đặt \(\mathbf{z}_{\text{sc}}(\mathbf{x}) = \frac{1}{\sqrt{m}}[\cos(\mathbf{W}\mathbf{x}),\, \sin(\mathbf{W}\mathbf{x})]^\top \in \mathbb{R}^{D_{\text{out}}}\). Dùng \(\cos(\alpha-\beta) = \cos\alpha\cos\beta + \sin\alpha\sin\beta\):\[\mathbf{z}_{\text{sc}}(\mathbf{x})^\top\mathbf{z}_{\text{sc}}(\mathbf{y}) = \frac{1}{m}\sum_{r=1}^m \cos\big(\boldsymbol{\omega}_r^\top(\mathbf{x}-\mathbf{y})\big) \implies \mathbb{E}\big[\mathbf{z}_{\text{sc}}(\mathbf{x})^\top\mathbf{z}_{\text{sc}}(\mathbf{y})\big] = k(\mathbf{x}, \mathbf{y}), \qquad \|\mathbf{z}_{\text{sc}}(\mathbf{x})\|_2^2 \equiv 1.\]
- (a) Random-Phase Cosine (
-
Định lý Giảm Phương sai
Sutherland & Schneider (UAI 2015): Tại cùng kích thước đặc trưng đầu ra \(D_{\text{out}}\):\[\operatorname{Var}\big(\hat{k}_{\text{cos}, D_{\text{out}}}(\boldsymbol{\Delta})\big) - \operatorname{Var}\big(\hat{k}_{\text{sc}, D_{\text{out}}}(\boldsymbol{\Delta})\big) = \frac{1}{D_{\text{out}}}\left(k(\boldsymbol{\Delta})^2 - \frac{1}{2}k(2\boldsymbol{\Delta})\right) \stackrel{\text{RBF}}{=} \frac{1}{D_{\text{out}}}\,k(\boldsymbol{\Delta})^2\left(1 - \frac{1}{2}k(\boldsymbol{\Delta})^2\right) > 0 \quad \forall \boldsymbol{\Delta}!\]Do đó
Paired Sin/Cosluôn chặt chẽ hơnRandom-Phase Cos, đồng thời giữ chuẩn đơn vị đường chéo chính xác0phương sai! Tiến xa hơn:Orthogonal Random Features (ORF — Yu et al., 2016): Thay ma trận Gaussian i.i.d. bằng khối trực giao Haar \(\mathbf{W}_{\text{ORF}} = \sqrt{2\gamma_{\text{rbf}}}\mathbf{S}\mathbf{Q}\) (\(\mathbf{Q}\) từ phân rã QR, \(s_r \sim \chi_d\)), tạo tương quan âm giữa các tần số giúp giảm thêm MSE bậc \(O(1/d)\) (vàSORFdùng biến đổi Hadamard \(O(D \log d)\)).Quasi-Monte Carlo (Halton/Sobol QMC — Avron et al., 2016): Lấy mẫu chuỗi độ lệch thấp \(\mathbf{u}_r \in (0,1)^d\) qua nghịch đảo Acklam \(\Phi^{-1}(\mathbf{u}_r)\), cải thiện hội tụ từ \(O(D^{-1/2})\) lên gần \(O((\log D)^d / D)\).- Số liệu Kiểm chứng
Test 10(D_out = 64):Random-Phase Cos RMSE = 0.1121(Var = 0.0123,diag_var = 0.0068) \(\to\)Paired Sin/Cos0.0946(Var = 0.0088, sai số chuẩn đường chéo7.77e-16) \(\to\)ORF0.0603(Var = 0.0036) \(\to\)Halton QMC0.0441.
2.3 Xấp xỉ Hạng thấp Nyström & Giao điểm Phổ Yang et al. (2012)#
Thay vì lấy mẫu tần số mù dữ liệu như RFF, phương pháp Nyström (Williams & Seeger, 2000) chọn \(m \ll n\) điểm mốc \(\mathbf{C} \in \mathbb{R}^{m \times d}\) (uniform, cụm k-means của Zhang et al. 2008, hoặc Ridge Leverage Score RLS của Musco & Musco 2017), tính \(\mathbf{K}_{nm} \in \mathbb{R}^{n\times m}\) và phân rã trị riêng \(\mathbf{K}_{mm} = \mathbf{U}_m \boldsymbol{\Lambda}_m \mathbf{U}_m^\top\) với ngưỡng cắt ổn định \(\lambda_j > \epsilon_{\text{eig}}\):
Bù Schur \(\mathbf{K}_{nn} - \tilde{\mathbf{K}}_{nn} \succeq \mathbf{0}\) luôn nửa xác định dương (min_eig = 3.94e-04 >= 0 trong Test 11). Khi suy luận sau khi đã giải trọng số sơ cấp \(\mathbf{w} \in \mathbb{R}^r\), ta gập sẵn ma trận làm trắng một lần thành \(\boldsymbol{\beta} := \mathbf{U}_{m,r}\boldsymbol{\Lambda}_{m,r}^{-1/2}\mathbf{w} \in \mathbb{R}^m\), đưa dự báo \(\hat{f}(\mathbf{x}_*) = \sum_{j=1}^m \beta_j K(\mathbf{x}_*, \mathbf{c}_j) + b\) về đúng \(O(md)\) mà không cần nhân ma trận \(m \times r\) (sai lệch gập trong lab chỉ 6.66e-16!).
- Định lý So sánh
Yang et al. (NeurIPS 2012)— Khi nàoNyströmthắngRFFvà ngược lại:- Khi phổ Gram suy giảm nhanh (dữ liệu phân cụm, chiều hiệu dụng \(d_{\text{eff}}(\lambda) \ll n\)):
Nyströmchiếu trực tiếp lên không gian riêng dữ liệu nên sai số suy giảmO(1/m), đè bẹp tốc độ \(O(1/\sqrt{D})\) củaRFF. Trong lab (84.6%năng lượng phổ tập trung ở top-16, ngân sách32),Nyströmđạt sai số Frobenius Gram0.0465so vớiRFF0.5654(12.2xchính xác hơn!). - Khi phổ phẳng (băng thông rất hẹp \(\gamma_{\text{rbf}}\) lớn) hoặc hệ thống Streaming không lưu dữ liệu mốc:
RFF/ORFchỉ lưu ma trận chiếu tĩnh \(O(Dd)\) (hoặc 1 seed!), hoạt động với bất kỳ nhân bất biến tịnh tiến nào mà không cần giữ bản ghi mẫu trong artifact phục vụ; cònNyströmáp dụng được cho mọi nhânPSDkể cảPolynomial,String,Chi-squared.
- Khi phổ Gram suy giảm nhanh (dữ liệu phân cụm, chiều hiệu dụng \(d_{\text{eff}}(\lambda) \ll n\)):
2.4 Cầu nối SOTA 2024–2026: Falkon Tỷ điểm, Neural Tangent Kernel (NTK) & Chú ý Tuyến tính Hóa Nhân#
- Bộ giải Tỷ điểm
Falkon,EigenPro 3.0,KeOps&RAPIDS cuML:Falkon(Meanti et al., NeurIPS 2020–2025): Giải bài toán Nyström trên \(n = 10^6\text{–}10^9\) điểm bằng Liên hợp Gradient Tiền điều kiện (Preconditioned Conjugate Gradient) dựng tiền điều kiện Cholesky hoàn toàn từ \(\mathbf{K}_{mm}\) kích thước \(m = O(\sqrt{n})\), đạt độ phức tạp \(O(n\sqrt{n}\, d)\) và RAM \(O(n)\) ngoài lõi đa GPU.KeOps&EigenPro 3.0(2023–2026):KeOpsdùng tensor ký hiệu hợp nhất trên SRAM GPU loại bỏ vật chất hóa \(\mathbf{K}_{nn}\), cònEigenPro 3.0tách số tâm nhân \(p\) khỏi \(n\) để huấn luyện Large Kernel Models đa GPU.
- Neural Tangent Kernel (
NTK— Jacot et al. 2018; Chẩn đoán 2024–2026): Mạng nơ-ron \(f(\mathbf{x}; \boldsymbol{\theta}_t)\) tiến hóa dưới dòng gradient tuân theo:\[\frac{df(\mathbf{x}; \boldsymbol{\theta}_t)}{dt} = -\sum_{i=1}^n \Theta_t(\mathbf{x}, \mathbf{x}_i)\frac{\partial \ell(f(\mathbf{x}_i; \boldsymbol{\theta}_t), y_i)}{\partial f}, \qquad \Theta_t(\mathbf{x}, \mathbf{z}) := \big\langle \nabla_{\boldsymbol{\theta}} f(\mathbf{x}; \boldsymbol{\theta}_t),\; \nabla_{\boldsymbol{\theta}} f(\mathbf{z}; \boldsymbol{\theta}_t) \big\rangle.\]Ở chế độ chuẩn hóa rộng vô hạn (Lazy Training), \(\Theta_t \equiv \Theta_0\) đóng băng (lazy_ntk_rel_drift = 0.0070trongTest 12, nghiệm khớp hồi quy nhân trên \(\Theta_0\) tớiMSE = 1.32e-04). Ngược lại, dưới tham số hóa học đặc trưng \(\mu\text{P}\) (Rich Regime), trọng số di chuyển mạnh (rich_ntk_rel_drift = 0.6418, gấp92xchế độ lười!) đẩy Mức độ Tương đồng Nhân–Đích (KTA) tăng từ0.069lên0.119— cung cấp phép kiểm toán trực tiếp xem một mạng sâu có thực sự học biểu diễn mới hay chỉ đang giải lại phương pháp nhânNTK! - Softmax Attention là Hồi quy Nhân Nadaraya–Watson & Mô hình Tuyến tính
FAVOR+/Hedgehog/BASED/LoLCATs: Chú ý chuẩn của Transformer chính xác là bộ làm mượt nhân với nhân mũ \(K_{\exp}(\mathbf{q}_i, \mathbf{k}_j) = \exp(\mathbf{q}_i^\top\mathbf{k}_j / \sqrt{d_k}) = \exp(\|\mathbf{q}_i\|^2/2\sqrt{d_k})\exp(\|\mathbf{k}_j\|^2/2\sqrt{d_k})K_{\text{RBF}}\):\[\operatorname{Attn}(\mathbf{q}_i, \mathbf{K}, \mathbf{V}) = \sum_{j=1}^L \frac{K_{\exp}(\mathbf{q}_i, \mathbf{k}_j)}{\sum_{m=1}^L K_{\exp}(\mathbf{q}_i, \mathbf{k}_m)}\mathbf{v}_j \approx \frac{\boldsymbol{\phi}(\mathbf{q}_i)^\top \overbrace{\big(\sum_{j=1}^L \boldsymbol{\phi}(\mathbf{k}_j)\mathbf{v}_j^\top\big)}^{\mathbf{S}_L \in \mathbb{R}^{D \times d_v}}}{\boldsymbol{\phi}(\mathbf{q}_i)^\top \big(\sum_{j=1}^L \boldsymbol{\phi}(\mathbf{k}_j)\big)}.\]Vìcos/sincủaRFFcó giá trị âm làm nổ mẫu số,Performer FAVOR+(Choromanski et al., ICLR 2021) dùng đồng nhất thức sinh mô-men Gauss \(\mathbb{E}[\exp(\boldsymbol{\omega}^\top\mathbf{z})] = \exp(\|\mathbf{z}\|^2/2)\) xây dựng ánh xạ dương ngặt trực giao \(\boldsymbol{\phi}_{\text{FAVOR+}}(\mathbf{x}) > \mathbf{0}\), rút chi phí chuỗi từ \(O(L^2)\) xuống \(O(L)\) với trạng tháiKVkích thước \(O(1)\) (associative parity diff = 2.22e-15, tăng tốc3.32xtại \(L = 2048\) trong lab). Từ2024–2026,BASEDdùng khai triển Taylor bậc 2 (\([1, \mathbf{x}, \frac{1}{\sqrt{2}}(\mathbf{x}\otimes\mathbf{x})]\),rel_err = 0.069trong lab!), cònHedgehog(ICLR 2024) vàLoLCATs(ICLR 2025) chưng cất trực tiếp ánh xạ dương có trọng số nhọn trênLlama 3.1giữ nguyên chất lượng hồi tưởng ở bộ nhớKVhằng số.
Trụ cột 3 — Hệ Sinh thái 2026, Mẹo Thực chiến R32.7, 4 Tình huống Công nghiệp (E32:E35) & Chống Phản mẫu#
3.1 Năm Mẹo Thực chiến Công nghiệp R32.7#
- Chuẩn hóa Đặc trưng Nội nếp Là Điều kiện Sống còn (Cả Dense lẫn Sparse): Với dữ liệu liên tục cho
RBF/Poly, bắt buộc đi quaYeo-Johnson/log1p+StandardScalerbên trong nếp CV (ch-08); tuyệt đối không fitStandardScalertrước chia CV (ch-04/ch-07) và cấm dùngStandardScaler(with_mean=True)cho ma trậnCSRthưa (TF-IDFphình192 MB -> 80 GBOOM; thay bằngMaxAbsScalerhoặc chuẩn hóa hàng \(L_2\)). - Định cỡ \((C, \gamma_{\text{rbf}})\) theo Sống lưng Chéo & Heuristic Trung vị: So sánh ba chuẩn khởi tạo \(\gamma_{\text{rbf}}\):
scale(\(\frac{1}{d \cdot \operatorname{Var}_{\text{flat}}(X)}\)) vàauto(\(1/d\)) trùng nhau sau chuẩn hóa chuẩn, còn Median Heuristic (\(\gamma_{\text{med}} = 1/\operatorname{median}(\|\mathbf{x}_i-\mathbf{x}_j\|_2^2)\) tính trên mẫu con \(M=350\text{–}2000\)) neo50%phần tử Gram vào \([e^{-1}, 1] = [0.368, 1]\). Vì nhânRBFco giãn bù trừ \((C \to \alpha C, \gamma_{\text{rbf}} \to \gamma_{\text{rbf}}/\alpha)\) ở chế độ \(\gamma\) nhỏ, tối ưu siêu tham sốHPOphải quét lưới logarit hai chiều (C = 2^k, gamma = 2^m) dọc đường sống lưng chéo, đồng thời gắn cổng cảnh báon_SV / n > 0.65chặn đảo ghi nhớ. - Mất cân bằng Lớp (\(C_+, C_-\)) & Cạm bẫy Đếm hai lần: Đặt
class_weight='balanced'tương đương \(C_+ / C_- = n_- / n_+\), kéo siêu phẳngf(x)=0dịch từ mức hậu nghiệm0.50sang \(\approx \pi_+\). Không bao giờ dùngSVC(probability=True)trong sản xuất (chạy vòng lặp 5-fold nội bộ bỏ qua thứ tự thời gian & nhómGroupKFold!). Tối ưu \(C_+/C_-\) choPR-AUC, trích xuất lềOOFsạch rồi mới hiệu chuẩn quach-07trước khi cắt ngưỡng chi phí Bayes \(t^*\). - Lề Thô Không Phải Xác suất: Do
hinge lossphẳng ngoài \(\pm 1\), cầnPlatt Scaling(khi \(n_{\text{cal}} < 500\)) hoặcCross Venn-Abers(CVAP,ch-07) khi có bất đối xứng đuôi để tránh sập lợi nhuận. - Ma trận Chọn Họ Mô hình (
SVMvs.RFF/Nyströmvs.Logisticvs.GBDTch-10):
| Họ Mô hình | Miền Dữ liệu Tối ưu | Độ nhạy Tỷ lệ & NaN |
Độ phức tạp Phục vụ (1 dòng) |
Khi nào Chọn / Từ chối |
|---|---|---|---|---|
Linear SVM (DCD/Pegasos) |
\(d \ge 10^4\) thưa chiều cao (TF-IDF, clickstream băm), \(n\) rất lớn |
Cần MaxAbs / \(L_2\) hàng; không nhận NaN |
\(O(\text{nnz}_x)\) (< 0.05 ms) |
Thắng tuyệt đối văn bản thưa/streaming; từ chối bảng phi tuyến/tương tác chéo. |
Logistic (L2/Firth/FTRL) |
CTR trực tuyến (ch-06), thẻ điểm tín dụng (WoE, ch-08) |
Chuẩn hóa trước khi fit; xuất log-odds hiệu chuẩn sẵn | \(O(d)\) hoặc \(O(\text{nnz}_x)\) (< 0.05 ms) |
Chọn khi cần xác suất chuẩn Log-Loss và mã lý do quy chuẩn SR 11-7. |
Exact RBF/Poly SVM |
\(n \le 10{,}000\text{–}20{,}000\), \(d \le 500\) liên tục trơn | Cực nhạy tỷ lệ (StandardScaler bắt buộc) |
\(O(n_{\text{SV}}\cdot d)\) (2–50+ ms) |
Chọn cho biên vật lý/sinh học/cảm biến cỡ vừa; cấm khi \(n > 20\text{k}\) hoặc SLA < 2 ms. |
RFF/Nyström + DCD/Pegasos |
\(n \in [20\text{k}, 10^7]\), \(d \le 2000\) liên tục / nhúng | Bắt buộc StandardScaler nội nếp |
\(O(Dd)\) / \(O(md)\) (< 0.5 ms, < 1 MB) |
Thay thế Exact Kernel SVM ở quy mô lớn với SLA < 2 ms và RAM giới hạn. |
GBDT (XGB/LGBM/CatBoost, ch-10) |
Dữ liệu bảng hỗn hợp lớn (\(n \ge 5\text{k}\)) | Bất biến co giãn đơn điệu; xử lý NaN trực tiếp |
\(O(T_{\text{trees}} \cdot \text{depth})\) (0.3–3 ms) |
Thống trị dữ liệu bảng kinh doanh nhiều biến phân loại rời rạc & thiếu dữ liệu. |
3.2 Bốn Tình huống Công nghiệp Thực tế (E32:E35 & Miền Trọng điểm)#
- Tình huống 1 — Cá nhân hóa E-Commerce & Xếp hạng Ý định Theo Hành trình Người dùng (
E32:E35):- Bối cảnh: Sau tầng truy xuất ứng viên
ANN(ch-11) trả về \(K_{\text{cand}} = 200\) sản phẩm trên hành trìnhHomepage -> Category -> PDP -> Checkout, tầng xếp hạng giai đoạn 2 cần tính xác suất chuyển đổi dưới SLA< 5 msp99 cho cả slate200ứng viên và< 5 MBRAM trạng thái trên worker CPU. - Thất bại của Exact RBF: Ở \(n = 150{,}000, d = 128\), ma trận Gram đòi
180.0 GBRAM (sập máy tức thì) và khi tỷ lệ SV chạm~32%(\(n_{\text{SV}} = 48{,}000\)), độ trễ slate phình lên300–800 ms. - Giải pháp & Số liệu Workbench: Áp dụng
Paired Sin/Cos RFFvàNyström k-meansgập trọng số +DCD+Platt Calibrationtrên \(\mathcal{D}_{\text{cal}}\) (ch-07) để xếp hạng theo biên lợi nhuận kỳ vọng \(\hat{p}_{\text{cal}} \cdot \text{GrossMargin}\). Kết quả đo được trongsvm_kernels_lab: slate200ứng viên giảm từ2.615 ms(Exact RBF AUC = 0.767) xuống0.245 ms(Paired RFF AUC = 0.779,NDCG@10 = 0.842, chỉ260 KiBở cấu hình150k!) và0.153 ms(Folded Nyström AUC = 0.780,770 KiB), đồng thờiPlattgiảmECEtừ0.085xuống0.081(giá trị giỏ hàng top-10 thực tế đạt $362.55).
- Bối cảnh: Sau tầng truy xuất ứng viên
- Tình huống 2 — Phát hiện Bất thường Thiết bị IoT & Thanh toán (
One-Class SVM/SVDD): Giảm chiều dữ liệu cảm biến 16 kênh xuốngm = 128mốcNyströmtrên thiết bị biên (< 200 KB), khóa \(\nu\) cao hơn tỷ lệ nhiễu nền~1%–2%để ngănn_SV >= nu * nlàm nổ RAM. Khi dùng nhânRBF,OC-SVMvàSVDDđồng thuận100.0%(max|alpha_diff| = 7.21e-15). - Tình huống 3 — Phân loại Danh mục Sản phẩm & Văn bản Thưa
TF-IDF(\(d = 400\text{–}50{,}000\)): Trên mặt cầu đơn vị \(\|\mathbf{x}_i\|_2 = 1\), hai mô tả sản phẩm ít trùng token cómedian ||x_i - x_j||^2 = 2.00. DùngRBFvừa chịu nguy cơ sụp Gram vừa tốn \(O(n^2)\), trong khiLinear DCDtrên ma trận thưa xử lý đúng các phần tử khác0đạt100.0%độ chính xác trong thời gian tuyến tính! - Tình huống 4 — Dự báo Giá Điện Nút Lưới & Chênh lệch Tín dụng Với \(\epsilon\)-SVR: Khi
3%số giờ có gai giá đột biến+380..+520 USD/MWh, mất mát toàn phương củaOLSbị kéo lệch nặng (MAE = 14.97 USD/MWhso với tín hiệu sạch), còn \(\epsilon\)-SVR hiệu chuẩn theoMAD(\(\epsilon_{\text{tube}} = 2.58\)) chỉ mất0.76 USD/MWh(19.6xchính xác hơn) và nén xuống còn11.1%vector hỗ trợ (so với96.7%ở \(\epsilon = 0.05\)).
3.3 Kiến trúc Ngân sách Sản xuất, 8 Phản mẫu & Mã Tham chiếu 2026#
| # | Phản mẫu Công nghiệp (Anti-Pattern) | Triệu chứng Thực địa | Cổng Phát hiện / Ngưỡng | Cách Khắc phục Chuẩn |
|---|---|---|---|---|
| 1 | Nạp thẳng biến lệch tỷ lệ vào RBF/Poly |
Test sụp về mức ngẫu nhiên (50.6% / 57.2%) |
median(K_off_diag) < 1e-6 hoặc > 0.99 |
Bọc log1p/Yeo-Johnson + StandardScaler nội nếp |
| 2 | Fit StandardScaler trước tách CV (Class 3) |
PR-AUC CV phồng giả; rò rỉ \(\gamma_{\text{scale}}\) |
Kiểm toán AST/Pipeline (ch-04/ch-07) |
Đặt scaler & Nyström landmark bên trong CV Pipeline |
| 3 | Gọi StandardScaler(with_mean=True) lên CSR thưa |
Tràn RAM tức thì (192 MB -> 80 GB) |
Kiểm tra issparse(X) trước khi chọn scaler |
Dùng MaxAbsScaler, with_mean=False, hoặc chuẩn hóa \(L_2\) |
| 4 | Cặp \((C, \gamma_{\text{rbf}})\) quá cao tạo Đảo ghi nhớ | Train 100%, Test rớt về đa số (55.6%) |
n_SV / n > 0.65 (cảnh báo) / > 0.85 (chặn) |
Quét lưới log theo đường chéo \((C, \gamma_{\text{rbf}})\), giám sát n_SV/n |
| 5 | Dùng Exact RBF khi \(n > 20\text{k}\) hoặc SLA < 5 ms |
OOM 80–180 GB hoặc vượt độ trễ slate |
Benchmark p99 vượt SLA; \(n_{\text{SV}} > 5{,}000\) | Chuyển sang Paired RFF / Folded Nyström + DCD/Pegasos |
| 6 | Lấy lề thô làm xác suất hoặc bật SVC(probability=True) |
Lỗi ECE cao, rò rỉ thời gian CV |
Kiểm định ECE/ACE/smECE* (ch-07) |
Đặt probability=False, hiệu chuẩn OOF Platt/CVAP (ch-07) |
| 7 | Dùng RBF trên TF-IDF \(d \ge 10^4\) thưa |
Huấn luyện nhiều giờ nhưng thua tuyến tính | IQR(||dx||^2) < 0.1 quanh 2.00 |
Mặc định dùng Linear DCD (LIBLINEAR) hoặc Pegasos |
| 8 | Giữ mặc định \(\epsilon = 0.1\) ở SVR hay \(\nu\) mù ở OC-SVM |
96.7% SV hoặc nổ báo động giả |
n_SV / n > 0.60 trong SVR; sai lệch \(\nu\) |
Đặt \(\epsilon_{\text{tube}} \propto \text{MAD}\) hoặc chuẩn hóa \(y\); chỉnh \(\nu\) theo tỷ lệ nhiễu |
from __future__ import annotations
import time
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.frozen import FrozenEstimator
from sklearn.kernel_approximation import Nystroem, RBFSampler
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PowerTransformer, StandardScaler
from sklearn.svm import LinearSVC, SVC
def train_primal_pegasos(
X: np.ndarray,
y_pm1: np.ndarray,
lam: float = 0.05,
n_steps: int = 800,
seed: int = 42,
) -> tuple[np.ndarray, float]:
"""Primal Pegasos stochastic subgradient solver with exact 1/sqrt(lam) ball projection."""
rng = np.random.default_rng(seed)
n, d = X.shape
w = np.zeros(d, dtype=np.float64)
b = 0.0
radius = 1.0 / np.sqrt(lam)
for t in range(1, n_steps + 1):
i = int(rng.integers(0, n))
eta = 1.0 / (lam * t)
margin = y_pm1[i] * (float(X[i] @ w) + b)
w *= 1.0 - eta * lam
if margin < 1.0:
w += eta * y_pm1[i] * X[i]
b += eta * 0.2 * y_pm1[i]
norm_w = float(np.linalg.norm(w))
if norm_w > radius:
w *= radius / norm_w
assert float(np.linalg.norm(w)) <= radius + 1e-12
return w, b
def benchmark_exact_vs_nystrom_rff_and_platt(seed: int = 42) -> dict[str, float]:
"""Compare Exact RBF SVC against RFF/Nystrom linear approximations + disjoint Platt."""
rng = np.random.default_rng(seed)
n_tot = 2200
X = rng.normal(0.0, 1.0, size=(n_tot, 12))
# Skewed monetary column to verify PowerTransformer + StandardScaler pipeline discipline
X[:, 0] = np.exp(2.0 + 1.1 * X[:, 0])
score_true = 1.3 * np.sin(X[:, 1]) + 0.9 * (X[:, 2] ** 2) - 0.7 * np.log1p(X[:, 0]) + 1.1 * X[:, 3]
y = (rng.uniform(size=n_tot) < 1.0 / (1.0 + np.exp(-score_true))).astype(np.int64)
X_tr, y_tr = X[:1200], y[:1200]
X_cal, y_cal = X[1200:1600], y[1200:1600]
X_te, y_te = X[1600:], y[1600:]
prep = Pipeline([("yj", PowerTransformer()), ("sc", StandardScaler())])
exact_pipe = Pipeline([("prep", prep), ("svc", SVC(C=1.5, kernel="rbf", gamma="scale"))])
rff_pipe = Pipeline(
[
("prep", prep),
("rff", RBFSampler(gamma="scale", n_components=256, random_state=seed)),
("clf", LinearSVC(C=0.5, dual="auto", max_iter=3000, random_state=seed)),
]
)
nys_pipe = Pipeline(
[
("prep", prep),
("nys", Nystroem(kernel="rbf", gamma=0.1, n_components=128, random_state=seed)),
("clf", LinearSVC(C=0.5, dual="auto", max_iter=3000, random_state=seed)),
]
)
exact_pipe.fit(X_tr, y_tr)
rff_pipe.fit(X_tr, y_tr)
nys_pipe.fit(X_tr, y_tr)
# Measure inference latency on test batch: Exact O(n_sv * d) vs RFF/Nystrom O(m * d)
t0 = time.perf_counter()
exact_scores = exact_pipe.decision_function(X_te)
exact_infer_ms = (time.perf_counter() - t0) * 1000.0
t1 = time.perf_counter()
_ = nys_pipe.decision_function(X_te)
nys_infer_ms = (time.perf_counter() - t1) * 1000.0
# Disjoint Platt calibration over raw Nystrom SVM margins on D_cal
cal_nys = CalibratedClassifierCV(FrozenEstimator(nys_pipe), method="sigmoid").fit(X_cal, y_cal)
p_uncal_raw = 1.0 / (1.0 + np.exp(-nys_pipe.decision_function(X_te)))
p_cal_platt = cal_nys.predict_proba(X_te)[:, 1]
w_peg, _ = train_primal_pegasos(prep.fit_transform(X_tr), 2.0 * y_tr - 1.0)
return {
"pegasos_w_norm": round(float(np.linalg.norm(w_peg)), 4),
"exact_auc": round(float(roc_auc_score(y_te, exact_scores)), 4),
"rff_auc": round(float(roc_auc_score(y_te, rff_pipe.decision_function(X_te))), 4),
"nys_auc": round(float(roc_auc_score(y_te, p_cal_platt)), 4),
"exact_infer_ms": round(exact_infer_ms, 2),
"nys_infer_ms": round(nys_infer_ms, 2),
"nys_brier_uncal": round(float(brier_score_loss(y_te, p_uncal_raw)), 5),
"nys_brier_platt": round(float(brier_score_loss(y_te, p_cal_platt)), 5),
}
if __name__ == "__main__":
print("SVM / RFF / Nystrom / Platt:", benchmark_exact_vs_nystrom_rff_and_platt())
Trụ cột 4 — Thực hành Lab 09 (svm_kernels_lab) & Kiểm định 14 Hợp đồng pytest#
4.1 Cấu trúc Gói & Hợp đồng Môi trường Sạch#
Toàn bộ thuật toán từ Ng–Jordan, Pegasos, DCD, Platt SMO, epsilon-SVR, nu-OCSVM/SVDD, OvO/OvR, PlattCalibrator, kiểm toán Mercer PSD, RFF/ORF/Halton-QMC, Nyström, NTK/KTA, đến FAVOR+/Taylor-2 đều được cài đặt từ con số 0 chỉ bằng Python stdlib + NumPy + Pandas + Pydantic v2 (uv.lock), kèm kiểm soát AST bảo mật deserialization (0 import pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal):
ch09-svm-and-kernels-workbench/
├── pyproject.toml
├── README.md
├── artifacts/
│ └── ch09_workbench_results.json
├── src/
│ └── svm_kernels_lab/
│ ├── __init__.py
│ ├── primal_and_dual_svm.py
│ └── kernels_and_approximations.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_svm_kernels_lab.py
4.2 Đồng bộ Kết quả Thực nghiệm CLI (artifacts/ch09_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 --output artifacts/ch09_workbench_results.json
Báo cáo artifacts/ch09_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) |
Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_ng_jordan_crossover (GNB O(log d) vs SVM O(d)) |
n=12: 14.6% vs 41.9% (n=320 -> 1.1%) |
ok — GNB (0.146) thắng tuyệt đối ở cỡ mẫu nhỏ n=12, nhưng Linear DCD đảo chiều ở n=320 (0.011 < GNB 0.018, LDA 0.008). |
kpi_smo_kkt_and_duality_gap (Platt SMO & Pegasos) |
gap 3.97e-04 (5 Free / 22 Bnd SV) |
ok — Primal = 42.6916, Dual = 42.6912, Non-SV = 93 (max_kkt_viol = 1.16e-04); Pegasos obj = 42.7247 (||w|| = 3.942 <= 15.492). |
kpi_rbf_scaling_and_island_trap (R32.7 Bẫy Tỷ lệ & Đảo) |
50.6% -> 79.4% (Island SV=100%) |
critical — Không chuẩn hóa khiến gamma='auto' kéo K -> I_n (median K = 0.0, test 50.6%), gamma='scale' đạt 57.2%; đảo (C=1000, gamma=10) khóa 100.0% SV (train 100.0% vs test 55.6%). |
kpi_gram_wall_and_steinwart (Bức tường 8n^2 & Steinwart) |
80 GB (100k) (SV 47.7% vs 2R* 35.8%) |
warn — Gram float64 đòi 800 MB (10k), 80 GB (100k), 8 TB (1M); khi \(R^*\) tăng 0.0007 -> 0.081 -> 0.179, tỷ lệ SV nhảy 10.4% -> 31.5% -> 47.7%. |
kpi_rff_nystrom_yang_tradeoff (RFF/ORF/QMC vs Nyström) |
Nys 0.046 vs RFF 0.565 (Rel Frob Err) |
ok — Tại D_out=64: Var(Paired)=0.0088 < Var(Cos)=0.0123 (diag err=7.77e-16), ORF RMSE=0.0603, Halton QMC=0.0441; trên cụm 84.6% top-16, Nyström thắng 0.046 vs 0.565 (gập trọng số lệch 6.66e-16). |
kpi_ecom_platt_and_linear_attn (E32:E35 + NTK + FAVOR+) |
ECE 0.085 -> 0.081 (FAVOR+ 3.3x @ L=2048) |
ok — E-Com slate 200 items: Exact 2.615 ms (AUC 0.767, 180 GB @ 150k) vs RFF 0.245 ms (AUC 0.779, NDCG@10 0.842, 260 KiB) vs Nyström 0.153 ms (AUC 0.780, 770 KiB); Rich KTA 0.069 -> 0.119; FAVOR+ khớp 2.22e-15. |
4.3 Hợp đồng 14 Kiểm thử Tự động pytest (tests/test_svm_kernels_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_01_generative_vs_discriminative_ng_jordan_crossover |
Kiểm chứng SVMConfig (extra="forbid"), GNB thắng ở n=12 (O(log d)) và Linear DCD đảo chiều thắng ở n=240 (O(d)). |
| 2 | test_02_linear_svm_geometry_pegasos_ball_and_dcd_equivalence |
Khẳng định coef_.flags.writeable == False, ||w||_2 <= 1/sqrt(lam), geom_margin = 1/||w||_2, bất biến tịnh tiến +500 của b, và DCD/Pegasos khớp SMO sơ cấp. |
| 3 | test_03_platt_smo_kkt_three_way_partition_and_duality_gap |
Khẳng định duality_gap < 1e-3, sum(alpha_i y_i) = 0, phân hoạch 3 nhóm KKT chuẩn xác và nhánh eta_SMO = 0 trong smo_two_variable_step. |
| 4 | test_04_mercer_psd_audit_poly_rbf_hik_chi2_and_string_kernels |
Khẳng định 7 họ nhân + string_spectrum_kernel đều PSD, vạch trần sigmoid có min_eig < -1e-4, và khớp explicit_poly2_feature_map tới 1e-11. |
| 5 | test_05_rbf_scaling_catastrophe_and_c_gamma_memorization_islands |
Tái tạo K -> I_n (median_k < 1e-6) khi quên chuẩn hóa, phục hồi với log1p + StandardScaler + median, và kiểm tra đảo ghi nhớ sv_ratio > 0.85. |
| 6 | test_06_epsilon_svr_tube_sparsity_and_outlier_clamping |
Khẳng định \(\alpha_i \alpha_i^* = 0\), \(\sum(\alpha_i-\alpha_i^*)=0\), MAD-\(\epsilon\) nén SV < 0.45 (vs > 0.80 ở eps=0.05) và thắng OLS >10x trước gai +400. |
| 7 | test_07_one_class_svm_vs_svdd_nu_bounds_and_rbf_equivalence |
Kiểm chứng outlier_frac <= nu <= sv_frac và đồng nhất nghiệm max|alpha_oc - alpha_svdd| < 1e-4 (100% đồng thuận dự báo) trên RBF. |
| 8 | test_08_multiclass_ovo_vs_ovr_and_oof_platt_calibration_bridge |
Khẳng định OvO tạo đúng \(K(K-1)/2 = 6\) cặp (>90% acc) và PlattCalibrator trên lề ngoài cắt giảm mạnh ECE thô. |
| 9 | test_09_gram_byte_footprint_and_steinwart_nonsparsity_theorem |
Khẳng định 800 MB, 80 GB, 8 TB cho 10k/100k/1M và tỷ lệ SV tăng theo \(R^*\) tiến gần \(2R^*\) (> 0.30). |
| 10 | test_10_rff_bochner_unbiasedness_paired_variance_orf_and_qmc |
Khẳng định Paired Sin/Cos giữ chuẩn đơn vị < 1e-12, phương sai nhỏ hơn ngặt Cos ở cùng D_out, ORF/Halton QMC hạ RMSE, và Laplace Cauchy không chệch. |
| 11 | test_11_nystrom_low_rank_psd_folding_and_yang_spectral_crossover |
Khẳng định Nyström thắng RFF trên phổ suy giảm nhanh (>70% top-16), bù Schur >= -1e-9, và gập trọng số khớp < 1e-11. |
| 12 | test_12_ntk_kta_drift_and_softmax_favor_plus_taylor_attention |
Khẳng định NTK PSD, chế độ giàu tăng KTA với trôi > 3x chế độ lười; FAVOR+ > 0 khớp nhân kết hợp < 1e-11 và tăng tốc tại L = 2048. |
| 13 | test_13_ecommerce_personalization_rff_nystrom_and_sparse_text |
Khẳng định RFF/Nyström vượt 0.72 AUC, nhanh hơn Exact RBF trên slate 200 items, Platt giảm ECE, và TF-IDF tập trung quanh ||dx||^2 ~ 2.0. |
| 14 | test_14_cli_demo_workbench_json_and_zero_forbidden_imports |
Chạy run_lab_demo.py (returncode == 0), kiểm tra 6 KPI, 4 bar, 4 bảng và quét AST bảo mật deserialization khẳng định 0 import không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bộ Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Cortes, C., & Vapnik, V. (1995); Platt, J. C. (1998); Keerthi, S. S., et al. (2001); Fan, R.-E., et al. (
LIBSVM, JMLR 2005); Hsieh, C.-J., et al. (LIBLINEAR DCD, ICML 2008); Shalev-Shwartz, S., et al. (Pegasos, Math. Program. 2011).
Vì sao quan trọng: Thiết lập toàn bộ nền tảng tối ưu sơ cấp–đối ngẫuKKT, thuật toánSMO/WSS3và bước nhảy từ độ phức tạp theo \(n\) sang \(O(1/(\lambda\varepsilon_{\text{opt}}))\) cho hệ thống tuyến tính lớn. - Ng, A. Y., & Jordan, M. I. (2001); Schölkopf, B., Herbrich, R., & Smola, A. J. (2001); Steinwart, I. (JMLR 2003).
Vì sao quan trọng: Khóa ranh giới \(O(\log d)\) vs. \(O(d)\) giữa Sinh và Phân biệt, Định lý Biểu diễn trongRKHS, và định lý \(n_{\text{SV}}/n \to 2R^*\) giải thích nút thắt suy luận củaExact SVM. - Rahimi, A., & Recht, B. (NeurIPS 2007); Sutherland, D. J., & Schneider, J. (UAI 2015); Yu, F. X., et al. (
ORF, NIPS 2016); Avron, H., et al. (QMC, JMLR 2016).
Vì sao quan trọng: Đặt nền móngBochner RFF, chứng minhPaired Sin/Cosưu việt tuyệt đối về phương sai, và khởi nguồn giảm phương sai trực giao/giả ngẫu nhiên. - Williams, C., & Seeger, M. (NIPS 2000); Yang, T., et al. (NeurIPS 2012); Musco, C., & Musco, C. (NeurIPS 2017); Meanti, G., et al. (
Falkon, NeurIPS 2020–2025).
Vì sao quan trọng: Phân định chính xác khi nàoNyströmvượtRFFnhờ suy giảm phổ và mở rộng phương pháp nhân tới quy mô tỷ điểm trên GPU. - Jacot, A., et al. (
NTK, NeurIPS 2018); Choromanski, K., et al. (Performer FAVOR+, ICLR 2021); Zhang, M., et al. (Hedgehog, ICLR 2024); Arora, S., et al. (BASED, ICML 2024); Zhang, M., et al. (LoLCATs, ICLR 2025).
Vì sao quan trọng: Kết nối trực tiếp lý thuyết nhân cổ điển với hai trụ cột Học sâu 2024–2026: chẩn đoánNTK/KTAvà chuyển đổiSoftmax Attentionsang chú ý tuyến tính \(O(L)\) trênLlama 3.1. - Schölkopf, B., et al. (
OC-SVM, 2001); Tax, D., & Duin, R. (SVDD, 2004); Hsu, C.-W., Chang, C.-C., & Lin, C.-J. (LIBSVM Practical Guide); Lin, H.-T., Lin, C.-J., & Weng, R. C. (Platt, 2007).
Vì sao quan trọng: Quy chuẩn hóa thực hành chọn \((C, \gamma_{\text{rbf}})\), mở rộng phát hiện bất thường và hiệu chuẩn xác suất tương thíchch-07.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Tại sao ở \(n = 12\) (\(d = 36\)),
GNBchỉ sai14.6%trong khiLinear SVMsai41.9%, nhưng ở \(n = 320\) thìLinear DCDđạt1.1%vượtGNB(1.8%)? - Q2: Chứng minh vì sao chuẩn hóa \(\min_i y_i(\mathbf{w}^\top\mathbf{x}_i + b) = 1\) dẫn tới \(\min \frac{1}{2}\|\mathbf{w}\|_2^2\), vì sao không được phạt \(b\), và vì sao
Pegasosgiữ nghiệm trong quả cầu \(\|\mathbf{w}\|_2 \le 1/\sqrt{\lambda}\)? - Q3: Trình bày phân hoạch
3nhómKKT(93Non-SV,5Free SV,22Bounded SV) và giải thích cáchPlatt SMOxử lý trường hợp suy biến \(\eta_{\text{SMO}} \le 0\). - Q4: Dùng phép chiếu trực giao chứng minh Định lý Biểu diễn trong
RKHS, chỉ ra vì sao nhânsigmoidvi phạm Mercer (min_eig = -0.235), và phân tích hình học của \(\gamma_{\text{rbf}} \to 0\) vs. \(\gamma_{\text{rbf}} \to \infty\). - Q5: Vì sao quên chuẩn hóa
cart_value_usdkhiếngamma='auto'chomedian K = 0.0(test 50.6%) vàgamma='scale'làm mất9biến tỷ lệ (57.2%)? Khi nào dùngMADcho \(\epsilon\)-SVR (11.1%SV vs.96.7%) và khi nàoSVDDtrùngnu-OCSVM? - Q6: Trình bày bùng nổ bộ nhớ \(8n^2\) (
80 GB@100k,8 TB@1M) và cơ chế khiến Định lýSteinwart (2003)buộc \(n_{\text{SV}}/n \to 2R^*\) (47.7%ở \(R^* = 0.179\)). - Q7: Chứng minh bất đẳng thức phương sai Sutherland–Schneider cho
Paired Sin/Cos(0.0088 < 0.0123) ở cùngD_out, và lý giải kết quả Yang et al. khiNyströmđạt lỗi0.046so vớiRFF0.565trên cụm phổ suy giảm nhanh. - Q8: Giải thích sự khác biệt giữa xếp hạng thô vs.
Platt-hiệu chuẩn trên E-Commerce (E32:E35,0.245 ms,260 KiB), sự tăng trưởngKTAtrongNTKgiàu (0.069 -> 0.119), và vì saoFAVOR+phải dùng ánh xạ mũ dương trực giao thay chocos/sin.
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 log-odds tuyến tínhGNB/LDAvà cận \(O(\log d)\) Ng–Jordan; kiểm chứngsimulate_ng_jordan_crossover, quả cầuPegasos, và bất biến tịnh tiến+500ởLinearSVMPrimal. - Bài tập 2 (
20%): Dẫn xuất đầy đủ đối ngẫu Lagrange và công thức 2 biếnPlatt SMO(quy ước+b); kiểm chứngKernelSMOSolver(duality_gap = 3.97e-04, 3 nhóm KKT) và nhánh \(\eta_{\text{SMO}} = 0\) trênsmo_two_variable_step. - Bài tập 3 (
15%): Chứng minh Định lý Biểu diễn, khai triểnexplicit_poly2_feature_map, kiểm toánaudit_kernel_psdtrên 8 họ nhân (sigmoidthất bại ở-0.235), và tái tạo sụp đổ tỷ lệ & đảo ghi nhớ quarun_scaling_and_island_diagnostics. - Bài tập 4 (
15%): Chứng minh \(\alpha_i \alpha_i^* = 0\) trong \(\epsilon\)-SVR, tính chất kép \(\nu\) và đồng nhấtRBFgiữanu-OCSVM&SVDD; chạyrun_svr_and_ocsvm_casesvà so sánhOvOvs.OvR. - Bài tập 5 (
15%): Chứng minh mật độ phổBochner(RBF/Laplace), bất đẳng thức phương saiPaired Sin/Cos, và công thức gậpNyström; chạyrun_steinwart_nonsparsity_experiment,benchmark_rff_variants, vàcompare_nystrom_vs_rff. - Bài tập 6 (
20%): Phân tích tập trung khoảng cáchTF-IDFtrên mặt cầu đơn vị, chạyrun_ecommerce_and_sparse_cases(E32:E35),run_ntk_and_kta_bridge,run_softmax_attention_kernel_bridge, và vượt qua trọn bộ14/14kiể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ẽ mọi định lý không nhảy bước (Ng–Jordan, lề chính tắc, Pegasos \(1/\sqrt{\lambda}\), đối ngẫu Lagrange + 3 nhóm KKT + Platt SMO \(\eta_{\text{SMO}} \le 0\), Mercer + Representer, Bochner RFF + Sutherland–Schneider + Nyström gập trọng số, FAVOR+); gói svm_kernels_lab đạt 14/14 pytest với 0 import deserialization không an toàn (Test 14); đồng bộ chuẩn xác toàn bộ số liệu workbench_panels. |
| Senior Standard | 75–89% | Triển khai thông suốt 14/14 pytest thuần NumPy/Pandas/Pydantic, nhưng giải thích còn thiếu độ sâu ở nhánh \(\eta_{\text{SMO}} \le 0\), định lý Steinwart \(2R^*\), điều kiện crossover Yang et al., hoặc sự chuyển pha Lazy vs. Rich NTK. |
| Needs Remediation | < 75% | Phạt nhầm hệ số chặn \(b\); đưa dữ liệu chưa chuẩn hóa vào RBF/Poly; dùng StandardScaler(with_mean=True) lên CSR thưa; triển khai Exact RBF khi \(n > 20\text{k}\) và SLA < 5 ms; bỏ qua hiệu chuẩn ngoài nếp (ch-07) trước xếp hạng GMV; hoặc để lọt pickle/joblib (CWE-502) trong lab. |
RBF Kernel Off-Diagonal RMSE at Equal Output Dim D_out=64 (RFF vs ORF vs QMC)
RBF Feature Scaling Catastrophe & High-(C, gamma) Memorization Island Accuracy
E-Commerce Personalization (E32:E35): Exact RBF SMO vs Paired RFF vs Nystrom Inference
Outlier Spikes (+400 USD/MWh): OLS vs Tight-eps SVR vs Calibrated-MAD eps-SVR MAE
Mercer Kernel PSD Spectral Verification (Gram Matrix Eigenvalue Bounds)
| kernel_name | min_eigenvalue | max_eigenvalue | mercer_verdict |
|---|---|---|---|
| linear | -3.494e-14 | 126.858 | PASS (Mercer PSD) |
| poly | -5.288e-14 | 329.008 | PASS (Mercer PSD) |
| rbf | 1.947e-03 | 13.962 | PASS (Mercer PSD) |
| laplace | 1.432e-01 | 11.806 | PASS (Mercer PSD) |
| hik | 4.584e-02 | 83.597 | PASS (Mercer PSD) |
| chi2_add | 2.761e-09 | 105.786 | PASS (Mercer PSD) |
| chi2_exp | 1.090e-03 | 19.807 | PASS (Mercer PSD) |
| sigmoid | -2.351e-01 | 35.042 | FAIL (Indefinite) |
Steinwart Theorem (2003): Support Vector Fraction n_SV / n -> 2 R^*
| bayes_regime | bayes_risk_r_star | theoretical_2r_star | empirical_sv_fraction |
|---|---|---|---|
| separable_low_risk | 0.0007 | 0.0014 | 0.1038 (27/260) |
| moderate_overlap | 0.0808 | 0.1615 | 0.3154 (82/260) |
| noisy_overlap | 0.1788 | 0.3576 | 0.4769 (124/260) |
Softmax Kernel Attention O(L^2) vs Positive Orthogonal FAVOR+ O(L) Crossover
| seq_length | exact_softmax_ms | favor_linear_ms | speedup |
|---|---|---|---|
| L = 256 | 1.249 ms | 2.032 ms | 0.61x |
| L = 1024 | 12.345 ms | 8.363 ms | 1.48x |
| L = 2048 | 71.667 ms | 21.586 ms | 3.32x |
Industry Production Benchmarks (E-Com E32:E35, Sparse Text, OC-SVM/SVDD, NTK)
| scenario | naive_or_exact_baseline | sota_remediation | verified_check |
|---|---|---|---|
| E-Com Personalization (E32:E35) | Exact RBF AUC 0.767 / 150k RAM=180 GB | RFF AUC 0.779 (260 KiB), Nys 0.780 | Platt ECE 0.085 -> 0.081 |
| Sparse Catalog Text (d=400) | RBF auto Acc 100.0% (||dx||^2=2.00) | Linear DCD Acc 100.0% (323.03 ms) | LINEAR_WINS_UNIT_SPHERE |
| OC-SVM vs SVDD (RBF nu=0.12) | Outliers 0.079 <= nu <= SV 0.211 | max|alpha_oc - alpha_svdd| = 7.21e-15 | Agreement 100.0% |
| NTK & KTA (2-Layer tanh MLP) | Lazy Drift=0.0070 (KTA=0.073) | Rich Drift=0.6418 (KTA 0.069->0.119) | NTK PSD=True |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/ch09-svm-and-kernels-workbench
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "svm-kernels-lab"
version = "0.1.0"
description = "Stage 5B Production Workbench for Generative vs Discriminative SVMs, Pegasos, DCD, Platt SMO, KKT Partitions, Mercer RKHS, epsilon-SVR, OC-SVM/SVDD, RFF/ORF/QMC, Nystrom, NTK, and Kernelized Linear Attention (T1-P2-U04)."
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"
"""svm_kernels_lab: First-Principles SVMs, SMO, Mercer RKHS, RFF/ORF/QMC, Nystrom & SOTA Kernel Bridges."""
from svm_kernels_lab.kernels_and_approximations import (
HaltonQMCRFF,
NystromFeatures,
OrthogonalRandomFeatures,
PairedSinCosRFF,
RandomPhaseCosRFF,
audit_kernel_psd,
benchmark_rff_variants,
compare_nystrom_vs_rff,
compute_gram_memory_footprint,
explicit_poly2_feature_map,
run_ecommerce_and_sparse_cases,
run_full_ch09_benchmarks,
run_ntk_and_kta_bridge,
run_scaling_and_island_diagnostics,
run_softmax_attention_kernel_bridge,
run_steinwart_nonsparsity_experiment,
run_svr_and_ocsvm_cases,
string_spectrum_kernel,
)
from svm_kernels_lab.primal_and_dual_svm import (
EpsilonSVR,
GaussianNaiveBayesClassifier,
KernelSMOSolver,
LinearSVMPrimal,
MulticlassSVM,
OneClassSVMSolver,
PlattCalibrator,
ShrinkageLDAClassifier,
SVDDSolver,
SVMConfig,
compute_ece,
compute_median_heuristic_gamma,
evaluate_kernel_matrix,
resolve_gamma,
simulate_ng_jordan_crossover,
smo_two_variable_step,
)
__all__ = [
"EpsilonSVR",
"GaussianNaiveBayesClassifier",
"HaltonQMCRFF",
"KernelSMOSolver",
"LinearSVMPrimal",
"MulticlassSVM",
"NystromFeatures",
"OneClassSVMSolver",
"OrthogonalRandomFeatures",
"PairedSinCosRFF",
"PlattCalibrator",
"RandomPhaseCosRFF",
"SVDDSolver",
"SVMConfig",
"ShrinkageLDAClassifier",
"audit_kernel_psd",
"benchmark_rff_variants",
"compare_nystrom_vs_rff",
"compute_ece",
"compute_gram_memory_footprint",
"compute_median_heuristic_gamma",
"evaluate_kernel_matrix",
"explicit_poly2_feature_map",
"resolve_gamma",
"run_ecommerce_and_sparse_cases",
"run_full_ch09_benchmarks",
"run_ntk_and_kta_bridge",
"run_scaling_and_island_diagnostics",
"run_softmax_attention_kernel_bridge",
"run_steinwart_nonsparsity_experiment",
"run_svr_and_ocsvm_cases",
"simulate_ng_jordan_crossover",
"smo_two_variable_step",
"string_spectrum_kernel",
]
"""Primal & Dual SVM Solvers, Generative Baselines, SMO, KKT Audits, SVR, OCSVM/SVDD & Calibration Bridge (T1-P2-U04)."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
class SVMConfig(BaseModel):
"""Strict configuration contract for SVM and kernel solvers."""
model_config = ConfigDict(extra="forbid")
c_reg: float = Field(default=1.0, gt=0.0)
tol: float = Field(default=1e-4, gt=0.0)
max_iter: int = Field(default=3000, ge=10)
kernel: Literal[
"linear",
"poly",
"rbf",
"laplace",
"hik",
"chi2_add",
"chi2_exp",
"string_spectrum",
"sigmoid",
] = "rbf"
gamma: float | Literal["scale", "auto"] = "scale"
degree: int = Field(default=3, ge=1)
coef0: float = 1.0
class_weight: Literal["balanced"] | None = None
seed: int = 42
def _make_rng(seed: int) -> np.random.Generator:
"""Create a deterministic NumPy Generator via SeedSequence."""
return np.random.default_rng(np.random.SeedSequence(seed))
def _ensure_signed_labels(y: np.ndarray) -> np.ndarray:
"""Convert binary labels in {0, 1} or {-1, +1} strictly to {-1.0, +1.0}."""
arr = np.asarray(y, dtype=np.float64).ravel()
uniq = set(np.unique(arr).tolist())
if uniq.issubset({0.0, 1.0}):
return np.where(arr > 0.5, 1.0, -1.0)
if uniq.issubset({-1.0, 1.0}):
return arr.copy()
raise ValueError(f"Expected binary labels in {{0,1}} or {{-1,+1}}, got {sorted(uniq)}")
def _pairwise_sq_dists(X1: np.ndarray, X2: np.ndarray) -> np.ndarray:
"""Compute squared Euclidean distance matrix ||x_i - z_j||_2^2 in float64."""
X1 = np.asarray(X1, dtype=np.float64)
X2 = np.asarray(X2, dtype=np.float64)
sq1 = np.sum(X1 * X1, axis=1, keepdims=True)
sq2 = np.sum(X2 * X2, axis=1, keepdims=True).T
dists = sq1 + sq2 - 2.0 * (X1 @ X2.T)
return np.maximum(dists, 0.0)
def resolve_gamma(X: np.ndarray, gamma: float | Literal["scale", "auto"]) -> float:
"""Resolve 'scale' (1 / (d * Var_flat(X))), 'auto' (1 / d), or positive numeric gamma."""
if isinstance(gamma, (int, float)):
g = float(gamma)
if g <= 0.0:
raise ValueError("Numeric gamma must be strictly positive.")
return g
X_arr = np.asarray(X, dtype=np.float64)
d = max(1, X_arr.shape[1])
if gamma == "auto":
return 1.0 / float(d)
if gamma == "scale":
flat_var = float(np.var(X_arr))
return 1.0 / max(1e-12, float(d) * flat_var)
raise ValueError(f"Unsupported gamma spec: {gamma}")
def compute_median_heuristic_gamma(
X: np.ndarray, max_samples: int = 350, seed: int = 42
) -> float:
"""Compute Jaakkola median heuristic gamma = 1 / median(||x_i - x_j||_2^2)."""
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
if n > max_samples:
idx = _make_rng(seed).choice(n, size=max_samples, replace=False)
X_sub = X_arr[idx]
else:
X_sub = X_arr
sq = _pairwise_sq_dists(X_sub, X_sub)
iu = np.triu_indices(X_sub.shape[0], k=1)
vals = sq[iu]
med = float(np.median(vals)) if vals.size > 0 else 1.0
return 1.0 / max(1e-12, med)
def evaluate_kernel_matrix(
X1: np.ndarray,
X2: np.ndarray,
kernel: str = "rbf",
gamma: float = 0.1,
degree: int = 3,
coef0: float = 1.0,
) -> np.ndarray:
"""Evaluate pairwise kernel Gram matrix K(X1, X2)."""
A = np.asarray(X1, dtype=np.float64)
B = np.asarray(X2, dtype=np.float64)
if kernel == "linear":
return A @ B.T
if kernel == "poly":
return (gamma * (A @ B.T) + coef0) ** degree
if kernel == "rbf":
return np.exp(-gamma * _pairwise_sq_dists(A, B))
if kernel == "laplace":
l1 = np.sum(np.abs(A[:, None, :] - B[None, :, :]), axis=2)
return np.exp(-gamma * l1)
if kernel == "hik":
return np.sum(np.minimum(A[:, None, :], B[None, :, :]), axis=2)
if kernel == "chi2_add":
num = 2.0 * (A[:, None, :] * B[None, :, :])
den = A[:, None, :] + B[None, :, :]
ratio = np.divide(num, den, out=np.zeros_like(num), where=den > 1e-15)
return np.sum(ratio, axis=2)
if kernel == "chi2_exp":
diff2 = (A[:, None, :] - B[None, :, :]) ** 2
den = A[:, None, :] + B[None, :, :]
dist = np.sum(np.divide(diff2, den, out=np.zeros_like(diff2), where=den > 1e-15), axis=2)
return np.exp(-gamma * dist)
if kernel == "sigmoid":
return np.tanh(gamma * (A @ B.T) + coef0)
raise ValueError(f"Unsupported numeric kernel: {kernel}")
class GaussianNaiveBayesClassifier:
"""Gaussian Naive Bayes supporting shared or class-specific variances."""
def __init__(self, shared_variance: bool = True, var_smoothing: float = 1e-9) -> None:
self.shared_variance = shared_variance
self.var_smoothing = float(var_smoothing)
self.classes_: np.ndarray = np.array([-1.0, 1.0])
self.priors_: np.ndarray | None = None
self.means_: np.ndarray | None = None
self.vars_: np.ndarray | None = None
def fit(self, X: np.ndarray, y: np.ndarray) -> GaussianNaiveBayesClassifier:
X_arr = np.asarray(X, dtype=np.float64)
y_s = _ensure_signed_labels(y)
n, d = X_arr.shape
priors = np.zeros(2, dtype=np.float64)
means = np.zeros((2, d), dtype=np.float64)
class_vars = np.zeros((2, d), dtype=np.float64)
counts = np.zeros(2, dtype=np.float64)
for idx, cls in enumerate((-1.0, 1.0)):
mask = y_s == cls
counts[idx] = float(np.sum(mask))
priors[idx] = counts[idx] / float(n)
X_c = X_arr[mask]
means[idx] = np.mean(X_c, axis=0)
class_vars[idx] = np.var(X_c, axis=0)
if self.shared_variance:
pooled = (counts[0] * class_vars[0] + counts[1] * class_vars[1]) / max(1.0, float(n))
vars_out = np.vstack([pooled, pooled])
else:
vars_out = class_vars
self.priors_ = priors
self.means_ = means
self.vars_ = vars_out + self.var_smoothing
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
assert self.priors_ is not None and self.means_ is not None and self.vars_ is not None
X_arr = np.asarray(X, dtype=np.float64)
log_lik = np.zeros((X_arr.shape[0], 2), dtype=np.float64)
for idx in (0, 1):
v = self.vars_[idx]
diff = X_arr - self.means_[idx]
log_lik[:, idx] = (
np.log(max(self.priors_[idx], 1e-12))
- 0.5 * np.sum(np.log(2.0 * np.pi * v))
- 0.5 * np.sum((diff * diff) / v, axis=1)
)
return log_lik[:, 1] - log_lik[:, 0]
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
class ShrinkageLDAClassifier:
"""Linear Discriminant Analysis with optional Ledoit-style diagonal shrinkage."""
def __init__(self, shrinkage: float = 0.05) -> None:
self.shrinkage = float(shrinkage)
self.coef_: np.ndarray | None = None
self.intercept_: float = 0.0
def fit(self, X: np.ndarray, y: np.ndarray) -> ShrinkageLDAClassifier:
X_arr = np.asarray(X, dtype=np.float64)
y_s = _ensure_signed_labels(y)
n, d = X_arr.shape
m_pos = y_s > 0.0
m_neg = ~m_pos
mu_pos = np.mean(X_arr[m_pos], axis=0)
mu_neg = np.mean(X_arr[m_neg], axis=0)
pi_pos = float(np.mean(m_pos))
pi_neg = 1.0 - pi_pos
res_pos = X_arr[m_pos] - mu_pos
res_neg = X_arr[m_neg] - mu_neg
cov = (res_pos.T @ res_pos + res_neg.T @ res_neg) / max(1.0, float(n - 2))
iso = (float(np.trace(cov)) / float(d)) * np.eye(d, dtype=np.float64)
cov_shrunk = (1.0 - self.shrinkage) * cov + self.shrinkage * iso + 1e-8 * np.eye(d)
inv_cov = np.linalg.pinv(cov_shrunk)
w = inv_cov @ (mu_pos - mu_neg)
b = 0.5 * float(mu_neg @ inv_cov @ mu_neg - mu_pos @ inv_cov @ mu_pos) + float(
np.log(max(pi_pos, 1e-12) / max(pi_neg, 1e-12))
)
w.setflags(write=False)
self.coef_ = w
self.intercept_ = b
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
assert self.coef_ is not None
return np.asarray(X, dtype=np.float64) @ self.coef_ + self.intercept_
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
def _optimal_1d_hinge_bias(margins_no_bias: np.ndarray, y_signed: np.ndarray) -> float:
"""Find exact global minimizer b of sum_i max(0, 1 - y_i*(m_i + b)) in O(n log n)."""
# Hinge knots lie at b_k = y_k - m_k; evaluate piecewise linear convex objective at knots.
knots = np.sort(y_signed - margins_no_bias)
# Candidate midpoints/knots: check unique sorted knots safely via vector evaluation for moderate n,
# or exact slope sweep in O(n log n).
n = y_signed.shape[0]
if n <= 4000:
# Subsample knots only if tiny, else O(n log n) exact sweep:
pass
# Exact O(n log n) slope sweep:
# For y_i = +1: term is max(0, (1 - m_i) - b), slope is -1 for b < (1 - m_i), 0 above.
# For y_i = -1: term is max(0, (1 + m_i) + b), slope is 0 for b < (-1 - m_i), +1 above.
# Starting at b -> -inf: slope = -n_pos; each knot (whether y=+1 or y=-1) increases slope by +1!
n_pos = int(np.sum(y_signed > 0.0))
if n_pos == 0:
return float(np.min(-1.0 - margins_no_bias) - 1.0)
if n_pos == n:
return float(np.max(1.0 - margins_no_bias) + 1.0)
# Slope crosses 0 between the (n_pos - 1)-th and n_pos-th sorted knot (0-indexed)!
b_low = float(knots[n_pos - 1])
b_high = float(knots[n_pos])
return 0.5 * (b_low + b_high)
class LinearSVMPrimal:
"""Linear SVM supporting Pegasos stochastic ball projection and LIBLINEAR-style DCD."""
def __init__(
self,
c_reg: float = 1.0,
solver: Literal["pegasos", "dcd", "dcd_l2"] = "dcd",
max_iter: int = 4000,
tol: float = 1e-5,
fit_intercept: bool = True,
seed: int = 42,
) -> None:
if c_reg <= 0.0:
raise ValueError("c_reg must be strictly positive.")
self.c_reg = float(c_reg)
self.solver = solver
self.max_iter = int(max_iter)
self.tol = float(tol)
self.fit_intercept = bool(fit_intercept)
self.seed = int(seed)
self.coef_: np.ndarray | None = None
self.intercept_: float = 0.0
self.lam_: float = 0.0
self.l2_ball_bound_: float = 0.0
self.geometric_margin_: float = 0.0
self.primal_objective_: float = 0.0
self.history_: list[dict[str, float]] = []
def primal_hinge_objective(
self, X: np.ndarray, y_signed: np.ndarray, w: np.ndarray, b: float
) -> float:
"""Compute canonical soft-margin primal 0.5*||w||^2 + C * sum(hinge)."""
scores = X @ w + b
if self.solver == "dcd_l2":
losses = np.maximum(0.0, 1.0 - y_signed * scores) ** 2
return 0.5 * float(w @ w) + 0.5 * self.c_reg * float(np.sum(losses))
losses = np.maximum(0.0, 1.0 - y_signed * scores)
return 0.5 * float(w @ w) + self.c_reg * float(np.sum(losses))
def fit(self, X: np.ndarray, y: np.ndarray) -> LinearSVMPrimal:
X_raw = np.asarray(X, dtype=np.float64)
y_s = _ensure_signed_labels(y)
n, d = X_raw.shape
rng = _make_rng(self.seed)
# Center internally during optimization so unpenalized intercept preserves exact
# translation equivariance even when X has huge offsets, then shift intercept back!
x_mean = np.mean(X_raw, axis=0) if self.fit_intercept else np.zeros(d, dtype=np.float64)
X_c = X_raw - x_mean
lam = 1.0 / (float(n) * self.c_reg)
self.lam_ = lam
ball_radius = 1.0 / np.sqrt(lam)
self.l2_ball_bound_ = float(ball_radius)
if self.solver == "pegasos":
w = np.zeros(d, dtype=np.float64)
b_c = 0.0
w_avg = np.zeros(d, dtype=np.float64)
n_avg = 0
batch_size = min(n, max(8, min(64, n // 4 if n >= 32 else n)))
burn_in = self.max_iter // 2
self.history_ = []
for t in range(1, self.max_iter + 1):
idx = rng.integers(0, n, size=batch_size)
Xb = X_c[idx]
yb = y_s[idx]
margins = yb * (Xb @ w + b_c)
viol = margins < 1.0
eta = 1.0 / (lam * float(t))
w_half = (1.0 - 1.0 / float(t)) * w
if np.any(viol):
grad_hinge = -(yb[viol, None] * Xb[viol]).sum(axis=0) / float(batch_size)
w_half = w_half - eta * grad_hinge
if self.fit_intercept:
grad_b = -float(np.sum(yb[viol])) / float(batch_size)
b_c = b_c - (1.0 / np.sqrt(float(t))) * grad_b
norm_w = float(np.linalg.norm(w_half))
if norm_w > ball_radius:
w = (ball_radius / norm_w) * w_half
else:
w = w_half
if t >= burn_in:
w_avg += w
n_avg += 1
if t in (1, self.max_iter // 4, self.max_iter // 2, self.max_iter):
self.history_.append(
{
"iter": float(t),
"w_norm": float(np.linalg.norm(w)),
"primal_obj": self.primal_hinge_objective(X_c, y_s, w, b_c),
}
)
w_final = w_avg / float(max(1, n_avg))
# Enforce exact ball bound post-averaging as well (convex set -> stays in ball)
nf = float(np.linalg.norm(w_final))
if nf > ball_radius:
w_final = (ball_radius / nf) * w_final
b_final_c = (
_optimal_1d_hinge_bias(X_c @ w_final, y_s) if self.fit_intercept else 0.0
)
w = w_final
b_c = b_final_c
elif self.solver in ("dcd", "dcd_l2"):
# Dual Coordinate Descent (Hsieh et al., 2008) on centered features + exact 1D bias polish
# We also include a weakly regularized bias coordinate scale B=20 during DCD sweeps
# so sum(alpha_i * y_i) ~ 0 is implicitly respected, then exact-polish b_c.
is_l2 = self.solver == "dcd_l2"
diag_reg = (1.0 / self.c_reg) if is_l2 else 0.0
upper = np.inf if is_l2 else self.c_reg
bias_scale = 2.0 if self.fit_intercept else 0.0
q_diag = np.sum(X_c * X_c, axis=1) + bias_scale * bias_scale + diag_reg
alpha = np.zeros(n, dtype=np.float64)
w = np.zeros(d, dtype=np.float64)
w_b = 0.0
epochs = max(120, min(500, self.max_iter // max(1, min(n, 15))))
self.history_ = []
for ep in range(1, epochs + 1):
perm = rng.permutation(n)
pg_max = -np.inf
pg_min = np.inf
for i in perm:
a_old = alpha[i]
xi = X_c[i]
yi = y_s[i]
g = yi * (float(w @ xi) + w_b * bias_scale) - 1.0 + diag_reg * a_old
pg = g
if a_old <= 1e-12:
pg = min(g, 0.0)
elif a_old >= upper - 1e-12:
pg = max(g, 0.0)
pg_max = max(pg_max, pg)
pg_min = min(pg_min, pg)
if abs(pg) > 1e-12:
qd = max(q_diag[i], 1e-12)
a_new = min(max(a_old - g / qd, 0.0), upper)
delta = (a_new - a_old) * yi
if delta != 0.0:
alpha[i] = a_new
w += delta * xi
w_b += delta * bias_scale
if ep in (1, max(1, epochs // 2), epochs):
b_tmp = w_b * bias_scale if self.fit_intercept else 0.0
self.history_.append(
{
"iter": float(ep),
"w_norm": float(np.linalg.norm(w)),
"primal_obj": self.primal_hinge_objective(X_c, y_s, w, b_tmp),
}
)
if pg_max - pg_min < self.tol:
break
b_c = (
_optimal_1d_hinge_bias(X_c @ w, y_s)
if (self.fit_intercept and not is_l2)
else (w_b * bias_scale if self.fit_intercept else 0.0)
)
else:
raise ValueError(f"Unknown solver: {self.solver}")
b_shifted = b_c - float(w @ x_mean) if self.fit_intercept else 0.0
w.setflags(write=False)
self.coef_ = w
self.intercept_ = float(b_shifted)
wnorm = float(np.linalg.norm(w))
self.geometric_margin_ = float(1.0 / wnorm) if wnorm > 1e-12 else np.inf
self.primal_objective_ = self.primal_hinge_objective(X_raw, y_s, w, b_shifted)
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
assert self.coef_ is not None
return np.asarray(X, dtype=np.float64) @ self.coef_ + self.intercept_
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
def smo_two_variable_step(
alpha_1: float,
alpha_2: float,
y_1: float,
y_2: float,
k11: float,
k22: float,
k12: float,
f1: float,
f2: float,
c1: float,
c2: float,
eps_tol: float = 1e-12,
) -> tuple[float, float, float, float, bool]:
"""Exact Platt (1998) 2-variable analytical SMO step with +b convention & eta<=0 fallback.
Here f_i = sum_j alpha_j y_j K_ji - y_i so E_1 - E_2 = f1 - f2.
Returns (alpha_1_new, alpha_2_new, L, H, used_degenerate_fallback).
"""
s = y_1 * y_2
if s > 0.0:
low = max(0.0, alpha_1 + alpha_2 - c1)
high = min(c2, alpha_1 + alpha_2)
else:
low = max(0.0, alpha_2 - alpha_1)
high = min(c2, c1 + alpha_2 - alpha_1)
if low >= high - 1e-15:
return alpha_1, alpha_2, low, high, False
eta = k11 + k22 - 2.0 * k12
used_fallback = False
if eta > 1e-12:
a2_unc = alpha_2 + y_2 * (f1 - f2) / eta
a2_new = min(high, max(low, a2_unc))
else:
used_fallback = True
# Evaluate 1D dual objective up to additive constant at endpoints L and H
lin = y_2 * (f1 - f2) + eta * alpha_2
obj_low = lin * low - 0.5 * eta * low * low
obj_high = lin * high - 0.5 * eta * high * high
if obj_low > obj_high + eps_tol:
a2_new = low
elif obj_high > obj_low + eps_tol:
a2_new = high
else:
a2_new = alpha_2
if abs(a2_new - alpha_2) < 1e-12 * (a2_new + alpha_2 + 1e-12):
return alpha_1, alpha_2, low, high, used_fallback
a1_new = alpha_1 + s * (alpha_2 - a2_new)
# Clamp numerical epsilon near 0 or C
if a1_new < 1e-12:
a1_new = 0.0
elif a1_new > c1 - 1e-12:
a1_new = c1
if a2_new < 1e-12:
a2_new = 0.0
elif a2_new > c2 - 1e-12:
a2_new = c2
return float(a1_new), float(a2_new), float(low), float(high), used_fallback
class KernelSMOSolver:
"""Exact Dual Quadratic Program SVM solver using Keerthi WSS + Platt analytical SMO step."""
def __init__(
self,
c_reg: float = 1.0,
tol: float = 1e-4,
max_iter: int = 8000,
kernel: str = "rbf",
gamma: float | Literal["scale", "auto"] = "scale",
degree: int = 3,
coef0: float = 1.0,
class_weight: Literal["balanced"] | None = None,
custom_kernel_fn: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None,
) -> None:
self.c_reg = float(c_reg)
self.tol = float(tol)
self.max_iter = int(max_iter)
self.kernel = kernel
self.gamma = gamma
self.degree = int(degree)
self.coef0 = float(coef0)
self.class_weight = class_weight
self.custom_kernel_fn = custom_kernel_fn
self.gamma_resolved_: float = 1.0
self.X_train_: np.ndarray | None = None
self.y_train_: np.ndarray | None = None
self.alphas_: np.ndarray | None = None
self.c_vec_: np.ndarray | None = None
self.intercept_: float = 0.0
self.support_indices_: np.ndarray = np.array([], dtype=np.int64)
self.dual_objective_: float = 0.0
self.primal_objective_: float = 0.0
self.duality_gap_: float = 0.0
self.kkt_summary_: dict[str, Any] = {}
self.n_iter_: int = 0
def _compute_gram(self, X1: np.ndarray, X2: np.ndarray) -> np.ndarray:
if self.custom_kernel_fn is not None:
return np.asarray(self.custom_kernel_fn(X1, X2), dtype=np.float64)
return evaluate_kernel_matrix(
X1,
X2,
kernel=self.kernel,
gamma=self.gamma_resolved_,
degree=self.degree,
coef0=self.coef0,
)
def fit(self, X: np.ndarray, y: np.ndarray) -> KernelSMOSolver:
X_arr = np.asarray(X, dtype=np.float64)
y_s = _ensure_signed_labels(y)
n = X_arr.shape[0]
self.gamma_resolved_ = resolve_gamma(X_arr, self.gamma)
K = self._compute_gram(X_arr, X_arr)
if self.class_weight == "balanced":
n_pos = max(1, int(np.sum(y_s > 0.0)))
n_neg = max(1, n - n_pos)
w_pos = float(n) / (2.0 * float(n_pos))
w_neg = float(n) / (2.0 * float(n_neg))
c_vec = np.where(y_s > 0.0, self.c_reg * w_pos, self.c_reg * w_neg)
else:
c_vec = np.full(n, self.c_reg, dtype=np.float64)
alpha = np.zeros(n, dtype=np.float64)
# F_i = sum_j alpha_j y_j K_ji - y_i; initially alpha = 0 => F = -y_s
F = -y_s.copy()
k_diag = np.diag(K)
eps_box = 1e-11
n_iter = 0
degenerate_hits = 0
for it in range(self.max_iter):
n_iter = it + 1
in_up = ((alpha < c_vec - eps_box) & (y_s > 0.0)) | (
(alpha > eps_box) & (y_s < 0.0)
)
in_low = ((alpha < c_vec - eps_box) & (y_s < 0.0)) | (
(alpha > eps_box) & (y_s > 0.0)
)
if not (np.any(in_up) and np.any(in_low)):
break
up_idx = np.where(in_up)[0]
low_idx = np.where(in_low)[0]
i_up = int(up_idx[int(np.argmin(F[up_idx]))])
f_up = float(F[i_up])
# Second-order WSS3 selection of j in I_low with F[j] > f_up
cand_low = low_idx[F[low_idx] > f_up]
if cand_low.size == 0:
break
f_low_max = float(np.max(F[cand_low]))
if f_low_max - f_up <= 2.0 * self.tol:
break
# Select j maximizing (F_j - f_up)^2 / max(eta, 1e-12) (Fan, Chen, Lin 2005)
diffs = F[cand_low] - f_up
etas = np.maximum(k_diag[i_up] + k_diag[cand_low] - 2.0 * K[i_up, cand_low], 1e-12)
scores = (diffs * diffs) / etas
j_low = int(cand_low[int(np.argmax(scores))])
a1_old = float(alpha[i_up])
a2_old = float(alpha[j_low])
a1_new, a2_new, _, _, used_fb = smo_two_variable_step(
a1_old,
a2_old,
float(y_s[i_up]),
float(y_s[j_low]),
float(k_diag[i_up]),
float(k_diag[j_low]),
float(K[i_up, j_low]),
float(F[i_up]),
float(F[j_low]),
float(c_vec[i_up]),
float(c_vec[j_low]),
)
if used_fb:
degenerate_hits += 1
da1 = a1_new - a1_old
da2 = a2_new - a2_old
if abs(da1) < 1e-13 and abs(da2) < 1e-13:
# Fallback to extreme Keerthi pair (i_up, argmax(F_low)) if WSS3 stalled
j_alt = int(low_idx[int(np.argmax(F[low_idx]))])
if j_alt == j_low:
break
a2_alt_old = float(alpha[j_alt])
a1_new, a2_new, _, _, used_fb = smo_two_variable_step(
a1_old,
a2_alt_old,
float(y_s[i_up]),
float(y_s[j_alt]),
float(k_diag[i_up]),
float(k_diag[j_alt]),
float(K[i_up, j_alt]),
float(F[i_up]),
float(F[j_alt]),
float(c_vec[i_up]),
float(c_vec[j_alt]),
)
da1 = a1_new - a1_old
da2 = a2_new - a2_alt_old
j_low = j_alt
if abs(da1) < 1e-13 and abs(da2) < 1e-13:
break
alpha[i_up] = a1_new
alpha[j_low] = a2_new
F += (y_s[i_up] * da1) * K[i_up, :] + (y_s[j_low] * da2) * K[j_low, :]
# Compute bias b^* from free margin support vectors (0 < alpha_i < C_i) or Keerthi midpoint
free_mask = (alpha > 1e-7) & (alpha < c_vec - 1e-7)
f_no_bias = K @ (alpha * y_s)
if np.any(free_mask):
b = float(np.mean(y_s[free_mask] - f_no_bias[free_mask]))
else:
in_up = ((alpha < c_vec - eps_box) & (y_s > 0.0)) | ((alpha > eps_box) & (y_s < 0.0))
in_low = ((alpha < c_vec - eps_box) & (y_s < 0.0)) | ((alpha > eps_box) & (y_s > 0.0))
b_up = float(np.min(F[in_up])) if np.any(in_up) else 0.0
b_low = float(np.max(F[in_low])) if np.any(in_low) else 0.0
b = -0.5 * (b_up + b_low)
margins = y_s * (f_no_bias + b)
slacks = np.maximum(0.0, 1.0 - margins)
rkhs_norm_sq = float((alpha * y_s) @ f_no_bias)
dual_obj = float(np.sum(alpha) - 0.5 * rkhs_norm_sq)
primal_obj = float(0.5 * rkhs_norm_sq + np.sum(c_vec * slacks))
non_sv_mask = alpha <= 1e-7
bounded_mask = alpha >= c_vec - 1e-7
free_mask = (~non_sv_mask) & (~bounded_mask)
sv_idx = np.where(~non_sv_mask)[0]
# Max KKT residual across all samples
err_vec = (f_no_bias + b) - y_s
y_err = y_s * err_vec
v_low = np.where(alpha < c_vec - 1e-7, np.maximum(0.0, -y_err), 0.0)
v_high = np.where(alpha > 1e-7, np.maximum(0.0, y_err), 0.0)
max_kkt_viol = float(max(np.max(v_low), np.max(v_high)))
alpha.setflags(write=False)
self.X_train_ = X_arr
self.y_train_ = y_s
self.alphas_ = alpha
self.c_vec_ = c_vec
self.intercept_ = float(b)
self.support_indices_ = sv_idx
self.dual_objective_ = dual_obj
self.primal_objective_ = primal_obj
self.duality_gap_ = max(0.0, primal_obj - dual_obj)
self.n_iter_ = n_iter
self.kkt_summary_ = {
"n_total": int(n),
"n_non_sv": int(np.sum(non_sv_mask)),
"n_free_sv": int(np.sum(free_mask)),
"n_bounded_sv": int(np.sum(bounded_mask)),
"n_support_vectors": int(sv_idx.size),
"sv_fraction": float(sv_idx.size) / float(n),
"max_kkt_violation": max_kkt_viol,
"duality_gap": self.duality_gap_,
"degenerate_eta_hits": int(degenerate_hits),
}
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
assert self.X_train_ is not None and self.y_train_ is not None and self.alphas_ is not None
X_arr = np.asarray(X, dtype=np.float64)
sv = self.support_indices_
if sv.size == 0:
return np.full(X_arr.shape[0], self.intercept_, dtype=np.float64)
K_sv = self._compute_gram(X_arr, self.X_train_[sv])
weights_sv = self.alphas_[sv] * self.y_train_[sv]
return K_sv @ weights_sv + self.intercept_
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
class EpsilonSVR:
"""Dual QP epsilon-Insensitive Support Vector Regression (Vapnik 1995 / LIBSVM 2n reduction)."""
def __init__(
self,
c_reg: float = 10.0,
epsilon_tube: float = 0.5,
kernel: str = "rbf",
gamma: float | Literal["scale", "auto"] = "scale",
degree: int = 3,
coef0: float = 1.0,
tol: float = 1e-4,
max_iter: int = 10000,
) -> None:
self.c_reg = float(c_reg)
self.epsilon_tube = float(epsilon_tube)
self.kernel = kernel
self.gamma = gamma
self.degree = int(degree)
self.coef0 = float(coef0)
self.tol = float(tol)
self.max_iter = int(max_iter)
self.gamma_resolved_: float = 1.0
self.X_train_: np.ndarray | None = None
self.alpha_pos_: np.ndarray | None = None
self.alpha_neg_: np.ndarray | None = None
self.alpha_diff_: np.ndarray | None = None
self.intercept_: float = 0.0
self.support_indices_: np.ndarray = np.array([], dtype=np.int64)
self.sv_fraction_: float = 0.0
def fit(self, X: np.ndarray, y: np.ndarray) -> EpsilonSVR:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.float64).ravel()
n = X_arr.shape[0]
self.gamma_resolved_ = resolve_gamma(X_arr, self.gamma)
K = evaluate_kernel_matrix(
X_arr,
X_arr,
kernel=self.kernel,
gamma=self.gamma_resolved_,
degree=self.degree,
coef0=self.coef0,
)
# 2n LIBSVM reduction:
# k in 0..n-1 => alpha_pos[k], sign s_k = +1, linear p_k = eps - y_k
# k in n..2n-1 => alpha_neg[k-n], sign s_k = -1, linear p_k = eps + y_k
# Minimize 0.5 * a^T Q a + p^T a s.t. s^T a = 0, 0 <= a <= C
C = self.c_reg
eps = self.epsilon_tube
signs = np.concatenate([np.ones(n, dtype=np.float64), -np.ones(n, dtype=np.float64)])
p_vec = np.concatenate([eps - y_arr, eps + y_arr])
a = np.zeros(2 * n, dtype=np.float64)
# Gradient G_k = (Q a)_k + p_k, so Keerthi F_k = s_k * G_k = (K (a_pos - a_neg))_{k%n} + s_k * p_k
# Specifically for k < n: F_k = f0_{k} + eps - y_k; for k >= n: F_k = f0_{k-n} - eps - y_{k-n}.
F = signs * p_vec
k_diag = np.diag(K)
eps_box = 1e-11
for _ in range(self.max_iter):
in_up = ((a < C - eps_box) & (signs > 0.0)) | ((a > eps_box) & (signs < 0.0))
in_low = ((a < C - eps_box) & (signs < 0.0)) | ((a > eps_box) & (signs > 0.0))
if not (np.any(in_up) and np.any(in_low)):
break
up_idx = np.where(in_up)[0]
low_idx = np.where(in_low)[0]
i_up = int(up_idx[int(np.argmin(F[up_idx]))])
j_low = int(low_idx[int(np.argmax(F[low_idx]))])
f_up = float(F[i_up])
f_low = float(F[j_low])
if f_low - f_up <= 2.0 * self.tol:
break
ii = i_up % n
jj = j_low % n
a1_old = float(a[i_up])
a2_old = float(a[j_low])
a1_new, a2_new, _, _, _ = smo_two_variable_step(
a1_old,
a2_old,
float(signs[i_up]),
float(signs[j_low]),
float(k_diag[ii]),
float(k_diag[jj]),
float(K[ii, jj]),
f_up,
f_low,
C,
C,
)
da1 = a1_new - a1_old
da2 = a2_new - a2_old
if abs(da1) < 1e-13 and abs(da2) < 1e-13:
break
a[i_up] = a1_new
a[j_low] = a2_new
delta_f0 = (signs[i_up] * da1) * K[ii, :] + (signs[j_low] * da2) * K[jj, :]
F[:n] += delta_f0
F[n:] += delta_f0
alpha_pos = a[:n].copy()
alpha_neg = a[n:].copy()
# Clean mutually cancelling dual mass if eps == 0
cancel = np.minimum(alpha_pos, alpha_neg)
alpha_pos -= cancel
alpha_neg -= cancel
alpha_diff = alpha_pos - alpha_neg
f0 = K @ alpha_diff
free_pos = (alpha_pos > 1e-7) & (alpha_pos < C - 1e-7)
free_neg = (alpha_neg > 1e-7) & (alpha_neg < C - 1e-7)
b_cands: list[float] = []
if np.any(free_pos):
b_cands.extend((y_arr[free_pos] - f0[free_pos] - eps).tolist())
if np.any(free_neg):
b_cands.extend((y_arr[free_neg] - f0[free_neg] + eps).tolist())
if b_cands:
b = float(np.mean(b_cands))
else:
in_up = ((a < C - eps_box) & (signs > 0.0)) | ((a > eps_box) & (signs < 0.0))
in_low = ((a < C - eps_box) & (signs < 0.0)) | ((a > eps_box) & (signs > 0.0))
b_up = float(np.min(F[in_up])) if np.any(in_up) else 0.0
b_low = float(np.max(F[in_low])) if np.any(in_low) else 0.0
b = -0.5 * (b_up + b_low)
sv_mask = np.abs(alpha_diff) > 1e-7
self.X_train_ = X_arr
self.alpha_pos_ = alpha_pos
self.alpha_neg_ = alpha_neg
self.alpha_diff_ = alpha_diff
self.intercept_ = float(b)
self.support_indices_ = np.where(sv_mask)[0]
self.sv_fraction_ = float(np.mean(sv_mask))
return self
def predict(self, X: np.ndarray) -> np.ndarray:
assert self.X_train_ is not None and self.alpha_diff_ is not None
X_arr = np.asarray(X, dtype=np.float64)
sv = self.support_indices_
if sv.size == 0:
return np.full(X_arr.shape[0], self.intercept_, dtype=np.float64)
K_sv = evaluate_kernel_matrix(
X_arr,
self.X_train_[sv],
kernel=self.kernel,
gamma=self.gamma_resolved_,
degree=self.degree,
coef0=self.coef0,
)
return K_sv @ self.alpha_diff_[sv] + self.intercept_
def _solve_simplex_box_qp(
K: np.ndarray,
linear_coeff: np.ndarray,
upper: float,
tol: float = 1e-6,
max_iter: int = 8000,
) -> np.ndarray:
"""Solve min 0.5 a^T K a + linear_coeff^T a s.t. 0 <= a_i <= upper, sum(a_i) = 1."""
n = K.shape[0]
a = np.full(n, 1.0 / float(n), dtype=np.float64)
if np.any(a > upper):
raise ValueError("Infeasible nu*n < 1 for simplex box constraint.")
grad = K @ a + linear_coeff
k_diag = np.diag(K)
eps_box = 1e-12
for _ in range(max_iter):
up_mask = a < upper - eps_box
low_mask = a > eps_box
if not (np.any(up_mask) and np.any(low_mask)):
break
up_idx = np.where(up_mask)[0]
low_idx = np.where(low_mask)[0]
i = int(up_idx[int(np.argmin(grad[up_idx]))])
j = int(low_idx[int(np.argmax(grad[low_idx]))])
if i == j or (grad[j] - grad[i] <= tol):
break
eta = k_diag[i] + k_diag[j] - 2.0 * K[i, j]
max_step = min(upper - a[i], a[j])
min_step = -min(a[i], upper - a[j])
if eta > 1e-12:
delta = (grad[j] - grad[i]) / eta
delta = min(max_step, max(min_step, delta))
else:
delta = max_step if grad[j] > grad[i] else min_step
if abs(delta) < 1e-13:
break
a[i] += delta
a[j] -= delta
grad += delta * (K[:, i] - K[:, j])
return a
class OneClassSVMSolver:
"""Scholkopf nu-One-Class SVM (origin separation in RKHS)."""
def __init__(
self,
nu: float = 0.05,
kernel: str = "rbf",
gamma: float | Literal["scale", "auto"] = "scale",
tol: float = 1e-6,
max_iter: int = 8000,
) -> None:
if not (0.0 < nu <= 1.0):
raise ValueError("nu must lie in (0, 1].")
self.nu = float(nu)
self.kernel = kernel
self.gamma = gamma
self.tol = float(tol)
self.max_iter = int(max_iter)
self.gamma_resolved_: float = 1.0
self.X_train_: np.ndarray | None = None
self.alphas_: np.ndarray | None = None
self.rho_: float = 0.0
self.support_indices_: np.ndarray = np.array([], dtype=np.int64)
self.outlier_fraction_: float = 0.0
self.sv_fraction_: float = 0.0
def fit(self, X: np.ndarray) -> OneClassSVMSolver:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
self.gamma_resolved_ = resolve_gamma(X_arr, self.gamma)
K = evaluate_kernel_matrix(X_arr, X_arr, kernel=self.kernel, gamma=self.gamma_resolved_)
upper = 1.0 / (self.nu * float(n))
a = _solve_simplex_box_qp(
K,
np.zeros(n, dtype=np.float64),
upper=upper,
tol=self.tol,
max_iter=self.max_iter,
)
f_vals = K @ a
free = (a > 1e-7) & (a < upper - 1e-7)
if np.any(free):
rho = float(np.mean(f_vals[free]))
else:
on_bnd = a >= upper - 1e-7
rho = float(np.percentile(f_vals, 100.0 * self.nu)) if not np.any(on_bnd) else float(
0.5 * (np.max(f_vals[on_bnd]) + np.min(f_vals[a <= 1e-7]))
if np.any(a <= 1e-7)
else np.max(f_vals[on_bnd])
)
sv_mask = a > 1e-7
self.X_train_ = X_arr
self.alphas_ = a
self.rho_ = rho
self.support_indices_ = np.where(sv_mask)[0]
self.sv_fraction_ = float(np.mean(sv_mask))
self.outlier_fraction_ = float(np.mean((f_vals - rho) < -1e-6))
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
assert self.X_train_ is not None and self.alphas_ is not None
sv = self.support_indices_
K_sv = evaluate_kernel_matrix(
np.asarray(X, dtype=np.float64),
self.X_train_[sv],
kernel=self.kernel,
gamma=self.gamma_resolved_,
)
return K_sv @ self.alphas_[sv] - self.rho_
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
class SVDDSolver:
"""Tax & Duin (2004) Support Vector Data Description (minimal enclosing hypersphere)."""
def __init__(
self,
nu: float = 0.05,
kernel: str = "rbf",
gamma: float | Literal["scale", "auto"] = "scale",
tol: float = 1e-6,
max_iter: int = 8000,
) -> None:
if not (0.0 < nu <= 1.0):
raise ValueError("nu must lie in (0, 1].")
self.nu = float(nu)
self.kernel = kernel
self.gamma = gamma
self.tol = float(tol)
self.max_iter = int(max_iter)
self.gamma_resolved_: float = 1.0
self.X_train_: np.ndarray | None = None
self.alphas_: np.ndarray | None = None
self.center_norm_sq_: float = 0.0
self.radius_sq_: float = 0.0
self.support_indices_: np.ndarray = np.array([], dtype=np.int64)
def fit(self, X: np.ndarray) -> SVDDSolver:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
self.gamma_resolved_ = resolve_gamma(X_arr, self.gamma)
K = evaluate_kernel_matrix(X_arr, X_arr, kernel=self.kernel, gamma=self.gamma_resolved_)
k_diag = np.diag(K)
upper = 1.0 / (self.nu * float(n))
# min 0.5 a^T K a - 0.5 diag(K)^T a <=> max sum a_i K_ii - a^T K a
a = _solve_simplex_box_qp(
K,
-0.5 * k_diag,
upper=upper,
tol=self.tol,
max_iter=self.max_iter,
)
c_norm_sq = float(a @ K @ a)
dist_sq = k_diag - 2.0 * (K @ a) + c_norm_sq
free = (a > 1e-7) & (a < upper - 1e-7)
if np.any(free):
r_sq = float(np.mean(dist_sq[free]))
else:
r_sq = float(np.percentile(dist_sq, 100.0 * (1.0 - self.nu)))
self.X_train_ = X_arr
self.alphas_ = a
self.center_norm_sq_ = c_norm_sq
self.radius_sq_ = r_sq
self.support_indices_ = np.where(a > 1e-7)[0]
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
"""Positive inside sphere (R^2 - ||phi(x) - a||^2 >= 0)."""
assert self.X_train_ is not None and self.alphas_ is not None
X_arr = np.asarray(X, dtype=np.float64)
sv = self.support_indices_
K_sv = evaluate_kernel_matrix(
X_arr,
self.X_train_[sv],
kernel=self.kernel,
gamma=self.gamma_resolved_,
)
if self.kernel == "rbf":
k_xx = np.ones(X_arr.shape[0], dtype=np.float64)
else:
k_xx = np.diag(
evaluate_kernel_matrix(X_arr, X_arr, kernel=self.kernel, gamma=self.gamma_resolved_)
)
dist_sq = k_xx - 2.0 * (K_sv @ self.alphas_[sv]) + self.center_norm_sq_
return 0.5 * (self.radius_sq_ - dist_sq)
def predict(self, X: np.ndarray) -> np.ndarray:
return np.where(self.decision_function(X) >= 0.0, 1.0, -1.0)
class MulticlassSVM:
"""Multiclass SVM supporting One-vs-One (OvO) and One-vs-Rest (OvR) over KernelSMOSolver."""
def __init__(
self,
strategy: Literal["ovo", "ovr"] = "ovo",
c_reg: float = 1.0,
kernel: str = "rbf",
gamma: float | Literal["scale", "auto"] = "scale",
tol: float = 1e-3,
max_iter: int = 4000,
) -> None:
self.strategy = strategy
self.c_reg = float(c_reg)
self.kernel = kernel
self.gamma = gamma
self.tol = float(tol)
self.max_iter = int(max_iter)
self.classes_: np.ndarray = np.array([], dtype=np.int64)
self.models_: list[tuple[tuple[int, int] | int, KernelSMOSolver]] = []
def fit(self, X: np.ndarray, y: np.ndarray) -> MulticlassSVM:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64).ravel()
classes = np.unique(y_arr)
self.classes_ = classes
self.models_ = []
g_resolved = resolve_gamma(X_arr, self.gamma)
if self.strategy == "ovo":
for idx_a in range(len(classes)):
for idx_b in range(idx_a + 1, len(classes)):
ca, cb = int(classes[idx_a]), int(classes[idx_b])
mask = (y_arr == ca) | (y_arr == cb)
y_bin = np.where(y_arr[mask] == ca, 1.0, -1.0)
clf = KernelSMOSolver(
c_reg=self.c_reg,
tol=self.tol,
max_iter=self.max_iter,
kernel=self.kernel,
gamma=g_resolved,
).fit(X_arr[mask], y_bin)
self.models_.append(((ca, cb), clf))
elif self.strategy == "ovr":
for c_val in classes:
c_int = int(c_val)
y_bin = np.where(y_arr == c_int, 1.0, -1.0)
clf = KernelSMOSolver(
c_reg=self.c_reg,
tol=self.tol,
max_iter=self.max_iter,
kernel=self.kernel,
gamma=g_resolved,
).fit(X_arr, y_bin)
self.models_.append((c_int, clf))
else:
raise ValueError(f"Unsupported multiclass strategy: {self.strategy}")
return self
def predict(self, X: np.ndarray) -> np.ndarray:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
k_cls = len(self.classes_)
if self.strategy == "ovr":
scores = np.column_stack([clf.decision_function(X_arr) for _, clf in self.models_])
return self.classes_[np.argmax(scores, axis=1)]
votes = np.zeros((n, k_cls), dtype=np.float64)
margin_sum = np.zeros((n, k_cls), dtype=np.float64)
cls_to_idx = {int(c): i for i, c in enumerate(self.classes_)}
for pair, clf in self.models_:
assert isinstance(pair, tuple)
ca, cb = pair
ia, ib = cls_to_idx[ca], cls_to_idx[cb]
dec = clf.decision_function(X_arr)
win_a = dec >= 0.0
votes[win_a, ia] += 1.0
votes[~win_a, ib] += 1.0
# Tie-breaker using normalized sigmoidal margin fraction
sig = 1.0 / (1.0 + np.exp(-np.clip(dec, -20.0, 20.0)))
margin_sum[:, ia] += sig
margin_sum[:, ib] += 1.0 - sig
combined = votes + 0.01 * margin_sum
return self.classes_[np.argmax(combined, axis=1)]
class PlattCalibrator:
"""Lin-Lin-Weng (2007) Damped 2D Newton Platt Scaling bridge (ch-07 compatible)."""
def __init__(self, max_iter: int = 100, min_step: float = 1e-10) -> None:
self.max_iter = int(max_iter)
self.min_step = float(min_step)
self.a_platt_: float = -1.0
self.b_platt_: float = 0.0
def fit(self, decision_margins: np.ndarray, y_binary_01: np.ndarray) -> PlattCalibrator:
f = np.asarray(decision_margins, dtype=np.float64).ravel()
y = np.asarray(y_binary_01, dtype=np.float64).ravel()
n_pos = float(np.sum(y > 0.5))
n_neg = float(y.shape[0] - n_pos)
hi_target = (n_pos + 1.0) / (n_pos + 2.0)
lo_target = 1.0 / (n_neg + 2.0)
t = np.where(y > 0.5, hi_target, lo_target)
a = 0.0
b = float(np.log((n_neg + 1.0) / (n_pos + 1.0)))
def _loss_and_p(a_v: float, b_v: float) -> tuple[float, np.ndarray]:
z = a_v * f + b_v
# Platt probability p = 1 / (1 + exp(z)) => NLL = -t*ln(p) - (1-t)*ln(1-p) = (t - 1)*z + ln(1 + exp(z))
p = np.where(z >= 0.0, np.exp(-z) / (1.0 + np.exp(-z)), 1.0 / (1.0 + np.exp(z)))
log_1p = np.where(z >= 0.0, z + np.log1p(np.exp(-z)), np.log1p(np.exp(z)))
nll = float(np.sum((t - 1.0) * z + log_1p))
return nll, p
cur_loss, p = _loss_and_p(a, b)
sigma = 1e-12
for _ in range(self.max_iter):
d1 = t - p
d2 = p * (1.0 - p)
h11 = float(np.sum(f * f * d2)) + sigma
h22 = float(np.sum(d2)) + sigma
h21 = float(np.sum(f * d2))
g1 = float(np.sum(f * d1))
g2 = float(np.sum(d1))
if abs(g1) < 1e-6 and abs(g2) < 1e-6:
break
det = h11 * h22 - h21 * h21
da = -(h22 * g1 - h21 * g2) / det
db = -(-h21 * g1 + h11 * g2) / det
gd = g1 * da + g2 * db
step = 1.0
while step >= self.min_step:
na = a + step * da
nb = b + step * db
new_loss, new_p = _loss_and_p(na, nb)
if new_loss <= cur_loss + 1e-4 * step * gd:
a, b, cur_loss, p = na, nb, new_loss, new_p
break
step *= 0.5
else:
break
self.a_platt_ = float(a)
self.b_platt_ = float(b)
return self
def predict_proba(self, decision_margins: np.ndarray) -> np.ndarray:
f = np.asarray(decision_margins, dtype=np.float64).ravel()
z = self.a_platt_ * f + self.b_platt_
return np.where(z >= 0.0, np.exp(-z) / (1.0 + np.exp(-z)), 1.0 / (1.0 + np.exp(z)))
def compute_ece(y_true_01: np.ndarray, y_prob: np.ndarray, n_bins: int = 10) -> float:
"""Compute equal-width Expected Calibration Error (ECE)."""
y = np.asarray(y_true_01, dtype=np.float64).ravel()
p = np.clip(np.asarray(y_prob, dtype=np.float64).ravel(), 0.0, 1.0)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
n = float(y.shape[0])
for b_idx in range(n_bins):
lo, hi = edges[b_idx], edges[b_idx + 1]
mask = (p >= lo) & (p <= hi if b_idx == n_bins - 1 else p < hi)
cnt = int(np.sum(mask))
if cnt > 0:
ece += (float(cnt) / n) * abs(float(np.mean(y[mask])) - float(np.mean(p[mask])))
return float(ece)
def simulate_ng_jordan_crossover(
d: int = 36,
sample_sizes: tuple[int, ...] = (12, 24, 64, 240),
n_trials: int = 15,
seed: int = 42,
) -> dict[str, Any]:
"""Demonstrate Ng & Jordan (2001) O(log d) GNB small-sample vs O(d) Discriminative asymptotic win."""
rng = _make_rng(seed)
# 12 correlated signal dims (var=0.36, pair corr=0.72, opposite signs creating GNB bias)
# plus remaining high-variance noise distractors (var=4.5):
# GNB normalizes coordinate variances in O(log d) samples; raw LinearSVM needs O(d) samples
# to suppress noise dims and untangle correlations, then beats GNB's asymptotic error floor.
n_sig = min(d, 12)
cov = np.eye(d, dtype=np.float64)
for j in range(n_sig):
cov[j, j] = 0.36
for b_start in range(0, n_sig - 1, 2):
cov[b_start, b_start + 1] = cov[b_start + 1, b_start] = 0.72 * 0.36
for j in range(n_sig, d):
cov[j, j] = 4.5
chol = np.linalg.cholesky(cov)
mu_pos = np.zeros(d, dtype=np.float64)
mu_pos[0:n_sig:2] = 0.42
mu_pos[1:n_sig:2] = -0.10
mu_neg = -mu_pos
n_test = 1500
y_test = np.where(np.arange(n_test) < n_test // 2, 1.0, -1.0)
X_test = rng.standard_normal((n_test, d)) @ chol.T + np.where(
y_test[:, None] > 0.0, mu_pos[None, :], mu_neg[None, :]
)
rows: list[dict[str, float]] = []
for n_tr in sample_sizes:
err_gnb: list[float] = []
err_lda: list[float] = []
err_svm: list[float] = []
for t_idx in range(n_trials):
n_half = n_tr // 2
y_tr = np.concatenate([np.ones(n_half), -np.ones(n_tr - n_half)])
X_tr = rng.standard_normal((n_tr, d)) @ chol.T + np.where(
y_tr[:, None] > 0.0, mu_pos[None, :], mu_neg[None, :]
)
gnb = GaussianNaiveBayesClassifier(shared_variance=True, var_smoothing=0.05).fit(
X_tr, y_tr
)
lda = ShrinkageLDAClassifier(shrinkage=0.10).fit(X_tr, y_tr)
svm = LinearSVMPrimal(c_reg=2.0, solver="dcd", seed=seed + t_idx).fit(X_tr, y_tr)
err_gnb.append(float(np.mean(gnb.predict(X_test) != y_test)))
err_lda.append(float(np.mean(lda.predict(X_test) != y_test)))
err_svm.append(float(np.mean(svm.predict(X_test) != y_test)))
rows.append(
{
"n_train": int(n_tr),
"gnb_error": float(np.mean(err_gnb)),
"lda_error": float(np.mean(err_lda)),
"svm_error": float(np.mean(err_svm)),
}
)
return {
"d_features": int(d),
"curve": rows,
"small_n_gnb_beats_svm": bool(rows[0]["gnb_error"] < rows[0]["svm_error"]),
"large_n_svm_beats_gnb": bool(rows[-1]["svm_error"] < rows[-1]["gnb_error"]),
}
"""Mercer Kernels, Scaling/Steinwart Diagnostics, RFF/ORF/QMC, Nystrom, NTK, Linear Attention & Benchmarks (T1-P2-U04)."""
from __future__ import annotations
import math
import time
from typing import Any, Literal
import numpy as np
from svm_kernels_lab.primal_and_dual_svm import (
EpsilonSVR,
KernelSMOSolver,
LinearSVMPrimal,
MulticlassSVM,
OneClassSVMSolver,
PlattCalibrator,
SVDDSolver,
_make_rng,
_pairwise_sq_dists,
compute_ece,
compute_median_heuristic_gamma,
evaluate_kernel_matrix,
simulate_ng_jordan_crossover,
)
def _norm_cdf(x: float) -> float:
"""Standard normal CDF via math.erfc (zero scipy)."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def _acklam_norm_ppf(u: np.ndarray) -> np.ndarray:
"""Acklam rational inverse standard normal CDF for QMC sequences (max err < 1.15e-9)."""
p = np.clip(np.asarray(u, dtype=np.float64), 1e-12, 1.0 - 1e-12)
a = np.array(
[
-3.969683028665376e01,
2.209460984245205e02,
-2.759285104469687e02,
1.383577518672690e02,
-3.066479806614716e01,
2.506628277459239e00,
]
)
b = np.array(
[
-5.447609879822406e01,
1.615858368580409e02,
-1.556989798598866e02,
6.680131188771972e01,
-1.328068155288572e01,
]
)
c = np.array(
[
-7.784894002430293e-03,
-3.223964580411365e-01,
-2.400758277161838e00,
-2.549732539343734e00,
4.374664141464968e00,
2.938163982698783e00,
]
)
d = np.array(
[
7.784695709041462e-03,
3.224671290700398e-01,
2.445134137142996e00,
3.754408661907416e00,
]
)
p_low = 0.02425
p_high = 1.0 - p_low
out = np.empty_like(p)
m_low = p < p_low
if np.any(m_low):
q = np.sqrt(-2.0 * np.log(p[m_low]))
out[m_low] = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / (
(((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0
)
m_mid = (~m_low) & (p <= p_high)
if np.any(m_mid):
q = p[m_mid] - 0.5
r = q * q
out[m_mid] = (
(((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q
) / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1.0)
m_high = p > p_high
if np.any(m_high):
q = np.sqrt(-2.0 * np.log(1.0 - p[m_high]))
out[m_high] = -(
(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5])
/ ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0)
)
return out
def explicit_poly2_feature_map(X: np.ndarray, gamma: float = 1.0, coef0: float = 1.0) -> np.ndarray:
"""Construct exact D = (d+2)(d+1)/2 monomial lift phi(x) for (gamma <x,z> + coef0)^2."""
X_arr = np.asarray(X, dtype=np.float64)
n, d = X_arr.shape
cols: list[np.ndarray] = [np.full((n, 1), float(coef0), dtype=np.float64)]
if coef0 > 0.0:
cols.append(np.sqrt(2.0 * gamma * coef0) * X_arr)
cols.append(gamma * (X_arr * X_arr))
if d > 1:
cross = []
scale = math.sqrt(2.0) * gamma
for j in range(d):
for k in range(j + 1, d):
cross.append(scale * X_arr[:, j] * X_arr[:, k])
cols.append(np.column_stack(cross))
return np.hstack(cols)
def string_spectrum_kernel(strings_a: list[str], strings_b: list[str], k: int = 3) -> np.ndarray:
"""Compute exact k-mer spectrum kernel K(s, t) = sum_u count(u, s) * count(u, t)."""
def _counts(s: str) -> dict[str, int]:
out: dict[str, int] = {}
for i in range(max(0, len(s) - k + 1)):
sub = s[i : i + k]
out[sub] = out.get(sub, 0) + 1
return out
maps_a = [_counts(s) for s in strings_a]
maps_b = [_counts(s) for s in strings_b]
K = np.zeros((len(maps_a), len(maps_b)), dtype=np.float64)
for i, ma in enumerate(maps_a):
for j, mb in enumerate(maps_b):
if len(ma) <= len(mb):
K[i, j] = float(sum(v * mb.get(tok, 0) for tok, v in ma.items()))
else:
K[i, j] = float(sum(v * ma.get(tok, 0) for tok, v in mb.items()))
return K
def audit_kernel_psd(K: np.ndarray, tol: float = 1e-9) -> dict[str, Any]:
"""Verify symmetry and spectral positive semi-definiteness (Mercer check)."""
K_arr = np.asarray(K, dtype=np.float64)
sym_err = float(np.max(np.abs(K_arr - K_arr.T)))
eigs = np.linalg.eigvalsh(0.5 * (K_arr + K_arr.T))
min_eig = float(np.min(eigs))
max_eig = float(np.max(eigs))
return {
"symmetry_max_err": sym_err,
"min_eigenvalue": min_eig,
"max_eigenvalue": max_eig,
"is_psd": bool(sym_err <= 1e-8 and min_eig >= -tol),
}
def compute_gram_memory_footprint(n: int, dtype_bytes: int = 8) -> dict[str, float]:
"""Return exact dense Gram matrix memory footprint in MB, GB, and TB (SI base-10^9/10^6)."""
total_bytes = float(n) * float(n) * float(dtype_bytes)
return {
"n_samples": float(n),
"dtype_bytes": float(dtype_bytes),
"bytes": total_bytes,
"megabytes": total_bytes / 1e6,
"gigabytes": total_bytes / 1e9,
"terabytes": total_bytes / 1e12,
}
class RandomPhaseCosRFF:
"""Rahimi & Recht (2007) random-phase RFF: z(x) = sqrt(2/D) * cos(W x + b)."""
def __init__(
self,
n_components: int = 128,
gamma: float = 0.1,
kernel: Literal["rbf", "laplace"] = "rbf",
seed: int = 42,
) -> None:
self.n_components = int(n_components)
self.gamma = float(gamma)
self.kernel = kernel
self.seed = int(seed)
self.weights_: np.ndarray | None = None
self.offsets_: np.ndarray | None = None
def fit(self, X: np.ndarray) -> RandomPhaseCosRFF:
d = np.asarray(X, dtype=np.float64).shape[1]
rng = _make_rng(self.seed)
if self.kernel == "rbf":
self.weights_ = rng.normal(0.0, math.sqrt(2.0 * self.gamma), size=(d, self.n_components))
elif self.kernel == "laplace":
self.weights_ = self.gamma * rng.standard_cauchy(size=(d, self.n_components))
else:
raise ValueError(f"Unsupported kernel for RFF: {self.kernel}")
self.offsets_ = rng.uniform(0.0, 2.0 * math.pi, size=self.n_components)
return self
def transform(self, X: np.ndarray) -> np.ndarray:
assert self.weights_ is not None and self.offsets_ is not None
proj = np.asarray(X, dtype=np.float64) @ self.weights_ + self.offsets_[None, :]
return math.sqrt(2.0 / float(self.n_components)) * np.cos(proj)
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
class PairedSinCosRFF:
"""Sutherland & Schneider (2015) paired sin/cos RFF with exact output dim D_out (even)."""
def __init__(
self,
n_components: int = 128,
gamma: float = 0.1,
kernel: Literal["rbf", "laplace"] = "rbf",
seed: int = 42,
) -> None:
if n_components % 2 != 0:
raise ValueError("PairedSinCosRFF requires even n_components = 2 * n_freqs.")
self.n_components = int(n_components)
self.n_freqs = self.n_components // 2
self.gamma = float(gamma)
self.kernel = kernel
self.seed = int(seed)
self.weights_: np.ndarray | None = None
def fit(self, X: np.ndarray) -> PairedSinCosRFF:
d = np.asarray(X, dtype=np.float64).shape[1]
rng = _make_rng(self.seed)
if self.kernel == "rbf":
self.weights_ = rng.normal(0.0, math.sqrt(2.0 * self.gamma), size=(d, self.n_freqs))
elif self.kernel == "laplace":
self.weights_ = self.gamma * rng.standard_cauchy(size=(d, self.n_freqs))
else:
raise ValueError(f"Unsupported kernel for RFF: {self.kernel}")
return self
def transform(self, X: np.ndarray) -> np.ndarray:
assert self.weights_ is not None
proj = np.asarray(X, dtype=np.float64) @ self.weights_
scale = 1.0 / math.sqrt(float(self.n_freqs))
return scale * np.hstack([np.cos(proj), np.sin(proj)])
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
class OrthogonalRandomFeatures:
"""Yu et al. (2016) Orthogonal Random Features (Haar QR orthogonal + chi_d scaling, paired sin/cos)."""
def __init__(self, n_components: int = 128, gamma: float = 0.1, seed: int = 42) -> None:
if n_components % 2 != 0:
raise ValueError("OrthogonalRandomFeatures requires even n_components = 2 * n_freqs.")
self.n_components = int(n_components)
self.n_freqs = self.n_components // 2
self.gamma = float(gamma)
self.seed = int(seed)
self.weights_: np.ndarray | None = None
def fit(self, X: np.ndarray) -> OrthogonalRandomFeatures:
d = np.asarray(X, dtype=np.float64).shape[1]
rng = _make_rng(self.seed)
n_blocks = math.ceil(self.n_freqs / float(d))
blocks: list[np.ndarray] = []
for _ in range(n_blocks):
G = rng.standard_normal((d, d))
Q, R = np.linalg.qr(G)
# Enforce Haar uniformity by absorbing signs of diag(R)
signs = np.where(np.diag(R) >= 0.0, 1.0, -1.0)
Q_haar = Q * signs[None, :]
# Chi_d radial lengths match ||N(0, I_d)||_2 marginally
chi_norms = np.linalg.norm(rng.standard_normal((d, d)), axis=0)
W_blk = math.sqrt(2.0 * self.gamma) * (Q_haar * chi_norms[None, :])
blocks.append(W_blk)
W_all = np.hstack(blocks)[:, : self.n_freqs]
self.weights_ = W_all
return self
def transform(self, X: np.ndarray) -> np.ndarray:
assert self.weights_ is not None
proj = np.asarray(X, dtype=np.float64) @ self.weights_
scale = 1.0 / math.sqrt(float(self.n_freqs))
return scale * np.hstack([np.cos(proj), np.sin(proj)])
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
class HaltonQMCRFF:
"""Quasi-Monte Carlo Halton RFF via Acklam inverse normal CDF + paired sin/cos."""
def __init__(self, n_components: int = 128, gamma: float = 0.1) -> None:
if n_components % 2 != 0:
raise ValueError("HaltonQMCRFF requires even n_components.")
self.n_components = int(n_components)
self.n_freqs = self.n_components // 2
self.gamma = float(gamma)
self.weights_: np.ndarray | None = None
@staticmethod
def _van_der_corput(n_pts: int, base: int) -> np.ndarray:
seq = np.empty(n_pts, dtype=np.float64)
for i in range(1, n_pts + 1):
val = 0.0
f = 1.0 / float(base)
idx = i
while idx > 0:
val += f * float(idx % base)
idx //= base
f /= float(base)
seq[i - 1] = val
return seq
@staticmethod
def _first_primes(count: int) -> list[int]:
primes: list[int] = []
cand = 2
while len(primes) < count:
if all(cand % p != 0 for p in primes):
primes.append(cand)
cand += 1
return primes
def fit(self, X: np.ndarray) -> HaltonQMCRFF:
d = np.asarray(X, dtype=np.float64).shape[1]
primes = self._first_primes(d)
U = np.vstack([self._van_der_corput(self.n_freqs, p) for p in primes])
Z = _acklam_norm_ppf(U)
self.weights_ = math.sqrt(2.0 * self.gamma) * Z
return self
def transform(self, X: np.ndarray) -> np.ndarray:
assert self.weights_ is not None
proj = np.asarray(X, dtype=np.float64) @ self.weights_
scale = 1.0 / math.sqrt(float(self.n_freqs))
return scale * np.hstack([np.cos(proj), np.sin(proj)])
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
class NystromFeatures:
"""Data-dependent Nystrom low-rank kernel approximation with eig floor & weight folding."""
def __init__(
self,
n_components: int = 64,
kernel: str = "rbf",
gamma: float = 0.1,
degree: int = 3,
coef0: float = 1.0,
landmark_mode: Literal["uniform", "kmeans", "leverage"] = "kmeans",
eig_floor: float = 1e-10,
seed: int = 42,
) -> None:
self.n_components = int(n_components)
self.kernel = kernel
self.gamma = float(gamma)
self.degree = int(degree)
self.coef0 = float(coef0)
self.landmark_mode = landmark_mode
self.eig_floor = float(eig_floor)
self.seed = int(seed)
self.landmarks_: np.ndarray | None = None
self.whitening_mat_: np.ndarray | None = None
self.effective_rank_: int = 0
self.top_eigenvalues_: np.ndarray = np.array([], dtype=np.float64)
def _select_kmeans_landmarks(self, X: np.ndarray, m: int, rng: np.random.Generator) -> np.ndarray:
n = X.shape[0]
init_idx = rng.choice(n, size=m, replace=False)
centers = X[init_idx].copy()
for _ in range(12):
dists = _pairwise_sq_dists(X, centers)
assign = np.argmin(dists, axis=1)
new_centers = np.empty_like(centers)
for k_idx in range(m):
pts = X[assign == k_idx]
if pts.shape[0] > 0:
new_centers[k_idx] = np.mean(pts, axis=0)
else:
new_centers[k_idx] = X[int(rng.integers(0, n))]
if float(np.max(np.abs(new_centers - centers))) < 1e-6:
centers = new_centers
break
centers = new_centers
return centers
def _select_leverage_landmarks(
self, X: np.ndarray, m: int, rng: np.random.Generator, reg: float = 1e-2
) -> np.ndarray:
"""Two-stage approximate Ridge Leverage Score (RLS) landmark sampling."""
n = X.shape[0]
pilot_m = min(n, max(16, m // 2))
pilot = X[rng.choice(n, size=pilot_m, replace=False)]
K_np = evaluate_kernel_matrix(
X, pilot, kernel=self.kernel, gamma=self.gamma, degree=self.degree, coef0=self.coef0
)
K_pp = evaluate_kernel_matrix(
pilot, pilot, kernel=self.kernel, gamma=self.gamma, degree=self.degree, coef0=self.coef0
)
# Approximate leverage scores tau_i ~ diag(K_np (K_np^T K_np + n*reg*K_pp)^+ K_np^T)
mat = K_np.T @ K_np + float(n) * reg * (K_pp + 1e-8 * np.eye(pilot_m))
inv_mat = np.linalg.pinv(mat)
scores = np.sum((K_np @ inv_mat) * K_np, axis=1)
probs = np.maximum(scores, 1e-12)
probs /= float(np.sum(probs))
idx = rng.choice(n, size=m, replace=False, p=probs)
return X[idx].copy()
def fit(self, X: np.ndarray) -> NystromFeatures:
X_arr = np.asarray(X, dtype=np.float64)
n = X_arr.shape[0]
m = min(n, self.n_components)
rng = _make_rng(self.seed)
if self.landmark_mode == "uniform":
landmarks = X_arr[rng.choice(n, size=m, replace=False)].copy()
elif self.landmark_mode == "kmeans":
landmarks = self._select_kmeans_landmarks(X_arr, m, rng)
elif self.landmark_mode == "leverage":
landmarks = self._select_leverage_landmarks(X_arr, m, rng)
else:
raise ValueError(f"Unknown landmark_mode: {self.landmark_mode}")
K_mm = evaluate_kernel_matrix(
landmarks,
landmarks,
kernel=self.kernel,
gamma=self.gamma,
degree=self.degree,
coef0=self.coef0,
)
K_mm = 0.5 * (K_mm + K_mm.T)
eigvals, eigvecs = np.linalg.eigh(K_mm)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
floor = max(self.eig_floor, 1e-12 * max(1.0, float(eigvals[0])))
keep = eigvals > floor
if not np.any(keep):
keep[0] = True
evals_k = eigvals[keep]
evecs_k = eigvecs[:, keep]
whitening = evecs_k / np.sqrt(evals_k)[None, :]
self.landmarks_ = landmarks
self.whitening_mat_ = whitening
self.effective_rank_ = int(evals_k.shape[0])
self.top_eigenvalues_ = eigvals
return self
def transform(self, X: np.ndarray) -> np.ndarray:
assert self.landmarks_ is not None and self.whitening_mat_ is not None
K_nm = evaluate_kernel_matrix(
np.asarray(X, dtype=np.float64),
self.landmarks_,
kernel=self.kernel,
gamma=self.gamma,
degree=self.degree,
coef0=self.coef0,
)
return K_nm @ self.whitening_mat_
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
def fold_linear_weights(self, w: np.ndarray) -> np.ndarray:
"""Pre-fold primal weights beta = U_r Lambda_r^{-1/2} w for O(m*d) direct inference."""
assert self.whitening_mat_ is not None
return self.whitening_mat_ @ np.asarray(w, dtype=np.float64)
def run_scaling_and_island_diagnostics(seed: int = 42) -> dict[str, Any]:
"""Reproduce Tip 1 unscaled RBF collapse & Tip 2 (C, gamma) memorization islands."""
rng = _make_rng(seed)
n_tr, n_te = 220, 180
n_tot = n_tr + n_te
def _gen_ecom(n: int) -> tuple[np.ndarray, np.ndarray]:
cart_usd = np.exp(rng.normal(4.8, 1.05, size=n)) # [~10, 5000] USD
rates = rng.beta(2.0, 12.0, size=(n, 9)) # [0, 1] behavioral rates
X = np.column_stack([cart_usd, rates])
z_cart = (np.log1p(cart_usd) - 4.8) / 1.05
z_r1 = (rates[:, 0] - 0.143) / 0.088
z_r2 = (rates[:, 1] - 0.143) / 0.088
# Radial non-linear propensity surface inside standardized behavioral space
score = 1.65 - (z_r1 * z_r1 + z_r2 * z_r2 + 0.55 * z_cart * z_cart) + 0.45 * z_r1 * z_cart
y = np.where(score + rng.normal(0.0, 0.25, size=n) >= 0.0, 1.0, -1.0)
return X, y
X_all, y_all = _gen_ecom(n_tot)
X_tr, X_te = X_all[:n_tr], X_all[n_tr:]
y_tr, y_te = y_all[:n_tr], y_all[n_tr:]
# 1) Unscaled gamma='auto' (= 1/d = 0.1) -> K -> I_n identity collapse
K_unscaled = evaluate_kernel_matrix(X_tr, X_tr, kernel="rbf", gamma=1.0 / X_tr.shape[1])
iu = np.triu_indices(n_tr, k=1)
med_k_unscaled_auto = float(np.median(K_unscaled[iu]))
svm_unscaled_auto = KernelSMOSolver(c_reg=2.0, kernel="rbf", gamma="auto", max_iter=2500).fit(
X_tr, y_tr
)
acc_unscaled_auto_tr = float(np.mean(svm_unscaled_auto.predict(X_tr) == y_tr))
acc_unscaled_auto_te = float(np.mean(svm_unscaled_auto.predict(X_te) == y_te))
# 2) Unscaled gamma='scale' -> Var_flat dominated by cart_usd, erasing behavioral rates
svm_unscaled_scale = KernelSMOSolver(c_reg=2.0, kernel="rbf", gamma="scale", max_iter=2500).fit(
X_tr, y_tr
)
acc_unscaled_scale_te = float(np.mean(svm_unscaled_scale.predict(X_te) == y_te))
# 3) In-fold log1p on skewed USD + StandardScaler + median heuristic
X_tr_clean = X_tr.copy()
X_te_clean = X_te.copy()
X_tr_clean[:, 0] = np.log1p(X_tr_clean[:, 0])
X_te_clean[:, 0] = np.log1p(X_te_clean[:, 0])
mu = np.mean(X_tr_clean, axis=0)
sd = np.maximum(np.std(X_tr_clean, axis=0), 1e-8)
X_tr_std = (X_tr_clean - mu) / sd
X_te_std = (X_te_clean - mu) / sd
g_med = compute_median_heuristic_gamma(X_tr_std, seed=seed)
K_scaled = evaluate_kernel_matrix(X_tr_std, X_tr_std, kernel="rbf", gamma=g_med)
med_k_scaled = float(np.median(K_scaled[iu]))
svm_scaled = KernelSMOSolver(c_reg=4.0, kernel="rbf", gamma=g_med, max_iter=3000).fit(
X_tr_std, y_tr
)
acc_scaled_te = float(np.mean(svm_scaled.predict(X_te_std) == y_te))
# 4) Memorization island regime (high C=1000, high gamma=10.0 on standardized data)
svm_island = KernelSMOSolver(c_reg=1000.0, kernel="rbf", gamma=10.0, max_iter=3500).fit(
X_tr_std, y_tr
)
acc_island_tr = float(np.mean(svm_island.predict(X_tr_std) == y_tr))
acc_island_te = float(np.mean(svm_island.predict(X_te_std) == y_te))
island_sv_ratio = float(svm_island.kkt_summary_["sv_fraction"])
return {
"unscaled_auto_median_k": med_k_unscaled_auto,
"unscaled_auto_sv_ratio": float(svm_unscaled_auto.kkt_summary_["sv_fraction"]),
"unscaled_auto_train_acc": acc_unscaled_auto_tr,
"unscaled_auto_test_acc": acc_unscaled_auto_te,
"unscaled_scale_gamma": float(svm_unscaled_scale.gamma_resolved_),
"unscaled_scale_test_acc": acc_unscaled_scale_te,
"scaled_median_gamma": float(g_med),
"scaled_median_k": med_k_scaled,
"scaled_test_acc": acc_scaled_te,
"scaled_sv_ratio": float(svm_scaled.kkt_summary_["sv_fraction"]),
"island_train_acc": acc_island_tr,
"island_test_acc": acc_island_te,
"island_sv_ratio": island_sv_ratio,
"majority_baseline_acc": float(max(np.mean(y_te > 0), np.mean(y_te < 0))),
}
def run_steinwart_nonsparsity_experiment(seed: int = 42) -> list[dict[str, float]]:
"""Verify Steinwart (2003): n_SV / n -> 2 * R^* as Bayes risk R^* increases."""
rng = _make_rng(seed)
# Two isotropic 2D Gaussians N(+mu, I) vs N(-mu, I); exact Bayes risk R^* = Phi(-||mu||_2)
configs = [
("separable_low_risk", 3.2), # R^* ~ 0.0007
("moderate_overlap", 1.40), # R^* ~ 0.0808 -> 2 R^* ~ 0.162
("noisy_overlap", 0.92), # R^* ~ 0.1788 -> 2 R^* ~ 0.358
]
n = 260
rows: list[dict[str, float]] = []
for label, mu_norm in configs:
mu = np.array([mu_norm / math.sqrt(2.0), mu_norm / math.sqrt(2.0)], dtype=np.float64)
y = np.concatenate([np.ones(n // 2), -np.ones(n - n // 2)])
X = rng.standard_normal((n, 2)) + np.where(y[:, None] > 0.0, mu[None, :], -mu[None, :])
r_bayes = _norm_cdf(-mu_norm)
clf = KernelSMOSolver(c_reg=1.0, kernel="rbf", gamma=0.35, tol=1e-3, max_iter=5000).fit(
X, y
)
sv_frac = float(clf.kkt_summary_["sv_fraction"])
rows.append(
{
"regime": label,
"mu_norm": float(mu_norm),
"bayes_risk_r_star": float(r_bayes),
"theoretical_2r_star": float(2.0 * r_bayes),
"empirical_sv_fraction": sv_frac,
"n_support_vectors": int(clf.kkt_summary_["n_support_vectors"]),
"n_samples": int(n),
}
)
return rows
def benchmark_rff_variants(
n: int = 64,
d: int = 4,
gamma: float = 0.20,
dim_out: int = 64,
n_trials: int = 40,
seed: int = 42,
) -> dict[str, Any]:
"""Compare Random-Phase vs Paired Sin/Cos vs ORF vs Halton-QMC at equal output dim."""
rng = _make_rng(seed)
X = rng.standard_normal((n, d)) * 0.75
K_exact = evaluate_kernel_matrix(X, X, kernel="rbf", gamma=gamma)
iu = np.triu_indices(n, k=1)
k_off = K_exact[iu]
cos_errs = np.zeros((n_trials, k_off.size), dtype=np.float64)
sc_errs = np.zeros((n_trials, k_off.size), dtype=np.float64)
orf_errs = np.zeros((n_trials, k_off.size), dtype=np.float64)
sc_diag_max_err = 0.0
cos_diag_var_samples: list[float] = []
for t in range(n_trials):
s_t = seed + 101 * t
Z_cos = RandomPhaseCosRFF(n_components=dim_out, gamma=gamma, seed=s_t).fit_transform(X)
Z_sc = PairedSinCosRFF(n_components=dim_out, gamma=gamma, seed=s_t).fit_transform(X)
Z_orf = OrthogonalRandomFeatures(n_components=dim_out, gamma=gamma, seed=s_t).fit_transform(X)
Kc = Z_cos @ Z_cos.T
Ks = Z_sc @ Z_sc.T
Ko = Z_orf @ Z_orf.T
cos_errs[t] = Kc[iu] - k_off
sc_errs[t] = Ks[iu] - k_off
orf_errs[t] = Ko[iu] - k_off
sc_diag_max_err = max(sc_diag_max_err, float(np.max(np.abs(np.diag(Ks) - 1.0))))
cos_diag_var_samples.append(float(np.var(np.diag(Kc))))
qmc = HaltonQMCRFF(n_components=dim_out, gamma=gamma).fit_transform(X)
Kq = qmc @ qmc.T
qmc_rmse = float(np.sqrt(np.mean((Kq[iu] - k_off) ** 2)))
var_cos = float(np.mean(np.var(cos_errs, axis=0)))
var_sc = float(np.mean(np.var(sc_errs, axis=0)))
var_orf = float(np.mean(np.var(orf_errs, axis=0)))
return {
"dim_out": int(dim_out),
"n_trials": int(n_trials),
"cos_mean_bias": float(np.mean(cos_errs)),
"paired_sc_mean_bias": float(np.mean(sc_errs)),
"cos_offdiag_var": var_cos,
"paired_sc_offdiag_var": var_sc,
"orf_offdiag_var": var_orf,
"cos_offdiag_rmse": float(np.sqrt(np.mean(cos_errs**2))),
"paired_sc_offdiag_rmse": float(np.sqrt(np.mean(sc_errs**2))),
"orf_offdiag_rmse": float(np.sqrt(np.mean(orf_errs**2))),
"halton_qmc_offdiag_rmse": qmc_rmse,
"paired_sc_diag_norm_max_err": float(sc_diag_max_err),
"cos_diag_norm_var": float(np.mean(cos_diag_var_samples)),
"sutherland_schneider_var_strictly_lower": bool(var_sc < var_cos),
}
def compare_nystrom_vs_rff(seed: int = 42) -> dict[str, Any]:
"""Reproduce Yang et al. (2012): Nystrom dominates RFF on rapid-decay clustered manifolds."""
rng = _make_rng(seed)
n_tr, n_te, d = 320, 200, 12
# Clustered manifold (6 tight clusters) -> fast Gram eigenspectrum decay (low d_eff)
centers = rng.normal(0.0, 2.2, size=(6, d))
center_labels = np.array([1.0, -1.0, 1.0, -1.0, 1.0, -1.0])
cid_tr = rng.integers(0, 6, size=n_tr)
cid_te = rng.integers(0, 6, size=n_te)
X_tr = centers[cid_tr] + rng.normal(0.0, 0.35, size=(n_tr, d))
y_tr = center_labels[cid_tr]
X_te = centers[cid_te] + rng.normal(0.0, 0.35, size=(n_te, d))
y_te = center_labels[cid_te]
gamma = 0.08
K_tr = evaluate_kernel_matrix(X_tr, X_tr, kernel="rbf", gamma=gamma)
eigs = np.sort(np.linalg.eigvalsh(K_tr))[::-1]
eigs_pos = np.maximum(eigs, 0.0)
top16_energy = float(np.sum(eigs_pos[:16]) / max(1e-12, float(np.sum(eigs_pos))))
budget = 32
rff = PairedSinCosRFF(n_components=budget, gamma=gamma, seed=seed).fit(X_tr)
Z_rff_tr, Z_rff_te = rff.transform(X_tr), rff.transform(X_te)
svm_rff = LinearSVMPrimal(c_reg=4.0, solver="dcd", seed=seed).fit(Z_rff_tr, y_tr)
acc_rff = float(np.mean(svm_rff.predict(Z_rff_te) == y_te))
nys = NystromFeatures(
n_components=budget, kernel="rbf", gamma=gamma, landmark_mode="kmeans", seed=seed
).fit(X_tr)
Z_nys_tr, Z_nys_te = nys.transform(X_tr), nys.transform(X_te)
svm_nys = LinearSVMPrimal(c_reg=4.0, solver="dcd", seed=seed).fit(Z_nys_tr, y_tr)
acc_nys = float(np.mean(svm_nys.predict(Z_nys_te) == y_te))
# Gram reconstruction Frobenius relative error
K_hat_rff = Z_rff_tr @ Z_rff_tr.T
K_hat_nys = Z_nys_tr @ Z_nys_tr.T
frob_k = float(np.linalg.norm(K_tr, "fro"))
rel_err_rff = float(np.linalg.norm(K_tr - K_hat_rff, "fro")) / frob_k
rel_err_nys = float(np.linalg.norm(K_tr - K_hat_nys, "fro")) / frob_k
# Verify Schur complement PSD: K_tr - K_hat_nys >= 0
resid_min_eig = float(np.min(np.linalg.eigvalsh(0.5 * ((K_tr - K_hat_nys) + (K_tr - K_hat_nys).T))))
# Verify exact weight folding parity: Z_nys(X_te) @ w == K(X_te, C) @ beta
assert svm_nys.coef_ is not None
beta_folded = nys.fold_linear_weights(svm_nys.coef_)
K_te_c = evaluate_kernel_matrix(X_te, nys.landmarks_, kernel="rbf", gamma=gamma)
pred_direct = Z_nys_te @ svm_nys.coef_ + svm_nys.intercept_
pred_folded = K_te_c @ beta_folded + svm_nys.intercept_
folded_max_diff = float(np.max(np.abs(pred_direct - pred_folded)))
return {
"feature_budget": int(budget),
"top16_spectral_energy_ratio": top16_energy,
"rff_gram_rel_fro_err": rel_err_rff,
"nystrom_gram_rel_fro_err": rel_err_nys,
"rff_test_acc": acc_rff,
"nystrom_test_acc": acc_nys,
"schur_residual_min_eig": resid_min_eig,
"folded_inference_max_diff": folded_max_diff,
"nystrom_beats_rff_gram_error": bool(rel_err_nys < rel_err_rff),
}
def run_ntk_and_kta_bridge(seed: int = 42) -> dict[str, Any]:
"""Compute exact 2-layer tanh MLP NTK Jacobian Theta = J J^T and track KTA drift (Lazy vs Rich)."""
rng = _make_rng(seed)
n, d, width = 90, 4, 64
X = rng.standard_normal((n, d)) * 0.8
# Parity / quadratic interaction y_i = x_0 * x_1
y = np.tanh(1.5 * X[:, 0] * X[:, 1])
def _ntk_and_forward(
W1: np.ndarray, W2: np.ndarray, scale: float
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
pre = X @ W1 # (n, width)
h = np.tanh(pre)
f = scale * (h @ W2) # (n,)
dh = 1.0 - h * h # (n, width)
# Analytic Jacobian wrt W2 (n, width) and W1 (n, d * width)
J_w2 = scale * h
J_w1 = scale * (X[:, :, None] * (dh * W2[None, :])[:, None, :])
J_w1_flat = J_w1.reshape(n, d * width)
J = np.hstack([J_w1_flat, J_w2])
theta = J @ J.T
return f, theta, J
def _kta(K: np.ndarray, target: np.ndarray) -> float:
yy = np.outer(target, target)
denom = float(np.linalg.norm(K, "fro") * np.linalg.norm(yy, "fro"))
return float(np.sum(K * yy) / max(1e-12, denom))
# 1) Lazy NTK initialization (1/sqrt(width) scaling, small lr)
W1_lazy = rng.standard_normal((d, width))
W2_lazy = rng.standard_normal(width)
scale_lazy = 1.0 / math.sqrt(float(width))
_, theta_lazy_0, _ = _ntk_and_forward(W1_lazy, W2_lazy, scale_lazy)
kta_lazy_0 = _kta(theta_lazy_0, y)
W1_l, W2_l = W1_lazy.copy(), W2_lazy.copy()
lr_lazy = 0.015
for _ in range(30):
f_l, _, _ = _ntk_and_forward(W1_l, W2_l, scale_lazy)
err = (f_l - y) / float(n)
pre = X @ W1_l
h = np.tanh(pre)
dh = 1.0 - h * h
g_w2 = scale_lazy * (h.T @ err)
g_w1 = scale_lazy * (X.T @ ((err[:, None] * W2_l[None, :]) * dh))
W1_l -= lr_lazy * g_w1
W2_l -= lr_lazy * g_w2
_, theta_lazy_T, _ = _ntk_and_forward(W1_l, W2_l, scale_lazy)
lazy_rel_drift = float(
np.linalg.norm(theta_lazy_T - theta_lazy_0, "fro") / np.linalg.norm(theta_lazy_0, "fro")
)
# 2) Rich / muP-like feature learning (1/width readout scaling, strong step)
W1_rich = rng.standard_normal((d, width)) * 0.4
W2_rich = rng.standard_normal(width) * 0.4
scale_rich = 1.0 / float(width)
_, theta_rich_0, _ = _ntk_and_forward(W1_rich, W2_rich, scale_rich)
kta_rich_0 = _kta(theta_rich_0, y)
W1_r, W2_r = W1_rich.copy(), W2_rich.copy()
for _ in range(55):
f_r, _, _ = _ntk_and_forward(W1_r, W2_r, scale_rich)
err = (f_r - y) / float(n)
pre = X @ W1_r
h = np.tanh(pre)
dh = 1.0 - h * h
g_w2 = (1.5 * scale_rich) * (h.T @ err)
g_w1 = 2.8 * (X.T @ ((err[:, None] * W2_r[None, :]) * dh))
W1_r -= g_w1
W2_r -= g_w2
f_rich_T, theta_rich_T, _ = _ntk_and_forward(W1_r, W2_r, scale_rich)
kta_rich_T = _kta(theta_rich_T, y)
rich_rel_drift = float(
np.linalg.norm(theta_rich_T - theta_rich_0, "fro") / np.linalg.norm(theta_rich_0, "fro")
)
ntk_psd = audit_kernel_psd(theta_lazy_0)
# Compare NTK Kernel Ridge Prediction vs target
alpha_ntk = np.linalg.solve(theta_lazy_0 + 1e-4 * np.eye(n), y)
ntk_train_mse = float(np.mean((theta_lazy_0 @ alpha_ntk - y) ** 2))
return {
"ntk_is_psd": bool(ntk_psd["is_psd"]),
"ntk_train_mse": ntk_train_mse,
"lazy_ntk_rel_drift": lazy_rel_drift,
"rich_ntk_rel_drift": rich_rel_drift,
"kta_lazy_init": kta_lazy_0,
"kta_rich_init": kta_rich_0,
"kta_rich_final": kta_rich_T,
"rich_increases_kta": bool(kta_rich_T > kta_rich_0),
"rich_mse": float(np.mean((f_rich_T - y) ** 2)),
}
def run_softmax_attention_kernel_bridge(seed: int = 42) -> dict[str, Any]:
"""Compare O(L^2) exact Softmax Kernel Attention vs O(L) FAVOR+ & Taylor-2 (BASED)."""
rng = _make_rng(seed)
d_k, d_v = 8, 8
m_favor = 96
def _favor_phi(X: np.ndarray, W: np.ndarray) -> np.ndarray:
# Positive orthogonal random features: Choromanski et al. (ICLR 2021)
sq = 0.5 * np.sum(X * X, axis=1, keepdims=True)
proj = X @ W
scale = 1.0 / math.sqrt(float(2 * W.shape[1]))
return scale * np.hstack(
[np.exp(np.clip(proj - sq, -30.0, 20.0)), np.exp(np.clip(-proj - sq, -30.0, 20.0))]
)
def _taylor2_phi(X: np.ndarray) -> np.ndarray:
# 2nd-order Taylor feature map [1, x, vec(x x^T)/sqrt(2)] (BASED)
n_s, dim = X.shape
outer = (X[:, :, None] * X[:, None, :]).reshape(n_s, dim * dim) / math.sqrt(2.0)
return np.hstack([np.ones((n_s, 1)), X, outer])
# Orthogonal Gaussian projection matrix for FAVOR+
n_blk = math.ceil(m_favor / float(d_k))
q_blocks = []
for _ in range(n_blk):
Q, R = np.linalg.qr(rng.standard_normal((d_k, d_k)))
Q_h = Q * np.where(np.diag(R) >= 0.0, 1.0, -1.0)[None, :]
norms = np.linalg.norm(rng.standard_normal((d_k, d_k)), axis=0)
q_blocks.append(Q_h * norms[None, :])
W_orth = np.hstack(q_blocks)[:, :m_favor]
# Check exact O(L^2) vs O(L) associative parity & positivity on structured semantic heads (L=128)
L_check = 128
anchors = rng.standard_normal((6, d_k)) * 0.45
Q_c = anchors[rng.integers(0, 6, size=L_check)] + rng.normal(0.0, 0.18, size=(L_check, d_k))
K_c = anchors[rng.integers(0, 6, size=L_check)] + rng.normal(0.0, 0.18, size=(L_check, d_k))
V_c = (K_c @ rng.standard_normal((d_k, d_v))) + 0.5
logits = Q_c @ K_c.T
logits -= np.max(logits, axis=1, keepdims=True)
A_soft = np.exp(logits)
A_soft /= np.sum(A_soft, axis=1, keepdims=True)
out_softmax = A_soft @ V_c
phi_q_fav = _favor_phi(Q_c, W_orth)
phi_k_fav = _favor_phi(K_c, W_orth)
# Quadratic explicit kernel vs O(L) associative KV factorization
kv_fav = phi_k_fav.T @ V_c
z_fav = np.sum(phi_k_fav, axis=0)
out_fav_linear = (phi_q_fav @ kv_fav) / np.maximum(phi_q_fav @ z_fav, 1e-12)[:, None]
K_fav_mat = phi_q_fav @ phi_k_fav.T
out_fav_quad = (K_fav_mat @ V_c) / np.maximum(np.sum(K_fav_mat, axis=1, keepdims=True), 1e-12)
favor_associative_diff = float(np.max(np.abs(out_fav_linear - out_fav_quad)))
phi_q_t2 = _taylor2_phi(Q_c)
phi_k_t2 = _taylor2_phi(K_c)
kv_t2 = phi_k_t2.T @ V_c
z_t2 = np.sum(phi_k_t2, axis=0)
out_t2_linear = (phi_q_t2 @ kv_t2) / np.maximum(phi_q_t2 @ z_t2, 1e-12)[:, None]
favor_rel_err = float(np.linalg.norm(out_fav_linear - out_softmax) / np.linalg.norm(out_softmax))
taylor2_rel_err = float(np.linalg.norm(out_t2_linear - out_softmax) / np.linalg.norm(out_softmax))
# Latency sweep across L showing O(L^2) vs O(L) crossover
timing_rows: list[dict[str, float]] = []
for L_val in (256, 1024, 2048):
Ql = rng.standard_normal((L_val, d_k)) * (d_k ** -0.25)
Kl = rng.standard_normal((L_val, d_k)) * (d_k ** -0.25)
Vl = rng.standard_normal((L_val, d_v))
t0 = time.perf_counter()
lg = Ql @ Kl.T
lg -= np.max(lg, axis=1, keepdims=True)
w_s = np.exp(lg)
w_s /= np.sum(w_s, axis=1, keepdims=True)
_ = w_s @ Vl
ms_soft = (time.perf_counter() - t0) * 1000.0
t1 = time.perf_counter()
pq = _favor_phi(Ql, W_orth)
pk = _favor_phi(Kl, W_orth)
kv = pk.T @ Vl
zv = np.sum(pk, axis=0)
_ = (pq @ kv) / np.maximum(pq @ zv, 1e-12)[:, None]
ms_fav = (time.perf_counter() - t1) * 1000.0
timing_rows.append(
{
"seq_len": int(L_val),
"softmax_ms": float(ms_soft),
"favor_linear_ms": float(ms_fav),
"speedup": float(ms_soft / max(1e-6, ms_fav)),
}
)
return {
"favor_strictly_positive": bool(np.all(phi_q_fav > 0.0) and np.all(phi_k_fav > 0.0)),
"favor_associative_parity_diff": favor_associative_diff,
"favor_rel_l2_err": favor_rel_err,
"taylor2_rel_l2_err": taylor2_rel_err,
"timing_sweep": timing_rows,
}
def _auc_binary(y_01: np.ndarray, scores: np.ndarray) -> float:
"""Compute exact Mann-Whitney ROC-AUC without sklearn."""
pos = scores[y_01 > 0.5]
neg = scores[y_01 <= 0.5]
if pos.size == 0 or neg.size == 0:
return 0.5
diff = pos[:, None] - neg[None, :]
return float(np.mean((diff > 0.0) + 0.5 * (diff == 0.0)))
def _ndcg_at_k(relevances_sorted: np.ndarray, k: int = 10) -> float:
"""Compute NDCG@k for binary relevance sorted by predicted score descending."""
rel = relevances_sorted[:k]
discounts = 1.0 / np.log2(np.arange(2, rel.size + 2))
dcg = float(np.sum(rel * discounts))
ideal = np.sort(relevances_sorted)[::-1][:k]
idcg = float(np.sum(ideal * discounts))
return dcg / idcg if idcg > 0.0 else 0.0
def run_ecommerce_and_sparse_cases(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Run E-Commerce Personalization (E32:E35) & Sparse TF-IDF Case Benchmarks."""
rng = _make_rng(seed)
# --- Case 1: E-Commerce Personalization (E32:E35) ---
n_tr = 520 if quick else 750
n_cal = 260
n_te = 260
d_ec = 8
# Clustered user-category + dense session propensity with realistic ~22% conversion base rate
centers = rng.normal(0.0, 1.2, size=(5, d_ec))
cid = rng.integers(0, 5, size=n_tr + n_cal + n_te)
X_raw = centers[cid] + rng.normal(0.0, 0.45, size=(n_tr + n_cal + n_te, d_ec))
latent = (
1.6 * (X_raw[:, 0] * X_raw[:, 1])
+ 1.4 * X_raw[:, 2]
+ 1.1 * X_raw[:, 3]
- 0.7 * (X_raw[:, 0] ** 2 + X_raw[:, 1] ** 2)
- 1.8
)
probs_true = 1.0 / (1.0 + np.exp(-latent))
y_01 = (rng.random(n_tr + n_cal + n_te) < probs_true).astype(np.float64)
y_signed = np.where(y_01 > 0.5, 1.0, -1.0)
gross_margin = rng.uniform(12.0, 85.0, size=n_te)
X_tr, X_cal, X_te = X_raw[:n_tr], X_raw[n_tr : n_tr + n_cal], X_raw[n_tr + n_cal :]
y_tr_s, y_cal_01, y_te_01 = (
y_signed[:n_tr],
y_01[n_tr : n_tr + n_cal],
y_01[n_tr + n_cal :],
)
# Inside-fold StandardScaler
mu = np.mean(X_tr, axis=0)
sd = np.maximum(np.std(X_tr, axis=0), 1e-8)
X_tr_s = (X_tr - mu) / sd
X_cal_s = (X_cal - mu) / sd
X_te_s = (X_te - mu) / sd
gamma_ec = compute_median_heuristic_gamma(X_tr_s, seed=seed)
# Exact RBF SMO baseline
t0 = time.perf_counter()
exact_svm = KernelSMOSolver(c_reg=2.0, kernel="rbf", gamma=gamma_ec, tol=1e-3, max_iter=3500).fit(
X_tr_s, y_tr_s
)
t_exact_fit_ms = (time.perf_counter() - t0) * 1000.0
_ = exact_svm.decision_function(X_te_s[:200]) # warmup
t1 = time.perf_counter()
for _ in range(10):
dec_exact_te = exact_svm.decision_function(X_te_s[:200])
t_exact_inf_ms = ((time.perf_counter() - t1) * 1000.0) / 10.0
dec_exact_te = exact_svm.decision_function(X_te_s)
# Paired RFF (D=128) + DCD primal
d_rff = 128
t2 = time.perf_counter()
rff = PairedSinCosRFF(n_components=d_rff, gamma=gamma_ec, seed=seed).fit(X_tr_s)
Z_tr_r = rff.transform(X_tr_s)
svm_rff = LinearSVMPrimal(c_reg=0.5, solver="dcd", seed=seed).fit(Z_tr_r, y_tr_s)
t_rff_fit_ms = (time.perf_counter() - t2) * 1000.0
_ = svm_rff.decision_function(rff.transform(X_te_s[:200]))
t3 = time.perf_counter()
for _ in range(10):
_ = svm_rff.decision_function(rff.transform(X_te_s[:200]))
t_rff_inf_ms = ((time.perf_counter() - t3) * 1000.0) / 10.0
dec_rff_te = svm_rff.decision_function(rff.transform(X_te_s))
# Nystrom (m=48 k-means) + DCD primal with folded beta
m_nys = 48
t4 = time.perf_counter()
nys = NystromFeatures(
n_components=m_nys, kernel="rbf", gamma=gamma_ec, landmark_mode="kmeans", seed=seed
).fit(X_tr_s)
svm_nys = LinearSVMPrimal(c_reg=0.5, solver="dcd", seed=seed).fit(nys.transform(X_tr_s), y_tr_s)
assert svm_nys.coef_ is not None
beta_nys = nys.fold_linear_weights(svm_nys.coef_)
t_nys_fit_ms = (time.perf_counter() - t4) * 1000.0
assert nys.landmarks_ is not None
_ = evaluate_kernel_matrix(X_te_s[:200], nys.landmarks_, kernel="rbf", gamma=gamma_ec) @ beta_nys
t5 = time.perf_counter()
for _ in range(10):
_ = (
evaluate_kernel_matrix(X_te_s[:200], nys.landmarks_, kernel="rbf", gamma=gamma_ec)
@ beta_nys
+ svm_nys.intercept_
)
t_nys_inf_ms = ((time.perf_counter() - t5) * 1000.0) / 10.0
dec_nys_te = (
evaluate_kernel_matrix(X_te_s, nys.landmarks_, kernel="rbf", gamma=gamma_ec) @ beta_nys
+ svm_nys.intercept_
)
# Out-of-fold / disjoint D_cal Platt calibration bridge (ch-07)
dec_rff_cal = svm_rff.decision_function(rff.transform(X_cal_s))
naive_sig = 1.0 / (1.0 + np.exp(-np.clip(dec_rff_te, -20.0, 20.0)))
platt = PlattCalibrator().fit(dec_rff_cal, y_cal_01)
platt_prob = platt.predict_proba(dec_rff_te)
ece_naive = compute_ece(y_te_01, naive_sig)
ece_platt = compute_ece(y_te_01, platt_prob)
# Probability NDCG@10 & Expected-GMV top-10 value on 200-candidate slate
order_rff_prob = np.argsort(platt_prob)[::-1]
ndcg10_rff = _ndcg_at_k(y_te_01[order_rff_prob], k=10)
order_prop = np.argsort(platt_prob * gross_margin)[::-1]
realized_gmv_top10 = float(np.sum(y_te_01[order_prop[:10]] * gross_margin[order_prop[:10]]))
order_exact = np.argsort(dec_exact_te)[::-1]
ndcg10_exact = _ndcg_at_k(y_te_01[order_exact], k=10)
# Production projection at n=150,000, d=128
exact_150k_gb = compute_gram_memory_footprint(150_000, 8)["gigabytes"]
rff_state_kib = float(128 * 256 * 8 + 512 * 8) / 1024.0
nys_state_kib = float(256 * 128 * 8 + 256 * 256 * 8 + 256 * 8) / 1024.0
# --- Case 3: High-Dim Sparse Unit-Norm Catalog Text (d=400) ---
n_txt, d_txt = 240, 400
X_txt = np.zeros((n_txt, d_txt), dtype=np.float64)
y_txt = np.where(np.arange(n_txt) % 2 == 0, 1.0, -1.0)
for i in range(n_txt):
base_toks = (
rng.choice(np.arange(0, 60), size=5, replace=False)
if y_txt[i] > 0
else rng.choice(np.arange(60, 120), size=5, replace=False)
)
noise_toks = rng.choice(np.arange(120, d_txt), size=7, replace=False)
toks = np.concatenate([base_toks, noise_toks])
vals = rng.uniform(0.5, 1.5, size=toks.size)
X_txt[i, toks] = vals / float(np.linalg.norm(vals))
sq_txt = _pairwise_sq_dists(X_txt[:120], X_txt[:120])
iu_txt = np.triu_indices(120, k=1)
median_sq_dist_unit_sphere = float(np.median(sq_txt[iu_txt]))
X_txt_tr, X_txt_te = X_txt[:160], X_txt[160:]
y_txt_tr, y_txt_te = y_txt[:160], y_txt[160:]
t_l0 = time.perf_counter()
lin_txt = LinearSVMPrimal(c_reg=2.0, solver="dcd", seed=seed).fit(X_txt_tr, y_txt_tr)
lin_txt_ms = (time.perf_counter() - t_l0) * 1000.0
acc_lin_txt = float(np.mean(lin_txt.predict(X_txt_te) == y_txt_te))
# RBF with 'auto' (1/d) suffers rank-1 collapse on unit sphere!
rbf_auto_txt = KernelSMOSolver(c_reg=2.0, kernel="rbf", gamma="auto", max_iter=2000).fit(
X_txt_tr, y_txt_tr
)
acc_rbf_auto_txt = float(np.mean(rbf_auto_txt.predict(X_txt_te) == y_txt_te))
return {
"ecommerce": {
"exact_auc": _auc_binary(y_te_01, dec_exact_te),
"rff_auc": _auc_binary(y_te_01, dec_rff_te),
"nystrom_auc": _auc_binary(y_te_01, dec_nys_te),
"exact_sv_ratio": float(exact_svm.kkt_summary_["sv_fraction"]),
"exact_fit_ms": t_exact_fit_ms,
"rff_fit_ms": t_rff_fit_ms,
"nystrom_fit_ms": t_nys_fit_ms,
"exact_slate_200_ms": t_exact_inf_ms,
"rff_slate_200_ms": t_rff_inf_ms,
"nystrom_slate_200_ms": t_nys_inf_ms,
"ece_raw_sigmoid": ece_naive,
"ece_platt_calibrated": ece_platt,
"ndcg10_exact": ndcg10_exact,
"ndcg10_rff_prob": ndcg10_rff,
"realized_gmv_top10": realized_gmv_top10,
"gram_150k_gb": exact_150k_gb,
"rff_state_kib_150k_prod": rff_state_kib,
"nystrom_state_kib_150k_prod": nys_state_kib,
},
"sparse_text": {
"median_sq_dist_unit_sphere": median_sq_dist_unit_sphere,
"linear_dcd_acc": acc_lin_txt,
"linear_dcd_ms": lin_txt_ms,
"rbf_auto_acc": acc_rbf_auto_txt,
"rbf_auto_gamma": float(rbf_auto_txt.gamma_resolved_),
},
}
def run_svr_and_ocsvm_cases(seed: int = 42) -> dict[str, Any]:
"""Run Case 4 (epsilon-SVR outlier robustness) and Case 2 (OC-SVM vs SVDD equivalence)."""
rng = _make_rng(seed)
# 1) epsilon-SVR vs OLS under +400 USD/MWh scarcity spikes
n_svr = 90
X_s = rng.uniform(-2.5, 2.5, size=(n_svr, 1))
y_clean = 35.0 + 4.0 * np.sin(1.1 * X_s[:, 0]) + 1.5 * X_s[:, 0]
y_obs = y_clean + rng.normal(0.0, 1.2, size=n_svr)
spike_idx = np.array([5, 27, 63])
y_obs[spike_idx] += np.array([380.0, 460.0, 520.0])
# OLS closed form
X_des = np.column_stack([np.ones(n_svr), X_s[:, 0]])
w_ols = np.linalg.lstsq(X_des, y_obs, rcond=None)[0]
y_ols = X_des @ w_ols
mae_ols_vs_clean = float(np.mean(np.abs(y_ols - y_clean)))
svr_tight = EpsilonSVR(c_reg=25.0, epsilon_tube=0.05, kernel="rbf", gamma=0.8).fit(X_s, y_obs)
mae_svr_tight = float(np.mean(np.abs(svr_tight.predict(X_s) - y_clean)))
mad_y = float(np.median(np.abs(y_obs - np.median(y_obs))))
eps_cal = max(1.5, 0.35 * 1.4826 * mad_y)
svr_cal = EpsilonSVR(c_reg=25.0, epsilon_tube=eps_cal, kernel="rbf", gamma=0.8).fit(X_s, y_obs)
mae_svr_cal = float(np.mean(np.abs(svr_cal.predict(X_s) - y_clean)))
# 2) One-Class SVM vs SVDD exact RBF equivalence
X_norm = rng.normal(0.0, 0.7, size=(70, 2))
X_out = rng.uniform(3.2, 4.5, size=(6, 2))
X_oc = np.vstack([X_norm, X_out])
nu = 0.12
oc = OneClassSVMSolver(nu=nu, kernel="rbf", gamma=0.5).fit(X_oc)
svdd = SVDDSolver(nu=nu, kernel="rbf", gamma=0.5).fit(X_oc)
assert oc.alphas_ is not None and svdd.alphas_ is not None
alpha_max_diff = float(np.max(np.abs(oc.alphas_ - svdd.alphas_)))
pred_agree = float(np.mean(oc.predict(X_oc) == svdd.predict(X_oc)))
return {
"svr": {
"ols_mae_vs_clean": mae_ols_vs_clean,
"svr_tight_eps005_mae": mae_svr_tight,
"svr_tight_sv_fraction": float(svr_tight.sv_fraction_),
"svr_calibrated_eps": float(eps_cal),
"svr_calibrated_mae": mae_svr_cal,
"svr_calibrated_sv_fraction": float(svr_cal.sv_fraction_),
},
"ocsvm_svdd": {
"nu": float(nu),
"ocsvm_outlier_fraction": float(oc.outlier_fraction_),
"ocsvm_sv_fraction": float(oc.sv_fraction_),
"rbf_alpha_max_diff": alpha_max_diff,
"rbf_prediction_agreement": pred_agree,
},
}
def run_full_ch09_benchmarks(seed: int = 42, quick: bool = True) -> dict[str, Any]:
"""Run all verified Chapter 09 experiments for CLI demo and unit audits."""
# 1) Generative vs Discriminative (Ng-Jordan)
ng_jordan = simulate_ng_jordan_crossover(
d=36,
sample_sizes=(12, 24, 64, 240) if quick else (12, 24, 48, 120, 320),
n_trials=10 if quick else 15,
seed=seed,
)
# 2) Linear Pegasos vs DCD vs SMO KKT 3-way partition
rng = _make_rng(seed)
X_lin = rng.standard_normal((120, 4))
y_lin = np.where(1.8 * X_lin[:, 0] - 1.1 * X_lin[:, 1] + 0.35 + rng.normal(0.0, 0.4, 120) >= 0.0, 1.0, -1.0)
peg = LinearSVMPrimal(c_reg=2.0, solver="pegasos", max_iter=1500, seed=seed).fit(X_lin, y_lin)
dcd = LinearSVMPrimal(c_reg=2.0, solver="dcd", max_iter=2000, seed=seed).fit(X_lin, y_lin)
smo_lin = KernelSMOSolver(c_reg=2.0, kernel="linear", tol=1e-4, max_iter=4000).fit(X_lin, y_lin)
# 3) Mercer PSD audit across kernels (showing sigmoid fails PSD)
X_ker = np.abs(rng.standard_normal((36, 4))) + 0.05
mercer_audit = {
k_name: audit_kernel_psd(
evaluate_kernel_matrix(X_ker, X_ker, kernel=k_name, gamma=0.5, degree=2, coef0=1.0)
)
for k_name in ("linear", "poly", "rbf", "laplace", "hik", "chi2_add", "chi2_exp", "sigmoid")
}
# 4) Scaling catastrophe + islands + Steinwart + RFF + Nystrom + SOTA bridges + Industry Cases
scaling = run_scaling_and_island_diagnostics(seed=seed)
steinwart = run_steinwart_nonsparsity_experiment(seed=seed)
gram_footprints = {
"n_10k": compute_gram_memory_footprint(10_000, 8),
"n_100k": compute_gram_memory_footprint(100_000, 8),
"n_1m": compute_gram_memory_footprint(1_000_000, 8),
}
rff_bench = benchmark_rff_variants(
n=64 if quick else 90,
d=4,
gamma=0.20,
dim_out=64,
n_trials=32 if quick else 40,
seed=seed,
)
nystrom_cmp = compare_nystrom_vs_rff(seed=seed)
ntk_bridge = run_ntk_and_kta_bridge(seed=seed)
attn_bridge = run_softmax_attention_kernel_bridge(seed=seed)
industry_cases = run_ecommerce_and_sparse_cases(seed=seed, quick=quick)
svr_oc = run_svr_and_ocsvm_cases(seed=seed)
# 5) OvO vs OvR multiclass benchmark
n_mc = 150
theta_mc = rng.uniform(0.0, 2.0 * math.pi, size=n_mc)
y_mc = (np.arange(n_mc) % 4).astype(np.int64)
radii = 1.0 + 1.2 * y_mc + rng.normal(0.0, 0.18, size=n_mc)
X_mc = np.column_stack([radii * np.cos(theta_mc), radii * np.sin(theta_mc)])
t_ovo0 = time.perf_counter()
mc_ovo = MulticlassSVM(strategy="ovo", c_reg=4.0, kernel="rbf", gamma=0.8).fit(X_mc, y_mc)
ovo_ms = (time.perf_counter() - t_ovo0) * 1000.0
t_ovr0 = time.perf_counter()
mc_ovr = MulticlassSVM(strategy="ovr", c_reg=4.0, kernel="rbf", gamma=0.8).fit(X_mc, y_mc)
ovr_ms = (time.perf_counter() - t_ovr0) * 1000.0
return {
"seed": int(seed),
"quick": bool(quick),
"ng_jordan": ng_jordan,
"primal_vs_smo": {
"pegasos_primal_obj": float(peg.primal_objective_),
"pegasos_w_norm": float(np.linalg.norm(peg.coef_)) if peg.coef_ is not None else 0.0,
"pegasos_ball_bound": float(peg.l2_ball_bound_),
"dcd_primal_obj": float(dcd.primal_objective_),
"smo_primal_obj": float(smo_lin.primal_objective_),
"smo_dual_obj": float(smo_lin.dual_objective_),
"smo_duality_gap": float(smo_lin.duality_gap_),
"smo_kkt_summary": smo_lin.kkt_summary_,
},
"mercer_audit": mercer_audit,
"scaling_and_islands": scaling,
"steinwart": steinwart,
"gram_footprints": gram_footprints,
"rff_variants": rff_bench,
"nystrom_vs_rff": nystrom_cmp,
"ntk_bridge": ntk_bridge,
"attention_bridge": attn_bridge,
"multiclass": {
"ovo_n_models": len(mc_ovo.models_),
"ovr_n_models": len(mc_ovr.models_),
"ovo_acc": float(np.mean(mc_ovo.predict(X_mc) == y_mc)),
"ovr_acc": float(np.mean(mc_ovr.predict(X_mc) == y_mc)),
"ovo_fit_ms": ovo_ms,
"ovr_fit_ms": ovr_ms,
},
"industry_cases": industry_cases,
"svr_and_ocsvm": svr_oc,
}
"""End-to-end CLI demonstration and workbench_panels JSON exporter for Lab 09 (svm_kernels_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 svm_kernels_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 svm_kernels_lab.kernels_and_approximations import run_full_ch09_benchmarks
def _sanitize_json_value(value: Any) -> Any:
"""Convert NumPy scalars/arrays and non-finite floats into strict JSON-safe primitives."""
if isinstance(value, np.ndarray):
return [_sanitize_json_value(v) for v in value.tolist()]
if isinstance(value, (np.floating, float)):
fval = float(value)
if math.isinf(fval):
return "inf" if fval > 0 else "-inf"
if math.isnan(fval):
return "nan"
return fval
if isinstance(value, (np.bool_, bool)):
return bool(value)
if isinstance(value, (np.integer, int)):
return int(value)
if isinstance(value, (tuple, list)):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _pos_bar(val: float, floor: float = 0.001) -> float:
"""Ensure strictly positive finite bar widths for HTML dashboard rendering."""
if not math.isfinite(val):
return floor
return float(max(floor, abs(val)))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the SVM & Kernel Methods Workbench."""
parser = argparse.ArgumentParser(
description="Run Lab 09: Generative vs Discriminative, Pegasos/DCD, Platt SMO, Scaling Traps, RFF/ORF/QMC, Nystrom, NTK & Linear Attention."
)
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/ch09_workbench_results.json).",
)
return parser.parse_args(argv)
def _build_workbench_panels(bench: dict[str, Any]) -> dict[str, Any]:
ng = bench["ng_jordan"]
ps = bench["primal_vs_smo"]
sc = bench["scaling_and_islands"]
st = bench["steinwart"]
gf = bench["gram_footprints"]
rf = bench["rff_variants"]
ny = bench["nystrom_vs_rff"]
ntk = bench["ntk_bridge"]
att = bench["attention_bridge"]
ec = bench["industry_cases"]["ecommerce"]
txt = bench["industry_cases"]["sparse_text"]
svro = bench["svr_and_ocsvm"]
ng_first = ng["curve"][0]
ng_last = ng["curve"][-1]
st_noisy = st[-1]
att_last = att["timing_sweep"][-1]
kpis = [
{
"id": "kpi_ng_jordan_crossover",
"label": "Ng-Jordan: GNB O(log d) vs SVM O(d)",
"value": f"n={ng_first['n_train']}: {ng_first['gnb_error']*100:.1f}% vs {ng_first['svm_error']*100:.1f}%",
"unit": f"n={ng_last['n_train']} -> {ng_last['svm_error']*100:.1f}%",
"status": "ok",
"detail": (
f"Small-n error favors GNB ({ng_first['gnb_error']:.3f} < SVM {ng_first['svm_error']:.3f}); "
f"at n={ng_last['n_train']} Linear DCD overtakes ({ng_last['svm_error']:.3f} < GNB {ng_last['gnb_error']:.3f})."
),
},
{
"id": "kpi_smo_kkt_and_duality_gap",
"label": "Platt SMO Duality Gap & KKT Partition",
"value": f"gap {ps['smo_duality_gap']:.2e}",
"unit": f"{ps['smo_kkt_summary']['n_free_sv']} Free / {ps['smo_kkt_summary']['n_bounded_sv']} Bnd SV",
"status": "ok",
"detail": (
f"Primal={ps['smo_primal_obj']:.4f}, Dual={ps['smo_dual_obj']:.4f}, "
f"Non-SV={ps['smo_kkt_summary']['n_non_sv']}; Pegasos obj={ps['pegasos_primal_obj']:.4f} "
f"(||w||={ps['pegasos_w_norm']:.3f} <= {ps['pegasos_ball_bound']:.3f})."
),
},
{
"id": "kpi_rbf_scaling_and_island_trap",
"label": "Unscaled RBF Trap & Island Collapse",
"value": f"{sc['unscaled_auto_test_acc']*100:.1f}% -> {sc['scaled_test_acc']*100:.1f}%",
"unit": f"Island SV={sc['island_sv_ratio']*100:.0f}%",
"status": "critical",
"detail": (
f"Unscaled gamma='auto' collapses K -> I_n (median K={sc['unscaled_auto_median_k']:.2e}, "
f"test={sc['unscaled_auto_test_acc']*100:.1f}%); high-(C,g) island locks "
f"{sc['island_sv_ratio']*100:.1f}% SVs (train {sc['island_train_acc']*100:.1f}% vs test {sc['island_test_acc']*100:.1f}%)."
),
},
{
"id": "kpi_gram_wall_and_steinwart",
"label": "Gram RAM Wall & Steinwart SV=Omega(n)",
"value": f"{gf['n_100k']['gigabytes']:.0f} GB (100k)",
"unit": f"SV {st_noisy['empirical_sv_fraction']*100:.1f}% vs 2R* {st_noisy['theoretical_2r_star']*100:.1f}%",
"status": "warn",
"detail": (
f"Exact float64 Gram needs {gf['n_10k']['megabytes']:.0f} MB (10k), {gf['n_100k']['gigabytes']:.0f} GB (100k), "
f"{gf['n_1m']['terabytes']:.0f} TB (1M); noisy R*={st_noisy['bayes_risk_r_star']:.3f} drives SV fraction to "
f"{st_noisy['empirical_sv_fraction']:.3f}."
),
},
{
"id": "kpi_rff_nystrom_yang_tradeoff",
"label": "Paired RFF vs Nystrom (Yang et al.)",
"value": f"Nys {ny['nystrom_gram_rel_fro_err']:.3f} vs RFF {ny['rff_gram_rel_fro_err']:.3f}",
"unit": "Rel Frob Err",
"status": "ok",
"detail": (
f"Sutherland-Schneider Var(sc)={rf['paired_sc_offdiag_var']:.4f} < Var(cos)={rf['cos_offdiag_var']:.4f}; "
f"Nystrom test acc={ny['nystrom_test_acc']*100:.1f}% vs RFF {ny['rff_test_acc']*100:.1f}% (fold diff={ny['folded_inference_max_diff']:.1e})."
),
},
{
"id": "kpi_ecom_platt_and_linear_attn",
"label": "E-Com Personalization & FAVOR+ Bridge",
"value": f"ECE {ec['ece_raw_sigmoid']:.3f} -> {ec['ece_platt_calibrated']:.3f}",
"unit": f"FAVOR+ {att_last['speedup']:.1f}x @ L={att_last['seq_len']}",
"status": "ok",
"detail": (
f"E-Com NDCG@10={ec['ndcg10_rff_prob']:.3f} (Exact {ec['ndcg10_exact']:.3f}, RFF AUC={ec['rff_auc']:.3f}, "
f"Nys AUC={ec['nystrom_auc']:.3f}, state={ec['rff_state_kib_150k_prod']:.0f} KiB vs {ec['gram_150k_gb']:.0f} GB); "
f"Rich KTA {ntk['kta_rich_init']:.3f} -> {ntk['kta_rich_final']:.3f}."
),
},
]
bars = [
{
"id": "bar_rff_estimator_rmse_comparison",
"title": f"RBF Kernel Off-Diagonal RMSE at Equal Output Dim D_out={rf['dim_out']} (RFF vs ORF vs QMC)",
"metric_label": "Kernel RMSE",
"items": [
{
"label": "random_phase_cos_rff",
"value": _pos_bar(rf["cos_offdiag_rmse"]),
"display": f"{rf['cos_offdiag_rmse']:.4f} (Var {rf['cos_offdiag_var']:.4f})",
"css_class": "is-slow",
},
{
"label": "paired_sincos_rff",
"value": _pos_bar(rf["paired_sc_offdiag_rmse"]),
"display": f"{rf['paired_sc_offdiag_rmse']:.4f} (Var {rf['paired_sc_offdiag_var']:.4f})",
"css_class": "is-mid",
},
{
"label": "orthogonal_orf_haar",
"value": _pos_bar(rf["orf_offdiag_rmse"]),
"display": f"{rf['orf_offdiag_rmse']:.4f} (Var {rf['orf_offdiag_var']:.4f})",
"css_class": "is-fast",
},
{
"label": "halton_qmc_rff",
"value": _pos_bar(rf["halton_qmc_offdiag_rmse"]),
"display": f"{rf['halton_qmc_offdiag_rmse']:.4f} (Low-Discrepancy)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_scaling_catastrophe_and_islands",
"title": "RBF Feature Scaling Catastrophe & High-(C, gamma) Memorization Island Accuracy",
"metric_label": "Test Accuracy",
"items": [
{
"label": "unscaled_rbf_gamma_auto",
"value": _pos_bar(sc["unscaled_auto_test_acc"]),
"display": f"{sc['unscaled_auto_test_acc']*100:.1f}% (K -> I_n)",
"css_class": "is-slow",
},
{
"label": "unscaled_rbf_gamma_scale",
"value": _pos_bar(sc["unscaled_scale_test_acc"]),
"display": f"{sc['unscaled_scale_test_acc']*100:.1f}% (Rates Erased)",
"css_class": "is-slow",
},
{
"label": "high_c_gamma_island_test",
"value": _pos_bar(sc["island_test_acc"]),
"display": f"{sc['island_test_acc']*100:.1f}% (Train {sc['island_train_acc']*100:.1f}%, SV {sc['island_sv_ratio']*100:.0f}%)",
"css_class": "is-mid",
},
{
"label": "infold_log1p_std_median_gamma",
"value": _pos_bar(sc["scaled_test_acc"]),
"display": f"{sc['scaled_test_acc']*100:.1f}% (SV {sc['scaled_sv_ratio']*100:.0f}%)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_ecommerce_kernel_vs_approx_latency",
"title": "E-Commerce Personalization (E32:E35): Exact RBF SMO vs Paired RFF vs Nystrom Inference",
"metric_label": "200-Item Slate (ms)",
"items": [
{
"label": "exact_rbf_smo_slate_ms",
"value": _pos_bar(ec["exact_slate_200_ms"]),
"display": f"{ec['exact_slate_200_ms']:.3f} ms (AUC {ec['exact_auc']:.3f})",
"css_class": "is-slow",
},
{
"label": "paired_rff_dcd_slate_ms",
"value": _pos_bar(ec["rff_slate_200_ms"]),
"display": f"{ec['rff_slate_200_ms']:.3f} ms (AUC {ec['rff_auc']:.3f})",
"css_class": "is-fast",
},
{
"label": "nystrom_folded_slate_ms",
"value": _pos_bar(ec["nystrom_slate_200_ms"]),
"display": f"{ec['nystrom_slate_200_ms']:.3f} ms (AUC {ec['nystrom_auc']:.3f})",
"css_class": "is-fast",
},
],
},
{
"id": "bar_svr_robustness_and_compression",
"title": "Outlier Spikes (+400 USD/MWh): OLS vs Tight-eps SVR vs Calibrated-MAD eps-SVR MAE",
"metric_label": "Clean-Signal MAE",
"items": [
{
"label": "ols_quadratic_loss_mae",
"value": _pos_bar(svro["svr"]["ols_mae_vs_clean"]),
"display": f"{svro['svr']['ols_mae_vs_clean']:.2f} (100% dense)",
"css_class": "is-slow",
},
{
"label": "svr_tight_eps005_mae",
"value": _pos_bar(svro["svr"]["svr_tight_eps005_mae"]),
"display": f"{svro['svr']['svr_tight_eps005_mae']:.2f} (SV {svro['svr']['svr_tight_sv_fraction']*100:.1f}%)",
"css_class": "is-mid",
},
{
"label": "svr_calibrated_mad_mae",
"value": _pos_bar(svro["svr"]["svr_calibrated_mae"]),
"display": f"{svro['svr']['svr_calibrated_mae']:.2f} (SV {svro['svr']['svr_calibrated_sv_fraction']*100:.1f}%)",
"css_class": "is-fast",
},
],
},
]
mercer_rows = []
for kname, m in bench["mercer_audit"].items():
mercer_rows.append(
[
kname,
f"{m['min_eigenvalue']:.3e}",
f"{m['max_eigenvalue']:.3f}",
"PASS (Mercer PSD)" if m["is_psd"] else "FAIL (Indefinite)",
]
)
steinwart_rows = [
[
r["regime"],
f"{r['bayes_risk_r_star']:.4f}",
f"{r['theoretical_2r_star']:.4f}",
f"{r['empirical_sv_fraction']:.4f} ({r['n_support_vectors']}/{r['n_samples']})",
]
for r in st
]
attn_rows = [
[
f"L = {row['seq_len']}",
f"{row['softmax_ms']:.3f} ms",
f"{row['favor_linear_ms']:.3f} ms",
f"{row['speedup']:.2f}x",
]
for row in att["timing_sweep"]
]
domain_rows = [
[
"E-Com Personalization (E32:E35)",
f"Exact RBF AUC {ec['exact_auc']:.3f} / 150k RAM={ec['gram_150k_gb']:.0f} GB",
f"RFF AUC {ec['rff_auc']:.3f} ({ec['rff_state_kib_150k_prod']:.0f} KiB), Nys {ec['nystrom_auc']:.3f}",
f"Platt ECE {ec['ece_raw_sigmoid']:.3f} -> {ec['ece_platt_calibrated']:.3f}",
],
[
"Sparse Catalog Text (d=400)",
f"RBF auto Acc {txt['rbf_auto_acc']*100:.1f}% (||dx||^2={txt['median_sq_dist_unit_sphere']:.2f})",
f"Linear DCD Acc {txt['linear_dcd_acc']*100:.1f}% ({txt['linear_dcd_ms']:.2f} ms)",
"LINEAR_WINS_UNIT_SPHERE",
],
[
"OC-SVM vs SVDD (RBF nu=0.12)",
f"Outliers {svro['ocsvm_svdd']['ocsvm_outlier_fraction']:.3f} <= nu <= SV {svro['ocsvm_svdd']['ocsvm_sv_fraction']:.3f}",
f"max|alpha_oc - alpha_svdd| = {svro['ocsvm_svdd']['rbf_alpha_max_diff']:.2e}",
f"Agreement {svro['ocsvm_svdd']['rbf_prediction_agreement']*100:.1f}%",
],
[
"NTK & KTA (2-Layer tanh MLP)",
f"Lazy Drift={ntk['lazy_ntk_rel_drift']:.4f} (KTA={ntk['kta_lazy_init']:.3f})",
f"Rich Drift={ntk['rich_ntk_rel_drift']:.4f} (KTA {ntk['kta_rich_init']:.3f}->{ntk['kta_rich_final']:.3f})",
f"NTK PSD={ntk['ntk_is_psd']}",
],
]
tables = [
{
"id": "table_mercer_psd_audit",
"title": "Mercer Kernel PSD Spectral Verification (Gram Matrix Eigenvalue Bounds)",
"columns": ["kernel_name", "min_eigenvalue", "max_eigenvalue", "mercer_verdict"],
"rows": mercer_rows,
},
{
"id": "table_steinwart_nonsparsity",
"title": "Steinwart Theorem (2003): Support Vector Fraction n_SV / n -> 2 R^*",
"columns": ["bayes_regime", "bayes_risk_r_star", "theoretical_2r_star", "empirical_sv_fraction"],
"rows": steinwart_rows,
},
{
"id": "table_softmax_vs_favor_linear_attention",
"title": "Softmax Kernel Attention O(L^2) vs Positive Orthogonal FAVOR+ O(L) Crossover",
"columns": ["seq_length", "exact_softmax_ms", "favor_linear_ms", "speedup"],
"rows": attn_rows,
},
{
"id": "table_industry_and_sota_benchmarks",
"title": "Industry Production Benchmarks (E-Com E32:E35, Sparse Text, OC-SVM/SVDD, NTK)",
"columns": ["scenario", "naive_or_exact_baseline", "sota_remediation", "verified_check"],
"rows": domain_rows,
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
bench = run_full_ch09_benchmarks(seed=args.seed, quick=args.quick)
panels = _build_workbench_panels(bench)
payload = _sanitize_json_value(
{
"config": {
"seed": args.seed,
"quick": args.quick,
"output": args.output,
},
"workbench_panels": panels,
**bench,
}
)
if args.output:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
print(f"Wrote workbench results to {out_path}")
else:
print(json.dumps(payload["workbench_panels"], indent=2, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""14 Automated Verification Contract Tests for svm_kernels_lab (T1-P2-U04)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from pydantic import ValidationError
from svm_kernels_lab import (
EpsilonSVR,
GaussianNaiveBayesClassifier,
KernelSMOSolver,
LinearSVMPrimal,
MulticlassSVM,
NystromFeatures,
PairedSinCosRFF,
PlattCalibrator,
SVMConfig,
audit_kernel_psd,
benchmark_rff_variants,
compare_nystrom_vs_rff,
compute_ece,
compute_gram_memory_footprint,
evaluate_kernel_matrix,
explicit_poly2_feature_map,
run_ntk_and_kta_bridge,
run_scaling_and_island_diagnostics,
run_softmax_attention_kernel_bridge,
run_steinwart_nonsparsity_experiment,
run_svr_and_ocsvm_cases,
simulate_ng_jordan_crossover,
smo_two_variable_step,
string_spectrum_kernel,
)
from svm_kernels_lab.kernels_and_approximations import run_ecommerce_and_sparse_cases
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
def test_01_generative_vs_discriminative_ng_jordan_crossover() -> None:
cfg = SVMConfig(c_reg=2.0, kernel="rbf", gamma="scale")
assert cfg.c_reg == 2.0
with pytest.raises(ValidationError):
SVMConfig(c_reg=1.0, unknown_param=123) # type: ignore[call-arg]
res = simulate_ng_jordan_crossover(d=36, sample_sizes=(12, 24, 64, 240), n_trials=10, seed=42)
assert res["small_n_gnb_beats_svm"] is True
assert res["large_n_svm_beats_gnb"] is True
assert res["curve"][-1]["svm_error"] < res["curve"][0]["svm_error"]
# GNB shared variance produces linear decision boundary
rng = np.random.default_rng(7)
X_g = rng.standard_normal((40, 3))
y_g = np.where(X_g[:, 0] > 0.0, 1.0, -1.0)
gnb = GaussianNaiveBayesClassifier(shared_variance=True).fit(X_g, y_g)
assert np.mean(gnb.predict(X_g) == y_g) > 0.85
def test_02_linear_svm_geometry_pegasos_ball_and_dcd_equivalence() -> None:
rng = np.random.default_rng(42)
X = rng.standard_normal((120, 4))
y = np.where(1.8 * X[:, 0] - 1.1 * X[:, 1] + 0.4 + rng.normal(0.0, 0.35, 120) >= 0.0, 1.0, -1.0)
peg = LinearSVMPrimal(c_reg=2.0, solver="pegasos", max_iter=2000, seed=42).fit(X, y)
dcd = LinearSVMPrimal(c_reg=2.0, solver="dcd", max_iter=3000, seed=42).fit(X, y)
smo = KernelSMOSolver(c_reg=2.0, kernel="linear", tol=1e-4, max_iter=4000).fit(X, y)
assert peg.coef_ is not None and dcd.coef_ is not None
assert peg.coef_.flags.writeable is False
assert dcd.coef_.flags.writeable is False
# Pegasos L2 ball bound ||w||_2 <= 1 / sqrt(lambda)
w_norm_peg = float(np.linalg.norm(peg.coef_))
assert w_norm_peg <= peg.l2_ball_bound_ + 1e-9
assert peg.geometric_margin_ == pytest.approx(1.0 / w_norm_peg, rel=1e-9)
# Unpenalized bias translation equivariance: shifting X + t shifts b -> b - w^T t
shift = np.array([500.0, -250.0, 100.0, 75.0])
dcd_shifted = LinearSVMPrimal(c_reg=2.0, solver="dcd", max_iter=3000, seed=42).fit(X + shift, y)
assert dcd_shifted.coef_ is not None
assert np.allclose(dcd_shifted.coef_, dcd.coef_, atol=1e-3)
assert dcd_shifted.intercept_ == pytest.approx(
dcd.intercept_ - float(dcd.coef_ @ shift), abs=1e-2
)
# Pegasos & DCD match exact SMO primal objective closely
assert dcd.primal_objective_ == pytest.approx(smo.primal_objective_, rel=1e-2)
assert peg.primal_objective_ <= smo.primal_objective_ * 1.03
def test_03_platt_smo_kkt_three_way_partition_and_duality_gap() -> None:
rng = np.random.default_rng(11)
X = rng.standard_normal((70, 2))
y = np.where(X[:, 0] + 0.7 * X[:, 1] + rng.normal(0.0, 0.55, 70) >= 0.0, 1.0, -1.0)
C = 1.5
smo = KernelSMOSolver(c_reg=C, kernel="linear", tol=1e-5, max_iter=6000).fit(X, y)
assert smo.alphas_ is not None
# Zero duality gap & equality sum(alpha_i y_i) = 0
assert abs(float(np.sum(smo.alphas_ * smo.y_train_))) < 1e-6
assert np.all((smo.alphas_ >= -1e-9) & (smo.alphas_ <= C + 1e-9))
assert smo.duality_gap_ < 1e-3
assert smo.kkt_summary_["max_kkt_violation"] < 1e-2
# Verify exact 3-way KKT partition invariants
f_vals = smo.decision_function(X)
yf = y * f_vals
a = smo.alphas_
non_sv = a <= 1e-7
bounded_sv = a >= C - 1e-7
free_sv = (~non_sv) & (~bounded_sv)
assert np.any(non_sv) and np.any(free_sv)
assert np.all(yf[non_sv] >= 1.0 - 5e-3)
assert np.allclose(yf[free_sv], 1.0, atol=5e-3)
if np.any(bounded_sv):
assert np.all(yf[bounded_sv] <= 1.0 + 5e-3)
# Verify degenerate eta <= 0 SMO step fallback on duplicate / non-PSD inputs
a1_n, a2_n, low, high, fb = smo_two_variable_step(
alpha_1=0.4,
alpha_2=0.3,
y_1=1.0,
y_2=-1.0,
k11=1.0,
k22=1.0,
k12=1.0, # eta = 0.0
f1=-0.8,
f2=-0.2,
c1=1.0,
c2=1.0,
)
assert fb is True
assert low <= a2_n <= high
assert abs((a1_n - a2_n) - (0.4 - 0.3)) < 1e-12
def test_04_mercer_psd_audit_poly_rbf_hik_chi2_and_string_kernels() -> None:
rng = np.random.default_rng(19)
X_pos = np.abs(rng.standard_normal((32, 4))) + 0.1
for kname in ("linear", "poly", "rbf", "laplace", "hik", "chi2_add", "chi2_exp"):
K = evaluate_kernel_matrix(X_pos, X_pos, kernel=kname, gamma=0.4, degree=2, coef0=1.0)
res = audit_kernel_psd(K)
assert res["is_psd"] is True, f"Expected PSD for {kname}, got min_eig={res['min_eigenvalue']}"
# Non-PSD sigmoid counterexample fails Mercer condition
K_sig = evaluate_kernel_matrix(X_pos, X_pos, kernel="sigmoid", gamma=1.5, coef0=-1.0)
res_sig = audit_kernel_psd(K_sig)
assert res_sig["min_eigenvalue"] < -1e-4
assert res_sig["is_psd"] is False
# Explicit d_poly = 2 monomial lift matches polynomial kernel identically
phi_2 = explicit_poly2_feature_map(X_pos, gamma=0.6, coef0=1.2)
assert phi_2.shape == (32, (4 + 2) * (4 + 1) // 2)
K_poly = evaluate_kernel_matrix(X_pos, X_pos, kernel="poly", gamma=0.6, degree=2, coef0=1.2)
assert np.allclose(phi_2 @ phi_2.T, K_poly, atol=1e-11)
# String k-spectrum kernel is strictly PSD
strs = ["checkout_cart_item", "checkout_item_buy", "home_scroll_view", "cart_add_checkout", "home_view_exit"]
K_str = string_spectrum_kernel(strs, strs, k=3)
assert audit_kernel_psd(K_str)["is_psd"] is True
def test_05_rbf_scaling_catastrophe_and_c_gamma_memorization_islands() -> None:
sc = run_scaling_and_island_diagnostics(seed=42)
# Unscaled heterogeneous features collapse K -> I_n under gamma='auto'
assert sc["unscaled_auto_median_k"] < 1e-6
assert sc["unscaled_auto_sv_ratio"] > 0.75
assert sc["scaled_test_acc"] > sc["unscaled_auto_test_acc"] + 0.08
assert sc["scaled_test_acc"] > sc["unscaled_scale_test_acc"] + 0.05
# High C + High gamma produces memorization islands (n_SV/n -> 1, 100% train vs collapsed test)
assert sc["island_sv_ratio"] > 0.85
assert sc["island_train_acc"] > 0.98
assert sc["island_test_acc"] < sc["scaled_test_acc"] - 0.10
def test_06_epsilon_svr_tube_sparsity_and_outlier_clamping() -> None:
res = run_svr_and_ocsvm_cases(seed=42)["svr"]
# Calibrated epsilon_tube compresses SVs sharply vs tiny eps=0.05 while defeating OLS >10x on spikes
assert res["svr_tight_sv_fraction"] > 0.80
assert res["svr_calibrated_sv_fraction"] < 0.45
assert res["ols_mae_vs_clean"] > 10.0 * res["svr_calibrated_mae"]
# Check KKT mutual exclusivity alpha_i * alpha_i^* == 0 and sum(alpha_i - alpha_i^*) == 0
rng = np.random.default_rng(5)
X = rng.uniform(-2.0, 2.0, size=(50, 1))
y = np.sin(X[:, 0]) + rng.normal(0.0, 0.1, size=50)
svr = EpsilonSVR(c_reg=5.0, epsilon_tube=0.15, kernel="rbf", gamma=1.0).fit(X, y)
assert svr.alpha_pos_ is not None and svr.alpha_neg_ is not None and svr.alpha_diff_ is not None
assert np.max(svr.alpha_pos_ * svr.alpha_neg_) < 1e-12
assert abs(float(np.sum(svr.alpha_diff_))) < 1e-5
def test_07_one_class_svm_vs_svdd_nu_bounds_and_rbf_equivalence() -> None:
res = run_svr_and_ocsvm_cases(seed=42)["ocsvm_svdd"]
nu = res["nu"]
# Scholkopf exact nu-property: outlier_fraction <= nu <= sv_fraction
assert res["ocsvm_outlier_fraction"] <= nu + 0.03
assert res["ocsvm_sv_fraction"] >= nu - 0.02
# Exact RBF dual multiplier and prediction equivalence between OC-SVM and SVDD
assert res["rbf_alpha_max_diff"] < 1e-4
assert res["rbf_prediction_agreement"] == pytest.approx(1.0, abs=1e-9)
def test_08_multiclass_ovo_vs_ovr_and_oof_platt_calibration_bridge() -> None:
rng = np.random.default_rng(42)
n = 120
theta = rng.uniform(0.0, 2.0 * np.pi, size=n)
y_mc = (np.arange(n) % 4).astype(np.int64)
rad = 1.0 + 1.25 * y_mc + rng.normal(0.0, 0.16, size=n)
X_mc = np.column_stack([rad * np.cos(theta), rad * np.sin(theta)])
ovo = MulticlassSVM(strategy="ovo", c_reg=4.0, kernel="rbf", gamma=0.8).fit(X_mc, y_mc)
ovr = MulticlassSVM(strategy="ovr", c_reg=4.0, kernel="rbf", gamma=0.8).fit(X_mc, y_mc)
assert len(ovo.models_) == 6 # K*(K-1)/2 = 4*3/2
assert len(ovr.models_) == 4
assert float(np.mean(ovo.predict(X_mc) == y_mc)) > 0.90
assert float(np.mean(ovr.predict(X_mc) == y_mc)) > 0.90
# Platt calibration bridge reduces ECE over raw uncalibrated sigmoid(margin)
X_b = rng.standard_normal((500, 3))
logits_true = 3.2 * X_b[:, 0] - 2.0 * X_b[:, 1] - 0.6
y_01 = (rng.random(500) < (1.0 / (1.0 + np.exp(-logits_true)))).astype(np.float64)
y_s = np.where(y_01 > 0.5, 1.0, -1.0)
svm_b = LinearSVMPrimal(c_reg=0.05, solver="dcd", seed=42).fit(X_b[:200], y_s[:200])
m_cal = svm_b.decision_function(X_b[200:350])
m_te = svm_b.decision_function(X_b[350:])
ece_raw = compute_ece(y_01[350:], 1.0 / (1.0 + np.exp(-np.clip(m_te, -20.0, 20.0))))
platt = PlattCalibrator().fit(m_cal, y_01[200:350])
ece_cal = compute_ece(y_01[350:], platt.predict_proba(m_te))
assert ece_cal < ece_raw * 0.65
def test_09_gram_byte_footprint_and_steinwart_nonsparsity_theorem() -> None:
f10k = compute_gram_memory_footprint(10_000, 8)
f100k = compute_gram_memory_footprint(100_000, 8)
f1m = compute_gram_memory_footprint(1_000_000, 8)
assert f10k["megabytes"] == pytest.approx(800.0)
assert f100k["gigabytes"] == pytest.approx(80.0)
assert f1m["terabytes"] == pytest.approx(8.0)
rows = run_steinwart_nonsparsity_experiment(seed=42)
assert rows[0]["empirical_sv_fraction"] < rows[1]["empirical_sv_fraction"] < rows[2]["empirical_sv_fraction"]
# Noisy regime exhibits Omega(n) support vectors tracking ~ 2 R^*
assert rows[-1]["empirical_sv_fraction"] > 0.30
assert abs(rows[-1]["empirical_sv_fraction"] - rows[-1]["theoretical_2r_star"]) < 0.15
def test_10_rff_bochner_unbiasedness_paired_variance_orf_and_qmc() -> None:
res = benchmark_rff_variants(n=64, d=4, gamma=0.20, dim_out=64, n_trials=32, seed=42)
assert abs(res["cos_mean_bias"]) < 0.02
assert abs(res["paired_sc_mean_bias"]) < 0.02
# Exact unit norm ||z_sc(x)||_2^2 == 1.0
assert res["paired_sc_diag_norm_max_err"] < 1e-12
assert res["cos_diag_norm_var"] > 1e-4
# Sutherland & Schneider (2015) strict variance inequality at equal D_out
assert res["sutherland_schneider_var_strictly_lower"] is True
assert res["orf_offdiag_rmse"] < res["cos_offdiag_rmse"]
assert res["halton_qmc_offdiag_rmse"] < res["cos_offdiag_rmse"]
# Also verify Bochner Laplace (Cauchy spectrum) unbiasedness
rng = np.random.default_rng(7)
X_l = rng.standard_normal((30, 4)) * 0.6
K_lap = evaluate_kernel_matrix(X_l, X_l, kernel="laplace", gamma=0.4)
Z_lap = PairedSinCosRFF(n_components=400, gamma=0.4, kernel="laplace", seed=7).fit_transform(X_l)
assert float(np.sqrt(np.mean((Z_lap @ Z_lap.T - K_lap) ** 2))) < 0.08
def test_11_nystrom_low_rank_psd_folding_and_yang_spectral_crossover() -> None:
res = compare_nystrom_vs_rff(seed=42)
assert res["top16_spectral_energy_ratio"] > 0.70
assert res["nystrom_beats_rff_gram_error"] is True
assert res["nystrom_test_acc"] >= res["rff_test_acc"] - 0.01
assert res["schur_residual_min_eig"] >= -1e-9
assert res["folded_inference_max_diff"] < 1e-11
# Also exercise leverage landmark mode cleanly
rng = np.random.default_rng(13)
X = rng.standard_normal((100, 6))
nys_lev = NystromFeatures(n_components=24, gamma=0.1, landmark_mode="leverage", seed=13).fit(X)
Z_lev = nys_lev.transform(X)
assert Z_lev.shape[0] == 100 and Z_lev.shape[1] <= 24
def test_12_ntk_kta_drift_and_softmax_favor_plus_taylor_attention() -> None:
ntk = run_ntk_and_kta_bridge(seed=42)
assert ntk["ntk_is_psd"] is True
assert ntk["ntk_train_mse"] < 1e-3
assert ntk["rich_ntk_rel_drift"] > ntk["lazy_ntk_rel_drift"] * 3.0
assert ntk["rich_increases_kta"] is True
att = run_softmax_attention_kernel_bridge(seed=42)
assert att["favor_strictly_positive"] is True
assert att["favor_associative_parity_diff"] < 1e-11
assert att["favor_rel_l2_err"] < 0.25
assert att["taylor2_rel_l2_err"] < 0.15
assert att["timing_sweep"][-1]["speedup"] > 1.0
def test_13_ecommerce_personalization_rff_nystrom_and_sparse_text() -> None:
cases = run_ecommerce_and_sparse_cases(seed=42, quick=True)
ec = cases["ecommerce"]
txt = cases["sparse_text"]
assert ec["rff_auc"] > 0.72 and ec["nystrom_auc"] > 0.72
assert ec["rff_slate_200_ms"] < ec["exact_slate_200_ms"]
assert ec["nystrom_slate_200_ms"] < ec["exact_slate_200_ms"]
assert ec["ece_platt_calibrated"] < ec["ece_raw_sigmoid"]
assert ec["rff_state_kib_150k_prod"] < 5120.0 # well inside 5 MB serving budget
# Sparse unit-sphere concentration: median ||x_i - x_j||^2 ~ 2.0
assert txt["median_sq_dist_unit_sphere"] > 1.85
assert txt["linear_dcd_acc"] >= 0.85
def test_14_cli_demo_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "ch09_test_results.json"
cmd = [
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_json),
]
proc = subprocess.run(cmd, cwd=str(LAB_ROOT), capture_output=True, text=True, check=False)
assert proc.returncode == 0, f"CLI failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
assert out_json.is_file()
payload = json.loads(out_json.read_text(encoding="utf-8"))
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
# Security-Only AST deserialization guard across src/, scripts/, tests/
py_files = (
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
violations: list[tuple[str, str]] = []
for pf in py_files:
tree = ast.parse(pf.read_text(encoding="utf-8"), filename=str(pf))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".", 1)[0]
if top in FORBIDDEN_UNSAFE_IMPORTS:
violations.append((pf.name, top))
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".", 1)[0]
if top in FORBIDDEN_UNSAFE_IMPORTS:
violations.append((pf.name, top))
assert violations == [], f"Unsafe deserialization imports detected: {violations}"
Gaussian Naive Bayes (GNB) đạt sai số thấp hơn hẳn Linear SVM (14.6% vs. 41.9%), nhưng đến \(n = 320\) thì Linear SVM lại đảo chiều thắng thế (1.1% vs. 1.8%)?GNB ước lượng rời từng chiều đạt ngưỡng ổn định sau \(O(\log d)\) mẫu (14.6% vs 41.9% ở n=12), nhưng giả định độc lập làm cộng dồn sai trọng số trên cặp tương quan (1.8% ở n=320). Linear SVM (DCD) cần O(d) mẫu (n=320) để vượt lên 1.1% (LDA = 0.8%).
Pegasos & Ràng buộc Quả cầu \(1/\sqrt{\lambda}\)
Linear SVM quy chuẩn hóa \(\min_{\mathbf{w}, b} \frac{\lambda}{2}\|\mathbf{w}\|_2^2 + \frac{1}{n}\sum_i \max(0, 1 - y_i(\mathbf{w}^\top\mathbf{x}_i + b))\) với \(\lambda = \frac{1}{nC}\), phát biểu nào ĐÚNG về chuẩn hóa lề, hệ số chặn \(b\) và thuật toán Pegasos?Pegasos giữ \(\|\mathbf{w}\|_2 = 3.942 \le 15.492\) (obj = 42.7247 sát SMO = 42.6916), và dịch trục +500 ở DCD giữ nguyên w và dịch đúng b -> b - w^T t.
KKT & Bước Platt SMO
KernelSMOSolver (n = 120, C = 2.0) đạt khoảng cách đối ngẫu duality_gap = 3.97e-04 (Primal 42.6916, Dual 42.6912), phân loại được 93 điểm không phải vector hỗ trợ, 5 Free Margin SV và 22 Bounded SV. Khẳng định nào ĐÚNG về điều kiện bù KKT và bước Platt SMO?SMO tối thiểu phải cập nhật cùng lúc 2 biến \((\alpha_1, \alpha_2)\). Khi \(\eta_{\text{SMO}} \le 0\) (ví dụ hai mẫu trùng nhau \(\mathbf{x}_1 = \mathbf{x}_2\) hoặc nhân không PSD), hàm mục tiêu 1D không lõm ngặt nên cực đại bắt buộc nằm tại biên \(L\) hoặc \(H\).
RKHS, Định lý Mercer, Định lý Biểu diễn & Độ rộng Băng thông RBF
audit_kernel_psd) và lý thuyết RKHS, nhận định nào ĐÚNG?Poly(d=2) có đúng \((d+2)(d+1)/2\) đơn thức tường minh, còn tanh có trị riêng âm -0.235.
RBF, Đảo Ghi nhớ (C, gamma) & Mở rộng eps-SVR / OC-SVM / SVDD
R32.7 trên tập E-Commerce có cột cart_value_usd [10, 5000] trộn với 9 tỷ lệ hành vi [0, 1], và bài toán hồi quy giá điện có 3 gai đột biến +380..+520 USD/MWh, kết luận thực nghiệm nào ĐÚNG?K_RBF(x, x) = 1 không đổi trên mọi điểm, bài toán đối ngẫu của SVDD (min a^T K a - sum a_i K_ii) rút gọn đồng nhất về nu-OCSVM (max|alpha_oc - alpha_svdd| = 7.21e-15, agreement = 100%), đồng thời thỏa mãn bất đẳng thức kép outliers (7.9%) <= nu (12.0%) <= SV (21.1%).
O(n^2) & Định lý Không thưa Steinwart (2003)
Exact RBF SMO không thể đáp ứng SLA < 5 ms khi mở rộng từ tập thử nghiệm lên quy mô công nghiệp \(n = 100{,}000\text{--}1{,}000{,}000\) có nhiễu nhãn thực tế \(R^* = 17.9\%\)?800 MB ở 10k, 80 GB ở 100k, 8 TB ở 1M). Khi dữ liệu có vùng chồng lấn \(R^* > 0\), các điểm nhiễu vượt lề buộc SMO giữ lại \(\ge 2R^* n\) vector hỗ trợ (47.7% ở R*=0.179 trong lab).
RFF Cặp Sin/Cos (Sutherland–Schneider), ORF/QMC & Nyström (Yang et al.)
D_out = 64 (hay budget = 32 trên dữ liệu phân cụm phổ suy giảm nhanh), kết quả lý thuyết và thực nghiệm nào sau đây ĐÚNG?D_out, \(\operatorname{Var}(\hat{k}_{\text{cos}}) - \operatorname{Var}(\hat{k}_{\text{sc}}) = \frac{1}{D_{\text{out}}}k(\Delta)^2(1 - \frac{1}{2}k(\Delta)^2) > 0\). Khi phổ Gram suy giảm nhanh (Yang et al., 2012), Nyström chiếu trực tiếp lên không gian riêng dữ liệu đạt lỗi 0.046 vs RFF 0.565, với bù Schur min_eig = 3.94e-04 >= 0.
E32:E35), Hiệu chuẩn Platt, NTK & Chú ý Tuyến tính FAVOR+
E32:E35, chiếu lên n=150,000, 200 ứng viên/slate) và hai cầu nối lý thuyết nhân SOTA (NTK & Softmax Attention), khẳng định nào ĐÚNG?+/-1 do mất mát bản lề nên phải hiệu chuẩn ngoại mẫu (D_cal / OOF -> ch-07) trước khi tính kỳ vọng GMV. Trong Attention, cos/sin nhận giá trị âm làm sập mẫu số chuẩn hóa, buộc FAVOR+ phải dùng ánh xạ mũ dương trực giao \(\phi_{\text{FAVOR+}} > 0\) (hoặc Hedgehog/BASED/LoLCATs 2024–2025).
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Định lý Ng–Jordan (O(log d) vs. O(d)) & Hình học Lề Chuẩn hóa 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết log-odds của GNB chia sẻ phương sai và LDA để chứng minh cả hai đều sinh siêu phẳng tuyến tính, rồi áp bất đẳng thức Hoeffding + Union Bound qua \(d\) chiều độc lập để suy ra tốc độ \(O(\log d)\) của GNB vs. cận \(\operatorname{VC} = d+1\) của phân biệt.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi simulate_ng_jordan_crossover và LinearSVMPrimal(solver='pegasos'|'dcd') kiểm chứng đường cong sai số n = 12..320, bất đẳng thức quả cầu ||w||_2 <= 1/sqrt(lambda), và dịch trục X + shift kiểm tra bất biến tịnh tiến của b.
Tiêu chí Đáp án & Số đối chứng
Tại n=12, GNB đạt sai số 14.6% so với Linear SVM 41.9% (LDA 41.6%), nhưng tại n=320 Linear DCD đảo chiều đạt 1.1% (LDA 0.8%) thắng GNB (1.8%). Pegasos giữ chuẩn ||w|| = 3.942 <= 15.492 (obj = 42.7247 sát SMO = 42.6916), và dịch trục giữ nguyên w trong sai số 1e-3.
Bài tập 2 — Dẫn xuất Đối ngẫu Lagrange, Phân hoạch 3 Nhóm KKT & Bước Platt SMO
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lập hàm Lagrange \(\mathcal{L}(\mathbf{w}, b, \boldsymbol{\xi}, \boldsymbol{\alpha}, \boldsymbol{\mu})\), triệt tiêu đạo hàm theo \(\mathbf{w}, b, \xi_i\) để thu QP đối ngẫu và hai phương trình bù KKT; đồng thời dẫn xuất cận hộp \([L, H]\) cùng bước 1D \(\alpha_2^{\text{new,unc}}\) dưới quy ước +b (kể cả nhánh biên \(\eta_{\text{SMO}} \le 0\)).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy KernelSMOSolver (C = 2.0, kernel='linear') và smo_two_variable_step với k11=k22=k12=1.0 để kiểm nghiệm phân hoạch 3 nhóm KKT (alpha=0, 0<alpha<C, alpha=C) và nhánh dự phòng \(\eta_{\text{SMO}} = 0\).
Tiêu chí Đáp án & Số đối chứng
Thực nghiệm đạt duality_gap = 3.97e-04 (Primal 42.6916, Dual 42.6912, max_kkt_violation = 1.16e-04), phân tách 93 Non-SV (y_i f >= 1), 5 Free Margin SV (y_i f = 1), và 22 Bounded SV (y_i f <= 1); bước eta_SMO = 0 chọn đúng biên L/H bảo toàn \(\alpha_1 y_1 + \alpha_2 y_2\).
Bài tập 3 — Phổ Mercer, Định lý Biểu diễn, Nhân Miền (HIK/Chi2/String) & Bẫy Tỷ lệ RBF
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng phép chiếu trực giao \(f = f_\parallel + f_\perp\) lên \(\operatorname{span}\{K(\mathbf{x}_i, \cdot)\}\) chứng minh Định lý Biểu diễn, khai triển đủ đơn thức của nhân đa thức d_poly=2, và chứng minh \(\min(a,b) = \int_0^\infty \mathbb{I}[a\ge u]\mathbb{I}[b\ge u]du\) cho HIK.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy audit_kernel_psd trên cả 8 nhân, kiểm tra explicit_poly2_feature_map khớp poly tới 1e-11, và chạy run_scaling_and_island_diagnostics tái tạo sụp đổ K -> I_n & đảo ghi nhớ (C=1000, gamma=10).
Tiêu chí Đáp án & Số đối chứng
7 nhân Mercer giữ min_eig >= -5.3e-14, còn sigmoid thất bại ở -0.235. Không chuẩn hóa cart_value_usd khiến gamma='auto' cho median K = 0.0 (test 50.6%), gamma='scale' chỉ đạt 57.2%, trong khi log1p + StandardScaler + median gamma=0.0537 nâng lên 79.4%; (C=1000, gamma=10) khóa 100% SV với test = 55.6%.
Bài tập 4 — Đối ngẫu epsilon-SVR, nu-OCSVM vs. SVDD & Phân loại Đa lớp OvO vs. OvR
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh tính loại trừ \(\alpha_i \alpha_i^* = 0\) trong epsilon-SVR khi \(\epsilon_{\text{tube}} > 0\), bất đẳng thức kép outlier_frac <= nu <= sv_frac của nu-OCSVM, và chứng minh SVDD trùng khít nu-OCSVM khi \(K(\mathbf{x}_i, \mathbf{x}_i) \equiv 1\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi run_svr_and_ocsvm_cases (so sánh OLS, SVR eps=0.05, và SVR eps=2.58 theo MAD trước gai +380..+520) và MulticlassSVM (ovo vs ovr, K_cls = 4).
Tiêu chí Đáp án & Số đối chứng
SVR theo MAD (eps=2.58) hạ MAE từ 14.97 (OLS) xuống 0.76 (19.6x bền vững) với chỉ 11.1% SV (vs 96.7% ở eps=0.05). OC-SVM thỏa 7.9% <= 12.0% <= 21.1% và khớp SVDD trên RBF với max|alpha_diff| = 7.21e-15 (100% đồng thuận); OvO fit 53.1 ms nhanh hơn OvR 63.7 ms.
Bài tập 5 — Định lý Steinwart, Bochner RFF (Paired/ORF/QMC) & Nyström (Yang et al.)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp Định lý Bochner phân tích phổ Fourier của RBF (\(\mathcal{N}(0, 2\gamma\mathbf{I}_d)\)) và Laplace (Cauchy), chứng minh bất đẳng thức phương sai Sutherland–Schneider (2015) giữa Paired Sin/Cos và Random-Phase Cos ở cùng D_out, và suy ra tái tạo Nyström \(\mathbf{Z}\mathbf{Z}^\top = \mathbf{K}_{nm}\mathbf{K}_{mm}^+\mathbf{K}_{mn}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi run_steinwart_nonsparsity_experiment, benchmark_rff_variants và compare_nystrom_vs_rff để kiểm chứng chuẩn đơn vị Paired, gập trọng số fold_linear_weights, và bù Schur PSD.
Tiêu chí Đáp án & Số đối chứng
Steinwart: SV% tăng 10.4% -> 31.5% -> 47.7% khi R* tăng 0.0007 -> 0.081 -> 0.179. Ở D_out=64, Paired giảm phương sai 0.0123 -> 0.0088 (chuẩn đường chéo sai số 7.77e-16), ORF = 0.0603, Halton QMC = 0.0441. Trên cụm phổ suy giảm nhanh (84.6% top-16), Nyström đạt lỗi Gram 0.046 vs RFF 0.565 với gập trọng số khớp 6.66e-16.
Bài tập 6 — Xếp hạng E-Commerce (E32:E35), Văn bản Thưa TF-IDF, NTK & Chú ý FAVOR+
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích hiện tượng tập trung khoảng cách trên mặt cầu đơn vị \(\|\mathbf{x}_i - \mathbf{x}_j\|_2^2 = 2(1 - \langle\mathbf{x}_i,\mathbf{x}_j\rangle) \approx 2\) với TF-IDF chuẩn hóa; đồng thời chứng minh nhân tử hóa kết hợp O(L) của FAVOR+ với ánh xạ mũ dương trực giao.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_ecommerce_and_sparse_cases, run_ntk_and_kta_bridge, run_softmax_attention_kernel_bridge và kiểm tra trọn bộ 14/14 kiểm thử pytest (kể cả Test 14 AST bảo mật deserialization không pickle/joblib).
Tiêu chí Đáp án & Số đối chứng
Trên E-Commerce, Paired RFF (0.245 ms, 260 KiB, AUC 0.779, NDCG@10 0.842) và Folded Nyström (0.153 ms, 770 KiB, AUC 0.780) thắng độ trễ Exact RBF (2.615 ms, 180 GB ở 150k), đồng thời Platt giảm ECE 0.085 -> 0.081. NTK xác nhận KTA tăng 0.069 -> 0.119 ở chế độ giàu, và FAVOR+ tăng tốc 3.32x ở L=2048 với sai lệch kết hợp 2.22e-15.