scm2cpp-learn 0.21.0__tar.gz → 0.23.0__tar.gz

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 (67) hide show
  1. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/PKG-INFO +89 -3
  2. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/README.md +88 -2
  3. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/pyproject.toml +1 -1
  4. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/setup.py +1 -1
  5. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/__init__.py +288 -4
  6. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_gramops_blas.py +17 -0
  7. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_gramops_loops.py +17 -0
  8. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/accel_cublas/accel.hpp +24 -17
  9. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/classifiers.hpp +116 -109
  10. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design.hpp +12 -12
  11. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design.hpp +13 -13
  12. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_loops/lasso_design.hpp +32 -32
  13. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_blas/gramops.cpp +2 -0
  14. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_blas/gramops.hpp +640 -232
  15. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_blas/gramops_capi.cpp +6 -0
  16. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_loops/gramops.cpp +2 -0
  17. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_loops/gramops.hpp +1085 -513
  18. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gramops_loops/gramops_capi.cpp +6 -0
  19. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_blas/nmf_cd.hpp +17 -17
  20. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd.hpp +21 -21
  21. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd.hpp +46 -46
  22. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/scm2cpp.hpp +213 -0
  23. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn.egg-info/PKG-INFO +89 -3
  24. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/setup.cfg +0 -0
  25. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_compat.py +0 -0
  26. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/__init__.py +0 -0
  27. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader.py +0 -0
  28. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_accel_cublas.py +0 -0
  29. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_classifiers.py +0 -0
  30. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_derived_blas.py +0 -0
  31. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_derived_cublas.py +0 -0
  32. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_derived_loops.py +0 -0
  33. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_gpu_cuda.py +0 -0
  34. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_nmf_blas.py +0 -0
  35. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_nmf_cublas.py +0 -0
  36. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/_loader_nmf_loops.py +0 -0
  37. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/accel_cublas/accel.cpp +0 -0
  38. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/accel_cublas/accel_capi.cpp +0 -0
  39. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/classifiers.cpp +0 -0
  40. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/classifiers_capi.cpp +0 -0
  41. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design.cpp +0 -0
  42. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design_capi.cpp +0 -0
  43. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design.cpp +0 -0
  44. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design_capi.cpp +0 -0
  45. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_loops/lasso_design.cpp +0 -0
  46. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/derived_loops/lasso_design_capi.cpp +0 -0
  47. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu.cpp +0 -0
  48. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu.hpp +0 -0
  49. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu_capi.cpp +0 -0
  50. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/lasso_cov.cpp +0 -0
  51. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/lasso_cov.hpp +0 -0
  52. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/lasso_cov_capi.cpp +0 -0
  53. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_blas/nmf_cd.cpp +0 -0
  54. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_blas/nmf_cd_capi.cpp +0 -0
  55. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd.cpp +0 -0
  56. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd_capi.cpp +0 -0
  57. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd.cpp +0 -0
  58. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd_capi.cpp +0 -0
  59. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/scm2cpp-blas.hpp +0 -0
  60. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/scm2cpp-cublas.hpp +0 -0
  61. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_generated/scm2cpp-cuda.hpp +0 -0
  62. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/_libfind.py +0 -0
  63. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn/batch_capi.cu +0 -0
  64. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn.egg-info/SOURCES.txt +0 -0
  65. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn.egg-info/dependency_links.txt +0 -0
  66. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn.egg-info/requires.txt +0 -0
  67. {scm2cpp_learn-0.21.0 → scm2cpp_learn-0.23.0}/src/scm2cpp_learn.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scm2cpp-learn
3
- Version: 0.21.0
3
+ Version: 0.23.0
4
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
5
  Author: Hirotaka Niitsuma
6
6
  License: MIT
@@ -37,7 +37,7 @@ with a DeprecationWarning.
37
37
  $ pip install scm2cpp-learn
38
38
  ```
39
39
 
40
- On Linux x86_64, macOS arm64 (macOS 14 or later) and Windows AMD64
40
+ On Linux x86_64, macOS arm64 (macOS 15 or later) and Windows AMD64
41
41
  this installs a wheel: compiled, nothing to build (with OpenBLAS
42
42
  inside on Linux and macOS; Windows has the loop variants). Elsewhere pip builds the sdist,
43
43
  which needs a C++17 compiler and nothing else. The wheels carry no
@@ -56,7 +56,13 @@ the translated loops; `SCM2CPP_NO_MKL=1` skips MKL. The translated
56
56
  loops that the dependence test proves independent run on OpenMP where
57
57
  the compiler has it (`SCM2CPP_NO_OPENMP=1` builds them serial). Both
58
58
  use every core unless told otherwise: `OMP_NUM_THREADS` (and
59
- `MKL_NUM_THREADS` / `OPENBLAS_NUM_THREADS`) set the threads.
59
+ `MKL_NUM_THREADS` / `OPENBLAS_NUM_THREADS`) set the threads. The
60
+ translated loops take one thread per physical core by default (on
61
+ Linux; `SCM2CPP_OMP_THREADS=n` for another number, and
62
+ `OMP_NUM_THREADS=n` is taken as given): two per core, OpenMP's own
63
+ default, made a LARS path five to twenty times slower whenever the
64
+ machine had other work. Where every core is busy with other
65
+ processes, start Python with `OMP_WAIT_POLICY=passive`.
60
66
 
61
67
  The batched GPU solver, the cuBLAS variants and the `--cuda`
62
68
  estimators are then built as well; without `nvcc` the package installs
@@ -210,6 +216,7 @@ package picks the fastest one present.
210
216
  | `GramElasticNet` | ElasticNet(precompute=True), fit(X, y) with the intercept, dense or sparse X | `lasso-cov.scm` | CPU | no |
211
217
  | `GramRidge` | Ridge, fit(X, y) with the intercept, one or many targets, dense or sparse X | `gram.scm` (Cholesky; dposv) | loops / BLAS | Ridge |
212
218
  | `GramLinearRegression` | LinearRegression, dense or sparse X, sample_weight | `linreg.scm` (Cholesky; dposv, dpocon) | loops / BLAS | no |
219
+ | `FrischNewtonQuantileRegressor` | QuantileRegressor, the L1 penalty and sample_weight included, dense X | `quantile.scm` (Frisch-Newton interior point; dsyrk, dposv) | loops / BLAS | no |
213
220
  | `GramRidgeCV` | RidgeCV (cv=None), leave-one-out over every alpha from one eigenproblem | `ridge-gcv.scm` | loops / BLAS | no |
214
221
  | `GramMultiTaskLasso` | MultiTaskLasso, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
215
222
  | `GramMultiTaskElasticNet` | MultiTaskElasticNet, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
@@ -482,6 +489,19 @@ a stock-feature design with n=743 and p=180, 0.21 s against 145 s for
482
489
  the descent on the same grid; at p=3495, 2.2 s, where the descent was
483
490
  stopped after 30 minutes. The default stays `solver="cd"`.
484
491
 
492
+ `working_set=k` (with `solver="lars"`, a dense X) is for a design too
493
+ wide for its Gram matrix -- p by p, 309 GB at p = 196,574. Each fold
494
+ and the refit are solved on a working set of columns: the k most
495
+ correlated with y to begin with; then, while a column outside the set
496
+ breaks the optimality conditions at some grid point (the gradient
497
+ against alpha over all p columns, 1e-5 relative), the k worst of them
498
+ join and the set is solved again. When none does, every grid solution
499
+ solves the whole problem -- checked, not assumed -- so the fit is the
500
+ full Gram's (`check-wheel.py`: 3e-13 at p = 3000, n = 150, the set
501
+ staying well below p), in memory O(np) plus the set's Gram.
502
+ `working_set_` records the rounds and the final set's size for each
503
+ fold and the refit.
504
+
485
505
  The elastic net cross-validates the same way: `CovLassoCV(l1_ratio=0.5)`
486
506
  against `ElasticNetCV(l1_ratio=0.5)` on the same folds and alpha grid
487
507
  (`bench/lasso-compare.py --cv-only --l1-ratio 0.5`, same conditions,
@@ -840,6 +860,72 @@ Measured (`bench/eigen-compare.py`, as above):
840
860
 
841
861
  The coefficients agree to 1e-13.
842
862
 
863
+ ## Quantile regression: `FrischNewtonQuantileRegressor`
864
+
865
+ scikit-learn's `QuantileRegressor` by an interior point method
866
+ (`examples/kernel-only/quantile.scm`): the same objective -- the mean
867
+ check loss at `quantile` plus `alpha` times the L1 norm of the
868
+ coefficients, the intercept not penalised -- minimised by the
869
+ Frisch-Newton predictor-corrector of Portnoy and Koenker (1997) on the
870
+ dual linear program. scikit-learn hands the program to HiGHS through
871
+ scipy's `linprog`, and its default `solver="highs"` runs HiGHS's dual
872
+ simplex. Each iteration here is one weighted Gram matrix of the design
873
+ (dsyrk) and a Cholesky solve (dposv), and some 15 to 45 iterations do
874
+ whatever the number of rows. The L1 penalty enters as one more row per
875
+ coefficient; `sample_weight` scales the rows.
876
+
877
+ An interior point method stops near the solution, not at a vertex of
878
+ the program, so the iterate (duality gap at most `tol` times the
879
+ objective) is then moved to the vertex it points to: the rows whose
880
+ dual variables lie farthest inside their bounds, as many as there are
881
+ unknowns, give a square system -- a penalty row among them holds its
882
+ coefficient at exact zero -- which the same Scheme file solves by
883
+ Gaussian elimination (`lu-solve`), and the vertex is taken when it does
884
+ not raise the objective. The coefficients are then those a simplex
885
+ code returns: the same zeros, the rest equal to rounding. The result
886
+ is checked by its own duality gap, recomputed from the returned
887
+ coefficients and dual variables. When the check fails (a design
888
+ without full column rank, more columns than rows with `alpha=0`) the
889
+ fit is scikit-learn's own program through `linprog` with `solver` and
890
+ `solver_options`, which are not used otherwise. Where the minimiser is
891
+ not unique the two may return different minimisers of the same
892
+ objective. Dense X only.
893
+
894
+ Measured (`bench/quantile-compare.py`: X Gaussian, y a linear model
895
+ with Student t(3) noise; `--threads 1` under `taskset`, and `--threads
896
+ all`; the MKL build, scikit-learn 1.9.1, load average 3-8, best of
897
+ three, one run where scikit-learn takes more than 5 s). The times are
898
+ those on one core. Against scikit-learn's default solver:
899
+
900
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
901
+ |---|---|---|---|---|
902
+ | 1,000 x 20, quantile 0.5, alpha 0 | 0.12 s | 0.002 s | 56x | 42x |
903
+ | 5,000 x 20, quantile 0.5, alpha 0 | 2.00 s | 0.012 s | 174x | 232x |
904
+ | 20,000 x 20, quantile 0.5, alpha 0 | 27.8 s | 0.058 s | 479x | 836x |
905
+ | 20,000 x 20, quantile 0.9, alpha 0 | 27.0 s | 0.074 s | 363x | 672x |
906
+ | 20,000 x 20, quantile 0.5, alpha 0.01 | 20.3 s | 0.081 s | 251x | 437x |
907
+ | 20,000 x 100, quantile 0.5, alpha 0 | 221 s | 0.43 s | 515x | 1549x |
908
+ | 20,000 x 100, quantile 0.1, alpha 0.005 | 63.2 s | 0.78 s | 81x | 331x |
909
+
910
+ Against `QuantileRegressor(solver="highs-ipm")`, HiGHS's own interior
911
+ point code (`--solver highs-ipm --big`):
912
+
913
+ | case | scikit-learn, highs-ipm | package | ratio, one core | ratio, 20 cores |
914
+ |---|---|---|---|---|
915
+ | 1,000 x 20, quantile 0.5, alpha 0 | 0.09 s | 0.002 s | 41x | 34x |
916
+ | 5,000 x 20, quantile 0.5, alpha 0 | 0.68 s | 0.014 s | 50x | 81x |
917
+ | 20,000 x 20, quantile 0.5, alpha 0 | 4.49 s | 0.062 s | 73x | 111x |
918
+ | 20,000 x 20, quantile 0.9, alpha 0 | 7.80 s | 0.077 s | 101x | 188x |
919
+ | 20,000 x 20, quantile 0.5, alpha 0.01 | 6.46 s | 0.086 s | 75x | 146x |
920
+ | 20,000 x 100, quantile 0.5, alpha 0 | 32.0 s | 0.51 s | 62x | 205x |
921
+ | 20,000 x 100, quantile 0.1, alpha 0.005 | 63.4 s | 0.95 s | 67x | 265x |
922
+ | 100,000 x 100, quantile 0.5, alpha 0 | 286 s | 2.76 s | 104x | 354x |
923
+
924
+ scikit-learn's times barely change with the cores (225 s and 28 s for
925
+ 20,000 x 100, quantile 0.5); the 20-core ratios are the package's dsyrk
926
+ on threads. In every row the objectives agree to 4e-16 of their value
927
+ and the coefficients to 5e-14.
928
+
843
929
  ## Sparse X
844
930
 
845
931
  `GramLasso`, `GramElasticNet`, `GramRidge`, `GramLinearRegression` and
@@ -19,7 +19,7 @@ with a DeprecationWarning.
19
19
  $ pip install scm2cpp-learn
20
20
  ```
21
21
 
22
- On Linux x86_64, macOS arm64 (macOS 14 or later) and Windows AMD64
22
+ On Linux x86_64, macOS arm64 (macOS 15 or later) and Windows AMD64
23
23
  this installs a wheel: compiled, nothing to build (with OpenBLAS
24
24
  inside on Linux and macOS; Windows has the loop variants). Elsewhere pip builds the sdist,
25
25
  which needs a C++17 compiler and nothing else. The wheels carry no
@@ -38,7 +38,13 @@ the translated loops; `SCM2CPP_NO_MKL=1` skips MKL. The translated
38
38
  loops that the dependence test proves independent run on OpenMP where
39
39
  the compiler has it (`SCM2CPP_NO_OPENMP=1` builds them serial). Both
40
40
  use every core unless told otherwise: `OMP_NUM_THREADS` (and
41
- `MKL_NUM_THREADS` / `OPENBLAS_NUM_THREADS`) set the threads.
41
+ `MKL_NUM_THREADS` / `OPENBLAS_NUM_THREADS`) set the threads. The
42
+ translated loops take one thread per physical core by default (on
43
+ Linux; `SCM2CPP_OMP_THREADS=n` for another number, and
44
+ `OMP_NUM_THREADS=n` is taken as given): two per core, OpenMP's own
45
+ default, made a LARS path five to twenty times slower whenever the
46
+ machine had other work. Where every core is busy with other
47
+ processes, start Python with `OMP_WAIT_POLICY=passive`.
42
48
 
43
49
  The batched GPU solver, the cuBLAS variants and the `--cuda`
44
50
  estimators are then built as well; without `nvcc` the package installs
@@ -192,6 +198,7 @@ package picks the fastest one present.
192
198
  | `GramElasticNet` | ElasticNet(precompute=True), fit(X, y) with the intercept, dense or sparse X | `lasso-cov.scm` | CPU | no |
193
199
  | `GramRidge` | Ridge, fit(X, y) with the intercept, one or many targets, dense or sparse X | `gram.scm` (Cholesky; dposv) | loops / BLAS | Ridge |
194
200
  | `GramLinearRegression` | LinearRegression, dense or sparse X, sample_weight | `linreg.scm` (Cholesky; dposv, dpocon) | loops / BLAS | no |
201
+ | `FrischNewtonQuantileRegressor` | QuantileRegressor, the L1 penalty and sample_weight included, dense X | `quantile.scm` (Frisch-Newton interior point; dsyrk, dposv) | loops / BLAS | no |
195
202
  | `GramRidgeCV` | RidgeCV (cv=None), leave-one-out over every alpha from one eigenproblem | `ridge-gcv.scm` | loops / BLAS | no |
196
203
  | `GramMultiTaskLasso` | MultiTaskLasso, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
197
204
  | `GramMultiTaskElasticNet` | MultiTaskElasticNet, fit(X, Y) with the intercept | `lasso-cov.scm` | CPU | no |
@@ -464,6 +471,19 @@ a stock-feature design with n=743 and p=180, 0.21 s against 145 s for
464
471
  the descent on the same grid; at p=3495, 2.2 s, where the descent was
465
472
  stopped after 30 minutes. The default stays `solver="cd"`.
466
473
 
474
+ `working_set=k` (with `solver="lars"`, a dense X) is for a design too
475
+ wide for its Gram matrix -- p by p, 309 GB at p = 196,574. Each fold
476
+ and the refit are solved on a working set of columns: the k most
477
+ correlated with y to begin with; then, while a column outside the set
478
+ breaks the optimality conditions at some grid point (the gradient
479
+ against alpha over all p columns, 1e-5 relative), the k worst of them
480
+ join and the set is solved again. When none does, every grid solution
481
+ solves the whole problem -- checked, not assumed -- so the fit is the
482
+ full Gram's (`check-wheel.py`: 3e-13 at p = 3000, n = 150, the set
483
+ staying well below p), in memory O(np) plus the set's Gram.
484
+ `working_set_` records the rounds and the final set's size for each
485
+ fold and the refit.
486
+
467
487
  The elastic net cross-validates the same way: `CovLassoCV(l1_ratio=0.5)`
468
488
  against `ElasticNetCV(l1_ratio=0.5)` on the same folds and alpha grid
469
489
  (`bench/lasso-compare.py --cv-only --l1-ratio 0.5`, same conditions,
@@ -822,6 +842,72 @@ Measured (`bench/eigen-compare.py`, as above):
822
842
 
823
843
  The coefficients agree to 1e-13.
824
844
 
845
+ ## Quantile regression: `FrischNewtonQuantileRegressor`
846
+
847
+ scikit-learn's `QuantileRegressor` by an interior point method
848
+ (`examples/kernel-only/quantile.scm`): the same objective -- the mean
849
+ check loss at `quantile` plus `alpha` times the L1 norm of the
850
+ coefficients, the intercept not penalised -- minimised by the
851
+ Frisch-Newton predictor-corrector of Portnoy and Koenker (1997) on the
852
+ dual linear program. scikit-learn hands the program to HiGHS through
853
+ scipy's `linprog`, and its default `solver="highs"` runs HiGHS's dual
854
+ simplex. Each iteration here is one weighted Gram matrix of the design
855
+ (dsyrk) and a Cholesky solve (dposv), and some 15 to 45 iterations do
856
+ whatever the number of rows. The L1 penalty enters as one more row per
857
+ coefficient; `sample_weight` scales the rows.
858
+
859
+ An interior point method stops near the solution, not at a vertex of
860
+ the program, so the iterate (duality gap at most `tol` times the
861
+ objective) is then moved to the vertex it points to: the rows whose
862
+ dual variables lie farthest inside their bounds, as many as there are
863
+ unknowns, give a square system -- a penalty row among them holds its
864
+ coefficient at exact zero -- which the same Scheme file solves by
865
+ Gaussian elimination (`lu-solve`), and the vertex is taken when it does
866
+ not raise the objective. The coefficients are then those a simplex
867
+ code returns: the same zeros, the rest equal to rounding. The result
868
+ is checked by its own duality gap, recomputed from the returned
869
+ coefficients and dual variables. When the check fails (a design
870
+ without full column rank, more columns than rows with `alpha=0`) the
871
+ fit is scikit-learn's own program through `linprog` with `solver` and
872
+ `solver_options`, which are not used otherwise. Where the minimiser is
873
+ not unique the two may return different minimisers of the same
874
+ objective. Dense X only.
875
+
876
+ Measured (`bench/quantile-compare.py`: X Gaussian, y a linear model
877
+ with Student t(3) noise; `--threads 1` under `taskset`, and `--threads
878
+ all`; the MKL build, scikit-learn 1.9.1, load average 3-8, best of
879
+ three, one run where scikit-learn takes more than 5 s). The times are
880
+ those on one core. Against scikit-learn's default solver:
881
+
882
+ | case | scikit-learn | package | ratio, one core | ratio, 20 cores |
883
+ |---|---|---|---|---|
884
+ | 1,000 x 20, quantile 0.5, alpha 0 | 0.12 s | 0.002 s | 56x | 42x |
885
+ | 5,000 x 20, quantile 0.5, alpha 0 | 2.00 s | 0.012 s | 174x | 232x |
886
+ | 20,000 x 20, quantile 0.5, alpha 0 | 27.8 s | 0.058 s | 479x | 836x |
887
+ | 20,000 x 20, quantile 0.9, alpha 0 | 27.0 s | 0.074 s | 363x | 672x |
888
+ | 20,000 x 20, quantile 0.5, alpha 0.01 | 20.3 s | 0.081 s | 251x | 437x |
889
+ | 20,000 x 100, quantile 0.5, alpha 0 | 221 s | 0.43 s | 515x | 1549x |
890
+ | 20,000 x 100, quantile 0.1, alpha 0.005 | 63.2 s | 0.78 s | 81x | 331x |
891
+
892
+ Against `QuantileRegressor(solver="highs-ipm")`, HiGHS's own interior
893
+ point code (`--solver highs-ipm --big`):
894
+
895
+ | case | scikit-learn, highs-ipm | package | ratio, one core | ratio, 20 cores |
896
+ |---|---|---|---|---|
897
+ | 1,000 x 20, quantile 0.5, alpha 0 | 0.09 s | 0.002 s | 41x | 34x |
898
+ | 5,000 x 20, quantile 0.5, alpha 0 | 0.68 s | 0.014 s | 50x | 81x |
899
+ | 20,000 x 20, quantile 0.5, alpha 0 | 4.49 s | 0.062 s | 73x | 111x |
900
+ | 20,000 x 20, quantile 0.9, alpha 0 | 7.80 s | 0.077 s | 101x | 188x |
901
+ | 20,000 x 20, quantile 0.5, alpha 0.01 | 6.46 s | 0.086 s | 75x | 146x |
902
+ | 20,000 x 100, quantile 0.5, alpha 0 | 32.0 s | 0.51 s | 62x | 205x |
903
+ | 20,000 x 100, quantile 0.1, alpha 0.005 | 63.4 s | 0.95 s | 67x | 265x |
904
+ | 100,000 x 100, quantile 0.5, alpha 0 | 286 s | 2.76 s | 104x | 354x |
905
+
906
+ scikit-learn's times barely change with the cores (225 s and 28 s for
907
+ 20,000 x 100, quantile 0.5); the 20-core ratios are the package's dsyrk
908
+ on threads. In every row the objectives agree to 4e-16 of their value
909
+ and the coefficients to 5e-14.
910
+
825
911
  ## Sparse X
826
912
 
827
913
  `GramLasso`, `GramElasticNet`, `GramRidge`, `GramLinearRegression` and
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scm2cpp-learn"
7
- version = "0.21.0"
7
+ version = "0.23.0"
8
8
  description = "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"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -154,7 +154,7 @@ def openmp_flags():
154
154
  else nothing -- the same sources then compile serial. Not on
155
155
  Windows (MSVC's OpenMP needs vcomp140.dll beside the wheel) nor
156
156
  with SCM2CPP_NO_OPENMP set. OMP_NUM_THREADS sets the threads at
157
- run time, all cores by default.
157
+ run time, one per physical core by default (scm2cpp.hpp's omp_team).
158
158
  """
159
159
  if os.name == "nt" or os.environ.get("SCM2CPP_NO_OPENMP"):
160
160
  return []
@@ -51,14 +51,14 @@ __all__ = ["GramLasso", "GramElasticNet", "GramRidge", "GramRidgeCV", "CovLasso"
51
51
  "LBFGSLogisticRegression", "LBFGSHuberRegressor", "LBFGSLogisticRegressionCV",
52
52
  "LBFGSPoissonRegressor", "LBFGSGammaRegressor", "LBFGSTweedieRegressor",
53
53
  "GramLarsCV", "GramLassoLarsCV", "GramOMPCV",
54
- "EMGaussianMixture", "CovPCA", "GramKernelPCA", "GramLDA", "GramTruncatedSVD", "GramPLSRegression", "GramPLSCanonical", "GramCCA", "GramPLSSVD", "GramFactorAnalysis", "GramLinearRegression", "ParallelFastICA", "CovARDRegression",
54
+ "EMGaussianMixture", "CovPCA", "GramKernelPCA", "GramLDA", "GramTruncatedSVD", "GramPLSRegression", "GramPLSCanonical", "GramCCA", "GramPLSSVD", "GramFactorAnalysis", "GramLinearRegression", "FrischNewtonQuantileRegressor", "ParallelFastICA", "CovARDRegression",
55
55
  "L1LinearSVM", "WeiszfeldTheilSen", "f_regression", "f_classif", "SelectKBest",
56
56
  "SelectPercentile", "GramRFE",
57
57
  "CovMultiTaskLasso", "CovMultiTaskLassoCV", "DerivedLasso",
58
58
  "GramLogisticRegression", "GramGroupLasso", "GramMultiTaskLasso",
59
59
  "GramMultiTaskElasticNet", "DesignLasso",
60
60
  "cuda_available", "derived_backend", "kernel"]
61
- __version__ = "0.21.0"
61
+ __version__ = "0.23.0"
62
62
 
63
63
  _BATCH = load_batch_lib()
64
64
  _DP = ctypes.POINTER(ctypes.c_double)
@@ -601,14 +601,27 @@ class CovLassoCV(Tagged, RegressorMixin, BaseEstimator):
601
601
  coordinate descent (n_polished_ counts them). The default "cd" is
602
602
  the descent.
603
603
 
604
+ working_set=k (with solver="lars", a dense X) is for a design too
605
+ wide for its Gram matrix (p x p: 309 GB at p = 196574). Each fold,
606
+ and the refit, is solved on a working set of columns: first the k
607
+ most correlated with y; then, while a column outside the set breaks
608
+ the optimality conditions at some grid point (|gradient| > alpha, to
609
+ 1e-5 relative, checked over all p columns), the k worst of them
610
+ join it and the set is solved again. When none does, every grid
611
+ solution is a solution of the whole problem -- checked, not assumed
612
+ -- so the fit is the one the full Gram gives, in memory O(n p) plus
613
+ the working set's Gram. The data is centred as a copy here. The
614
+ default None forms the full Gram.
615
+
604
616
  Attributes after fit: alphas_, mse_path_ (num, n_folds), alpha_,
605
617
  coef_, intercept_; with solver="lars" also n_polished_ and n_iter_ (the refit's
606
- path steps).
618
+ path steps); with working_set also working_set_, the (rounds,
619
+ columns in the final set) of each fold and, last, of the refit.
607
620
  """
608
621
 
609
622
  def __init__(self, cv=5, num=100, eps=1e-3, tol=1e-8, l1_ratio=1.0,
610
623
  force_cpu=False, force_gpu=False, n_jobs=1, fit_intercept=False,
611
- solver="cd"):
624
+ solver="cd", working_set=None):
612
625
  # Folds are independent, the descent is a ctypes call and the
613
626
  # products are BLAS calls, both of which release the GIL, so
614
627
  # plain threads scale the CPU path across folds. Default 1:
@@ -617,6 +630,105 @@ class CovLassoCV(Tagged, RegressorMixin, BaseEstimator):
617
630
  self.l1_ratio, self.force_cpu, self.force_gpu = l1_ratio, force_cpu, force_gpu
618
631
  self.n_jobs, self.fit_intercept = n_jobs, fit_intercept
619
632
  self.solver = solver
633
+ self.working_set = working_set
634
+
635
+ def _ws_grid(self, Xc, yc):
636
+ """The lasso solutions at alphas_ (rows, p columns) for centred
637
+ Xc, yc by _lars_grid on a working set S of columns, with the
638
+ (rounds, columns of S) it took.
639
+
640
+ S starts as the working_set columns most correlated with yc.
641
+ After each solve the gradient Xc'(yc - Xc b)/n of every grid
642
+ solution is formed over all columns; a column outside S whose
643
+ gradient exceeds alpha (1e-5 relative, the tolerance the path
644
+ itself is held to) breaks the optimality conditions, and the
645
+ working_set worst of them join S. The loop ends when no column
646
+ breaks them. Columns equal up to a factor are cut by _lars_grid
647
+ as before; one of larger norm outside S shows up as a violation
648
+ and takes its copy's place."""
649
+ n, p = Xc.shape
650
+ k = int(self.working_set)
651
+ a = self.alphas_
652
+ den = np.where(a > 0, a, 1.0)
653
+ c = Xc.T @ yc
654
+ S = np.sort(np.argsort(-np.abs(c), kind="stable")[:min(k, p)])
655
+ rounds = 0
656
+ while True:
657
+ rounds += 1
658
+ XS = Xc[:, S]
659
+ BS, it = self._lars_grid(XS.T @ XS, c[S], n)
660
+ R = yc[:, None] - XS @ BS.T
661
+ viol = (np.abs(Xc.T @ R) / n - a[None, :]) / den[None, :]
662
+ viol[S] = 0.0
663
+ worst = viol.max(axis=1)
664
+ bad = np.flatnonzero(worst > 1e-5)
665
+ if bad.size == 0:
666
+ B = np.zeros((len(a), p))
667
+ B[:, S] = BS
668
+ return B, it, (rounds, int(S.size))
669
+ bad = bad[np.argsort(-worst[bad], kind="stable")[:k]]
670
+ S = np.union1d(S, bad)
671
+
672
+ def _fit_working_set(self, X, y):
673
+ """fit for working_set: the same grid, folds, centring,
674
+ validation error, choice and refit as the full Gram's, each
675
+ solve by _ws_grid on a centred copy of its rows."""
676
+ if self.solver != "lars":
677
+ raise ValueError("working_set needs solver='lars'")
678
+ if float(self.l1_ratio) != 1.0:
679
+ raise ValueError("solver='lars' solves the lasso only (l1_ratio=1)")
680
+ if _issparse(X):
681
+ raise ValueError("working_set needs a dense X")
682
+ if int(self.working_set) < 1:
683
+ raise ValueError(f"working_set must be a positive number of columns, got {self.working_set!r}")
684
+ n, num = len(y), int(self.num)
685
+ fi = bool(self.fit_intercept)
686
+ self._lars_polished_ = 0
687
+
688
+ def centre(Xt, yt):
689
+ if not fi:
690
+ return Xt, yt, np.zeros(Xt.shape[1]), 0.0
691
+ xm, ym = Xt.mean(axis=0), float(yt.mean())
692
+ return Xt - xm, yt - ym, xm, ym
693
+ # all rows first: the grid starts at their lambda_max, and their
694
+ # solutions at the grid are the refit's, whichever alpha wins
695
+ Xc, yc, xm_all, ym_all = centre(X, y)
696
+ hi = float(np.max(np.abs(Xc.T @ yc))) / n
697
+ self.alphas_ = hi * np.logspace(0, np.log10(float(self.eps)), num)
698
+ B_all, self.n_iter_, info_all = self._ws_grid(Xc, yc)
699
+ del Xc, yc
700
+ folds = self._folds(X, y, n)
701
+ self.mse_path_ = np.empty((num, len(folds)))
702
+ info = [None] * len(folds)
703
+
704
+ def one_fold(k):
705
+ train, test = folds[k]
706
+ if train is None:
707
+ tr = np.ones(n, dtype=bool)
708
+ tr[test] = False
709
+ else:
710
+ tr = train
711
+ Xc, yc, xm, ym = centre(X[tr], y[tr])
712
+ B, _, info[k] = self._ws_grid(Xc, yc)
713
+ del Xc
714
+ resid = (X[test] - xm) @ B.T - (y[test] - ym)[:, None]
715
+ self.mse_path_[:, k] = np.mean(resid * resid, axis=0)
716
+
717
+ if int(self.n_jobs) > 1:
718
+ from concurrent.futures import ThreadPoolExecutor
719
+ with ThreadPoolExecutor(max_workers=int(self.n_jobs)) as ex:
720
+ list(ex.map(one_fold, range(len(folds))))
721
+ else:
722
+ for k in range(len(folds)):
723
+ one_fold(k)
724
+ # alphas_ descends, so argmin's first hit is the larger penalty
725
+ ib = int(np.argmin(self.mse_path_.mean(axis=1)))
726
+ self.alpha_ = float(self.alphas_[ib])
727
+ self.coef_ = B_all[ib].copy()
728
+ self.intercept_ = ym_all - float(xm_all @ self.coef_)
729
+ self.n_polished_ = self._lars_polished_
730
+ self.working_set_ = info + [info_all]
731
+ return self
620
732
 
621
733
  def _lars_grid(self, G, c, nobs):
622
734
  """The lasso solutions at alphas_ (rows) for Gram G and
@@ -749,6 +861,8 @@ class CovLassoCV(Tagged, RegressorMixin, BaseEstimator):
749
861
 
750
862
  def fit(self, X, y):
751
863
  X, y = fit_xy(self, X, y)
864
+ if self.working_set is not None:
865
+ return self._fit_working_set(X, y)
752
866
  n = len(y)
753
867
  num = int(self.num)
754
868
  tol, l1_ratio = float(self.tol), float(self.l1_ratio)
@@ -3070,6 +3184,176 @@ class GramLinearRegression(Tagged, RegressorMixin, BaseEstimator):
3070
3184
  return (_dot(X, self.coef_.T) if _issparse(X) else X @ self.coef_.T) + self.intercept_
3071
3185
 
3072
3186
 
3187
+ def _check_loss(r, q):
3188
+ # the quantile (check, pinball) loss of the residuals r at the levels q
3189
+ return np.where(r < 0.0, (q - 1.0) * r, q * r)
3190
+
3191
+
3192
+ class FrischNewtonQuantileRegressor(Tagged, RegressorMixin, BaseEstimator):
3193
+ """scikit-learn's ``QuantileRegressor`` by an interior point method
3194
+ (``examples/kernel-only/quantile.scm``): the same objective,
3195
+ mean check loss at ``quantile`` plus ``alpha`` times the L1 norm of
3196
+ the coefficients (the intercept not penalised), minimised by the
3197
+ Frisch-Newton predictor-corrector of Portnoy and Koenker (1997) on
3198
+ the dual linear program, where scikit-learn's default hands the
3199
+ program to a simplex code. Each iteration is one weighted Gram
3200
+ matrix of the design (dsyrk) and a Cholesky solve (dposv), and some
3201
+ 15 to 45 iterations do whatever the number of rows. The L1 penalty
3202
+ enters as one more row per coefficient.
3203
+
3204
+ The iterate the method stops at (duality gap at most ``tol`` times
3205
+ the objective) is then moved to the vertex it points to -- the fit
3206
+ through the rows whose dual variables are strictly inside their
3207
+ bounds, with the coefficients the penalty holds at zero exactly
3208
+ zero -- when that does not raise the objective. The result is
3209
+ checked by its own duality gap, recomputed from the returned
3210
+ coefficients and dual variables; when the check fails (a design
3211
+ without full column rank, more columns than rows with ``alpha=0``)
3212
+ the fit is scikit-learn's own linear program through scipy's
3213
+ ``linprog`` with ``solver`` and ``solver_options``, which are not
3214
+ used otherwise. Where the minimiser is not unique the two may
3215
+ return different minimisers of the same objective. Dense X only.
3216
+
3217
+ ``sample_weight`` weights the check losses, and ``alpha`` is scaled
3218
+ by its sum, as in scikit-learn.
3219
+
3220
+ Attributes after fit: coef_, intercept_, n_iter_ (interior point
3221
+ iterations, or linprog's), n_features_in_.
3222
+ """
3223
+
3224
+ def __init__(self, *, quantile=0.5, alpha=1.0, fit_intercept=True, solver="highs",
3225
+ solver_options=None, tol=1e-10, max_iter=100):
3226
+ self.quantile, self.alpha, self.fit_intercept = quantile, alpha, fit_intercept
3227
+ self.solver, self.solver_options = solver, solver_options
3228
+ self.tol, self.max_iter = tol, max_iter
3229
+
3230
+ def fit(self, X, y, sample_weight=None):
3231
+ X, y = fit_xy(self, X, y)
3232
+ n, p = X.shape
3233
+ q, alpha, tol = float(self.quantile), float(self.alpha), float(self.tol)
3234
+ if not 0.0 < q < 1.0:
3235
+ raise ValueError(f"quantile must be strictly between 0 and 1, got {self.quantile!r}")
3236
+ if not alpha >= 0.0:
3237
+ raise ValueError(f"alpha must be non-negative, got {self.alpha!r}")
3238
+ if sample_weight is not None:
3239
+ sw = np.asarray(sample_weight, dtype=np.float64)
3240
+ sw = np.full(n, float(sw)) if sw.ndim == 0 else sw
3241
+ if sw.shape != (n,):
3242
+ raise ValueError(f"sample_weight.shape == {sw.shape}, expected {(n,)}!")
3243
+ if not np.all(sw >= 0.0):
3244
+ raise ValueError("sample_weight must be non-negative and finite")
3245
+ if np.all(sw == 0):
3246
+ raise ValueError("Sample weights must contain at least one non-zero number.")
3247
+ if np.all(sw == 1.0):
3248
+ sw = None
3249
+ elif not np.all(sw > 0.0):
3250
+ # a row of weight zero is a row left out, as scikit-learn has it
3251
+ keep = sw > 0.0
3252
+ X, y, sw = X[keep], y[keep], sw[keep]
3253
+ n = X.shape[0]
3254
+ else:
3255
+ sw = None
3256
+ S = float(n) if sw is None else float(sw.sum())
3257
+ k = 1 if self.fit_intercept else 0
3258
+ m = p + k
3259
+ rows = n + (p if alpha > 0.0 else 0)
3260
+ # the columns and y about their means when there is an intercept
3261
+ # to absorb them: the Gram matrices stay well conditioned
3262
+ if k:
3263
+ xm, ym = X.mean(axis=0), float(y.mean())
3264
+ else:
3265
+ xm, ym = np.zeros(p), 0.0
3266
+ yy = np.zeros(rows)
3267
+ yy[:n] = y - ym
3268
+ if sw is not None:
3269
+ yy[:n] *= sw
3270
+ coef, it = None, 0
3271
+ if not yy.any():
3272
+ coef = np.zeros(m) # the objective is zero there
3273
+ elif m <= rows:
3274
+ A = np.zeros((rows, m))
3275
+ np.subtract(X, xm, out=A[:n, k:])
3276
+ if sw is not None:
3277
+ A[:n, k:] *= sw[:, None]
3278
+ if k:
3279
+ A[:n, 0] = 1.0 if sw is None else sw
3280
+ if alpha > 0.0:
3281
+ # alpha S |b_j| is the check loss at 1/2 of the row 2 alpha S e_j
3282
+ A[n + np.arange(p), k + np.arange(p)] = 2.0 * alpha * S
3283
+ tq = np.full(rows, q)
3284
+ tq[n:] = 0.5
3285
+ x0 = 1.0 - tq
3286
+ x = x0.copy()
3287
+ b = np.zeros(m)
3288
+ out = np.zeros(3)
3289
+ it = _gramops_kernels().quantile_fn(A, np.ascontiguousarray(-yy), x, b, out, tol,
3290
+ int(self.max_iter), rows, m)
3291
+ if out[2] != 2.0 and np.all(np.isfinite(b)) and np.all(np.isfinite(x)):
3292
+ eps = 64.0 * np.finfo(np.float64).eps * float(np.abs(yy).sum())
3293
+ loss = float(_check_loss(yy - A @ b, tq).sum())
3294
+ # weak duality: the optimum is at least yy'd - (A'd)'b for
3295
+ # d = x - x0 within its bounds, A'd = 0 up to rounding
3296
+ d = x - x0
3297
+ gap = loss - float(yy @ d) + float(np.abs(A.T @ d) @ np.abs(b))
3298
+ if gap <= max(100.0 * tol, 1e-9) * loss + eps:
3299
+ coef = b
3300
+ # the vertex: the m rows strictly inside (0, 1) fitted
3301
+ # exactly; a penalty row among them is a zero coefficient
3302
+ h = np.argpartition(np.minimum(x, 1.0 - x), rows - m)[rows - m:]
3303
+ zero = np.zeros(m, dtype=bool)
3304
+ zero[k + h[h >= n] - n] = True
3305
+ # by the kernel's own elimination, on one thread: a
3306
+ # threaded LAPACK's LU of a system this small can take
3307
+ # longer than the whole fit on a busy machine
3308
+ hd = np.sort(h[h < n])
3309
+ sq = np.ascontiguousarray(A[np.ix_(hd, ~zero)])
3310
+ rhs = np.ascontiguousarray(yy[hd])
3311
+ v = np.zeros(m)
3312
+ if len(rhs) and _gramops_kernels().lu_solve(sq, rhs, len(rhs)) == 0:
3313
+ v[~zero] = rhs
3314
+ elif len(rhs):
3315
+ v = None
3316
+ if (v is not None and np.all(np.isfinite(v))
3317
+ and float(_check_loss(yy - A @ v, tq).sum()) <= loss + eps):
3318
+ coef = v
3319
+ if coef is None:
3320
+ # on the data as given, so that the vertex is scikit-learn's
3321
+ coef, it = self._linprog(X, y, sw, q, alpha * S, k)
3322
+ xm, ym = np.zeros(p), 0.0
3323
+ self.coef_ = coef[k:].copy()
3324
+ self.intercept_ = float(ym + coef[0] - xm @ self.coef_) if k else 0.0
3325
+ self.n_iter_ = int(it)
3326
+ return self
3327
+
3328
+ def _linprog(self, X, y, sw, q, alpha, k):
3329
+ # scikit-learn's program: min c'v over v = (s, t, u, v) >= 0 with
3330
+ # the parameters s - t and the residual u - v
3331
+ try:
3332
+ from scipy import sparse
3333
+ from scipy.optimize import linprog
3334
+ except ImportError:
3335
+ raise RuntimeError("the design has no full column rank (or more columns than rows "
3336
+ "with alpha=0): this fit needs scipy's linprog") from None
3337
+ n, p = X.shape
3338
+ m = p + k
3339
+ w = np.ones(n) if sw is None else sw
3340
+ c = np.concatenate([np.full(2 * m, alpha), w * q, w * (1.0 - q)])
3341
+ if k:
3342
+ c[0] = c[m] = 0.0
3343
+ eye = sparse.eye(n, dtype=np.float64, format="csc")
3344
+ Xs = sparse.csc_matrix(np.hstack([np.ones((n, 1)), X]) if k else X)
3345
+ A_eq = sparse.hstack([Xs, -Xs, eye, -eye], format="csc")
3346
+ res = linprog(c=c, A_eq=A_eq, b_eq=y, method=self.solver, options=self.solver_options)
3347
+ if not res.success:
3348
+ warnings.warn("Linear programming for QuantileRegressor did not succeed.\n"
3349
+ f"Status is {res.status}: {res.message}", _convergence_warning())
3350
+ v = res.x
3351
+ return v[:m] - v[m:2 * m], res.nit
3352
+
3353
+ def predict(self, X):
3354
+ return pred_x(self, X) @ self.coef_ + self.intercept_
3355
+
3356
+
3073
3357
  def _pls_moments(X, Y, scale):
3074
3358
  """Centred (and, with scale, standardised) Cxx, Cxy, Cyy, with the
3075
3359
  means and deviations: from X'X, X'Y and Y'Y less the n m m' terms,
@@ -834,3 +834,20 @@ def csr_mm(rp, ci, v, b, c, n, k):
834
834
  c = np.ascontiguousarray(c, dtype=np.float64)
835
835
  return _lib.scm2cpp_csr_mm(rp.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), ci.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), v.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), b.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), n, k)
836
836
 
837
+ _lib.scm2cpp_lu_solve.restype = ctypes.c_int64
838
+ _lib.scm2cpp_lu_solve.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_int64]
839
+ def lu_solve(a, b, n):
840
+ a = np.ascontiguousarray(a, dtype=np.float64)
841
+ b = np.ascontiguousarray(b, dtype=np.float64)
842
+ return _lib.scm2cpp_lu_solve(a.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), b.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), n)
843
+
844
+ _lib.scm2cpp_quantile_fn.restype = ctypes.c_int64
845
+ _lib.scm2cpp_quantile_fn.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64]
846
+ def quantile_fn(a, c, x, coef, out, tol, maxit, n, m):
847
+ a = np.ascontiguousarray(a, dtype=np.float64)
848
+ c = np.ascontiguousarray(c, dtype=np.float64)
849
+ x = np.ascontiguousarray(x, dtype=np.float64)
850
+ coef = np.ascontiguousarray(coef, dtype=np.float64)
851
+ out = np.ascontiguousarray(out, dtype=np.float64)
852
+ return _lib.scm2cpp_quantile_fn(a.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), x.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), coef.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), out.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), tol, maxit, n, m)
853
+
@@ -853,3 +853,20 @@ def csr_mm(rp, ci, v, b, c, n, k):
853
853
  c = np.ascontiguousarray(c, dtype=np.float64)
854
854
  return _lib.scm2cpp_csr_mm(rp.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), ci.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), v.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), b.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), n, k)
855
855
 
856
+ _lib.scm2cpp_lu_solve.restype = ctypes.c_int64
857
+ _lib.scm2cpp_lu_solve.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_int64]
858
+ def lu_solve(a, b, n):
859
+ a = np.ascontiguousarray(a, dtype=np.float64)
860
+ b = np.ascontiguousarray(b, dtype=np.float64)
861
+ return _lib.scm2cpp_lu_solve(a.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), b.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), n)
862
+
863
+ _lib.scm2cpp_quantile_fn.restype = ctypes.c_int64
864
+ _lib.scm2cpp_quantile_fn.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64]
865
+ def quantile_fn(a, c, x, coef, out, tol, maxit, n, m):
866
+ a = np.ascontiguousarray(a, dtype=np.float64)
867
+ c = np.ascontiguousarray(c, dtype=np.float64)
868
+ x = np.ascontiguousarray(x, dtype=np.float64)
869
+ coef = np.ascontiguousarray(coef, dtype=np.float64)
870
+ out = np.ascontiguousarray(out, dtype=np.float64)
871
+ return _lib.scm2cpp_quantile_fn(a.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), x.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), coef.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), out.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), tol, maxit, n, m)
872
+