scm2cpp-learn 0.20.0__tar.gz → 0.21.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.
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/PKG-INFO +27 -1
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/README.md +26 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/pyproject.toml +1 -1
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/setup.py +29 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/__init__.py +304 -62
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_compat.py +8 -6
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader.py +6 -6
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_accel_cublas.py +36 -36
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_classifiers.py +52 -52
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_derived_blas.py +2 -2
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_derived_cublas.py +2 -2
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_derived_loops.py +2 -2
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_gpu_cuda.py +41 -41
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_gramops_blas.py +159 -159
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_gramops_loops.py +163 -163
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_nmf_blas.py +3 -3
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_nmf_cublas.py +3 -3
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/_loader_nmf_loops.py +3 -3
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/accel_cublas/accel.hpp +1250 -0
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/accel_cublas/accel_capi.cpp +82 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/classifiers.hpp +768 -768
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/classifiers_capi.cpp +115 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design.hpp +38 -38
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design_capi.cpp +1 -1
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design.hpp +39 -39
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design_capi.cpp +1 -1
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/derived_loops/lasso_design.hpp +179 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_loops/lasso_design_capi.cpp +1 -1
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu.hpp +675 -675
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu_capi.cpp +44 -44
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gramops_blas/gramops.hpp +1799 -1799
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/gramops_blas/gramops_capi.cpp +295 -0
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/gramops_loops/gramops.hpp +7711 -0
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/gramops_loops/gramops_capi.cpp +301 -0
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/lasso_cov.hpp +152 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/lasso_cov_capi.cpp +3 -3
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/nmf_blas/nmf_cd.hpp +39 -39
- {scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/nmf_cublas → scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/nmf_blas}/nmf_cd_capi.cpp +2 -2
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd.hpp +136 -0
- {scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/nmf_loops → scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/nmf_cublas}/nmf_cd_capi.cpp +2 -2
- scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd.hpp +167 -0
- {scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/nmf_blas → scm2cpp_learn-0.21.0/src/scm2cpp_learn/_generated/nmf_loops}/nmf_cd_capi.cpp +2 -2
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/scm2cpp.hpp +15 -1
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/batch_capi.cu +7 -4
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn.egg-info/PKG-INFO +27 -1
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/accel_cublas/accel.hpp +0 -1250
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/accel_cublas/accel_capi.cpp +0 -82
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/classifiers_capi.cpp +0 -115
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/derived_loops/lasso_design.hpp +0 -179
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/gramops_blas/gramops_capi.cpp +0 -295
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/gramops_loops/gramops.hpp +0 -7711
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/gramops_loops/gramops_capi.cpp +0 -301
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/lasso_cov.hpp +0 -152
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd.hpp +0 -136
- scm2cpp_learn-0.20.0/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd.hpp +0 -167
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/setup.cfg +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/__init__.py +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/accel_cublas/accel.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/classifiers.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_blas/lasso_design.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_cublas/lasso_design.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/derived_loops/lasso_design.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gpu_cuda/gpu.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gramops_blas/gramops.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/gramops_loops/gramops.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/lasso_cov.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/nmf_blas/nmf_cd.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/nmf_cublas/nmf_cd.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/nmf_loops/nmf_cd.cpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/scm2cpp-blas.hpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/scm2cpp-cublas.hpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_generated/scm2cpp-cuda.hpp +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn/_libfind.py +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn.egg-info/SOURCES.txt +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn.egg-info/dependency_links.txt +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.0}/src/scm2cpp_learn.egg-info/requires.txt +0 -0
- {scm2cpp_learn-0.20.0 → scm2cpp_learn-0.21.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.
|
|
3
|
+
Version: 0.21.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
|
|
@@ -456,6 +456,32 @@ the pick is exact at n=5,000 and one grid step apart on a near-tie
|
|
|
456
456
|
elsewhere (mean-MSE relative gap at most 2.6e-4), and sklearn at
|
|
457
457
|
tol=1e-10 picks our alpha at every size.
|
|
458
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
|
+
|
|
459
485
|
The elastic net cross-validates the same way: `CovLassoCV(l1_ratio=0.5)`
|
|
460
486
|
against `ElasticNetCV(l1_ratio=0.5)` on the same folds and alpha grid
|
|
461
487
|
(`bench/lasso-compare.py --cv-only --l1-ratio 0.5`, same conditions,
|
|
@@ -438,6 +438,32 @@ the pick is exact at n=5,000 and one grid step apart on a near-tie
|
|
|
438
438
|
elsewhere (mean-MSE relative gap at most 2.6e-4), and sklearn at
|
|
439
439
|
tol=1e-10 picks our alpha at every size.
|
|
440
440
|
|
|
441
|
+
`cv` may also be a splitter (`TimeSeriesSplit`, a shuffled `KFold`, ...)
|
|
442
|
+
or a list of (train, test) index pairs, and `fit_intercept=True` centres
|
|
443
|
+
each fold's training rows as `LassoCV` does (through the Gram, not a
|
|
444
|
+
centred copy); the default stays the fit through the origin. A
|
|
445
|
+
`TimeSeriesSplit` fold's training rows are a prefix, so its Gram is the
|
|
446
|
+
previous fold's plus the new rows' -- the five folds cost one pass over
|
|
447
|
+
the training rows, not five. Against `LassoCV` on the same grid the
|
|
448
|
+
validation errors agree to 1e-11 and the coefficients and intercept
|
|
449
|
+
to 1e-11.
|
|
450
|
+
|
|
451
|
+
`solver="lars"` (lasso only) solves each fold and the refit by the
|
|
452
|
+
translated least angle regression over the same Gram
|
|
453
|
+
(`examples/kernel-only/lars.scm`, method "lasso") and reads the
|
|
454
|
+
solutions at the grid off the recorded path, which is piecewise linear
|
|
455
|
+
in alpha: exact up to rounding, with no tolerance, and with a cost set
|
|
456
|
+
by the number of path steps rather than by conditioning. Columns equal
|
|
457
|
+
up to a factor are cut to the longest one first (two equal columns tie
|
|
458
|
+
in the path; scikit-learn's `lars_path` stops early there), and a grid
|
|
459
|
+
point whose solution misses the optimality conditions (1e-5 relative)
|
|
460
|
+
is finished by coordinate descent (`n_polished_`). Where the columns
|
|
461
|
+
are strongly correlated -- moving averages over overlapping windows --
|
|
462
|
+
coordinate descent needs thousands of sweeps and LARS is far faster: on
|
|
463
|
+
a stock-feature design with n=743 and p=180, 0.21 s against 145 s for
|
|
464
|
+
the descent on the same grid; at p=3495, 2.2 s, where the descent was
|
|
465
|
+
stopped after 30 minutes. The default stays `solver="cd"`.
|
|
466
|
+
|
|
441
467
|
The elastic net cross-validates the same way: `CovLassoCV(l1_ratio=0.5)`
|
|
442
468
|
against `ElasticNetCV(l1_ratio=0.5)` on the same folds and alpha grid
|
|
443
469
|
(`bench/lasso-compare.py --cv-only --l1-ratio 0.5`, same conditions,
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "scm2cpp-learn"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.21.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"
|
|
@@ -12,6 +12,7 @@ device, or a failed nvcc all leave a working CPU package behind, and
|
|
|
12
12
|
the batch path notices at import and falls back.
|
|
13
13
|
"""
|
|
14
14
|
import os
|
|
15
|
+
import platform
|
|
15
16
|
import re
|
|
16
17
|
import shutil
|
|
17
18
|
import subprocess
|
|
@@ -33,6 +34,33 @@ GEN = PKG / "_generated"
|
|
|
33
34
|
MSVC = ["/O2", "/std:c++17", "/EHsc", "/bigobj"]
|
|
34
35
|
CXXFLAGS = ["-O2", "-std=c++17"] if os.name != "nt" else MSVC
|
|
35
36
|
|
|
37
|
+
|
|
38
|
+
def align_flags():
|
|
39
|
+
"""-Wa,-mbranches-within-32B-boundaries where the assembler takes it.
|
|
40
|
+
|
|
41
|
+
Skylake-family x86 cores slow a jump that crosses or ends on a 32-byte
|
|
42
|
+
boundary (the JCC erratum microcode), so where a hot loop's branch
|
|
43
|
+
lands depends on unrelated code around it: the linear SVM's sweep
|
|
44
|
+
moved 10-20% between builds that differed only elsewhere. The GNU
|
|
45
|
+
assembler pads such branches away. Other assemblers and other
|
|
46
|
+
machines get nothing.
|
|
47
|
+
"""
|
|
48
|
+
if os.name == "nt" or platform.machine().lower() not in ("x86_64", "amd64"):
|
|
49
|
+
return []
|
|
50
|
+
cxx = os.environ.get("CXX", "c++")
|
|
51
|
+
flag = "-Wa,-mbranches-within-32B-boundaries"
|
|
52
|
+
try:
|
|
53
|
+
r = subprocess.run([cxx, flag, "-x", "c++", "-c", "-", "-o", os.devnull],
|
|
54
|
+
input="int f(int n){int s=0;for(int i=0;i<n;i++)s+=i;return s;}\n",
|
|
55
|
+
capture_output=True, text=True)
|
|
56
|
+
except OSError:
|
|
57
|
+
return []
|
|
58
|
+
return [flag] if r.returncode == 0 else []
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_align = align_flags()
|
|
62
|
+
CXXFLAGS = CXXFLAGS + _align
|
|
63
|
+
|
|
36
64
|
kernel = Extension(
|
|
37
65
|
"scm2cpp_learn._lasso_cov",
|
|
38
66
|
sources=[GEN_REL + "/lasso_cov_capi.cpp"],
|
|
@@ -252,6 +280,7 @@ def cuda_home():
|
|
|
252
280
|
# the flat index i*p + j as an induction variable, and the linear SVM's
|
|
253
281
|
# sweep runs 25% slower.
|
|
254
282
|
_cls_flags = ["-O3", "-std=c++17", "-fstrict-overflow"] if os.name != "nt" else MSVC
|
|
283
|
+
_cls_flags = _cls_flags + _align
|
|
255
284
|
classifiers = Extension(
|
|
256
285
|
"scm2cpp_learn._classifiers",
|
|
257
286
|
sources=[GEN_REL + "/classifiers_capi.cpp"],
|
|
@@ -58,7 +58,7 @@ __all__ = ["GramLasso", "GramElasticNet", "GramRidge", "GramRidgeCV", "CovLasso"
|
|
|
58
58
|
"GramLogisticRegression", "GramGroupLasso", "GramMultiTaskLasso",
|
|
59
59
|
"GramMultiTaskElasticNet", "DesignLasso",
|
|
60
60
|
"cuda_available", "derived_backend", "kernel"]
|
|
61
|
-
__version__ = "0.
|
|
61
|
+
__version__ = "0.21.0"
|
|
62
62
|
|
|
63
63
|
_BATCH = load_batch_lib()
|
|
64
64
|
_DP = ctypes.POINTER(ctypes.c_double)
|
|
@@ -91,6 +91,66 @@ def cuda_available():
|
|
|
91
91
|
20, 20, 1e-8)
|
|
92
92
|
|
|
93
93
|
|
|
94
|
+
def _dedup_columns(G, tol=1e-10):
|
|
95
|
+
"""Indices (ascending) keeping, of each group of columns equal up to
|
|
96
|
+
a factor, the one of largest norm; zero columns are dropped."""
|
|
97
|
+
s = np.sqrt(np.maximum(np.diag(G), 0.0))
|
|
98
|
+
d = np.where(s > 0, s, 1.0)
|
|
99
|
+
gs = G / np.outer(d, d)
|
|
100
|
+
gone = s == 0
|
|
101
|
+
keep = []
|
|
102
|
+
for j in np.argsort(-s, kind="stable"):
|
|
103
|
+
if gone[j]:
|
|
104
|
+
continue
|
|
105
|
+
keep.append(j)
|
|
106
|
+
gone |= np.abs(gs[j]) > 1.0 - tol
|
|
107
|
+
return np.sort(np.array(keep, dtype=np.intp))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _kkt_violation(r, beta, nobs, a):
|
|
111
|
+
"""How far beta misses the lasso's optimality conditions at alpha a,
|
|
112
|
+
relative to a; r = c - G beta. A coefficient below 1e-9 of the
|
|
113
|
+
largest counts as zero (interpolation leaves ~1e-19 at a knot)."""
|
|
114
|
+
g = r / nobs
|
|
115
|
+
big = np.abs(beta).max() if beta.size else 0.0
|
|
116
|
+
act = np.abs(beta) > 1e-9 * max(big, 1e-300)
|
|
117
|
+
v = np.where(act, np.abs(g - a * np.sign(beta)), np.maximum(np.abs(g) - a, 0.0))
|
|
118
|
+
return float(v.max()) / a if v.size else 0.0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _polish_lasso(G, c, nobs, alphas, B, tol, kkt_tol=1e-5, chunk=20, max_sweeps=100000):
|
|
122
|
+
"""Rows of B (solutions at alphas) that miss the optimality
|
|
123
|
+
conditions are redone in place by coordinate descent, from the
|
|
124
|
+
better (lower objective) of the row and the previous row, until
|
|
125
|
+
they meet them or the move falls below tol as in fit_path.
|
|
126
|
+
Returns how many rows were redone."""
|
|
127
|
+
p = c.shape[0]
|
|
128
|
+
g = np.ascontiguousarray(G).ravel()
|
|
129
|
+
redone = 0
|
|
130
|
+
|
|
131
|
+
def obj(b, a):
|
|
132
|
+
return 0.5 * (b @ G @ b - 2.0 * c @ b) / nobs + a * np.abs(b).sum()
|
|
133
|
+
for i, a in enumerate(alphas):
|
|
134
|
+
a = float(a)
|
|
135
|
+
r = c - G @ B[i]
|
|
136
|
+
if _kkt_violation(r, B[i], nobs, a) <= kkt_tol:
|
|
137
|
+
continue
|
|
138
|
+
cands = [B[i]] + ([B[i - 1]] if i > 0 else [])
|
|
139
|
+
beta = np.array(min(cands, key=lambda b: obj(b, a)), dtype=np.float64)
|
|
140
|
+
r = np.ascontiguousarray(c - G @ beta)
|
|
141
|
+
prev = np.empty(p)
|
|
142
|
+
swept = 0
|
|
143
|
+
while swept < max_sweeps and _kkt_violation(r, beta, nobs, a) > kkt_tol:
|
|
144
|
+
prev[:] = beta
|
|
145
|
+
kernel.enet_descend(g, r, beta, a, 0.0, chunk, nobs, p)
|
|
146
|
+
swept += chunk
|
|
147
|
+
if np.max(np.abs(beta - prev)) < tol * _scale(beta):
|
|
148
|
+
break
|
|
149
|
+
B[i] = beta
|
|
150
|
+
redone += 1
|
|
151
|
+
return redone
|
|
152
|
+
|
|
153
|
+
|
|
94
154
|
class CovLasso:
|
|
95
155
|
"""Lasso over a design given by its Gram matrix.
|
|
96
156
|
|
|
@@ -501,122 +561,304 @@ class CovLassoCV(Tagged, RegressorMixin, BaseEstimator):
|
|
|
501
561
|
"""Cross-validated lasso, scikit-learn's LassoCV semantics.
|
|
502
562
|
|
|
503
563
|
The lambda grid comes from the full data (lambda_max down, the
|
|
504
|
-
sklearn construction),
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
564
|
+
sklearn construction), and validation error is one matrix product
|
|
565
|
+
per fold. alpha_ minimises the mean validation MSE, ties going to
|
|
566
|
+
the larger penalty as in scikit-learn, and coef_ is the refit on all
|
|
567
|
+
rows at alpha_.
|
|
568
|
+
|
|
569
|
+
cv is a number of folds -- contiguous splits in row order,
|
|
570
|
+
scikit-learn's KFold(shuffle=False) -- or a splitter with a split
|
|
571
|
+
method (TimeSeriesSplit, KFold(shuffle=True), ...) or an iterable of
|
|
572
|
+
(train, test) index arrays. A fold's training Gram is formed the
|
|
573
|
+
cheapest way its rows allow: as the full Gram minus the test rows'
|
|
574
|
+
when train is the complement of test, as a running sum when the
|
|
575
|
+
training sets are growing prefixes (TimeSeriesSplit), and from its
|
|
576
|
+
own rows otherwise.
|
|
577
|
+
|
|
578
|
+
fit_intercept=True centres each fold's training data -- the Gram
|
|
579
|
+
corrected by its means, not a centred copy -- and its test rows by
|
|
580
|
+
the same means, as LassoCV does; the default False keeps the data
|
|
581
|
+
as given (the fit through the origin this class has always made).
|
|
582
|
+
|
|
583
|
+
With a GPU the whole grid -- folds by num penalties, each from
|
|
511
584
|
zero -- is one launch with one block of threads per problem, the
|
|
512
585
|
fold's Gram matrix shared by its problems; on the CPU each fold's
|
|
513
586
|
path is walked warm. force_cpu picks the CPU path; force_gpu is
|
|
514
587
|
accepted for compatibility (the GPU is now taken whenever it is
|
|
515
588
|
there and force_cpu is not set).
|
|
516
589
|
|
|
517
|
-
|
|
590
|
+
solver="lars" (lasso only, l1_ratio=1) solves each fold, and the
|
|
591
|
+
refit, by the translated least angle regression over the same Gram
|
|
592
|
+
(``examples/kernel-only/lars.scm``, method "lasso", the path
|
|
593
|
+
recorded) and reads the solutions at the grid off the path, which is
|
|
594
|
+
piecewise linear in alpha: exact up to rounding, with no tolerance,
|
|
595
|
+
and with a cost set by the number of path steps rather than by
|
|
596
|
+
conditioning. Coordinate descent needs many sweeps when the columns
|
|
597
|
+
are strongly correlated (moving averages over overlapping windows,
|
|
598
|
+
say); there LARS is much faster. Columns equal up to a factor are
|
|
599
|
+
cut to one first (two of them break the path), and a grid point
|
|
600
|
+
whose solution misses the optimality conditions is finished by
|
|
601
|
+
coordinate descent (n_polished_ counts them). The default "cd" is
|
|
602
|
+
the descent.
|
|
603
|
+
|
|
604
|
+
Attributes after fit: alphas_, mse_path_ (num, n_folds), alpha_,
|
|
605
|
+
coef_, intercept_; with solver="lars" also n_polished_ and n_iter_ (the refit's
|
|
606
|
+
path steps).
|
|
518
607
|
"""
|
|
519
608
|
|
|
520
609
|
def __init__(self, cv=5, num=100, eps=1e-3, tol=1e-8, l1_ratio=1.0,
|
|
521
|
-
force_cpu=False, force_gpu=False, n_jobs=1
|
|
610
|
+
force_cpu=False, force_gpu=False, n_jobs=1, fit_intercept=False,
|
|
611
|
+
solver="cd"):
|
|
522
612
|
# Folds are independent, the descent is a ctypes call and the
|
|
523
613
|
# products are BLAS calls, both of which release the GIL, so
|
|
524
614
|
# plain threads scale the CPU path across folds. Default 1:
|
|
525
615
|
# sequential, like scikit-learn's n_jobs=None.
|
|
526
616
|
self.cv, self.num, self.eps, self.tol = cv, num, eps, tol
|
|
527
617
|
self.l1_ratio, self.force_cpu, self.force_gpu = l1_ratio, force_cpu, force_gpu
|
|
528
|
-
self.n_jobs = n_jobs
|
|
618
|
+
self.n_jobs, self.fit_intercept = n_jobs, fit_intercept
|
|
619
|
+
self.solver = solver
|
|
620
|
+
|
|
621
|
+
def _lars_grid(self, G, c, nobs):
|
|
622
|
+
"""The lasso solutions at alphas_ (rows) for Gram G and
|
|
623
|
+
correlations c, by the translated LARS path interpolated on the
|
|
624
|
+
grid; also the number of path steps.
|
|
625
|
+
|
|
626
|
+
Columns equal up to a factor (|correlation| > 1 - 1e-10) are cut
|
|
627
|
+
to the one of largest norm first: the lasso puts the whole
|
|
628
|
+
weight of such a group on that column anyway, and two equal
|
|
629
|
+
columns tie in LARS's correlations and break its Cholesky
|
|
630
|
+
updates. The path is rerun with twice the steps while it stops
|
|
631
|
+
short of the grid's end. A grid point whose solution still
|
|
632
|
+
misses the optimality conditions (|gradient| <= alpha, equal on
|
|
633
|
+
the support, to 1e-5 relative) is finished by coordinate
|
|
634
|
+
descent from it."""
|
|
635
|
+
p = c.shape[0]
|
|
636
|
+
G = np.array(G, dtype=np.float64).reshape(p, p)
|
|
637
|
+
c = np.array(c, dtype=np.float64)
|
|
638
|
+
alphas = self.alphas_
|
|
639
|
+
keep = _dedup_columns(G)
|
|
640
|
+
out = np.zeros((len(alphas), p))
|
|
641
|
+
it = 0
|
|
642
|
+
if keep.size:
|
|
643
|
+
q = keep.size
|
|
644
|
+
Gk = np.ascontiguousarray(G[np.ix_(keep, keep)])
|
|
645
|
+
# the path's stopping test compares alpha with an absolute
|
|
646
|
+
# 1.2e-7 (scikit-learn's): solve with the correlations scaled
|
|
647
|
+
# so that the largest alpha is 1 (coefficients and alphas
|
|
648
|
+
# scale with them), and run to just below the grid's end
|
|
649
|
+
sc = float(np.max(np.abs(c[keep]))) / float(nobs)
|
|
650
|
+
sc = sc if sc > 0 else 1.0
|
|
651
|
+
amin = 0.999 * float(alphas[-1]) / sc
|
|
652
|
+
maxiter = 2 * min(int(nobs), q) + 100
|
|
653
|
+
while True:
|
|
654
|
+
path = np.zeros((maxiter + 1, q))
|
|
655
|
+
knots = np.zeros(maxiter + 1)
|
|
656
|
+
it = _classifier_kernels().lars(
|
|
657
|
+
Gk.copy(), c[keep] / sc, np.zeros(q), path, knots, 1, float(nobs),
|
|
658
|
+
amin, 1, maxiter, float(np.finfo(np.float64).eps), q)
|
|
659
|
+
if it < maxiter or knots[it] <= amin or maxiter > 64 * q + 1000:
|
|
660
|
+
break
|
|
661
|
+
maxiter *= 2
|
|
662
|
+
al, coefs = knots[:it + 1] * sc, path[:it + 1] * sc
|
|
663
|
+
# knots descend; grid point a lies between knots k-1 and k
|
|
664
|
+
k = np.searchsorted(-al, -alphas)
|
|
665
|
+
sub = np.empty((len(alphas), q))
|
|
666
|
+
lo = k == 0
|
|
667
|
+
hi = k >= len(al)
|
|
668
|
+
mid = ~(lo | hi)
|
|
669
|
+
sub[lo] = coefs[0]
|
|
670
|
+
sub[hi] = coefs[-1]
|
|
671
|
+
km = k[mid]
|
|
672
|
+
t = (al[km - 1] - alphas[mid]) / (al[km - 1] - al[km])
|
|
673
|
+
sub[mid] = coefs[km - 1] + t[:, None] * (coefs[km] - coefs[km - 1])
|
|
674
|
+
out[:, keep] = sub
|
|
675
|
+
self._lars_polished_ = getattr(self, "_lars_polished_", 0) + _polish_lasso(
|
|
676
|
+
G, c, float(nobs), alphas, out, self.tol)
|
|
677
|
+
return out, int(it)
|
|
678
|
+
|
|
679
|
+
def _folds(self, X, y, n):
|
|
680
|
+
"""[(train, test)] with train None when it is test's complement;
|
|
681
|
+
test (and a non-None train) is an index array or a slice."""
|
|
682
|
+
if isinstance(self.cv, (int, np.integer)):
|
|
683
|
+
# contiguous folds in row order, sizes as even as they come --
|
|
684
|
+
# sklearn's KFold(shuffle=False)
|
|
685
|
+
bounds = np.linspace(0, n, int(self.cv) + 1).astype(int)
|
|
686
|
+
return [(None, slice(lo, hi)) for lo, hi in zip(bounds[:-1], bounds[1:])]
|
|
687
|
+
splits = self.cv.split(X, y) if hasattr(self.cv, "split") else self.cv
|
|
688
|
+
folds = []
|
|
689
|
+
for tr, te in splits:
|
|
690
|
+
tr, te = np.asarray(tr, dtype=np.intp), np.asarray(te, dtype=np.intp)
|
|
691
|
+
seen = np.zeros(n, dtype=bool)
|
|
692
|
+
seen[tr] = True
|
|
693
|
+
if tr.size + te.size == n and not seen[te].any() and seen.sum() == tr.size:
|
|
694
|
+
folds.append((None, te))
|
|
695
|
+
elif tr.size and tr[0] == 0 and tr[-1] == tr.size - 1 and np.all(np.diff(tr) == 1):
|
|
696
|
+
folds.append((slice(0, tr.size), te))
|
|
697
|
+
else:
|
|
698
|
+
folds.append((tr, te))
|
|
699
|
+
if not folds:
|
|
700
|
+
raise ValueError("cv produced no folds")
|
|
701
|
+
return folds
|
|
702
|
+
|
|
703
|
+
def _fold_stats(self, X, y, n, raw, train, test, prefix):
|
|
704
|
+
"""(Gram, correlations, nobs, x mean, y mean) of a fold's training
|
|
705
|
+
rows, centred when fit_intercept. prefix is [rows, G, c, sx, sy]
|
|
706
|
+
of the last prefix formed, advanced in place."""
|
|
707
|
+
G, c0 = raw.g.reshape(raw.p, raw.p), raw.c0
|
|
708
|
+
if train is None:
|
|
709
|
+
Xf, yf = X[test], y[test]
|
|
710
|
+
Gt, ct = G - Xf.T @ Xf, c0 - Xf.T @ yf
|
|
711
|
+
nt = n - yf.shape[0]
|
|
712
|
+
sx, sy = self._sx - Xf.sum(axis=0), self._sy - yf.sum()
|
|
713
|
+
elif isinstance(train, slice):
|
|
714
|
+
# growing prefixes: add the rows since the last one
|
|
715
|
+
a, b = prefix[0], train.stop
|
|
716
|
+
if b < a:
|
|
717
|
+
prefix[:] = [0, np.zeros_like(G), np.zeros_like(c0), np.zeros(raw.p), 0.0]
|
|
718
|
+
a = 0
|
|
719
|
+
Xd, yd = X[a:b], y[a:b]
|
|
720
|
+
prefix[1] = prefix[1] + Xd.T @ Xd
|
|
721
|
+
prefix[2] = prefix[2] + Xd.T @ yd
|
|
722
|
+
prefix[3] = prefix[3] + Xd.sum(axis=0)
|
|
723
|
+
prefix[4] = prefix[4] + yd.sum()
|
|
724
|
+
prefix[0] = b
|
|
725
|
+
Gt, ct, nt, sx, sy = prefix[1].copy(), prefix[2].copy(), b, prefix[3], prefix[4]
|
|
726
|
+
else:
|
|
727
|
+
Xt, yt = X[train], y[train]
|
|
728
|
+
Gt, ct, nt = Xt.T @ Xt, Xt.T @ yt, yt.shape[0]
|
|
729
|
+
sx, sy = Xt.sum(axis=0), yt.sum()
|
|
730
|
+
if not self.fit_intercept:
|
|
731
|
+
return Gt, ct, nt, np.zeros(raw.p), 0.0
|
|
732
|
+
xm, ym = sx / nt, sy / nt
|
|
733
|
+
nm2 = nt * xm * xm
|
|
734
|
+
if np.all(np.diagonal(Gt) - nm2 > 1e-4 * nm2):
|
|
735
|
+
Gt -= np.outer(xm, nt * xm)
|
|
736
|
+
ct -= nt * xm * ym
|
|
737
|
+
else:
|
|
738
|
+
# a column whose mean dwarfs its spread: the correction would
|
|
739
|
+
# cancel its digits (see _centered_gram), so centre the rows
|
|
740
|
+
if train is None:
|
|
741
|
+
keep = np.ones(n, dtype=bool)
|
|
742
|
+
keep[test] = False
|
|
743
|
+
Xt, yt = X[keep], y[keep]
|
|
744
|
+
else:
|
|
745
|
+
Xt, yt = X[train], y[train]
|
|
746
|
+
Xc = Xt - xm
|
|
747
|
+
Gt, ct = Xc.T @ Xc, Xc.T @ (yt - ym)
|
|
748
|
+
return Gt, ct, nt, xm, ym
|
|
529
749
|
|
|
530
750
|
def fit(self, X, y):
|
|
531
751
|
X, y = fit_xy(self, X, y)
|
|
532
752
|
n = len(y)
|
|
533
|
-
|
|
753
|
+
num = int(self.num)
|
|
534
754
|
tol, l1_ratio = float(self.tol), float(self.l1_ratio)
|
|
535
|
-
|
|
755
|
+
raw = CovLasso(X, y)
|
|
756
|
+
self._sx, self._sy = X.sum(axis=0), float(y.sum())
|
|
757
|
+
if self.fit_intercept:
|
|
758
|
+
G, c, xm, ym = _centered_gram(X, y, True)
|
|
759
|
+
full = CovLasso(gram=G, corr=c, nobs=n)
|
|
760
|
+
self._xm, self._ym = xm, float(ym)
|
|
761
|
+
else:
|
|
762
|
+
full = raw
|
|
763
|
+
self._xm, self._ym = np.zeros(X.shape[1]), 0.0
|
|
536
764
|
self.alphas_ = full.lambda_grid(num=num, eps=float(self.eps),
|
|
537
765
|
l1_ratio=l1_ratio)
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
766
|
+
folds = self._folds(X, y, n)
|
|
767
|
+
self.mse_path_ = np.empty((num, len(folds)))
|
|
768
|
+
if self.solver not in ("cd", "lars"):
|
|
769
|
+
raise ValueError(f"solver must be 'cd' or 'lars', got {self.solver!r}")
|
|
770
|
+
lars = self.solver == "lars"
|
|
771
|
+
self._lars_polished_ = 0
|
|
772
|
+
if lars and l1_ratio != 1.0:
|
|
773
|
+
raise ValueError("solver='lars' solves the lasso only (l1_ratio=1)")
|
|
774
|
+
self._full = full
|
|
775
|
+
if cuda_available() and not self.force_cpu and not lars:
|
|
776
|
+
done = self._fit_gpu(X, y, raw, full, folds, n)
|
|
545
777
|
if done is not None:
|
|
546
778
|
return done
|
|
547
779
|
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
# Over five folds that is the whole Gram work twice instead
|
|
555
|
-
# of four times, and the Gram is the dominant O(n p^2) step.
|
|
556
|
-
m = CovLasso(gram=(G - Xf.T @ Xf).ravel(),
|
|
557
|
-
corr=full.c0 - Xf.T @ yf,
|
|
558
|
-
nobs=n - (hi - lo))
|
|
780
|
+
prefix = [0, np.zeros((raw.p, raw.p)), np.zeros(raw.p), np.zeros(raw.p), 0.0]
|
|
781
|
+
|
|
782
|
+
def one_fold(k, stats=None):
|
|
783
|
+
train, test = folds[k]
|
|
784
|
+
Gt, ct, nt, xm, ym = stats or self._fold_stats(X, y, n, raw, train, test, prefix)
|
|
785
|
+
m = CovLasso(gram=Gt.ravel(), corr=ct, nobs=nt)
|
|
559
786
|
# The warm-started path: after the Gram, each lambda resumes
|
|
560
787
|
# where the previous stopped and costs O(p) per moving
|
|
561
788
|
# coordinate. That warm path is what makes searching the
|
|
562
789
|
# alpha grid cheap -- the grid costs barely more than its
|
|
563
790
|
# hardest single alpha.
|
|
564
|
-
|
|
565
|
-
|
|
791
|
+
if lars:
|
|
792
|
+
path, _ = self._lars_grid(Gt, ct, nt)
|
|
793
|
+
else:
|
|
794
|
+
path = m.fit_path(self.alphas_, tol=tol, l1_ratio=l1_ratio)
|
|
795
|
+
resid = (X[test] - xm) @ path.T - (y[test] - ym)[:, None]
|
|
566
796
|
self.mse_path_[:, k] = np.mean(resid * resid, axis=0)
|
|
567
797
|
|
|
568
798
|
if int(self.n_jobs) > 1:
|
|
569
799
|
from concurrent.futures import ThreadPoolExecutor
|
|
800
|
+
# a prefix sum runs in fold order, so a prefix fold's statistics
|
|
801
|
+
# are formed here and only the descents run in the threads
|
|
802
|
+
pre = {k: self._fold_stats(X, y, n, raw, *folds[k], prefix)
|
|
803
|
+
for k in range(len(folds)) if isinstance(folds[k][0], slice)}
|
|
570
804
|
with ThreadPoolExecutor(max_workers=int(self.n_jobs)) as ex:
|
|
571
|
-
list(ex.map(one_fold, range(
|
|
805
|
+
list(ex.map(lambda k: one_fold(k, pre.get(k)), range(len(folds))))
|
|
572
806
|
else:
|
|
573
|
-
for k in range(
|
|
807
|
+
for k in range(len(folds)):
|
|
574
808
|
one_fold(k)
|
|
575
809
|
return self._finish(full)
|
|
576
810
|
|
|
577
|
-
def _fit_gpu(self, X, y,
|
|
811
|
+
def _fit_gpu(self, X, y, raw, full, folds, n):
|
|
578
812
|
# Every fold and every alpha is an independent problem, so all of
|
|
579
813
|
# them go to the device as one batch, one block per problem,
|
|
580
814
|
# the problems of a fold sharing its Gram on the device. Fold
|
|
581
|
-
# sizes may differ
|
|
582
|
-
#
|
|
583
|
-
#
|
|
584
|
-
#
|
|
585
|
-
#
|
|
815
|
+
# sizes may differ; the kernel only ever uses lam through the
|
|
816
|
+
# product lam * nobs, so each problem's nobs is absorbed into its
|
|
817
|
+
# lambda and nobs is passed as 1 -- exact, not approximate.
|
|
818
|
+
# Returns None when the device declined, and the CPU path takes
|
|
819
|
+
# over.
|
|
586
820
|
p_ = full.p
|
|
587
|
-
num,
|
|
588
|
-
grams = np.empty((
|
|
589
|
-
corrs = np.empty((
|
|
590
|
-
nobs_k = np.empty(
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
corrs[k] =
|
|
596
|
-
|
|
597
|
-
lams = (np.tile(self.alphas_,
|
|
821
|
+
num, nf = int(self.num), len(folds)
|
|
822
|
+
grams = np.empty((nf, p_ * p_))
|
|
823
|
+
corrs = np.empty((nf, p_))
|
|
824
|
+
nobs_k = np.empty(nf)
|
|
825
|
+
means = []
|
|
826
|
+
prefix = [0, np.zeros((p_, p_)), np.zeros(p_), np.zeros(p_), 0.0]
|
|
827
|
+
for k, (train, test) in enumerate(folds):
|
|
828
|
+
Gt, ct, nt, xm, ym = self._fold_stats(X, y, n, raw, train, test, prefix)
|
|
829
|
+
grams[k], corrs[k], nobs_k[k] = Gt.ravel(), ct, nt
|
|
830
|
+
means.append((xm, ym))
|
|
831
|
+
lams = (np.tile(self.alphas_, nf) * np.repeat(nobs_k, num))
|
|
598
832
|
betas = _grid_descend(grams, corrs, lams, p_, 0, tol=float(self.tol),
|
|
599
833
|
l1_ratio=float(self.l1_ratio))
|
|
600
834
|
if betas is None:
|
|
601
835
|
return None
|
|
602
|
-
betas = betas.reshape(
|
|
603
|
-
for k in
|
|
604
|
-
|
|
605
|
-
resid = X[
|
|
836
|
+
betas = betas.reshape(nf, num, p_)
|
|
837
|
+
for k, (train, test) in enumerate(folds):
|
|
838
|
+
xm, ym = means[k]
|
|
839
|
+
resid = (X[test] - xm) @ betas[k].T - (y[test] - ym)[:, None]
|
|
606
840
|
self.mse_path_[:, k] = np.mean(resid * resid, axis=0)
|
|
607
841
|
return self._finish(full)
|
|
608
842
|
|
|
609
843
|
def _finish(self, full):
|
|
610
844
|
mean = self.mse_path_.mean(axis=1)
|
|
611
845
|
# alphas_ descends, so argmin's first hit is the larger penalty
|
|
612
|
-
|
|
613
|
-
self.
|
|
614
|
-
|
|
615
|
-
|
|
846
|
+
ib = int(np.argmin(mean))
|
|
847
|
+
self.alpha_ = float(self.alphas_[ib])
|
|
848
|
+
if self.solver == "lars":
|
|
849
|
+
path, self.n_iter_ = self._lars_grid(full.g.reshape(full.p, full.p), full.c0,
|
|
850
|
+
full.nobs)
|
|
851
|
+
self.coef_ = path[ib].copy()
|
|
852
|
+
self.n_polished_ = self._lars_polished_
|
|
853
|
+
else:
|
|
854
|
+
self.coef_ = full.fit(self.alpha_, tol=float(self.tol),
|
|
855
|
+
l1_ratio=float(self.l1_ratio))
|
|
856
|
+
self.intercept_ = self._ym - float(self._xm @ self.coef_)
|
|
857
|
+
del self._sx, self._sy, self._xm, self._ym, self._full
|
|
616
858
|
return self
|
|
617
859
|
|
|
618
860
|
def predict(self, X):
|
|
619
|
-
return pred_x(self, X) @ self.coef_
|
|
861
|
+
return pred_x(self, X) @ self.coef_ + self.intercept_
|
|
620
862
|
|
|
621
863
|
|
|
622
864
|
class CovRidge:
|
|
@@ -3281,7 +3523,7 @@ def _dot(X, B, transpose=False):
|
|
|
3281
3523
|
else:
|
|
3282
3524
|
A = X.tocsc() if transpose else X
|
|
3283
3525
|
out = np.zeros((m, B2.shape[1]))
|
|
3284
|
-
_gramops_kernels().csr_mm(np.ascontiguousarray(A.indptr, dtype=np.
|
|
3526
|
+
_gramops_kernels().csr_mm(np.ascontiguousarray(A.indptr, dtype=np.int64),
|
|
3285
3527
|
np.ascontiguousarray(A.indices, dtype=np.int32),
|
|
3286
3528
|
np.ascontiguousarray(A.data, dtype=np.float64),
|
|
3287
3529
|
B2, out, m, B2.shape[1])
|
|
@@ -199,16 +199,18 @@ def _issparse(X):
|
|
|
199
199
|
|
|
200
200
|
def as_csr(X):
|
|
201
201
|
"""X (any scipy.sparse format) as CSR the kernels take: float64 data,
|
|
202
|
-
int32 indices
|
|
203
|
-
|
|
202
|
+
int32 column indices, int64 row pointers (so nnz may pass 2^31; the
|
|
203
|
+
rows and columns, which index into both CSR and CSC, may not). The
|
|
204
|
+
caller's matrix is not changed; duplicate entries may stay (both
|
|
205
|
+
kernels add them, which is what they mean)."""
|
|
204
206
|
X = X.tocsr()
|
|
205
207
|
if X.dtype != np.float64:
|
|
206
208
|
X = X.astype(np.float64)
|
|
207
|
-
if X.
|
|
208
|
-
|
|
209
|
-
|
|
209
|
+
if max(X.shape) >= 2 ** 31:
|
|
210
|
+
raise ValueError("a sparse X with 2^31 or more rows or columns is not taken")
|
|
211
|
+
if X.indices.dtype != np.int32 or X.indptr.dtype != np.int64:
|
|
210
212
|
X = X.copy()
|
|
211
|
-
X.indices, X.indptr = X.indices.astype(np.int32), X.indptr.astype(np.
|
|
213
|
+
X.indices, X.indptr = X.indices.astype(np.int32), X.indptr.astype(np.int64)
|
|
212
214
|
return X
|
|
213
215
|
|
|
214
216
|
|
|
@@ -15,24 +15,24 @@ _lib.scm2cpp_soft_threshold.argtypes = [ctypes.c_double, ctypes.c_double]
|
|
|
15
15
|
def soft_threshold(z, g):
|
|
16
16
|
return _lib.scm2cpp_soft_threshold(z, g)
|
|
17
17
|
|
|
18
|
-
_lib.scm2cpp_cov_descend.restype = ctypes.
|
|
19
|
-
_lib.scm2cpp_cov_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.
|
|
18
|
+
_lib.scm2cpp_cov_descend.restype = ctypes.c_int64
|
|
19
|
+
_lib.scm2cpp_cov_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_int64, ctypes.c_double, ctypes.c_int64]
|
|
20
20
|
def cov_descend(g, c, beta, lam, iters, nobs, p):
|
|
21
21
|
g = np.ascontiguousarray(g, dtype=np.float64)
|
|
22
22
|
c = np.ascontiguousarray(c, dtype=np.float64)
|
|
23
23
|
beta = np.ascontiguousarray(beta, dtype=np.float64)
|
|
24
24
|
return _lib.scm2cpp_cov_descend(g.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), beta.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), lam, iters, nobs, p)
|
|
25
25
|
|
|
26
|
-
_lib.scm2cpp_enet_descend.restype = ctypes.
|
|
27
|
-
_lib.scm2cpp_enet_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_double, ctypes.
|
|
26
|
+
_lib.scm2cpp_enet_descend.restype = ctypes.c_int64
|
|
27
|
+
_lib.scm2cpp_enet_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_double, ctypes.c_int64, ctypes.c_double, ctypes.c_int64]
|
|
28
28
|
def enet_descend(g, c, beta, lam1, lam2, iters, nobs, p):
|
|
29
29
|
g = np.ascontiguousarray(g, dtype=np.float64)
|
|
30
30
|
c = np.ascontiguousarray(c, dtype=np.float64)
|
|
31
31
|
beta = np.ascontiguousarray(beta, dtype=np.float64)
|
|
32
32
|
return _lib.scm2cpp_enet_descend(g.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), c.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), beta.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), lam1, lam2, iters, nobs, p)
|
|
33
33
|
|
|
34
|
-
_lib.scm2cpp_mt_descend.restype = ctypes.
|
|
35
|
-
_lib.scm2cpp_mt_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_double, ctypes.
|
|
34
|
+
_lib.scm2cpp_mt_descend.restype = ctypes.c_int64
|
|
35
|
+
_lib.scm2cpp_mt_descend.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_double, ctypes.c_int64, ctypes.c_double, ctypes.c_int64, ctypes.c_int64]
|
|
36
36
|
def mt_descend(g, c, w, lam1, lam2, iters, nobs, p, ntask):
|
|
37
37
|
g = np.ascontiguousarray(g, dtype=np.float64)
|
|
38
38
|
c = np.ascontiguousarray(c, dtype=np.float64)
|