scm2cpp-learn 0.22.0__py3-none-macosx_15_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. scm2cpp_learn/.dylibs/libgcc_s.1.1.dylib +0 -0
  2. scm2cpp_learn/.dylibs/libgfortran.5.dylib +0 -0
  3. scm2cpp_learn/.dylibs/libomp.dylib +0 -0
  4. scm2cpp_learn/.dylibs/libopenblasp-r0.3.34.dylib +0 -0
  5. scm2cpp_learn/.dylibs/libquadmath.0.dylib +0 -0
  6. scm2cpp_learn/__init__.py +4794 -0
  7. scm2cpp_learn/_classifiers.cpython-312-darwin.so +0 -0
  8. scm2cpp_learn/_compat.py +354 -0
  9. scm2cpp_learn/_generated/__init__.py +0 -0
  10. scm2cpp_learn/_generated/_loader.py +41 -0
  11. scm2cpp_learn/_generated/_loader_accel_cublas.py +185 -0
  12. scm2cpp_learn/_generated/_loader_classifiers.py +308 -0
  13. scm2cpp_learn/_generated/_loader_derived_blas.py +29 -0
  14. scm2cpp_learn/_generated/_loader_derived_cublas.py +29 -0
  15. scm2cpp_learn/_generated/_loader_derived_loops.py +29 -0
  16. scm2cpp_learn/_generated/_loader_gpu_cuda.py +313 -0
  17. scm2cpp_learn/_generated/_loader_gramops_blas.py +836 -0
  18. scm2cpp_learn/_generated/_loader_gramops_loops.py +855 -0
  19. scm2cpp_learn/_generated/_loader_nmf_blas.py +29 -0
  20. scm2cpp_learn/_generated/_loader_nmf_cublas.py +29 -0
  21. scm2cpp_learn/_generated/_loader_nmf_loops.py +29 -0
  22. scm2cpp_learn/_generated/accel_cublas/accel.cpp +26 -0
  23. scm2cpp_learn/_generated/accel_cublas/accel.hpp +1250 -0
  24. scm2cpp_learn/_generated/accel_cublas/accel_capi.cpp +82 -0
  25. scm2cpp_learn/_generated/classifiers.cpp +37 -0
  26. scm2cpp_learn/_generated/classifiers.hpp +3745 -0
  27. scm2cpp_learn/_generated/classifiers_capi.cpp +115 -0
  28. scm2cpp_learn/_generated/derived_blas/lasso_design.cpp +5 -0
  29. scm2cpp_learn/_generated/derived_blas/lasso_design.hpp +156 -0
  30. scm2cpp_learn/_generated/derived_blas/lasso_design_capi.cpp +19 -0
  31. scm2cpp_learn/_generated/derived_cublas/lasso_design.cpp +5 -0
  32. scm2cpp_learn/_generated/derived_cublas/lasso_design.hpp +158 -0
  33. scm2cpp_learn/_generated/derived_cublas/lasso_design_capi.cpp +19 -0
  34. scm2cpp_learn/_generated/derived_loops/lasso_design.cpp +5 -0
  35. scm2cpp_learn/_generated/derived_loops/lasso_design.hpp +179 -0
  36. scm2cpp_learn/_generated/derived_loops/lasso_design_capi.cpp +19 -0
  37. scm2cpp_learn/_generated/gpu_cuda/gpu.cpp +37 -0
  38. scm2cpp_learn/_generated/gpu_cuda/gpu.hpp +3846 -0
  39. scm2cpp_learn/_generated/gpu_cuda/gpu_capi.cpp +308 -0
  40. scm2cpp_learn/_generated/gramops_blas/gramops.cpp +99 -0
  41. scm2cpp_learn/_generated/gramops_blas/gramops.hpp +6655 -0
  42. scm2cpp_learn/_generated/gramops_blas/gramops_capi.cpp +295 -0
  43. scm2cpp_learn/_generated/gramops_loops/gramops.cpp +99 -0
  44. scm2cpp_learn/_generated/gramops_loops/gramops.hpp +7711 -0
  45. scm2cpp_learn/_generated/gramops_loops/gramops_capi.cpp +301 -0
  46. scm2cpp_learn/_generated/lasso_cov.cpp +7 -0
  47. scm2cpp_learn/_generated/lasso_cov.hpp +152 -0
  48. scm2cpp_learn/_generated/lasso_cov_capi.cpp +25 -0
  49. scm2cpp_learn/_generated/nmf_blas/nmf_cd.cpp +5 -0
  50. scm2cpp_learn/_generated/nmf_blas/nmf_cd.hpp +132 -0
  51. scm2cpp_learn/_generated/nmf_blas/nmf_cd_capi.cpp +19 -0
  52. scm2cpp_learn/_generated/nmf_cublas/nmf_cd.cpp +5 -0
  53. scm2cpp_learn/_generated/nmf_cublas/nmf_cd.hpp +136 -0
  54. scm2cpp_learn/_generated/nmf_cublas/nmf_cd_capi.cpp +19 -0
  55. scm2cpp_learn/_generated/nmf_loops/nmf_cd.cpp +5 -0
  56. scm2cpp_learn/_generated/nmf_loops/nmf_cd.hpp +167 -0
  57. scm2cpp_learn/_generated/nmf_loops/nmf_cd_capi.cpp +19 -0
  58. scm2cpp_learn/_generated/scm2cpp-blas.hpp +176 -0
  59. scm2cpp_learn/_generated/scm2cpp-cublas.hpp +155 -0
  60. scm2cpp_learn/_generated/scm2cpp-cuda.hpp +285 -0
  61. scm2cpp_learn/_generated/scm2cpp.hpp +1641 -0
  62. scm2cpp_learn/_gramops_blas.cpython-312-darwin.so +0 -0
  63. scm2cpp_learn/_lasso_cov.cpython-312-darwin.so +0 -0
  64. scm2cpp_learn/_lasso_derived_blas.cpython-312-darwin.so +0 -0
  65. scm2cpp_learn/_libfind.py +153 -0
  66. scm2cpp_learn/_nmf_blas.cpython-312-darwin.so +0 -0
  67. scm2cpp_learn/batch_capi.cu +431 -0
  68. scm2cpp_learn-0.22.0.dist-info/METADATA +1350 -0
  69. scm2cpp_learn-0.22.0.dist-info/RECORD +71 -0
  70. scm2cpp_learn-0.22.0.dist-info/WHEEL +6 -0
  71. scm2cpp_learn-0.22.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1350 @@
1
+ Metadata-Version: 2.4
2
+ Name: scm2cpp-learn
3
+ Version: 0.22.0
4
+ Summary: scikit-learn estimators (lasso, elastic net, ridge, RidgeCV, ARD, SVM, SVR, logistic regression, GLMs, Huber, Theil-Sen, F-score selection, RFE, NMF, Gaussian mixture, FastICA, PCA, KernelPCA, LDA, TruncatedSVD, PLS, CCA, graphical lasso, RANSAC, SGD, OMP, LARS) translated from Scheme to C++ by scm2cpp; GPU batch solver and CUDA kernels included
5
+ Author: Hirotaka Niitsuma
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/niitsuma/scm2cpp
8
+ Project-URL: Source, https://github.com/niitsuma/scm2cpp/tree/master/python/scm2cpp-learn
9
+ Keywords: scikit-learn,lasso,elastic-net,ridge,svm,logistic-regression,pca,lda,coordinate-descent,lapack,cuda,compiler
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: C++
13
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
14
+ Classifier: Intended Audience :: Science/Research
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: numpy>=1.17
18
+
19
+ # scm2cpp-learn
20
+
21
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/niitsuma/scm2cpp/blob/master/notebooks/compare-sklearn.ipynb)
22
+
23
+ *[Japanese (README.ja.md)](README.ja.md)*
24
+
25
+ About fifty scikit-learn estimators -- the lasso and its relatives,
26
+ ridge and RidgeCV, SVMs, GLMs, PCA, KernelPCA, LDA, TruncatedSVD,
27
+ mixtures, feature selection and more -- each written in Scheme and
28
+ translated to C++ by [scm2cpp](https://github.com/niitsuma/scm2cpp),
29
+ with BLAS/LAPACK, OpenMP and an optional GPU path.
30
+
31
+ Up to 0.17.0 this package was published as `scm2cpp-lasso` (imported as
32
+ `scm2cpp_lasso`). That name still installs it: `scm2cpp-lasso` 0.18.0
33
+ depends on this package, and `import scm2cpp_lasso` gives this module,
34
+ with a DeprecationWarning.
35
+
36
+ ```console
37
+ $ pip install scm2cpp-learn
38
+ ```
39
+
40
+ On Linux x86_64, macOS arm64 (macOS 15 or later) and Windows AMD64
41
+ this installs a wheel: compiled, nothing to build (with OpenBLAS
42
+ inside on Linux and macOS; Windows has the loop variants). Elsewhere pip builds the sdist,
43
+ which needs a C++17 compiler and nothing else. The wheels carry no
44
+ GPU code (a wheel cannot know the device); for the GPU builds, install
45
+ from the sdist on a machine with `nvcc` on the path:
46
+
47
+ ```console
48
+ $ pip install --no-binary scm2cpp-learn scm2cpp-learn
49
+ ```
50
+
51
+ Built from the sdist, the products and the eigen- and singular value
52
+ problems go to Intel MKL where pkg-config knows it
53
+ (`mkl-dynamic-lp64-gomp`, GNU OpenMP threading, as Gentoo's
54
+ `sci-libs/mkl` installs it), else to an OpenBLAS with LAPACKE, else to
55
+ the translated loops; `SCM2CPP_NO_MKL=1` skips MKL. The translated
56
+ loops that the dependence test proves independent run on OpenMP where
57
+ the compiler has it (`SCM2CPP_NO_OPENMP=1` builds them serial). Both
58
+ use every core unless told otherwise: `OMP_NUM_THREADS` (and
59
+ `MKL_NUM_THREADS` / `OPENBLAS_NUM_THREADS`) set the threads.
60
+
61
+ The batched GPU solver, the cuBLAS variants and the `--cuda`
62
+ estimators are then built as well; without `nvcc` the package installs
63
+ and works exactly the same, minus those.
64
+
65
+ Three of a hundred candidate columns carry the signal; the solver is
66
+ asked which, and answers with them and nothing else:
67
+
68
+ ```python
69
+ import numpy as np
70
+ from scm2cpp_learn import CovLasso
71
+
72
+ rng = np.random.default_rng(0)
73
+ X = rng.standard_normal((500, 100)) # 500 rows, 100 candidates
74
+ beta = np.zeros(100)
75
+ beta[[7, 23, 61]] = [2.0, -1.5, 0.8] # only three of them matter
76
+ y = X @ beta + 0.1 * rng.standard_normal(500)
77
+
78
+ model = CovLasso(X, y) # the Gram matrix, built once
79
+ path = model.fit_path(model.lambda_grid()) # 100 lambdas, warm-started
80
+
81
+ fit = path[60]
82
+ for j in np.flatnonzero(np.abs(fit) > 1e-6):
83
+ print(f" x{j:<3} {fit[j]:+.3f}")
84
+ ```
85
+
86
+ ```console
87
+ x7 +1.965
88
+ x23 -1.474
89
+ x61 +0.770
90
+ ```
91
+
92
+ The other 97 are exactly zero -- that is what the penalty is for -- and
93
+ the coefficients are the planted ones, shrunk toward zero by it.
94
+
95
+ The rest of the interface:
96
+
97
+ ```python
98
+ from scm2cpp_learn import cuda_available
99
+
100
+ lambdas = model.lambda_grid(num=100) # from lambda_max down
101
+ path = model.fit_path(lambdas) # warm-started, sequential
102
+ grid = model.fit_path_batch(lambdas) # every lambda from zero
103
+ one = model.fit(lambdas[60]) # a single lambda, if you must
104
+ print("GPU:", cuda_available())
105
+ ```
106
+
107
+ `fit` is the one-element special case of `fit_path` -- the Gram matrix
108
+ was built in the constructor, so a whole warm-started path costs barely
109
+ more than one penalty, which is why the path is the primary interface.
110
+
111
+ The objective is scikit-learn's, with `fit_intercept=False`:
112
+
113
+ (1 / 2 nobs) ||y - X b||^2 + lam ||b||_1
114
+
115
+ Penalties are compared against correlations on the features' own
116
+ scale, so the useful range of `lam` depends on the data.
117
+ `lambda_max()` is the smallest penalty that leaves every coefficient
118
+ at zero, and `lambda_grid()` walks down from it -- the construction
119
+ scikit-learn uses. If your columns differ wildly in scale, standardize
120
+ them first; this solver does not do it for you.
121
+
122
+ ## scikit-learn compatibility
123
+
124
+ From 0.14.0 every estimator with a `fit(X, y)` (or `fit(X)`) derives
125
+ from scikit-learn's `BaseEstimator` and the matching mixin, so `clone`,
126
+ `get_params` / `set_params`, `GridSearchCV`, `Pipeline` and
127
+ `cross_val_score` take them, and all 44 pass
128
+ `sklearn.utils.estimator_checks.check_estimator` (`check-sklearn.py`
129
+ runs it; the one expected failure is `LBFGSLogisticRegressionCV`'s
130
+ `n_iter_` of 0 for a C whose warm start is already converged, which
131
+ scikit-learn's own `LogisticRegressionCV` reports on the same data).
132
+ scikit-learn stays optional: without it a numpy-only stand-in gives
133
+ `get_params`, `set_params`, `score` and the same input checks.
134
+
135
+ ```python
136
+ from sklearn.model_selection import GridSearchCV
137
+ from scm2cpp_learn import GramLasso
138
+
139
+ GridSearchCV(GramLasso(), {"alpha": [0.01, 0.1, 1.0]}, cv=5).fit(X, y)
140
+ ```
141
+
142
+ `CovLasso`, `CovRidge`, `DerivedLasso`, `CovLogistic`,
143
+ `CovGroupLasso` and `CovMultiTaskLasso` keep their
144
+ data-in-the-constructor interface, which solves a whole path at once;
145
+ each has a `fit(X, y)` form with the intercept beside it (0.15.0):
146
+
147
+ | data in the constructor | `fit(X, y)` | scikit-learn |
148
+ |---|---|---|
149
+ | `CovLasso` | `GramLasso`, `GramElasticNet` | Lasso, ElasticNet |
150
+ | `CovRidge` | `GramRidge` | Ridge |
151
+ | `DerivedLasso` | `DesignLasso` | Lasso |
152
+ | `CovLogistic` | `GramLogisticRegression` | LogisticRegression(l1_ratio=1, solver="liblinear") |
153
+ | `CovGroupLasso` | `GramGroupLasso` (`groups=None`: the lasso) | (none) |
154
+ | `CovMultiTaskLasso` | `GramMultiTaskLasso`, `GramMultiTaskElasticNet` | MultiTaskLasso, MultiTaskElasticNet |
155
+
156
+ Against scikit-learn on 400 x 30 with an intercept: `DesignLasso` and
157
+ `GramGroupLasso(groups=None)` agree with `Lasso` to 1.5e-10, the
158
+ multi-task pair with `MultiTaskLasso` / `MultiTaskElasticNet` to
159
+ 5e-14, and `GramLogisticRegression` reaches liblinear's objective to
160
+ eight digits with the same predictions.
161
+
162
+ Against the class each one wraps (one alpha, one core), which fits no
163
+ intercept and is unchanged: with `fit_intercept=False` the input checks
164
+ add 15 to 30 us a call (up to +50% on a 0.06 ms fit) and the finiteness
165
+ sum 8 to 14% on 20000 x 200 (none under `assume_finite`); with the
166
+ intercept, the column means add 20 to 30% on 20000 x 200 for the
167
+ Gram-matrix ones, which correct X'X
168
+ for the means rather than copy X to centre it, and about 55% for
169
+ `DesignLasso`, whose kernel needs the centred X itself.
170
+ `GramLogisticRegression` is slower than liblinear by its algorithm, 2.5x
171
+ at 20000 x 200 and more on small problems; `L1LogisticRegression` is
172
+ the fast one for that problem.
173
+
174
+ What it costs is the input checks: X must be a finite 2-D float64
175
+ array with the feature count of the fit. A plain C-ordered float64
176
+ ndarray is checked directly (one sum for finiteness); anything else (a
177
+ list, a DataFrame, another dtype) goes through scikit-learn's
178
+ `validate_data`, which raises the errors scikit-learn raises. The
179
+ checks alone, per call (`bench/sklearn-compat-overhead.py --checks`):
180
+
181
+ | X | fit | predict | predict, 50 rows | validate_data |
182
+ |---|---|---|---|---|
183
+ | 200 x 10 | 13 us | 7 us | 9 us | 173 us |
184
+ | 2000 x 50 | 47 us | 36 us | 9 us | 224 us |
185
+ | 20000 x 200 | 2.7 ms | 3.2 ms | 13 us | 3.2 ms |
186
+
187
+ The finiteness sum is the size-dependent part; under
188
+ `sklearn.set_config(assume_finite=True)` every row is about 3 us.
189
+ Whole calls, before and after (`bench/sklearn-compat-overhead.py`, 30
190
+ estimators, three shapes, the two packages alternating on one core of
191
+ a loaded machine): fits of a millisecond or more are unchanged within
192
+ the run-to-run spread (about 10%); fits of about 0.1 ms take 10 to
193
+ 30% (10 to 40 us) longer; predict on 20000 x 200 takes about twice as
194
+ long (3 ms to 6 ms, the finiteness sum costing as much as the product
195
+ itself), and on small inputs 5 to 10 us longer.
196
+
197
+ ## Estimators at a glance
198
+
199
+ Every estimator, the scikit-learn estimator it reproduces, the Scheme
200
+ kernel under `examples/kernel-only/` it is translated from, the builds
201
+ it runs on, and whether Intel's sklearnex accelerates the scikit-learn
202
+ side. Builds: *loops* is the plain translation, *BLAS* / *cuBLAS* the
203
+ products handed to (cu)BLAS, *--cuda* the translator's GPU kernels
204
+ (`gpu_cuda/`), *GPU batch* the hand-written CUDA batch solver; the
205
+ package picks the fastest one present.
206
+
207
+ | class | scikit-learn | Scheme kernel | builds | sklearnex accelerates |
208
+ |---|---|---|---|---|
209
+ | `GramLasso` | Lasso(precompute=True), fit(X, y) with the intercept, dense or sparse X | `lasso-cov.scm` | CPU | no |
210
+ | `GramElasticNet` | ElasticNet(precompute=True), fit(X, y) with the intercept, dense or sparse X | `lasso-cov.scm` | CPU | no |
211
+ | `GramRidge` | Ridge, fit(X, y) with the intercept, one or many targets, dense or sparse X | `gram.scm` (Cholesky; dposv) | loops / BLAS | Ridge |
212
+ | `GramLinearRegression` | LinearRegression, dense or sparse X, sample_weight | `linreg.scm` (Cholesky; dposv, dpocon) | loops / BLAS | no |
213
+ | `GramRidgeCV` | RidgeCV (cv=None), leave-one-out over every alpha from one eigenproblem | `ridge-gcv.scm` | loops / BLAS | no |
214
+ | `GramMultiTaskLasso` | MultiTaskLasso, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
215
+ | `GramMultiTaskElasticNet` | MultiTaskElasticNet, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
216
+ | `GramGroupLasso` | (none; skglm GroupLasso), fit(X, y) with the intercept | `lasso-cov.scm` | CPU | - |
217
+ | `GramLogisticRegression` | LogisticRegression(l1_ratio=1, solver='liblinear'), by majorization | `lasso-cov.scm` | CPU | no |
218
+ | `DesignLasso` | Lasso, fit(X, y) with the intercept, from the design | `lasso-design.scm (--derive)` | loops / BLAS / cuBLAS | no |
219
+ | `CovLasso` | Lasso, ElasticNet, lasso_path(precompute=True) | `lasso-cov.scm` | CPU; GPU batch (fit_path_batch, bootstrap) | no |
220
+ | `CovLassoCV` | LassoCV, ElasticNetCV | `lasso-cov.scm` | CPU; GPU batch | no |
221
+ | `DerivedLasso` | lasso_path, from the design | `lasso-design.scm (--derive)` | loops / BLAS / cuBLAS | no |
222
+ | `CovMultiTaskLasso` | MultiTaskLasso, MultiTaskElasticNet | `lasso-cov.scm` | CPU | no |
223
+ | `CovMultiTaskLassoCV` | MultiTaskLassoCV, MultiTaskElasticNetCV | `lasso-cov.scm` | CPU; GPU batch | no |
224
+ | `CovGroupLasso` | (none; skglm GroupLasso) | `lasso-cov.scm` | CPU | - |
225
+ | `CovLogistic` | LogisticRegression(penalty='l1'), by majorization | `lasso-cov.scm` | CPU | no |
226
+ | `CovRidge` | Ridge(fit_intercept=False), a whole alpha path | `lasso-cov.scm` | CPU | Ridge |
227
+ | `CovBayesianRidge` | BayesianRidge | `lasso-cov.scm` | CPU | no |
228
+ | `CovARDRegression` | ARDRegression (n >= p) | `ard.scm` | loops / BLAS | no |
229
+ | `GramLars` | Lars | `lars.scm` | CPU | no |
230
+ | `GramLassoLars` | LassoLars | `lars.scm` | CPU | no |
231
+ | `GramLassoLarsIC` | LassoLarsIC | `lars.scm` | CPU; device Gram | no |
232
+ | `GramLarsCV` | LarsCV | `lars.scm` | CPU | no |
233
+ | `GramLassoLarsCV` | LassoLarsCV | `lars.scm` | CPU; device Gram | no |
234
+ | `GramOMP` | OrthogonalMatchingPursuit | `omp.scm` | loops / BLAS | no |
235
+ | `GramOMPCV` | OrthogonalMatchingPursuitCV | `omp.scm` | loops / BLAS | no |
236
+ | `LBFGSLogisticRegression` | LogisticRegression(solver='lbfgs') | `logistic-lbfgs.scm, lbfgs.scm` | loops / BLAS / --cuda | LogisticRegression |
237
+ | `LBFGSLogisticRegressionCV` | LogisticRegressionCV | `logistic-lbfgs.scm, lbfgs.scm` | loops / BLAS / --cuda | no |
238
+ | `LBFGSHuberRegressor` | HuberRegressor | `huber.scm, lbfgs.scm` | loops / BLAS / --cuda | no |
239
+ | `LBFGSPoissonRegressor` | PoissonRegressor | `glm.scm, lbfgs.scm` | loops / BLAS / --cuda | no |
240
+ | `LBFGSGammaRegressor` | GammaRegressor | `glm.scm, lbfgs.scm` | loops / BLAS / --cuda | no |
241
+ | `LBFGSTweedieRegressor` | TweedieRegressor | `glm.scm, lbfgs.scm` | loops / BLAS / --cuda | no |
242
+ | `LinearSVM` | LinearSVC(loss='hinge') | `svm-liblinear.scm` | CPU | no |
243
+ | `L1LinearSVM` | LinearSVC(penalty='l1', dual=False) | `svm-l1.scm` | CPU | no |
244
+ | `KernelSVM` | SVC | `svm-smo.scm` | CPU | SVC |
245
+ | `LinearSVR` | LinearSVR | `svr-liblinear.scm` | CPU | no |
246
+ | `KernelSVR` | SVR | `svm-smo.scm` | CPU | SVR |
247
+ | `L1LogisticRegression` | LogisticRegression(penalty='l1', solver='liblinear') | `logistic-l1.scm` | CPU | no |
248
+ | `SGDLinearClassifier` | SGDClassifier(shuffle=False) | `sgd.scm` | CPU | no |
249
+ | `SGDLinearRegressor` | SGDRegressor(shuffle=False) | `sgd.scm` | CPU | no |
250
+ | `SGDPerceptron` | Perceptron(shuffle=False) | `sgd.scm` | CPU | no |
251
+ | `LinearRANSAC` | RANSACRegressor (given subsets) | `ransac.scm` | CPU | no |
252
+ | `WeiszfeldTheilSen` | TheilSenRegressor | `theilsen.scm` | CPU | no |
253
+ | `CDNMF` | NMF(solver='cd') | `nmf-cd.scm (--derive)` | loops / BLAS / cuBLAS | no |
254
+ | `CDGraphicalLasso` | GraphicalLasso | `graphical-lasso.scm` | loops / BLAS | no |
255
+ | `EMGaussianMixture` | GaussianMixture(covariance_type='full') | `gmm.scm` | loops / BLAS / --cuda | no |
256
+ | `ParallelFastICA` | FastICA | `fastica.scm` | loops / BLAS / --cuda | no |
257
+ | `CovPCA` | PCA(svd_solver='covariance_eigh') | `pca.scm` | loops / BLAS / cuBLAS | PCA |
258
+ | `GramKernelPCA` | KernelPCA (no inverse_transform) | `kernel-pca.scm` | loops / BLAS | no |
259
+ | `GramLDA` | LinearDiscriminantAnalysis (svd, lsqr, eigen) | `lda.scm` | loops / BLAS | no |
260
+ | `GramTruncatedSVD` | TruncatedSVD on dense or sparse X (exact, as arpack) | `truncated-svd.scm`, `sparse.scm` | loops / BLAS | no |
261
+ | `GramPLSRegression`, `GramPLSCanonical`, `GramCCA`, `GramPLSSVD` | PLSRegression, PLSCanonical, CCA, PLSSVD | `pls.scm` | loops / BLAS | no |
262
+ | `GramFactorAnalysis` | FactorAnalysis (exact, as svd_method='lapack'; rotations) | `fa.scm` | loops / BLAS | no |
263
+ | `f_regression, f_classif` | f_regression, f_classif | `fscore.scm` | loops / BLAS / cuBLAS | no |
264
+ | `SelectKBest, SelectPercentile` | SelectKBest, SelectPercentile | `fscore.scm` | loops / BLAS / cuBLAS | no |
265
+ | `GramRFE` | RFE(Ridge), RFE(LinearRegression) | `rfe.scm` | loops / BLAS / cuBLAS | inside: Ridge |
266
+
267
+ ## Two kernels: `CovLasso` and `DerivedLasso`
268
+
269
+ Everything above, and the cross-validation, bootstrap and GPU methods
270
+ below, runs on one kernel: numpy forms the Gram matrix, and a
271
+ hand-written coordinate-descent sweep over it
272
+ (`examples/kernel-only/lasso-cov.scm` in the repository, translated to
273
+ C++) does the rest. That is the usable one.
274
+
275
+ `DerivedLasso` is the other kernel, and it is there to show the
276
+ translator's work rather than to be the better estimator. Its source
277
+ is `examples/kernel-only/lasso-design.scm`: the residual-form
278
+ coordinate descent -- the algorithm inside scikit-learn's
279
+ `Lasso(precompute=False)` -- written as flat loops over X exactly as
280
+ numpy holds it (n rows of p, `x[i*p+j]`), the residual copied from y
281
+ and the column norms taken inside, with no Gram matrix anywhere in
282
+ it. The translator's `--derive` turns
283
+ that into the Gram form: it raises the loops to an array algebra,
284
+ notices that the residual is only ever updated by a scaled column and
285
+ read in dot products against columns, replaces it by the memo `c =
286
+ X'r` kept current through a Gram matrix it hoists in front of the
287
+ penalty path, folds the column norms into that Gram's diagonal, folds
288
+ the three products into one `dsyrk` and two `dgemv` calls (`--blas`), and puts the whole thing under
289
+ `(if (< p n) ..)` with the sweep as written in the else branch --
290
+ scikit-learn's `precompute='auto'` rule, derived rather than written.
291
+ The C++ of that derivation, as the translator emitted it, is what
292
+ `DerivedLasso` calls; numpy prepares nothing -- X and y go in as they
293
+ are, no transposed copy, no norms.
294
+
295
+ ```python
296
+ from scm2cpp_learn import DerivedLasso, derived_backend
297
+
298
+ model = DerivedLasso(X, y) # X and y; the kernel builds its own Gram
299
+ path = model.fit_path(model.lambda_grid()) # one call, the whole warm-started path
300
+ print(derived_backend()) # 'cublas', 'blas' or 'loops': what this machine built
301
+ gpu = DerivedLasso(X, y, backend="cublas") # insist on one
302
+ ```
303
+
304
+ A lambda is done when no coefficient moved by more than `tol`
305
+ (absolute, default 1e-8) in a sweep, or at `max_sweeps`; `tol=0.0`
306
+ asks for the exact fixed point. Three translations of the one
307
+ derivation are committed and `pip` builds what the machine allows:
308
+ `--derive --cublas` where the CUDA toolkit is (the three products on
309
+ the device through cuBLAS, X uploaded once per `fit_path` call --
310
+ taken by default when a device answers), `--derive --blas` where
311
+ `cblas.h` and an OpenBLAS are, and `--derive` alone otherwise, the
312
+ same program with its Gram matrix as a scalar loop nest, correct but
313
+ slow on large designs. `check-derived.py` in the package directory runs
314
+ the two kernels and scikit-learn on the same path and prints the
315
+ differences and the times; on AR(1) designs (rho 0.9), 20 penalties
316
+ from lambda_max to 0.01 lambda_max, one core, best of three (load
317
+ about 3), whole calls with the Gram matrix wherever it is built:
318
+
319
+ | n x p | 1,800 x 200 | 5,000 x 1000 | 100,000 x 200 | 100,000 x 500 |
320
+ |-----------------------------------------|-------------|--------------|---------------|---------------|
321
+ | `DerivedLasso`, cuBLAS (upload included) | 0.003 s | 0.024 s | 0.052 s | 0.11 s |
322
+ | `DerivedLasso`, CBLAS | 0.003 s | 0.076 s | 0.12 s | 0.44 s |
323
+ | `CovLasso(X, y).fit_path`, tol 1e-8 | 0.004 s | 0.080 s | 0.11 s | 0.42 s |
324
+ | sklearn `lasso_path(precompute=True)`, tol 1e-4 | 0.005 s | 0.10 s | 0.24 s | 0.76 s |
325
+
326
+ The CBLAS run is the same `dsyrk` and the same sweeps as `CovLasso`'s
327
+ numpy Gram and path, and times the same; the cuBLAS run is the same
328
+ program with the three products on the device, the upload of X
329
+ counted, and is 4.2x, 4.5x and 6.7x ahead of scikit-learn at the
330
+ three larger shapes -- the figures of the repository's equal-work
331
+ table, now reached from the package with nothing in front of the
332
+ kernel: the constructor keeps X and y and the kernel takes the
333
+ residual and the column norms itself (the norms folded into the Gram
334
+ diagonal by the derivation). Threads change the picture less than one might expect: scikit-learn's
335
+ sweeps are single-threaded Cython and only its Gram product scales,
336
+ so with 20 BLAS threads `lasso_path` takes 0.051 / 0.227 / 0.450 s on
337
+ the three larger shapes, against 0.023 / 0.050 / 0.113 s for the
338
+ cuBLAS build (2.2x, 4.5x, 4.0x) and 0.025 / 0.036 / 0.123 s for the
339
+ CBLAS build (2.0x, 6.3x, 3.7x), whose `dsyrk` scales with the
340
+ threads; the GPU figures do not move. Against a reference driven to
341
+ tol=1e-12, `DerivedLasso` lands within 5e-8 on every backend (its
342
+ tolerance is absolute, on one sweep's largest move), `CovLasso`
343
+ within 2e-10 (it tests every 20 sweeps and overshoots), and
344
+ scikit-learn at its default within 1e-3.
345
+
346
+ ### Deriving it yourself
347
+
348
+ Everything `DerivedLasso` runs is reproducible from the Scheme with
349
+ the translator; this is what `regenerate.sh` does for the package,
350
+ spelled out for one kernel (Racket 8 and a C++17 compiler; a CBLAS
351
+ for `--blas`, the CUDA toolkit for `--cublas`):
352
+
353
+ ```console
354
+ $ git clone https://github.com/niitsuma/scm2cpp && cd scm2cpp
355
+ $ raco link --user vendor/rkanren # once per machine
356
+ $ mkdir /tmp/k && cp examples/kernel-only/lasso-design.scm examples/kernel-only/soft-threshold.scm /tmp/k/
357
+ $ racket scm2cpp-file.scm -t scm2c.typ --derive --cublas -M -S /tmp/k/lasso-design.scm
358
+ derive: lasso-design: raise differencing merge matmul guard
359
+ ```
360
+
361
+ `derive:` on stderr names what fired: the loops raised to the array
362
+ algebra, the residual differenced into the memo, the column norms
363
+ merged into the Gram diagonal, the products folded to contractions,
364
+ the `(if (< p n) ..)` guard. The run leaves, beside the source,
365
+ `lasso-design.hpp` (the derived kernel as C++: one `blas_syrk`, two
366
+ `blas_gemv`, the sweep), `lasso-design_capi.cpp` and
367
+ `lasso_design.py` (the `-M` C ABI and its ctypes loader -- what the
368
+ package's `_loader_derived_*.py` are), and `lasso-design.expanded.scm`
369
+ (`-S`: the derived program as Scheme, before C++ -- read this to see
370
+ what the derivation did). `--blas` instead of `--cublas` gives the
371
+ CBLAS variant, neither the loop variant. To call it from numpy
372
+ without the package:
373
+
374
+ ```console
375
+ $ g++ -O2 -std=c++17 -shared -fPIC -I. -I$CUDA_HOME/include -o /tmp/k/liblasso-design.so \
376
+ /tmp/k/lasso-design_capi.cpp -L$CUDA_HOME/lib64 -lcublas -lcudart # -lopenblas for --blas
377
+ $ cd /tmp/k && python3 -c 'import lasso_design' # lasso_design.lasso_design(x, y, resid, xnorm, beta, lams, betas, iters, tol, n, p, nlam)
378
+ ```
379
+
380
+ (`-M` names the Python module after the file with `-` read as `_`,
381
+ and the loader looks for `liblasso-design.so` beside it.)
382
+ `examples/kernel-only/README.md` walks through the same `-M` flow on
383
+ the row-major kernel, and `python/PACKAGING.md` through turning such
384
+ a kernel into a pip package.
385
+
386
+ ## Against the other lassos pip can install
387
+
388
+ `bench/lasso-compare.py` in the repository runs the same
389
+ cross-validation-shaped grid -- 4096 lambdas, each solved from zero,
390
+ p=200, n=1800 -- against every lasso a `pip install` produces:
391
+ scikit-learn 1.9.1, celer 0.7.4, skglm 0.5, and RAPIDS cuML 26.8.
392
+ Every solver runs at its own default tolerance (ours at the tighter
393
+ 1e-8), each gets one untimed warm-up fit, cuML's data is on the device
394
+ before the clock starts, and the last column is each solver's
395
+ objective minus ours at the smallest lambda -- a fast row with a loose
396
+ answer would show as one:
397
+
398
+ | solver | time | objective gap |
399
+ |----------------------------------------|---------|---------------|
400
+ | scm2cpp-learn, 1 CPU core (tol 1e-8) | 0.91 s | 0 |
401
+ | scm2cpp-learn, GPU, one block/lambda | 0.044 s | 0 |
402
+ | sklearn `Lasso.fit` per lambda | 9.6 s | +1.6e-09 |
403
+ | celer per lambda | 13.5 s | 0 |
404
+ | skglm per lambda | 14.5 s | +2.8e-17 |
405
+ | cuML per lambda, GPU | 53.6 s | +9.1e-07 |
406
+
407
+ (One sitting on an otherwise idle machine, best of three runs; cuML
408
+ 26.08 on CUDA 12.9.)
409
+
410
+ celer and skglm are built for very large sparse designs, where their
411
+ screening rules dominate; at this size they pay their setup per fit.
412
+ cuML parallelises *within* one fit, which wins when a fit is large; at
413
+ this size its launch overhead dominates, while our GPU row
414
+ parallelises *across* lambdas -- one block of CUDA threads per
415
+ penalty, the axis a cross-validation grid actually offers.
416
+
417
+ `CovLassoCV` is scikit-learn's `LassoCV` over this machinery -- same
418
+ grid construction, same contiguous folds, same minimum-mean-MSE choice
419
+ -- with two structural savings. A fold's training Gram is a
420
+ *subtraction* (the Gram is additive over rows, so G - Xf'Xf costs one
421
+ fold's work where rebuilding costs four folds'), and once the Grams
422
+ exist nothing downstream ever touches the n rows again -- which is why
423
+ the gap grows with n. With a GPU the whole grid is one launch: one
424
+ *block* of threads per (fold, alpha) cell, the fold's Gram read in
425
+ place (cv Gram matrices on the device, not cv x 100), thread 0 of the
426
+ block doing the coordinate step and the block spreading the O(p)
427
+ update of the correlations. cv x 100 = 500 cells are too few
428
+ problems to fill a device one thread each, and a block per problem is
429
+ what turns that count into enough parallel work; `bench/cv-grid-designs.py`
430
+ times the alternatives (one thread per cell, warm runs of several
431
+ alphas per thread or block) side by side, and the block per cell wins
432
+ at every size tried. The GPU is the default when a device answers
433
+ (`force_cpu` takes the warm CPU path). Measured at cv=5, 100 alphas,
434
+ one CPU core, sklearn 1.9.1, best of three runs, whole estimator
435
+ including the Grams:
436
+
437
+ | n | p | CPU | CUDA | sklearn `LassoCV` |
438
+ |---------|------|--------|--------|-------------------|
439
+ | 1,800 | 200 | 0.21 s | 0.02 s | 0.10 s |
440
+ | 5,000 | 1000 | 1.48 s | 0.25 s | 0.90 s |
441
+ | 100,000 | 200 | 0.49 s | 0.34 s | 1.72 s |
442
+ | 100,000 | 500 | 1.32 s | 1.09 s | 4.82 s |
443
+
444
+ (Taken on an otherwise idle machine, load 2-3 on 20 threads. sklearn's
445
+ `LassoCV` at its default `precompute='auto'` takes the Gram route at
446
+ every size here, n > p, rebuilding each fold's Gram from that fold's
447
+ rows where we subtract it from the whole.) The grid
448
+ launch itself takes 9 ms at n=1,800 and 64 ms at n=5,000, p=1000; at
449
+ n=100,000 the CUDA column is nearly all Gram products, which the CPU
450
+ path pays as well. Large n is where the machinery pays either way:
451
+ nothing downstream of the Grams touches the 100,000 rows again. At
452
+ n=5,000, p=1000 sklearn's raw-X descent beats our Gram-heavy CPU path,
453
+ and the GPU makes up the difference three and a half times over. CPU and CUDA
454
+ choose the same alpha everywhere and agree to 1e-14; against sklearn
455
+ the pick is exact at n=5,000 and one grid step apart on a near-tie
456
+ elsewhere (mean-MSE relative gap at most 2.6e-4), and sklearn at
457
+ tol=1e-10 picks our alpha at every size.
458
+
459
+ `cv` may also be a splitter (`TimeSeriesSplit`, a shuffled `KFold`, ...)
460
+ or a list of (train, test) index pairs, and `fit_intercept=True` centres
461
+ each fold's training rows as `LassoCV` does (through the Gram, not a
462
+ centred copy); the default stays the fit through the origin. A
463
+ `TimeSeriesSplit` fold's training rows are a prefix, so its Gram is the
464
+ previous fold's plus the new rows' -- the five folds cost one pass over
465
+ the training rows, not five. Against `LassoCV` on the same grid the
466
+ validation errors agree to 1e-11 and the coefficients and intercept
467
+ to 1e-11.
468
+
469
+ `solver="lars"` (lasso only) solves each fold and the refit by the
470
+ translated least angle regression over the same Gram
471
+ (`examples/kernel-only/lars.scm`, method "lasso") and reads the
472
+ solutions at the grid off the recorded path, which is piecewise linear
473
+ in alpha: exact up to rounding, with no tolerance, and with a cost set
474
+ by the number of path steps rather than by conditioning. Columns equal
475
+ up to a factor are cut to the longest one first (two equal columns tie
476
+ in the path; scikit-learn's `lars_path` stops early there), and a grid
477
+ point whose solution misses the optimality conditions (1e-5 relative)
478
+ is finished by coordinate descent (`n_polished_`). Where the columns
479
+ are strongly correlated -- moving averages over overlapping windows --
480
+ coordinate descent needs thousands of sweeps and LARS is far faster: on
481
+ a stock-feature design with n=743 and p=180, 0.21 s against 145 s for
482
+ the descent on the same grid; at p=3495, 2.2 s, where the descent was
483
+ stopped after 30 minutes. The default stays `solver="cd"`.
484
+
485
+ `working_set=k` (with `solver="lars"`, a dense X) is for a design too
486
+ wide for its Gram matrix -- p by p, 309 GB at p = 196,574. Each fold
487
+ and the refit are solved on a working set of columns: the k most
488
+ correlated with y to begin with; then, while a column outside the set
489
+ breaks the optimality conditions at some grid point (the gradient
490
+ against alpha over all p columns, 1e-5 relative), the k worst of them
491
+ join and the set is solved again. When none does, every grid solution
492
+ solves the whole problem -- checked, not assumed -- so the fit is the
493
+ full Gram's (`check-wheel.py`: 3e-13 at p = 3000, n = 150, the set
494
+ staying well below p), in memory O(np) plus the set's Gram.
495
+ `working_set_` records the rounds and the final set's size for each
496
+ fold and the refit.
497
+
498
+ The elastic net cross-validates the same way: `CovLassoCV(l1_ratio=0.5)`
499
+ against `ElasticNetCV(l1_ratio=0.5)` on the same folds and alpha grid
500
+ (`bench/lasso-compare.py --cv-only --l1-ratio 0.5`, same conditions,
501
+ load under 1):
502
+
503
+ | n | p | CPU | CUDA | sklearn `ElasticNetCV` |
504
+ |---------|------|--------|--------|------------------------|
505
+ | 1,800 | 200 | 0.35 s | 0.02 s | 0.11 s |
506
+ | 5,000 | 1000 | 1.55 s | 0.26 s | 0.98 s |
507
+ | 100,000 | 200 | 0.52 s | 0.35 s | 1.76 s |
508
+ | 100,000 | 500 | 1.38 s | 1.15 s | 4.97 s |
509
+
510
+ The picture is the lasso's: on the CPU, 3.4-3.6x at 100,000 rows and
511
+ slower than sklearn at the two small shapes; with CUDA, 3.8-5.5x
512
+ everywhere. The chosen alpha is sklearn's at all four sizes, the
513
+ coefficients within 8e-6 (sklearn's default tolerance).
514
+
515
+ `CovMultiTaskLasso` and `CovMultiTaskLassoCV` are the multi-task
516
+ family over the same machinery: scikit-learn's `MultiTaskLasso`,
517
+ `MultiTaskElasticNet` (through `l1_ratio`), `MultiTaskLassoCV` and
518
+ `MultiTaskElasticNetCV`. The penalty ties each feature's row of W
519
+ together across tasks, so the coordinate update becomes a block soft
520
+ threshold on the row's L2 norm; C = X'Y - GW is maintained per task
521
+ exactly as the single-task C is, and nothing downstream of the Grams
522
+ touches the n rows -- the kernel is the same translated Scheme
523
+ (`mt-descend`). Folds are independent and both the descent (ctypes)
524
+ and the products (BLAS) release the GIL, so `n_jobs` threads scale the
525
+ CV across folds; the default is sequential, as scikit-learn's
526
+ `n_jobs=None` is, and the benchmark pins BLAS to one thread on both
527
+ sides either way. With a GPU the CV grid is one launch exactly as
528
+ `CovLassoCV`'s is, a block per (fold, alpha) cell with the p x T
529
+ coefficient block in shared memory (`force_cpu` opts out). Same
530
+ protocol as above, 8 tasks; single fits at alpha = 0.1 lambda_max;
531
+ the CV pairs share the 100-alpha grid:
532
+
533
+ | estimator | n | p | ours | ours `n_jobs=5` | ours CUDA | sklearn |
534
+ |-----------------------|---------|-----|--------|-----------------|-----------|---------|
535
+ | MultiTaskLasso | 100,000 | 200 | 0.14 s | -- | -- | 0.76 s |
536
+ | MultiTaskLasso | 100,000 | 500 | 0.53 s | -- | -- | 1.7 s |
537
+ | MultiTaskLassoCV | 1,800 | 200 | 1.4 s | 0.51 s | 0.07 s | 0.42 s |
538
+ | MultiTaskLassoCV | 100,000 | 200 | 1.6 s | 0.64 s | 1.3 s | 74 s |
539
+ | MultiTaskElasticNetCV | 1,800 | 200 | 1.4 s | 0.49 s | 0.08 s | 0.75 s |
540
+ | MultiTaskElasticNetCV | 100,000 | 200 | 1.6 s | 0.68 s | 1.3 s | 162 s |
541
+
542
+ (`MultiTaskElasticNet` single fits time the same as `MultiTaskLasso`'s;
543
+ every column was taken in one sitting on the idle machine of the
544
+ `CovLassoCV` table above, sklearn 1.9.1. scikit-learn has no Gram
545
+ route for its multi-task estimators -- its path code sets
546
+ `precompute=False` for 2-D targets, "No Gram variant of multi-task
547
+ exists right now" -- so its column is raw-X descent at every n, which
548
+ is why it grows with n where `LassoCV`'s did not.) At n=1,800 our sequential CV
549
+ is slower than sklearn's: the default tol=1e-8 runs more sweeps than
550
+ sklearn's 1e-4 dual-gap stop, and at that size there are no rows to
551
+ save -- and the GPU grid takes the whole thing in a tenth of a second.
552
+ At n=100,000 the Gram route is 46x and 100x ahead, essentially
553
+ unchanged from n=1,800 in absolute time; the CUDA column there is
554
+ the Gram products, the same ones the CPU path forms. Coefficients agree with scikit-learn's to 1e-15 at tight
555
+ tolerance, and the CV pair picks the same alpha with coefficients to
556
+ 1e-13.
557
+
558
+ ## Which method
559
+
560
+ `fit_path` walks a single path, each lambda starting from the previous
561
+ solution -- the descent is exactly resumable, so this costs almost
562
+ nothing per lambda after the first. `fit_path_batch` solves every
563
+ lambda from zero, which is what a cross-validation grid needs, where
564
+ the folds differ and warm starting across lambdas is not on offer; the
565
+ problems are independent, so they go to the GPU together.
566
+
567
+ Over a 400-lambda path at p=200 and 1800 rows, on an RTX 4090 and an
568
+ i9-10900X:
569
+
570
+ | call | time |
571
+ |---------------------------------------|---------|
572
+ | `fit_path` (warm, sequential) | 0.091 s |
573
+ | `fit_path_batch` (GPU) | 0.047 s |
574
+ | `fit_path_batch(force_cpu=True)` | 0.178 s |
575
+
576
+ GPU and CPU agree to 2e-14, and the objectives are within 3e-17 of
577
+ scikit-learn's `lasso_path` on the same grid.
578
+
579
+ ## Elastic net and ridge
580
+
581
+ The same Gram matrix serves two more estimators. `fit_path` and
582
+ `fit_path_batch` take `l1_ratio` (scikit-learn's mixing parameter):
583
+ the L2 share of the penalty enters only the update's denominator, so
584
+ the elastic net runs on the identical machinery, GPU path included,
585
+ and `l1_ratio=1` is bit-for-bit the lasso.
586
+
587
+ `CovRidge` is the closed form: one symmetric eigendecomposition,
588
+ then every alpha costs O(p^2), so thousands of alphas cost what one
589
+ does. Its objective matches scikit-learn's `Ridge` with
590
+ `fit_intercept=False` (which, unlike the lasso, is not scaled by the
591
+ number of rows), and agrees with it to machine precision.
592
+
593
+ ```python
594
+ path = model.fit_path(lambdas, l1_ratio=0.5) # elastic net
595
+ ridge = CovRidge(X, y)
596
+ betas = ridge.fit_path(ridge.alpha_grid()) # a whole ridge path
597
+ ```
598
+
599
+ Measured (`bench/ridge-enet-compare.py` in the repository: AR(1)
600
+ designs, 20 penalties, whole calls with the Gram matrix wherever one
601
+ is built, one core, best of three):
602
+
603
+ | n x p | 1,800 x 200 | 5,000 x 1000 | 100,000 x 200 | 100,000 x 500 |
604
+ |----------------------------------------------|-------------|--------------|---------------|---------------|
605
+ | elastic net, `CovLasso.fit_path(l1_ratio=0.5)`, tol 1e-8 | 0.007 s | 0.092 s | 0.11 s | 0.40 s |
606
+ | elastic net, sklearn `enet_path(precompute=True)`, tol 1e-4 | 0.005 s | 0.099 s | 0.23 s | 0.74 s |
607
+ | ridge, `CovRidge.fit_path(alphas)` | 0.004 s | 0.21 s | 0.10 s | 0.41 s |
608
+ | ridge, sklearn `Ridge(alpha).fit` per alpha | 0.060 s | 2.05 s | 3.37 s | 11.2 s |
609
+ | ridge, sklearn `RidgeCV(alphas)` (its LOO path) | 0.093 s | 3.40 s | 5.38 s | 19.0 s |
610
+
611
+ The elastic net is the same coordinate descent on both sides, so the
612
+ two rows differ by the Gram and the warm path, not the sweeps: level
613
+ at small n, 1.8-2.2x at 100,000 rows, and ours lands within 2e-10 of
614
+ a tight reference where scikit-learn's default tolerance lands within
615
+ 6e-4. The ridge rows compare a whole path against what a user
616
+ writes -- one `Ridge.fit` per alpha, each forming X'X and solving
617
+ afresh, O(np^2 + p^3) every time -- so the gap is the path's: 10-33x,
618
+ agreeing to 1e-14. `RidgeCV` is given for scale (it picks one alpha
619
+ by leave-one-out rather than returning the path). Neither row runs
620
+ on the GPU: the ridge is one eigendecomposition and the elastic net's
621
+ sweeps are the lasso's; `fit_path_batch(l1_ratio=..)` is the GPU
622
+ grid for the elastic net.
623
+
624
+ ## Leave-one-out ridge: `GramRidgeCV`
625
+
626
+ `GramRidgeCV` is scikit-learn's `RidgeCV` with `cv=None`: the alpha
627
+ whose leave-one-out mean squared error is least, without a refit per
628
+ row. With the centred design Xc and H = Xc (Xc'Xc + alpha I)^-1 Xc'
629
+ (plus 1/n for the intercept), the leave-one-out residual is
630
+ (y - yhat) / (1 - diag H). One eigenproblem gives H = Z diag(1 /
631
+ (lam + alpha)) Z' for every alpha: Z = Xc V from Xc'Xc = V diag(lam) V'
632
+ when n > p (X'X by dsyrk), Z = Q diag(sqrt mu) from Xc Xc' = Q diag(mu)
633
+ Q' otherwise. Then diag H and yhat at all the alphas are two products,
634
+ (Z o Z) W and Z (R o W) with W[k, a] = 1 / (lam_k + alpha_a): the
635
+ alphas cost one dgemm, where scikit-learn loops over them in numpy
636
+ (`examples/kernel-only/ridge-gcv.scm`; the eigenproblem is LAPACK's
637
+ dsyevd in the BLAS build).
638
+
639
+ ```python
640
+ from scm2cpp_learn import GramRidgeCV
641
+ m = GramRidgeCV(alphas=np.logspace(-2, 4, 50)).fit(X, y)
642
+ m.alpha_, m.best_score_, m.coef_, m.intercept_
643
+ ```
644
+
645
+ It takes `fit_intercept`, `gcv_mode` (`"svd"` / `"eigen"` choose the
646
+ two Zs), `store_cv_results` and `alpha_per_target`, y one target or
647
+ several; `cv` and `scoring` must stay None. The chosen alpha is
648
+ scikit-learn's, the coefficients agree to 1e-12 and `cv_results_` to
649
+ 1e-7 relative (the wide case near interpolation). Measured
650
+ (`bench/eigen-compare.py`, the MKL build, best of three):
651
+
652
+ | case | scikit-learn `RidgeCV` | `GramRidgeCV` | ratio, one core | ratio, 20 cores |
653
+ |---|---|---|---|---|
654
+ | 200,000 x 200, 3 alphas | 2.04 s | 0.80 s | 2.6x | 3.6x |
655
+ | 200,000 x 200, 50 alphas | 26.6 s | 0.96 s | 27.7x | 29.0x |
656
+ | 20,000 x 500, 50 alphas | 9.64 s | 0.33 s | 28.9x | 29.2x |
657
+ | 2,000 x 5,000, 50 alphas | 3.16 s | 1.47 s | 2.1x | 4.5x |
658
+
659
+ ## Kernel PCA: `GramKernelPCA`
660
+
661
+ `GramKernelPCA` is scikit-learn's `KernelPCA`: the kernel matrix
662
+ (linear, rbf, poly, sigmoid, cosine or precomputed), centred in feature
663
+ space, its largest eigenpairs with svd_flip's signs
664
+ (`examples/kernel-only/kernel-pca.scm`). Where the eigenpairs come from
665
+ is what differs:
666
+
667
+ - fewer than 10 components of more than 200 rows, where scikit-learn
668
+ takes ARPACK (Lanczos, one matrix-vector product at a time): subspace
669
+ iteration on c + 25 columns, so each step is one dgemm, stopped when
670
+ every residual |K u - lam u| is under 1e-12 of the largest value
671
+ (falling back to the dense route if it is not reached);
672
+ - otherwise LAPACK's dsyevr over the wanted index range, which is what
673
+ scipy's `eigh(subset_by_index=..)` runs for scikit-learn;
674
+ - the linear kernel with no more components than features, n > p:
675
+ through Xc'Xc, p x p (the eigenvectors of Xc Xc' are Xc v / sqrt(lam)),
676
+ where scikit-learn forms the n x n kernel.
677
+
678
+ ```python
679
+ from scm2cpp_learn import GramKernelPCA
680
+ Z = GramKernelPCA(5, kernel="rbf", gamma=0.05).fit_transform(X)
681
+ ```
682
+
683
+ Eigenvalues, eigenvectors and transforms agree with scikit-learn's to
684
+ 1e-12 on every kernel; no `inverse_transform`. Measured
685
+ (`bench/eigen-compare.py`, the MKL build, best of three):
686
+
687
+ | case | scikit-learn `KernelPCA` | `GramKernelPCA` | ratio, one core | ratio, 20 cores |
688
+ |---|---|---|---|---|
689
+ | rbf, 3,000 x 20, 5 components | 1.11 s (ARPACK) | 0.35 s (subspace) | 3.2x | 3.0x |
690
+ | rbf, 6,000 x 20, 5 components | 4.63 s (ARPACK) | 1.33 s (subspace) | 3.5x | 4.2x |
691
+ | rbf, 3,000 x 20, 50 components | 3.48 s (dense) | 3.63 s (dense) | 1.0x | 1.2x |
692
+ | linear, 5,000 x 50, 10 components | 19.8 s (ARPACK on 5,000 x 5,000) | 0.002 s (X'X) | 10,000x | 2,100x |
693
+
694
+ The linear row is the algorithm (an n x n problem against a p x p one),
695
+ not the code.
696
+
697
+ ## Linear discriminant analysis: `GramLDA`
698
+
699
+ `GramLDA` is scikit-learn's `LinearDiscriminantAnalysis` with the n x p
700
+ work moved to the Gram matrix (`examples/kernel-only/lda.scm`): one pass
701
+ gives the class means and X'X (dsyrk), and the within-class covariance
702
+ is Sw = (X'X - sum_k n_k mu_k mu_k') / n. Each solver then runs its own
703
+ steps on p x p matrices:
704
+
705
+ - `"svd"` (the default) takes the SVD of the standardised within-class
706
+ design Xc D^-1 / sqrt(n), n x p. Its right singular vectors and values
707
+ are the eigenvectors and square roots of the eigenvalues of
708
+ D^-1 Sw D^-1, so one p x p eigenproblem (dsyevd) replaces it; the
709
+ second, classes x rank SVD and the coefficients follow as in
710
+ scikit-learn;
711
+ - `"lsqr"` solves Sw W = M' by Cholesky;
712
+ - `"eigen"` solves Sb v = lam Sw v (`sym-eigen-gen`, LAPACK's dsygvd).
713
+
714
+ ```python
715
+ from scm2cpp_learn import GramLDA
716
+ clf = GramLDA().fit(X, y) # solver="svd"
717
+ clf.predict(X), clf.transform(X)
718
+ ```
719
+
720
+ `shrinkage` takes None or a float (it is linear in Sw, so the Gram route
721
+ keeps it), not "auto"; custom `priors` form a Gram per class. The
722
+ coefficients, intercepts, probabilities and explained variance agree
723
+ with scikit-learn's to 1e-12, the predictions exactly, and `transform`
724
+ up to the sign of each column. Measured (`bench/eigen-compare.py`, the
725
+ MKL build, best of three):
726
+
727
+ | case | scikit-learn | `GramLDA` | ratio, one core | ratio, 20 cores |
728
+ |---|---|---|---|---|
729
+ | svd (default), 200,000 x 100, 5 classes | 4.80 s | 0.092 s | 52x | 35x |
730
+ | svd, 50,000 x 500, 10 classes | 4.07 s | 0.25 s | 16x | 14x |
731
+ | lsqr, 200,000 x 100, 5 classes | 0.42 s | 0.089 s | 4.7x | 8.9x |
732
+ | eigen, 200,000 x 100, 5 classes | 0.56 s | 0.094 s | 6.0x | 12x |
733
+
734
+ ## Truncated SVD: `GramTruncatedSVD`
735
+
736
+ `GramTruncatedSVD` is scikit-learn's `TruncatedSVD` on a dense X
737
+ (`examples/kernel-only/truncated-svd.scm`): the leading pairs of X'X
738
+ (X'X by dsyrk; X X' when X is wide) by dsyevr over the wanted index
739
+ range, the transformed data by one dgemm, svd_flip's signs. The answer
740
+ is the exact truncated SVD, which `algorithm="arpack"` computes and the
741
+ default `"randomized"` approximates: against arpack the components agree
742
+ to 1e-13, against randomized they differ by its error (up to 1.3 on a
743
+ slowly falling spectrum). Measured (`bench/eigen-compare.py`, the MKL
744
+ build, best of three):
745
+
746
+ | case | scikit-learn | `GramTruncatedSVD` | ratio, one core | ratio, 20 cores |
747
+ |---|---|---|---|---|
748
+ | 200,000 x 100, 10 components, randomized | 1.16 s | 0.22 s | 5.4x | 7.0x |
749
+ | 200,000 x 100, 10 components, arpack | 4.46 s | 0.22 s | 20x | 25x |
750
+ | 50,000 x 500, 20 components, randomized | 1.27 s | 0.39 s | 3.3x | 5.1x |
751
+ | 50,000 x 500, 20 components, arpack | 10.1 s | 0.41 s | 24x | 21x |
752
+ | 5,000 x 2,000, 20 components, randomized | 0.46 s | 0.96 s | 0.5x | 3.5x |
753
+ | 5,000 x 2,000, 20 components, arpack | 5.17 s | 1.01 s | 5.1x | 9.1x |
754
+
755
+ The exact route costs O(n p^2 + p^3); with few components of many
756
+ features (2,000 here) the randomized one does less work, and on one core
757
+ it is faster, at its accuracy. Sparse X is not taken yet.
758
+
759
+ ## PLS and CCA: `GramPLSRegression`, `GramPLSCanonical`, `GramCCA`, `GramPLSSVD`
760
+
761
+ scikit-learn's `cross_decomposition` estimators over the cross products
762
+ (`examples/kernel-only/pls.scm`). NIPALS multiplies the blocks only by
763
+ weight vectors, and each such product is one of Cxx = X'X, Cxy = X'Y,
764
+ Cyy = Y'Y times a vector: the Y score is Y c for a coefficient vector c,
765
+ so X'(Y c) = Cxy c. The deflations are rank-one updates of the three
766
+ matrices (with a = Cxx w, b = Cxy'w and s2 = w'Cxx w, regression mode is
767
+ Cxx -= a a'/s2, Cxy -= a b'/s2, Cyy -= b b'/s2). So X and Y are read
768
+ once, for the three products (dsyrk and dgemm), and every power
769
+ iteration after that costs O(p^2 + pq + q^2) where scikit-learn's costs
770
+ O(n(p + q)). CCA's mode B takes pinv(X) y = Cxx^+ X'y, Cxx^+ from its
771
+ eigenproblem; PLSSVD is the SVD of Cxy.
772
+
773
+ ```python
774
+ from scm2cpp_learn import GramPLSRegression, GramCCA
775
+ pls = GramPLSRegression(n_components=5).fit(X, Y)
776
+ pls.predict(X), pls.transform(X), pls.x_scores_
777
+ ```
778
+
779
+ Weights, loadings, rotations, coefficients, scores and transforms agree
780
+ with scikit-learn's to 1e-13, with the same iteration counts. One cut
781
+ differs: a deflated block loses a rank exactly, which its SVD shows as a
782
+ singular value near eps but its Gram as an eigenvalue near eps
783
+ lam_max, so mode B's pinv also drops eigenvalues under 1e3 eps lam_max
784
+ (singular values under about 5e-7 of the largest, where scikit-learn's
785
+ cut is 2.2e-10). Measured (`bench/eigen-compare.py`, the MKL build, best
786
+ of three):
787
+
788
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
789
+ |---|---|---|---|---|
790
+ | PLSRegression, 200,000 x 100 -> 5, 5 components | 5.64 s | 0.26 s | 21x | 19x |
791
+ | PLSCanonical, 200,000 x 100 -> 5, 5 components | 5.63 s | 0.14 s | 40x | 59x |
792
+ | CCA, 200,000 x 100 -> 5, 5 components | 31.9 s | 0.14 s | 220x | 190x |
793
+ | PLSSVD, 200,000 x 100 -> 5, 5 components | 0.28 s | 0.14 s | 2.0x | 4.0x |
794
+ | PLSRegression, 50,000 x 500 -> 10, 10 components | 45.5 s | 0.75 s | 61x | 57x |
795
+ | PLSCanonical, 50,000 x 500 -> 10, 10 components | 45.3 s | 0.60 s | 76x | 100x |
796
+ | CCA, 50,000 x 500 -> 10, 10 components | 132 s | 1.21 s | 109x | 151x |
797
+ | PLSSVD, 50,000 x 500 -> 10, 10 components | 0.34 s | 0.34 s | 1.0x | 3.4x |
798
+
799
+ PLSSVD is one SVD of X'Y on both sides, so only the product differs.
800
+
801
+ ## Factor analysis: `GramFactorAnalysis`
802
+
803
+ scikit-learn's `FactorAnalysis` over the covariance
804
+ (`examples/kernel-only/fa.scm`). Every iteration of scikit-learn's takes
805
+ the SVD of the n x p matrix Xc / (sqrt(psi) sqrt(n)); its squared
806
+ singular values and right singular vectors are the eigenpairs of
807
+ D^-1 C D^-1, C = Xc'Xc / n and D = diag(sqrt psi). So C is formed once
808
+ (dsyrk) and each iteration is the top `n_components` eigenpairs of a
809
+ p x p matrix (dsyevr), then scikit-learn's own updates of the
810
+ components, the log-likelihood and psi. The eigenproblem is exact: what
811
+ `svd_method="lapack"` computes, which the fit matches to 1e-13 with the
812
+ same iterations; scikit-learn's default `"randomized"` approximates it
813
+ (here to 1e-6 in psi). Rotations (varimax, quartimax), `transform`,
814
+ `score`, `get_covariance` and `get_precision` are scikit-learn's.
815
+
816
+ ```python
817
+ from scm2cpp_learn import GramFactorAnalysis
818
+ fa = GramFactorAnalysis(n_components=10).fit(X)
819
+ fa.components_, fa.noise_variance_, fa.transform(X)
820
+ ```
821
+
822
+ Measured (`bench/eigen-compare.py`, the MKL build, best of two; load
823
+ average 10 to 16 from other jobs):
824
+
825
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
826
+ |---|---|---|---|---|
827
+ | FactorAnalysis(randomized), 200,000 x 100, 10 factors | 7.06 s | 0.11 s | 62x | 56x |
828
+ | FactorAnalysis(lapack), 200,000 x 100, 10 factors | 28.4 s | 0.10 s | 286x | 219x |
829
+ | FactorAnalysis(randomized), 50,000 x 500, 20 factors | 4.37 s | 0.33 s | 13x | 28x |
830
+ | FactorAnalysis(lapack), 50,000 x 500, 20 factors | 22.0 s | 0.33 s | 67x | 106x |
831
+
832
+ ## Least squares: `GramLinearRegression`
833
+
834
+ scikit-learn's `LinearRegression` over the Gram matrix
835
+ (`examples/kernel-only/linreg.scm`): Xc'Xc and Xc'y in one pass, then
836
+ the normal equations of the column-scaled Gram by Cholesky (dposv),
837
+ where scikit-learn runs LAPACK's gelsd on the n x p design. The normal
838
+ equations square the condition number, so the answer is taken only
839
+ when the scaled Gram's condition (dpocon's estimate) is at most 1e6,
840
+ which bounds the relative error near 1e-10, and the design has full
841
+ rank at `tol`; otherwise, and for `positive=True`, the fit is
842
+ scikit-learn's own (gelsd, or nnls). `rank_` and `singular_` come from
843
+ the Gram's eigenvalues when first read. A sparse X is taken (below).
844
+
845
+ Measured (`bench/eigen-compare.py`, as above):
846
+
847
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
848
+ |---|---|---|---|---|
849
+ | LinearRegression, 500,000 x 100 | 7.25 s | 0.39 s | 19x | 19x |
850
+ | LinearRegression, 200,000 x 500 | 10.9 s | 1.15 s | 9.5x | 50x |
851
+ | LinearRegression, 200,000 x 100, 10 targets | 2.83 s | 0.17 s | 17x | 18x |
852
+ | LinearRegression, 20,000 x 2,000 | 12.3 s | 1.41 s | 8.7x | 123x |
853
+
854
+ The coefficients agree to 1e-13.
855
+
856
+ ## Sparse X
857
+
858
+ `GramLasso`, `GramElasticNet`, `GramRidge`, `GramLinearRegression` and
859
+ `GramTruncatedSVD` take a scipy.sparse X (any format; CSR reaches the
860
+ kernels). X'X is formed by `examples/kernel-only/sparse.scm`'s
861
+ `csr-gram` -- each row's outer product into the upper triangle, rows in
862
+ order, blocks of rows on threads into their own G's -- and X'y and X B
863
+ by `csr-mm`; the intercept is the n xm xm' correction, as scikit-learn's
864
+ sparse coordinate descent keeps X uncentred too. After X'X the fits are
865
+ the dense ones, so the answers equal the dense X's to 1e-15 and are
866
+ exact: scikit-learn's sparse Ridge and LinearRegression are iterative
867
+ (sparse_cg, lsqr) and agree with its own dense answers only to their
868
+ tolerance (1e-5 and 1e-7 here).
869
+
870
+ Measured (`bench/sparse-compare.py`, the MKL build, best of two; load
871
+ average 10 to 29):
872
+
873
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
874
+ |---|---|---|---|---|
875
+ | Lasso, 200,000 x 200, 5% dense | 0.16 s | 0.067 s | 2.4x | 2.6x |
876
+ | ElasticNet, 200,000 x 200, 5% dense | 0.16 s | 0.059 s | 2.6x | 3.4x |
877
+ | Ridge, 200,000 x 200, 5% dense | 0.056 s | 0.064 s | 0.9x | 0.9x |
878
+ | LinearRegression, 200,000 x 200, 5% dense | 0.074 s | 0.076 s | 1.0x | 1.3x |
879
+ | TruncatedSVD (randomized), 200,000 x 200, 5% dense | 0.86 s | 0.11 s | 8.1x | 6.2x |
880
+ | TruncatedSVD (arpack), 200,000 x 200, 5% dense | 1.54 s | 0.11 s | 15x | 13x |
881
+ | Lasso, 100,000 x 1,000, 1% dense | 0.14 s | 0.069 s | 2.1x | 3.0x |
882
+ | Ridge, 100,000 x 1,000, 1% dense | 0.043 s | 0.082 s | 0.5x | 0.6x |
883
+ | TruncatedSVD (arpack), 100,000 x 1,000, 1% dense | 1.41 s | 0.16 s | 8.7x | 8.7x |
884
+ | Lasso, 50,000 x 2,000, 0.5% dense | 0.11 s | 0.15 s | 0.7x | 1.2x |
885
+ | Ridge, 50,000 x 2,000, 0.5% dense | 0.024 s | 0.23 s | 0.1x | 0.2x |
886
+ | TruncatedSVD (randomized), 50,000 x 2,000, 0.5% dense | 0.16 s | 1.49 s | 0.1x | 0.6x |
887
+
888
+ The Gram route pays p^2 memory and p^3 for the solve or the
889
+ eigenproblem whatever the sparsity, where scikit-learn's iterative
890
+ sparse solvers pay a few passes over the nonzeros. So it wins for
891
+ moderate p (a few hundred) and for TruncatedSVD against arpack, and
892
+ loses for p in the thousands with few nonzeros per row: there, Ridge
893
+ and LinearRegression are better left to scikit-learn's sparse solvers
894
+ (at their tolerance), and the randomized TruncatedSVD to scikit-learn.
895
+
896
+ ## Bayesian ridge
897
+
898
+ `CovBayesianRidge` is scikit-learn's `BayesianRidge` -- the same model,
899
+ the same defaults, the same iteration (MacKay's updates of the noise
900
+ precision `alpha_` and the weight precision `lambda_`, stopping when
901
+ the posterior mean moves by less than `tol`) -- with the linear
902
+ algebra moved into the eigenbasis of the Gram matrix. scikit-learn
903
+ takes the SVD of X once and multiplies by X again in every iteration
904
+ for the squared error. Here X enters once, through X'X (X X' when
905
+ n <= p): one eigendecomposition, after which the posterior mean, its
906
+ norm and the squared error are sums over the eigenvalues, O(p) per
907
+ iteration. `sigma_` (the posterior covariance) and
908
+ `predict(return_std=True)` are there as in scikit-learn.
909
+
910
+ ```python
911
+ from scm2cpp_learn import CovBayesianRidge
912
+ m = CovBayesianRidge().fit(X, y) # fit_intercept=True, as sklearn
913
+ mean, std = m.predict(X_new, return_std=True)
914
+ ```
915
+
916
+ Measured (`bench/bayesian-ridge-compare.py` in the repository:
917
+ Gaussian designs, a sparse truth plus noise, whole fits including
918
+ `sigma_`, one core, best of three, sklearn 1.9.1):
919
+
920
+ | n x p | `CovBayesianRidge` | sklearn `BayesianRidge` | ratio | iterations (both) | max coefficient difference |
921
+ |----------------|--------------------|-------------------------|-------|-------------------|----------------------------|
922
+ | 1,800 x 200 | 0.005 s | 0.026 s | 5.2x | 3 | 3.6e-15 |
923
+ | 5,000 x 1000 | 0.257 s | 1.231 s | 4.8x | 4 | 6.7e-15 |
924
+ | 100,000 x 200 | 0.126 s | 3.495 s | 27.8x | 3 | 2.8e-14 |
925
+ | 100,000 x 500 | 0.475 s | 8.909 s | 18.8x | 3 | 1.6e-14 |
926
+ | 500 x 5000 | 0.662 s | 8.689 s | 13.1x | 71 | 1.7e-15 |
927
+
928
+ The iteration counts are identical and the coefficients agree to
929
+ rounding, so the gap is the linear algebra alone: X'X by one BLAS
930
+ product against a full SVD of the tall X, and no pass over X inside
931
+ the loop. At 500 x 5000 scikit-learn takes the full 5000 x 5000 SVD
932
+ for `sigma_`; here `sigma_` comes from the 500 x 500 kernel side by
933
+ the Woodbury identity. This estimator is numpy, not translated code:
934
+ the eigendecomposition is LAPACK's either way.
935
+
936
+ ## Classifiers and SVRs: `LinearSVM`, `KernelSVM`, `LinearSVR`, `KernelSVR`, `L1LogisticRegression`
937
+
938
+ Three classifiers and two regressors, each the algorithm scikit-learn runs, written out
939
+ in the Scheme subset and translated plainly (no derivation; the C++
940
+ is committed under `_generated/classifiers*`):
941
+
942
+ | class | algorithm | scikit-learn counterpart |
943
+ |---|---|---|
944
+ | `LinearSVM` | liblinear's dual coordinate descent for the hinge loss (random order, shrinking) | `LinearSVC(loss="hinge", dual=True, fit_intercept=False)` |
945
+ | `KernelSVM` | libsvm's SMO (WSS3, shrinking, the bias) over the whole kernel matrix | `SVC` (`kernel="rbf"`, `"linear"` or `"precomputed"`) |
946
+ | `L1LogisticRegression` | liblinear's newGLMNET (Newton over coordinate descent, line search) | `LogisticRegression(l1_ratio=1, solver="liblinear", fit_intercept=False)` |
947
+ | `LinearSVR` | liblinear's dual coordinate descent for the epsilon-insensitive loss (random order, shrinking) | `LinearSVR(loss="epsilon_insensitive", dual=True, fit_intercept=False)` |
948
+ | `KernelSVR` | the same SMO as `KernelSVM`, set up as libsvm's epsilon-SVR (2n variables) | `SVR` (`kernel="rbf"`, `"linear"` or `"precomputed"`) |
949
+
950
+ ```python
951
+ from scm2cpp_learn import LinearSVM, KernelSVM, L1LogisticRegression
952
+ LinearSVM(C=1.0).fit(X, y).predict(X_new)
953
+ KernelSVM(C=1.0, gamma="scale").fit(X, y).decision_function(X_new)
954
+ L1LogisticRegression(C=0.1).fit(X, y).predict_proba(X_new)
955
+ ```
956
+
957
+ The classifiers take two classes (the second of `classes_` is the
958
+ positive one), and `tol` / `max_iter` mean what they mean in scikit-learn.
959
+ `KernelSVM` and `KernelSVR` build the kernel matrix in numpy and keep all of it,
960
+ n x n doubles (800 MB at n = 10,000), where `SVC` computes rows on
961
+ demand through a cache; that is its price.
962
+
963
+ Measured with `check-classifiers.py` (in this directory): the same
964
+ problem and stopping rule on both sides, one core, best of three,
965
+ sklearn 1.9.1, load average under 2. Ours includes building the kernel
966
+ matrix (`KernelSVM`) or transposing X into columns
967
+ (`L1LogisticRegression`):
968
+
969
+ | problem | ours | scikit-learn | ratio | objective (ours / sklearn) | same predictions |
970
+ |---|---|---|---|---|---|
971
+ | `LinearSVM`, 5,000 x 200 | 0.379 s | 0.598 s | 1.6x | 1541.06 / 1541.29 | 99.5% |
972
+ | `LinearSVM`, 100,000 x 200 | 23.0 s | 41.7 s | 1.8x | 34503.5 / 34500.7 | 98.9% |
973
+ | `LinearSVM`, 2,000 x 20,000 | 0.975 s | 1.894 s | 1.9x | 0.052484 / 0.052428 | 100% |
974
+ | `KernelSVM` rbf, 2,000 x 50 | 0.068 s | 0.139 s (precomputed 0.081 s) | 2.1x (1.2x) | -1065.5026 / -1065.5026 | 100% |
975
+ | `KernelSVM` rbf, 5,000 x 50 | 0.501 s | 1.032 s (precomputed 0.588 s) | 2.1x (1.2x) | -2628.1422 / -2628.1422 | 100% |
976
+ | `KernelSVM` rbf, 10,000 x 50 | 2.12 s | 4.15 s (precomputed 2.61 s) | 2.0x (1.2x) | -4994.9982 / -4994.9982 | 100% |
977
+ | `L1LogisticRegression`, 5,000 x 200, C=0.1 | 0.064 s | 0.103 s | 1.6x | 61.676698 / 61.676708 | 100% |
978
+ | `L1LogisticRegression`, 20,000 x 500, C=0.05 | 1.20 s | 2.23 s | 1.9x | 106.77913 / 106.77915 | 100% |
979
+ | `L1LogisticRegression`, 100,000 x 200, C=0.05 | 9.06 s | 18.7 s | 2.1x | 349.61154 / 349.61216 | 100% |
980
+
981
+ On 2,000 x 20,000 neither side reaches the optimum at tol 1e-4 (the
982
+ objective at tol 1e-10 is 0.0519588), and where each stops depends on
983
+ the coordinate order: over eight seeds ours stops at 0.05240 to
984
+ 0.05251 (0.9 to 1.1% above the optimum), `LinearSVC`, whose order is
985
+ random unless `random_state` is given, at 0.05242 to 0.05319 (0.9 to
986
+ 2.4%). When `LinearSVC` draws one of its worse orders the gap passes
987
+ the script's 0.5% bound and the row prints `<-- disagrees`; ours is
988
+ then the better solution of the two, so the flag there is not a fault.
989
+
990
+ The regressors, from the same script (C = 1, epsilon 0.1):
991
+
992
+ | problem | ours | scikit-learn | ratio | agreement |
993
+ |---|---|---|---|---|
994
+ | `LinearSVR`, 5,000 x 200 | 1.32 s | 2.53 s | 1.9x | both at the 1,000-sweep cap; objective 779.99 / 790.72 |
995
+ | `LinearSVR`, 20,000 x 500 | 22.1 s | 36.6 s | 1.7x | both at the cap; objective 3741.4 / 3712.2 |
996
+ | `KernelSVR` rbf, 1,000 x 10 | 0.023 s | 0.043 s | 1.9x | iterations 2,172 / 2,177; predictions within 4e-4 |
997
+ | `KernelSVR` rbf, 3,000 x 10 | 0.246 s | 0.332 s | 1.3x | iterations 7,471 / 7,581; within 5e-4 |
998
+ | `KernelSVR` rbf, 6,000 x 10 | 1.18 s | 1.38 s | 1.2x | iterations 16,805 / 16,630; within 5e-4 |
999
+
1000
+ `LinearSVR` on these data does not reach its tolerance in 1,000 sweeps on
1001
+ either side, and at the cap the random order alone moves the objective
1002
+ by about 1% (scikit-learn's own seeds give 776-789 at 5,000 x 200);
1003
+ with 20,000 sweeps both land on 728.58. `KernelSVR`'s gain shrinks
1004
+ with n here because the 10 features make each kernel row cheap for
1005
+ libsvm to compute, while ours reads the rows of a matrix of n^2
1006
+ doubles; the predictions agree to within scikit-learn's tolerance.
1007
+
1008
+ The objectives agree to the stopping tolerance on both sides, not to
1009
+ rounding. The linear SVM on tall data stops at the 1,000-sweep cap on
1010
+ both sides, so there the two land a hair apart and 1% of the
1011
+ predictions differ. The gain is the same in all three: the same
1012
+ algorithm, run as dense loops that vectorise, against libsvm's and
1013
+ liblinear's sparse rows. The classifiers are compiled at `-O3` with
1014
+ `-fstrict-overflow`: Python's build flags carry
1015
+ `-fno-strict-overflow`, which keeps the compiler from treating the
1016
+ flat index `i*p + j` as an induction variable and makes the linear
1017
+ SVM 25% slower.
1018
+
1019
+ ## NMF: `CDNMF`
1020
+
1021
+ `CDNMF` is scikit-learn's `NMF(solver="cd")` -- Frobenius loss, no
1022
+ regularization, no shuffling -- as the translator derives it.
1023
+ `examples/kernel-only/nmf-cd.scm` writes the half step with the
1024
+ residual R = X - W H and no Gram matrix. `--derive` memoises R H' over
1025
+ the hoisted H H' and distributes the residual through the memo, so the
1026
+ compiled half step is scikit-learn's `XHt - W HHt` with R never formed.
1027
+ Like `DerivedLasso`, it is built in three variants (`nmf_backend()`
1028
+ says which is taken: cublas when a device answers, else blas, else
1029
+ loops).
1030
+
1031
+ ```python
1032
+ from scm2cpp_learn import CDNMF
1033
+ model = CDNMF(n_components=20, random_state=0) # init="random", as sklearn's
1034
+ W = model.fit_transform(X) # H in model.components_
1035
+ ```
1036
+
1037
+ `init="random"` draws the start as scikit-learn does, so the same seed
1038
+ gives the same W and H. scikit-learn's default `"nndsvda"` is not
1039
+ offered; pass `init="custom"` with its W and H for that start.
1040
+ Measured with `check-classifiers.py --only nmf` against
1041
+ `NMF(solver="cd", init="random")` from the same seed, tol 1e-4, at most
1042
+ 200 iterations, one core:
1043
+
1044
+ | n x p, k | `CDNMF` cuBLAS | `CDNMF` BLAS | sklearn | iterations | max \|H - H_sklearn\| |
1045
+ |---|---|---|---|---|---|
1046
+ | 1,000 x 500, 10 | 0.441 s (0.6x) | 0.212 s (1.15x) | 0.244 s | 200 / 200 | 1.3e-13 |
1047
+ | 5,000 x 2,000, 20 | 7.01 s (1.6x) | 8.27 s (1.36x) | 11.25 s | 200 / 200 | 4.1e-12 |
1048
+ | 20,000 x 1,000, 30 | 16.9 s (1.8x) | 20.6 s (1.46x) | 30.1 s | 200 / 200 | 2.4e-12 |
1049
+
1050
+ The iterates are scikit-learn's to rounding. The cuBLAS variant pays
1051
+ from the middle size on; at 1,000 x 500 its transfers cost more than
1052
+ the products save, and `backend="blas"` is the faster choice there.
1053
+
1054
+ ## Graphical lasso and RANSAC: `CDGraphicalLasso`, `LinearRANSAC`
1055
+
1056
+ Two more of scikit-learn's algorithms, written out in the Scheme subset
1057
+ and translated plainly.
1058
+
1059
+ - `CDGraphicalLasso` is `GraphicalLasso(mode="cd")`: `_graphical_lasso`
1060
+ with `enet_coordinate_descent_gram` inside it, its two matrix-vector
1061
+ products as dgemv. `alpha`, `tol`, `enet_tol`, `max_iter` and
1062
+ `assume_centered` mean what they mean in scikit-learn. scikit-learn's
1063
+ `costs_` (a log-determinant every iteration) is not computed.
1064
+ - `LinearRANSAC` is `RANSACRegressor` around `LinearRegression`, with
1065
+ the same defaults. With scikit-learn installed, the subsets are drawn
1066
+ exactly as it draws them, so `random_state` gives scikit-learn's fit.
1067
+
1068
+ ```python
1069
+ from scm2cpp_learn import CDGraphicalLasso, LinearRANSAC
1070
+ prec = CDGraphicalLasso(alpha=0.1).fit(X).precision_
1071
+ fit = LinearRANSAC(random_state=0).fit(X, y) # fit.coef_, fit.inlier_mask_
1072
+ ```
1073
+
1074
+ Measured through the package, one core, best of three, against
1075
+ scikit-learn on the same data (an AR(1) design with n = 20p for the
1076
+ graphical lasso, 100 iterations on both sides; a linear model with
1077
+ outliers for RANSAC, max_trials 1000):
1078
+
1079
+ | problem | ours | scikit-learn | ratio | agreement |
1080
+ |---|---|---|---|---|
1081
+ | `CDGraphicalLasso`, p = 50 | 0.0069 s | 0.306 s | 44.5x | 100 / 100 iterations, precision to 1.8e-14 |
1082
+ | `CDGraphicalLasso`, p = 200 | 0.286 s | 1.62 s | 5.7x | precision to 2.6e-14 |
1083
+ | `CDGraphicalLasso`, p = 800 | 33.9 s | 43.8 s | 1.3x | precision to 5.0e-14 |
1084
+ | `LinearRANSAC`, 10,000 x 5 | 0.0254 s | 0.0916 s | 3.6x | 98 / 98 trials, same inliers |
1085
+ | `LinearRANSAC`, 100,000 x 10 | 0.153 s | 0.241 s | 1.6x | 97 / 97 trials, same inliers |
1086
+ | `LinearRANSAC`, 20,000 x 20 | 0.470 s | 1.19 s | 2.5x | 1,000 / 1,000 trials, same inliers |
1087
+
1088
+ Both gains are mostly scikit-learn's Python between its compiled steps:
1089
+ the per-column bookkeeping of the graphical lasso, and the per-trial
1090
+ validation and fitting of RANSAC. They shrink as the compiled part
1091
+ grows (the graphical lasso at large p).
1092
+
1093
+ ## SGD, OMP and LARS: `SGDLinearClassifier`, `SGDLinearRegressor`, `GramOMP`, `GramLars`, `GramLassoLars`
1094
+
1095
+ scikit-learn's own algorithms, translated:
1096
+
1097
+ - `SGDLinearClassifier` and `SGDLinearRegressor` are
1098
+ `SGDClassifier` / `SGDRegressor` at their defaults, run by
1099
+ `_plain_sgd` with the points in order. Against
1100
+ `shuffle=False` the weights are bit-identical. scikit-learn's
1101
+ shuffling generator is not reproduced.
1102
+ - `GramOMP` is `OrthogonalMatchingPursuit` over the Gram matrix (its
1103
+ route for n > p, taken here always; X'X and X'y by dsyrk and dgemv).
1104
+ - `GramLars` and `GramLassoLars` are `Lars` and `LassoLars` over the
1105
+ Gram (their route for n > p, taken here always; the Gram formed in
1106
+ numpy).
1107
+
1108
+ ```python
1109
+ from scm2cpp_learn import SGDLinearClassifier, GramOMP, GramLassoLars
1110
+ SGDLinearClassifier().fit(X, y).predict(X_new)
1111
+ GramOMP(n_nonzero_coefs=10).fit(X, y).coef_
1112
+ GramLassoLars(alpha=0.01).fit(X, y).coef_
1113
+ ```
1114
+
1115
+ Each gives scikit-learn's coefficients, to the bit for SGD and to 1e-15
1116
+ for the rest, with the same number of epochs or steps. The speed is the
1117
+ repository README's table: 1.0-3.3x for SGD, 1.1-2.8x for OMP and
1118
+ 1.2-5.0x for LARS, largest on small problems, where scikit-learn's
1119
+ Python between steps dominates.
1120
+
1121
+ ## L2 logistic regression and Huber: `LBFGSLogisticRegression`, `LBFGSHuberRegressor`
1122
+
1123
+ `LogisticRegression(solver="lbfgs")` (the default; two classes
1124
+ binomial, more multinomial) and `HuberRegressor`, with scipy's
1125
+ L-BFGS-B written out in the subset under them. The products are dgemm
1126
+ or dgemv where a CBLAS links.
1127
+
1128
+ ```python
1129
+ from scm2cpp_learn import LBFGSLogisticRegression, LBFGSHuberRegressor
1130
+ LBFGSLogisticRegression(C=1.0).fit(X, y).predict_proba(X_new)
1131
+ LBFGSHuberRegressor(epsilon=1.35).fit(X, y).coef_
1132
+ ```
1133
+
1134
+ Both take scikit-learn's iterations one for one and give its
1135
+ coefficients to rounding (1e-13 at worst). The speed is the repository
1136
+ README's table: 1.1-8x for the logistic regression (near 1x on a large
1137
+ binary problem, where both sides are two matrix-vector products per
1138
+ evaluation) and 2.5-18x for Huber.
1139
+
1140
+ ## Gaussian mixture, FastICA, PCA: `EMGaussianMixture`, `ParallelFastICA`, `CovPCA`
1141
+
1142
+ `GaussianMixture(covariance_type="full")`, `FastICA` at its defaults
1143
+ and `PCA` by the covariance's eigenvectors (scikit-learn's
1144
+ "covariance_eigh", what "auto" picks for a tall design), each
1145
+ scikit-learn's algorithm translated, the products dgemm / dsyrk where a
1146
+ CBLAS links and the eigenproblem written in the subset.
1147
+
1148
+ ```python
1149
+ from scm2cpp_learn import EMGaussianMixture, ParallelFastICA, CovPCA
1150
+ EMGaussianMixture(4, random_state=0).fit(X).predict(X) # KMeans start: scikit-learn's
1151
+ ParallelFastICA(random_state=0).fit(X).transform(X)
1152
+ CovPCA(n_components=10).fit(X).components_
1153
+ ```
1154
+
1155
+ From the same `random_state` each takes scikit-learn's iterations and
1156
+ lands on its parameters to rounding. The speed is the repository
1157
+ README's table: 1.6-2.4x for the mixture, 1.1-1.4x for FastICA, and
1158
+ for PCA 1.3-4x up to about 100 features, 0.6-0.8x at 200-500, where
1159
+ LAPACK's eigensolver wins.
1160
+
1161
+ ## Perceptron, ARD, LassoLarsIC, L1 linear SVM: `SGDPerceptron`, `CovARDRegression`, `GramLassoLarsIC`, `L1LinearSVM`
1162
+
1163
+ - `SGDPerceptron` is `Perceptron`. `SGDLinearClassifier` /
1164
+ `SGDLinearRegressor` also take `loss="perceptron"` /
1165
+ `"epsilon_insensitive"`, `learning_rate="constant"` / `"pa1"` /
1166
+ `"pa2"` and `penalty=None`, which covers scikit-learn's replacements
1167
+ for the passive-aggressive estimators. All run with shuffle=False.
1168
+ - `CovARDRegression` is `ARDRegression` (n >= p). With `hoist=True`,
1169
+ the default, the kept features' Gram comes from X'X formed once;
1170
+ `hoist=False` forms it every iteration, as scikit-learn does.
1171
+ - `GramLassoLarsIC` is `LassoLarsIC`. The whole lasso path comes from
1172
+ the translated LARS, and the criterion is evaluated from the Gram.
1173
+ - `L1LinearSVM` is `LinearSVC(penalty="l1", dual=False)`, liblinear's
1174
+ solve_l1r_l2_svc. It agrees with scikit-learn to the tolerance,
1175
+ because the coordinate order comes from another generator.
1176
+
1177
+ ```python
1178
+ from scm2cpp_learn import SGDPerceptron, CovARDRegression, GramLassoLarsIC, L1LinearSVM
1179
+ SGDPerceptron().fit(X, y)
1180
+ CovARDRegression().fit(X, y).coef_
1181
+ GramLassoLarsIC("bic").fit(X, y).alpha_
1182
+ L1LinearSVM(C=1.0).fit(X, y).coef_
1183
+ ```
1184
+
1185
+ Speed, from the repository README's table: SGD 1.2-3x, ARD 1.6-1.9x
1186
+ (3x with the Gram hoisted), LassoLarsIC 8-20x, the L1 SVM 1.1-1.5x.
1187
+
1188
+ ## GLMs, CV and Theil-Sen: `LBFGSPoissonRegressor`, `LBFGSGammaRegressor`, `LBFGSTweedieRegressor`, `LBFGSLogisticRegressionCV`, `GramLarsCV`, `GramLassoLarsCV`, `GramOMPCV`, `WeiszfeldTheilSen`
1189
+
1190
+ - The GLMs are `PoissonRegressor`, `GammaRegressor` and
1191
+ `TweedieRegressor` (solver "lbfgs"), over the same L-BFGS-B as
1192
+ `LBFGSLogisticRegression`.
1193
+ - The CV classes reproduce `LogisticRegressionCV`, `LarsCV`,
1194
+ `LassoLarsCV` and `OrthogonalMatchingPursuitCV`: the same folds (KFold
1195
+ / StratifiedKFold without shuffling), the same choice of C, alpha or
1196
+ number of columns, and the same refit.
1197
+ - `WeiszfeldTheilSen` is `TheilSenRegressor` on scikit-learn's own
1198
+ subsets.
1199
+
1200
+ ```python
1201
+ from scm2cpp_learn import LBFGSPoissonRegressor, LBFGSLogisticRegressionCV, GramLassoLarsCV
1202
+ LBFGSPoissonRegressor(alpha=1e-3).fit(X, counts).predict(X_new)
1203
+ LBFGSLogisticRegressionCV().fit(X, labels).C_
1204
+ GramLassoLarsCV().fit(X, y).alpha_
1205
+ ```
1206
+
1207
+ Speed, from the repository README's table: the GLMs 1.1-6x, the CV
1208
+ estimators 1.6-6.6x, Theil-Sen 1.3-1.8x (its subset drawing dominates).
1209
+
1210
+ ## Feature selection: `f_regression`, `f_classif`, `SelectKBest`, `SelectPercentile`, `GramRFE`
1211
+
1212
+ scikit-learn's univariate F statistics and its selectors over them,
1213
+ and `RFE` around `Ridge` / `LinearRegression`, translated.
1214
+ `f_regression` also takes an n x q array of targets: the q results in
1215
+ one product, on the device when one answers.
1216
+
1217
+ ```python
1218
+ from scm2cpp_learn import SelectKBest, GramRFE, f_regression
1219
+ SelectKBest("f_regression", k=20).fit(X, y).get_support()
1220
+ GramRFE(alpha=1.0, n_features_to_select=10).fit(X, y).ranking_
1221
+ F, p = f_regression(X, Y) # Y: n x q, every target at once
1222
+ ```
1223
+
1224
+ The same scores, ranking and features as scikit-learn. RFE is 80-1,000x
1225
+ faster (one Gram and one Cholesky factor, downdated, instead of a refit
1226
+ per round), and f_regression over many targets 30-50x. The Gram-route
1227
+ estimators (`GramLassoLarsIC`, `GramLarsCV`, `GramLassoLarsCV`,
1228
+ `GramLars`, `GramLassoLars`, `CovPCA`) form a large X'X on the device
1229
+ when one answers. `SCM2CPP_NO_DEVICE=1` keeps everything on the CPU.
1230
+
1231
+ ## Against Intel's sklearnex
1232
+
1233
+ sklearnex (scikit-learn-intelex 2026.2, oneDAL underneath) replaces
1234
+ some scikit-learn estimators with its own. `bench/sklearnex-compare.py`
1235
+ times the ones with a counterpart here, sklearnex's estimators
1236
+ imported directly (not patched in) so that scikit-learn itself is
1237
+ timed in the same process. The ratios are scikit-learn's or
1238
+ sklearnex's time over the package's best (its CPU build, or the device
1239
+ build where one answers). The package was built against Intel MKL
1240
+ (see the build section), its loops under OpenMP; the load average was
1241
+ about 2.3, so the times move by some percent.
1242
+
1243
+ | estimator, n x p | iterations (sk / sklearnex / ours) | vs scikit-learn, one core | vs sklearnex, one core | vs sklearnex, 20 cores |
1244
+ |---|---|---|---|---|
1245
+ | LogisticRegression, 200,000 x 100 | 6 / 12 / 6 | 6.8x (device) | 6.4x (device) | 1.8x (device); on the CPU 0.9x |
1246
+ | Ridge (alpha 1, no intercept), 200,000 x 200 | - | 1.7x | 0.8x | 2.3x |
1247
+ | PCA (10 components), 100,000 x 50 | - | 1.4x | 2.2x | 1.4x |
1248
+ | PCA (10 components), 50,000 x 500 | - | 1.1x | 1.4x | 1.6x (device); on the CPU 1.2x |
1249
+ | SVC (rbf), 5,000 x 20 | 4,858 / 7 / 4,882 | 1.4x | 1.6x | 0.5x |
1250
+ | SVR (rbf), 5,000 x 20 | 12,821 / 10 / 12,824 | 1.4x | 1.4x | 0.4x |
1251
+ | RFE(Ridge), 20 of 200 kept, 20,000 x 200 | - | 138x | 106x | 116x |
1252
+
1253
+ On one core the package is ahead everywhere but Ridge, where both
1254
+ sides are one symmetric rank-k update of the same size and sklearnex
1255
+ is 0.180 s to 0.219 s. With 20 cores both sides use every core: the
1256
+ package's loops run under OpenMP and its products in MKL's threads,
1257
+ so it is ahead on Ridge (the Gram by dsyrk and a Cholesky solve), PCA,
1258
+ the device build of logistic regression and RFE (an algorithm that
1259
+ does less work: the Gram once, the Cholesky factor downdated per drop,
1260
+ where scikit-learn refits), level on logistic regression on the CPU,
1261
+ and behind on the SVMs: SMO takes thousands of short steps, each
1262
+ waiting on the last, where sklearnex's solver takes 7 to 10 long ones. sklearnex is
1263
+ not scikit-learn's arithmetic: its logistic regression takes 12
1264
+ iterations to scikit-learn's 6 and its coefficients differ from
1265
+ scikit-learn's by 6e-3, where the package's agree to 4e-15; its SVMs
1266
+ report a different iteration count. This sklearnex accelerates no
1267
+ lasso, so the lasso tables above stand against scikit-learn alone.
1268
+
1269
+ ## The GPU build
1270
+
1271
+ Where the CUDA toolkit is at install time, `ParallelFastICA`,
1272
+ `EMGaussianMixture`, `LBFGSLogisticRegression`,
1273
+ `LBFGSLogisticRegressionCV`, `LBFGSHuberRegressor` and the `LBFGS*`
1274
+ GLMs also get the same Scheme translated with `--cuda`
1275
+ (`libscm2cpp_gpu.so`). Its loops are CUDA kernels and its products
1276
+ cuBLAS, on arrays that stay on the device. The classes take it when a
1277
+ device answers and the data has a million entries or more, and give
1278
+ the CPU build's iterations and results to the last digits. Measured
1279
+ against scikit-learn: 10-22x for the L-BFGS fits, 6.7x FastICA, 3x the
1280
+ mixture and LogisticRegressionCV (the repository README's table).
1281
+ `SCM2CPP_NO_DEVICE=1` keeps everything on the CPU.
1282
+
1283
+ ## Logistic regression with L1
1284
+
1285
+ `CovLogistic` solves L1-penalized logistic regression by
1286
+ majorization: the logistic Hessian is bounded by X'X/4, so the
1287
+ quadratic term is the same Gram matrix, fixed once, and each outer
1288
+ round costs one gradient pass before handing the majorizer to the
1289
+ same coordinate descent the lasso uses. Objectives agree with
1290
+ scikit-learn's `LogisticRegression(penalty="l1",
1291
+ fit_intercept=False)` at `C = 1/(n lam)` to 9e-15.
1292
+
1293
+ ## Group lasso
1294
+
1295
+ `CovGroupLasso` penalizes whole groups -- `lam * sum_g sqrt(|g|)
1296
+ ||b_g||` -- so correlated features enter or leave together. Block
1297
+ coordinate descent on the same Gram machinery: each block visit is
1298
+ one majorized proximal step (the group's Gram block dominated by its
1299
+ top eigenvalue, found once), descending monotonically. With size-one
1300
+ groups it reduces exactly to the lasso -- verified against sklearn to
1301
+ 9e-16 -- and at convergence the group KKT conditions hold to 2e-12.
1302
+
1303
+ ## Bootstrap on the GPU
1304
+
1305
+ `bootstrap` draws pairs-bootstrap resamples and refits them all at
1306
+ one lambda. Each resample's Gram matrix is `X' diag(m) X` for its
1307
+ multiplicity counts `m`, written as `Xs' Xs` with `Xs = diag(sqrt m) X`
1308
+ so that numpy hands it to the symmetric rank-k product (`dsyrk`,
1309
+ half the flops of `X' (diag(m) X)`) -- one BLAS call -- and because
1310
+ the problems are independent, the descents run as one batch: on the
1311
+ GPU, one block of threads per resample, each reading its own Gram
1312
+ matrix. The products are the cost: at n=5000, p=1000 a hundred
1313
+ resamples took 18.1 s as general products and 11.2 s as `dsyrk`,
1314
+ descents included.
1315
+
1316
+ ```python
1317
+ betas = model.bootstrap(lam, n_boot=500, seed=0) # (500, p)
1318
+ freq = (abs(betas) > 1e-9).mean(axis=0) # selection frequency
1319
+ ```
1320
+
1321
+ Requires constructing the model from `X, y` (a Gram matrix alone
1322
+ cannot be resampled by rows). GPU and CPU agree to machine
1323
+ precision.
1324
+
1325
+ ## A design with structure
1326
+
1327
+ When the design matrix has structure, forming X'X the general way is
1328
+ the wrong move. `kernel` exposes the translated functions directly,
1329
+ and [`scm2cpp-tfs`](https://pypi.org/project/scm2cpp-tfs/) does exactly
1330
+ that for moving-average designs: it builds the Gram matrix from a
1331
+ series' prefix sums in O(n p) time, never forming the design. That
1332
+ package stands alone -- it carries its own copy of this descent -- so
1333
+ neither installs the other.
1334
+
1335
+ ## Where this comes from
1336
+
1337
+ The C++ this compiles is committed to `python/scm2cpp-learn/` in the
1338
+ scm2cpp repository. `CovLasso` and the rest run on the translation of
1339
+ `examples/kernel-only/lasso-cov.scm`, a covariance-update sweep
1340
+ written by hand at the Gram level; `DerivedLasso` runs on the
1341
+ translation of `examples/kernel-only/lasso-design.scm`, the naive
1342
+ residual-form descent over X as numpy holds it, with the translator's `--derive --blas`
1343
+ deriving the same covariance form from it. The two are the same
1344
+ sweep over the same `dsyrk`, and they time the same. To refresh the
1345
+ committed C++ after changing the Scheme, run `regenerate.sh` -- that
1346
+ step, and only that step, needs Racket.
1347
+
1348
+ ## License
1349
+
1350
+ MIT, the same as scm2cpp.